1//===--- SemaExpr.cpp - Semantic Analysis for Expressions -----------------===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8//
9// This file implements semantic analysis for expressions.
10//
11//===----------------------------------------------------------------------===//
12
13#include "CheckExprLifetime.h"
14#include "TreeTransform.h"
15#include "UsedDeclVisitor.h"
16#include "clang/AST/ASTConsumer.h"
17#include "clang/AST/ASTContext.h"
18#include "clang/AST/ASTDiagnostic.h"
19#include "clang/AST/ASTLambda.h"
20#include "clang/AST/ASTMutationListener.h"
21#include "clang/AST/Attr.h"
22#include "clang/AST/CXXInheritance.h"
23#include "clang/AST/Decl.h"
24#include "clang/AST/DeclObjC.h"
25#include "clang/AST/DeclTemplate.h"
26#include "clang/AST/DynamicRecursiveASTVisitor.h"
27#include "clang/AST/EvaluatedExprVisitor.h"
28#include "clang/AST/Expr.h"
29#include "clang/AST/ExprCXX.h"
30#include "clang/AST/ExprObjC.h"
31#include "clang/AST/MangleNumberingContext.h"
32#include "clang/AST/OperationKinds.h"
33#include "clang/AST/StmtVisitor.h"
34#include "clang/AST/Type.h"
35#include "clang/AST/TypeLoc.h"
36#include "clang/Basic/Builtins.h"
37#include "clang/Basic/DiagnosticSema.h"
38#include "clang/Basic/PartialDiagnostic.h"
39#include "clang/Basic/SourceManager.h"
40#include "clang/Basic/Specifiers.h"
41#include "clang/Basic/TargetInfo.h"
42#include "clang/Basic/TypeTraits.h"
43#include "clang/Lex/LiteralSupport.h"
44#include "clang/Lex/Preprocessor.h"
45#include "clang/Sema/AnalysisBasedWarnings.h"
46#include "clang/Sema/DeclSpec.h"
47#include "clang/Sema/DelayedDiagnostic.h"
48#include "clang/Sema/Designator.h"
49#include "clang/Sema/EnterExpressionEvaluationContext.h"
50#include "clang/Sema/Initialization.h"
51#include "clang/Sema/Lookup.h"
52#include "clang/Sema/Overload.h"
53#include "clang/Sema/ParsedTemplate.h"
54#include "clang/Sema/Scope.h"
55#include "clang/Sema/ScopeInfo.h"
56#include "clang/Sema/SemaAMDGPU.h"
57#include "clang/Sema/SemaARM.h"
58#include "clang/Sema/SemaCUDA.h"
59#include "clang/Sema/SemaFixItUtils.h"
60#include "clang/Sema/SemaHLSL.h"
61#include "clang/Sema/SemaObjC.h"
62#include "clang/Sema/SemaOpenMP.h"
63#include "clang/Sema/SemaPseudoObject.h"
64#include "clang/Sema/Template.h"
65#include "llvm/ADT/STLExtras.h"
66#include "llvm/ADT/StringExtras.h"
67#include "llvm/Support/ConvertUTF.h"
68#include "llvm/Support/SaveAndRestore.h"
69#include "llvm/Support/TimeProfiler.h"
70#include "llvm/Support/TypeSize.h"
71#include <limits>
72#include <optional>
73
74using namespace clang;
75using namespace sema;
76
77bool Sema::CanUseDecl(NamedDecl *D, bool TreatUnavailableAsInvalid) {
78 // See if this is an auto-typed variable whose initializer we are parsing.
79 if (ParsingInitForAutoVars.count(Ptr: D))
80 return false;
81
82 // See if this is a deleted function.
83 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Val: D)) {
84 if (FD->isDeleted())
85 return false;
86
87 // If the function has a deduced return type, and we can't deduce it,
88 // then we can't use it either.
89 if (getLangOpts().CPlusPlus14 && FD->getReturnType()->isUndeducedType() &&
90 DeduceReturnType(FD, Loc: SourceLocation(), /*Diagnose*/ false))
91 return false;
92
93 // See if this is an aligned allocation/deallocation function that is
94 // unavailable.
95 if (TreatUnavailableAsInvalid &&
96 isUnavailableAlignedAllocationFunction(FD: *FD))
97 return false;
98 }
99
100 // See if this function is unavailable.
101 if (TreatUnavailableAsInvalid && D->getAvailability() == AR_Unavailable &&
102 cast<Decl>(Val: CurContext)->getAvailability() != AR_Unavailable)
103 return false;
104
105 if (isa<UnresolvedUsingIfExistsDecl>(Val: D))
106 return false;
107
108 return true;
109}
110
111static void DiagnoseUnusedOfDecl(Sema &S, NamedDecl *D, SourceLocation Loc) {
112 // Warn if this is used but marked unused.
113 if (const auto *A = D->getAttr<UnusedAttr>()) {
114 // [[maybe_unused]] should not diagnose uses, but __attribute__((unused))
115 // should diagnose them.
116 if (A->getSemanticSpelling() != UnusedAttr::CXX11_maybe_unused &&
117 A->getSemanticSpelling() != UnusedAttr::C23_maybe_unused) {
118 const Decl *DC = cast_or_null<Decl>(Val: S.ObjC().getCurObjCLexicalContext());
119 if (DC && !DC->hasAttr<UnusedAttr>())
120 S.Diag(Loc, DiagID: diag::warn_used_but_marked_unused) << D;
121 }
122 }
123}
124
125void Sema::NoteDeletedFunction(FunctionDecl *Decl) {
126 assert(Decl && Decl->isDeleted());
127
128 if (Decl->isDefaulted()) {
129 // If the method was explicitly defaulted, point at that declaration.
130 if (!Decl->isImplicit())
131 Diag(Loc: Decl->getLocation(), DiagID: diag::note_implicitly_deleted);
132
133 // Try to diagnose why this special member function was implicitly
134 // deleted. This might fail, if that reason no longer applies.
135 DiagnoseDeletedDefaultedFunction(FD: Decl);
136 return;
137 }
138
139 auto *Ctor = dyn_cast<CXXConstructorDecl>(Val: Decl);
140 if (Ctor && Ctor->isInheritingConstructor())
141 return NoteDeletedInheritingConstructor(CD: Ctor);
142
143 Diag(Loc: Decl->getLocation(), DiagID: diag::note_availability_specified_here)
144 << Decl << 1;
145}
146
147/// Determine whether a FunctionDecl was ever declared with an
148/// explicit storage class.
149static bool hasAnyExplicitStorageClass(const FunctionDecl *D) {
150 for (auto *I : D->redecls()) {
151 if (I->getStorageClass() != SC_None)
152 return true;
153 }
154 return false;
155}
156
157/// Check whether we're in an extern inline function and referring to a
158/// variable or function with internal linkage (C11 6.7.4p3).
159///
160/// This is only a warning because we used to silently accept this code, but
161/// in many cases it will not behave correctly. This is not enabled in C++ mode
162/// because the restriction language is a bit weaker (C++11 [basic.def.odr]p6)
163/// and so while there may still be user mistakes, most of the time we can't
164/// prove that there are errors.
165static void diagnoseUseOfInternalDeclInInlineFunction(Sema &S,
166 const NamedDecl *D,
167 SourceLocation Loc) {
168 // This is disabled under C++; there are too many ways for this to fire in
169 // contexts where the warning is a false positive, or where it is technically
170 // correct but benign.
171 //
172 // WG14 N3622 which removed the constraint entirely in C2y. It is left
173 // enabled in earlier language modes because this is a constraint in those
174 // language modes. But in C2y mode, we still want to issue the "incompatible
175 // with previous standards" diagnostic, too.
176 if (S.getLangOpts().CPlusPlus)
177 return;
178
179 // Check if this is an inlined function or method.
180 FunctionDecl *Current = S.getCurFunctionDecl();
181 if (!Current)
182 return;
183 if (!Current->isInlined())
184 return;
185 if (!Current->isExternallyVisible())
186 return;
187
188 // Check if the decl has internal linkage.
189 if (D->getFormalLinkage() != Linkage::Internal)
190 return;
191
192 // Downgrade from ExtWarn to Extension if
193 // (1) the supposedly external inline function is in the main file,
194 // and probably won't be included anywhere else.
195 // (2) the thing we're referencing is a pure function.
196 // (3) the thing we're referencing is another inline function.
197 // This last can give us false negatives, but it's better than warning on
198 // wrappers for simple C library functions.
199 const FunctionDecl *UsedFn = dyn_cast<FunctionDecl>(Val: D);
200 unsigned DiagID;
201 if (S.getLangOpts().C2y)
202 DiagID = diag::warn_c2y_compat_internal_in_extern_inline;
203 else if ((UsedFn && (UsedFn->isInlined() || UsedFn->hasAttr<ConstAttr>())) ||
204 S.getSourceManager().isInMainFile(Loc))
205 DiagID = diag::ext_internal_in_extern_inline_quiet;
206 else
207 DiagID = diag::ext_internal_in_extern_inline;
208
209 S.Diag(Loc, DiagID) << /*IsVar=*/!UsedFn << D;
210 S.MaybeSuggestAddingStaticToDecl(D: Current);
211 S.Diag(Loc: D->getCanonicalDecl()->getLocation(), DiagID: diag::note_entity_declared_at)
212 << D;
213}
214
215void Sema::MaybeSuggestAddingStaticToDecl(const FunctionDecl *Cur) {
216 const FunctionDecl *First = Cur->getFirstDecl();
217
218 // Suggest "static" on the function, if possible.
219 if (!hasAnyExplicitStorageClass(D: First)) {
220 SourceLocation DeclBegin = First->getSourceRange().getBegin();
221 Diag(Loc: DeclBegin, DiagID: diag::note_convert_inline_to_static)
222 << Cur << FixItHint::CreateInsertion(InsertionLoc: DeclBegin, Code: "static ");
223 }
224}
225
226bool Sema::DiagnoseUseOfDecl(NamedDecl *D, ArrayRef<SourceLocation> Locs,
227 const ObjCInterfaceDecl *UnknownObjCClass,
228 bool ObjCPropertyAccess,
229 bool AvoidPartialAvailabilityChecks,
230 ObjCInterfaceDecl *ClassReceiver,
231 bool SkipTrailingRequiresClause) {
232 SourceLocation Loc = Locs.front();
233 if (getLangOpts().CPlusPlus && isa<FunctionDecl>(Val: D)) {
234 // If there were any diagnostics suppressed by template argument deduction,
235 // emit them now.
236 auto Pos = SuppressedDiagnostics.find(Val: D->getCanonicalDecl());
237 if (Pos != SuppressedDiagnostics.end()) {
238 for (const auto &[DiagLoc, PD] : Pos->second) {
239 DiagnosticBuilder Builder(Diags.Report(Loc: DiagLoc, DiagID: PD.getDiagID()));
240 PD.Emit(DB: Builder);
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>(Val: D)->isMain())
252 Diag(Loc, DiagID: 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(Ptr: D)) {
259 if (isa<BindingDecl>(Val: D)) {
260 Diag(Loc, DiagID: diag::err_binding_cannot_appear_in_own_initializer)
261 << D->getDeclName();
262 } else {
263 Diag(Loc, DiagID: diag::err_auto_variable_cannot_appear_in_own_initializer)
264 << diag::ParsingInitFor::Var << D->getDeclName()
265 << cast<VarDecl>(Val: D)->getType();
266 }
267 return true;
268 }
269
270 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Val: D)) {
271 // See if this is a deleted function.
272 if (FD->isDeleted()) {
273 auto *Ctor = dyn_cast<CXXConstructorDecl>(Val: FD);
274 if (Ctor && Ctor->isInheritingConstructor())
275 Diag(Loc, DiagID: diag::err_deleted_inherited_ctor_use)
276 << Ctor->getParent()
277 << Ctor->getInheritedConstructor().getConstructor()->getParent();
278 else {
279 StringLiteral *Msg = FD->getDeletedMessage();
280 Diag(Loc, DiagID: diag::err_deleted_function_use)
281 << (Msg != nullptr) << (Msg ? Msg->getString() : StringRef());
282 }
283 NoteDeletedFunction(Decl: FD);
284 return true;
285 }
286
287 // [expr.prim.id]p4
288 // A program that refers explicitly or implicitly to a function with a
289 // trailing requires-clause whose constraint-expression is not satisfied,
290 // other than to declare it, is ill-formed. [...]
291 //
292 // See if this is a function with constraints that need to be satisfied.
293 // Check this before deducing the return type, as it might instantiate the
294 // definition.
295 if (!SkipTrailingRequiresClause && FD->getTrailingRequiresClause()) {
296 ConstraintSatisfaction Satisfaction;
297 if (CheckFunctionConstraints(FD, Satisfaction, UsageLoc: Loc,
298 /*ForOverloadResolution*/ true))
299 // A diagnostic will have already been generated (non-constant
300 // constraint expression, for example)
301 return true;
302 if (!Satisfaction.IsSatisfied) {
303 Diag(Loc,
304 DiagID: diag::err_reference_to_function_with_unsatisfied_constraints)
305 << D;
306 DiagnoseUnsatisfiedConstraint(Satisfaction);
307 return true;
308 }
309 }
310
311 // If the function has a deduced return type, and we can't deduce it,
312 // then we can't use it either.
313 if (getLangOpts().CPlusPlus14 && FD->getReturnType()->isUndeducedType() &&
314 DeduceReturnType(FD, Loc))
315 return true;
316
317 if (getLangOpts().CUDA && !CUDA().CheckCall(Loc, Callee: FD))
318 return true;
319
320 }
321
322 if (auto *Concept = dyn_cast<ConceptDecl>(Val: D);
323 Concept && CheckConceptUseInDefinition(Concept, Loc))
324 return true;
325
326 if (auto *MD = dyn_cast<CXXMethodDecl>(Val: D)) {
327 // Lambdas are only default-constructible or assignable in C++2a onwards.
328 if (MD->getParent()->isLambda() &&
329 ((isa<CXXConstructorDecl>(Val: MD) &&
330 cast<CXXConstructorDecl>(Val: MD)->isDefaultConstructor()) ||
331 MD->isCopyAssignmentOperator() || MD->isMoveAssignmentOperator())) {
332 Diag(Loc, DiagID: diag::warn_cxx17_compat_lambda_def_ctor_assign)
333 << !isa<CXXConstructorDecl>(Val: MD);
334 }
335 }
336
337 auto getReferencedObjCProp = [](const NamedDecl *D) ->
338 const ObjCPropertyDecl * {
339 if (const auto *MD = dyn_cast<ObjCMethodDecl>(Val: D))
340 return MD->findPropertyDecl();
341 return nullptr;
342 };
343 if (const ObjCPropertyDecl *ObjCPDecl = getReferencedObjCProp(D)) {
344 if (diagnoseArgIndependentDiagnoseIfAttrs(ND: ObjCPDecl, Loc))
345 return true;
346 } else if (diagnoseArgIndependentDiagnoseIfAttrs(ND: D, Loc)) {
347 return true;
348 }
349
350 // [OpenMP 4.0], 2.15 declare reduction Directive, Restrictions
351 // Only the variables omp_in and omp_out are allowed in the combiner.
352 // Only the variables omp_priv and omp_orig are allowed in the
353 // initializer-clause.
354 auto *DRD = dyn_cast<OMPDeclareReductionDecl>(Val: CurContext);
355 if (LangOpts.OpenMP && DRD && !CurContext->containsDecl(D) &&
356 isa<VarDecl>(Val: D)) {
357 Diag(Loc, DiagID: diag::err_omp_wrong_var_in_declare_reduction)
358 << getCurFunction()->HasOMPDeclareReductionCombiner;
359 Diag(Loc: D->getLocation(), DiagID: diag::note_entity_declared_at) << D;
360 return true;
361 }
362
363 // [OpenMP 5.0], 2.19.7.3. declare mapper Directive, Restrictions
364 // List-items in map clauses on this construct may only refer to the declared
365 // variable var and entities that could be referenced by a procedure defined
366 // at the same location.
367 // [OpenMP 5.2] Also allow iterator declared variables.
368 if (LangOpts.OpenMP && isa<VarDecl>(Val: D) &&
369 !OpenMP().isOpenMPDeclareMapperVarDeclAllowed(VD: cast<VarDecl>(Val: D))) {
370 Diag(Loc, DiagID: diag::err_omp_declare_mapper_wrong_var)
371 << OpenMP().getOpenMPDeclareMapperVarName();
372 Diag(Loc: D->getLocation(), DiagID: diag::note_entity_declared_at) << D;
373 return true;
374 }
375
376 if (const auto *EmptyD = dyn_cast<UnresolvedUsingIfExistsDecl>(Val: D)) {
377 Diag(Loc, DiagID: diag::err_use_of_empty_using_if_exists);
378 Diag(Loc: EmptyD->getLocation(), DiagID: diag::note_empty_using_if_exists_here);
379 return true;
380 }
381
382 DiagnoseAvailabilityOfDecl(D, Locs, UnknownObjCClass, ObjCPropertyAccess,
383 AvoidPartialAvailabilityChecks, ClassReceiver);
384
385 DiagnoseUnusedOfDecl(S&: *this, D, Loc);
386
387 diagnoseUseOfInternalDeclInInlineFunction(S&: *this, D, Loc);
388
389 if (D->hasAttr<AvailableOnlyInDefaultEvalMethodAttr>()) {
390 if (getLangOpts().getFPEvalMethod() !=
391 LangOptions::FPEvalMethodKind::FEM_UnsetOnCommandLine &&
392 PP.getLastFPEvalPragmaLocation().isValid() &&
393 PP.getCurrentFPEvalMethod() != getLangOpts().getFPEvalMethod())
394 Diag(Loc: D->getLocation(),
395 DiagID: diag::err_type_available_only_in_default_eval_method)
396 << D->getName();
397 }
398
399 if (auto *VD = dyn_cast<ValueDecl>(Val: D))
400 checkTypeSupport(Ty: VD->getType(), Loc, D: VD);
401
402 if (LangOpts.SYCLIsDevice ||
403 (LangOpts.OpenMP && LangOpts.OpenMPIsTargetDevice)) {
404 if (!Context.getTargetInfo().isTLSSupported())
405 if (const auto *VD = dyn_cast<VarDecl>(Val: D))
406 if (VD->getTLSKind() != VarDecl::TLS_None)
407 targetDiag(Loc: *Locs.begin(), DiagID: diag::err_thread_unsupported);
408 }
409
410 if (LangOpts.SYCLIsDevice && isa<FunctionDecl>(Val: D))
411 SYCL().CheckDeviceUseOfDecl(ND: D, Loc);
412
413 return false;
414}
415
416void Sema::DiagnoseSentinelCalls(const NamedDecl *D, SourceLocation Loc,
417 ArrayRef<Expr *> Args) {
418 const SentinelAttr *Attr = D->getAttr<SentinelAttr>();
419 if (!Attr)
420 return;
421
422 // The number of formal parameters of the declaration.
423 unsigned NumFormalParams;
424
425 // The kind of declaration. This is also an index into a %select in
426 // the diagnostic.
427 enum { CK_Function, CK_Method, CK_Block } CalleeKind;
428
429 if (const auto *MD = dyn_cast<ObjCMethodDecl>(Val: D)) {
430 NumFormalParams = MD->param_size();
431 CalleeKind = CK_Method;
432 } else if (const auto *FD = dyn_cast<FunctionDecl>(Val: D)) {
433 NumFormalParams = FD->param_size();
434 CalleeKind = CK_Function;
435 } else if (const auto *VD = dyn_cast<VarDecl>(Val: D)) {
436 QualType Ty = VD->getType();
437 const FunctionType *Fn = nullptr;
438 if (const auto *PtrTy = Ty->getAs<PointerType>()) {
439 Fn = PtrTy->getPointeeType()->getAs<FunctionType>();
440 if (!Fn)
441 return;
442 CalleeKind = CK_Function;
443 } else if (const auto *PtrTy = Ty->getAs<BlockPointerType>()) {
444 Fn = PtrTy->getPointeeType()->castAs<FunctionType>();
445 CalleeKind = CK_Block;
446 } else {
447 return;
448 }
449
450 if (const auto *proto = dyn_cast<FunctionProtoType>(Val: Fn))
451 NumFormalParams = proto->getNumParams();
452 else
453 NumFormalParams = 0;
454 } else {
455 return;
456 }
457
458 // "NullPos" is the number of formal parameters at the end which
459 // effectively count as part of the variadic arguments. This is
460 // useful if you would prefer to not have *any* formal parameters,
461 // but the language forces you to have at least one.
462 unsigned NullPos = Attr->getNullPos();
463 assert((NullPos == 0 || NullPos == 1) && "invalid null position on sentinel");
464 NumFormalParams = (NullPos > NumFormalParams ? 0 : NumFormalParams - NullPos);
465
466 // The number of arguments which should follow the sentinel.
467 unsigned NumArgsAfterSentinel = Attr->getSentinel();
468
469 // If there aren't enough arguments for all the formal parameters,
470 // the sentinel, and the args after the sentinel, complain.
471 if (Args.size() < NumFormalParams + NumArgsAfterSentinel + 1) {
472 Diag(Loc, DiagID: diag::warn_not_enough_argument) << D->getDeclName();
473 Diag(Loc: D->getLocation(), DiagID: diag::note_sentinel_here) << int(CalleeKind);
474 return;
475 }
476
477 // Otherwise, find the sentinel expression.
478 const Expr *SentinelExpr = Args[Args.size() - NumArgsAfterSentinel - 1];
479 if (!SentinelExpr)
480 return;
481 if (SentinelExpr->isValueDependent())
482 return;
483 if (Context.isSentinelNullExpr(E: SentinelExpr))
484 return;
485
486 // Pick a reasonable string to insert. Optimistically use 'nil', 'nullptr',
487 // or 'NULL' if those are actually defined in the context. Only use
488 // 'nil' for ObjC methods, where it's much more likely that the
489 // variadic arguments form a list of object pointers.
490 SourceLocation MissingNilLoc = getLocForEndOfToken(Loc: SentinelExpr->getEndLoc());
491 std::string NullValue;
492 if (CalleeKind == CK_Method && PP.isMacroDefined(Id: "nil"))
493 NullValue = "nil";
494 else if (getLangOpts().CPlusPlus11)
495 NullValue = "nullptr";
496 else if (PP.isMacroDefined(Id: "NULL"))
497 NullValue = "NULL";
498 else
499 NullValue = "(void*) 0";
500
501 if (MissingNilLoc.isInvalid())
502 Diag(Loc, DiagID: diag::warn_missing_sentinel) << int(CalleeKind);
503 else
504 Diag(Loc: MissingNilLoc, DiagID: diag::warn_missing_sentinel)
505 << int(CalleeKind)
506 << FixItHint::CreateInsertion(InsertionLoc: MissingNilLoc, Code: ", " + NullValue);
507 Diag(Loc: D->getLocation(), DiagID: diag::note_sentinel_here)
508 << int(CalleeKind) << Attr->getRange();
509}
510
511SourceRange Sema::getExprRange(Expr *E) const {
512 return E ? E->getSourceRange() : SourceRange();
513}
514
515//===----------------------------------------------------------------------===//
516// Standard Promotions and Conversions
517//===----------------------------------------------------------------------===//
518
519/// DefaultFunctionArrayConversion (C99 6.3.2.1p3, C99 6.3.2.1p4).
520ExprResult Sema::DefaultFunctionArrayConversion(Expr *E, bool Diagnose) {
521 // Handle any placeholder expressions which made it here.
522 if (E->hasPlaceholderType()) {
523 ExprResult result = CheckPlaceholderExpr(E);
524 if (result.isInvalid()) return ExprError();
525 E = result.get();
526 }
527
528 QualType Ty = E->getType();
529 assert(!Ty.isNull() && "DefaultFunctionArrayConversion - missing type");
530
531 if (Ty->isFunctionType()) {
532 if (auto *DRE = dyn_cast<DeclRefExpr>(Val: E->IgnoreParenCasts()))
533 if (auto *FD = dyn_cast<FunctionDecl>(Val: DRE->getDecl()))
534 if (!checkAddressOfFunctionIsAvailable(Function: FD, Complain: Diagnose, Loc: E->getExprLoc()))
535 return ExprError();
536
537 E = ImpCastExprToType(E, Type: Context.getPointerType(T: Ty),
538 CK: CK_FunctionToPointerDecay).get();
539 } else if (Ty->isArrayType()) {
540 // In C90 mode, arrays only promote to pointers if the array expression is
541 // an lvalue. The relevant legalese is C90 6.2.2.1p3: "an lvalue that has
542 // type 'array of type' is converted to an expression that has type 'pointer
543 // to type'...". In C99 this was changed to: C99 6.3.2.1p3: "an expression
544 // that has type 'array of type' ...". The relevant change is "an lvalue"
545 // (C90) to "an expression" (C99).
546 //
547 // C++ 4.2p1:
548 // An lvalue or rvalue of type "array of N T" or "array of unknown bound of
549 // T" can be converted to an rvalue of type "pointer to T".
550 //
551 if (getLangOpts().C99 || getLangOpts().CPlusPlus || E->isLValue()) {
552 ExprResult Res = ImpCastExprToType(E, Type: Context.getArrayDecayedType(T: Ty),
553 CK: CK_ArrayToPointerDecay);
554 if (Res.isInvalid())
555 return ExprError();
556 E = Res.get();
557 }
558 }
559 return E;
560}
561
562static void CheckForNullPointerDereference(Sema &S, Expr *E) {
563 // Check to see if we are dereferencing a null pointer. If so,
564 // and if not volatile-qualified, this is undefined behavior that the
565 // optimizer will delete, so warn about it. People sometimes try to use this
566 // to get a deterministic trap and are surprised by clang's behavior. This
567 // only handles the pattern "*null", which is a very syntactic check.
568 const auto *UO = dyn_cast<UnaryOperator>(Val: E->IgnoreParenCasts());
569 if (UO && UO->getOpcode() == UO_Deref &&
570 UO->getSubExpr()->getType()->isPointerType()) {
571 const LangAS AS =
572 UO->getSubExpr()->getType()->getPointeeType().getAddressSpace();
573 if ((!isTargetAddressSpace(AS) ||
574 (isTargetAddressSpace(AS) && toTargetAddressSpace(AS) == 0)) &&
575 UO->getSubExpr()->IgnoreParenCasts()->isNullPointerConstant(
576 Ctx&: S.Context, NPC: Expr::NPC_ValueDependentIsNotNull) &&
577 !UO->getType().isVolatileQualified()) {
578 S.DiagRuntimeBehavior(Loc: UO->getOperatorLoc(), Statement: UO,
579 PD: S.PDiag(DiagID: diag::warn_indirection_through_null)
580 << UO->getSubExpr()->getSourceRange());
581 S.DiagRuntimeBehavior(Loc: UO->getOperatorLoc(), Statement: UO,
582 PD: S.PDiag(DiagID: diag::note_indirection_through_null));
583 }
584 }
585}
586
587static void DiagnoseDirectIsaAccess(Sema &S, const ObjCIvarRefExpr *OIRE,
588 SourceLocation AssignLoc,
589 const Expr* RHS) {
590 const ObjCIvarDecl *IV = OIRE->getDecl();
591 if (!IV)
592 return;
593
594 DeclarationName MemberName = IV->getDeclName();
595 IdentifierInfo *Member = MemberName.getAsIdentifierInfo();
596 if (!Member || !Member->isStr(Str: "isa"))
597 return;
598
599 const Expr *Base = OIRE->getBase();
600 QualType BaseType = Base->getType();
601 if (OIRE->isArrow())
602 BaseType = BaseType->getPointeeType();
603 if (const ObjCObjectType *OTy = BaseType->getAs<ObjCObjectType>())
604 if (ObjCInterfaceDecl *IDecl = OTy->getInterface()) {
605 ObjCInterfaceDecl *ClassDeclared = nullptr;
606 ObjCIvarDecl *IV = IDecl->lookupInstanceVariable(IVarName: Member, ClassDeclared);
607 if (!ClassDeclared->getSuperClass()
608 && (*ClassDeclared->ivar_begin()) == IV) {
609 if (RHS) {
610 NamedDecl *ObjectSetClass =
611 S.LookupSingleName(S: S.TUScope,
612 Name: &S.Context.Idents.get(Name: "object_setClass"),
613 Loc: SourceLocation(), NameKind: S.LookupOrdinaryName);
614 if (ObjectSetClass) {
615 SourceLocation RHSLocEnd = S.getLocForEndOfToken(Loc: RHS->getEndLoc());
616 S.Diag(Loc: OIRE->getExprLoc(), DiagID: diag::warn_objc_isa_assign)
617 << FixItHint::CreateInsertion(InsertionLoc: OIRE->getBeginLoc(),
618 Code: "object_setClass(")
619 << FixItHint::CreateReplacement(
620 RemoveRange: SourceRange(OIRE->getOpLoc(), AssignLoc), Code: ",")
621 << FixItHint::CreateInsertion(InsertionLoc: RHSLocEnd, Code: ")");
622 }
623 else
624 S.Diag(Loc: OIRE->getLocation(), DiagID: diag::warn_objc_isa_assign);
625 } else {
626 NamedDecl *ObjectGetClass =
627 S.LookupSingleName(S: S.TUScope,
628 Name: &S.Context.Idents.get(Name: "object_getClass"),
629 Loc: SourceLocation(), NameKind: S.LookupOrdinaryName);
630 if (ObjectGetClass)
631 S.Diag(Loc: OIRE->getExprLoc(), DiagID: diag::warn_objc_isa_use)
632 << FixItHint::CreateInsertion(InsertionLoc: OIRE->getBeginLoc(),
633 Code: "object_getClass(")
634 << FixItHint::CreateReplacement(
635 RemoveRange: SourceRange(OIRE->getOpLoc(), OIRE->getEndLoc()), Code: ")");
636 else
637 S.Diag(Loc: OIRE->getLocation(), DiagID: diag::warn_objc_isa_use);
638 }
639 S.Diag(Loc: IV->getLocation(), DiagID: diag::note_ivar_decl);
640 }
641 }
642}
643
644ExprResult Sema::DefaultLvalueConversion(Expr *E) {
645 // Handle any placeholder expressions which made it here.
646 if (E->hasPlaceholderType()) {
647 ExprResult result = CheckPlaceholderExpr(E);
648 if (result.isInvalid()) return ExprError();
649 E = result.get();
650 }
651
652 // C++ [conv.lval]p1:
653 // A glvalue of a non-function, non-array type T can be
654 // converted to a prvalue.
655 if (!E->isGLValue()) return E;
656
657 QualType T = E->getType();
658 assert(!T.isNull() && "r-value conversion on typeless expression?");
659
660 // lvalue-to-rvalue conversion cannot be applied to types that decay to
661 // pointers (i.e. function or array types).
662 if (T->canDecayToPointerType())
663 return E;
664
665 // We don't want to throw lvalue-to-rvalue casts on top of
666 // expressions of certain types in C++.
667 if (getLangOpts().CPlusPlus) {
668 if (T == Context.OverloadTy || T->isRecordType() ||
669 (T->isDependentType() && !T->isAnyPointerType() &&
670 !T->isMemberPointerType()))
671 return E;
672 }
673
674 // The C standard is actually really unclear on this point, and
675 // DR106 tells us what the result should be but not why. It's
676 // generally best to say that void types just doesn't undergo
677 // lvalue-to-rvalue at all. Note that expressions of unqualified
678 // 'void' type are never l-values, but qualified void can be.
679 if (T->isVoidType())
680 return E;
681
682 // OpenCL usually rejects direct accesses to values of 'half' type.
683 if (getLangOpts().OpenCL &&
684 !getOpenCLOptions().isAvailableOption(Ext: "cl_khr_fp16", LO: getLangOpts()) &&
685 T->isHalfType()) {
686 Diag(Loc: E->getExprLoc(), DiagID: diag::err_opencl_half_load_store)
687 << 0 << T;
688 return ExprError();
689 }
690
691 CheckForNullPointerDereference(S&: *this, E);
692 if (const ObjCIsaExpr *OISA = dyn_cast<ObjCIsaExpr>(Val: E->IgnoreParenCasts())) {
693 NamedDecl *ObjectGetClass = LookupSingleName(S: TUScope,
694 Name: &Context.Idents.get(Name: "object_getClass"),
695 Loc: SourceLocation(), NameKind: LookupOrdinaryName);
696 if (ObjectGetClass)
697 Diag(Loc: E->getExprLoc(), DiagID: diag::warn_objc_isa_use)
698 << FixItHint::CreateInsertion(InsertionLoc: OISA->getBeginLoc(), Code: "object_getClass(")
699 << FixItHint::CreateReplacement(
700 RemoveRange: SourceRange(OISA->getOpLoc(), OISA->getIsaMemberLoc()), Code: ")");
701 else
702 Diag(Loc: E->getExprLoc(), DiagID: diag::warn_objc_isa_use);
703 }
704 else if (const ObjCIvarRefExpr *OIRE =
705 dyn_cast<ObjCIvarRefExpr>(Val: E->IgnoreParenCasts()))
706 DiagnoseDirectIsaAccess(S&: *this, OIRE, AssignLoc: SourceLocation(), /* Expr*/RHS: nullptr);
707
708 // C++ [conv.lval]p1:
709 // [...] If T is a non-class type, the type of the prvalue is the
710 // cv-unqualified version of T. Otherwise, the type of the
711 // rvalue is T.
712 //
713 // C99 6.3.2.1p2:
714 // If the lvalue has qualified type, the value has the unqualified
715 // version of the type of the lvalue; otherwise, the value has the
716 // type of the lvalue.
717 if (T.hasQualifiers())
718 T = T.getUnqualifiedType();
719
720 // Under the MS ABI, lock down the inheritance model now.
721 if (T->isMemberPointerType() &&
722 Context.getTargetInfo().getCXXABI().isMicrosoft())
723 (void)isCompleteType(Loc: E->getExprLoc(), T);
724
725 ExprResult Res = CheckLValueToRValueConversionOperand(E);
726 if (Res.isInvalid())
727 return Res;
728 E = Res.get();
729
730 // Loading a __weak object implicitly retains the value, so we need a cleanup to
731 // balance that.
732 if (E->getType().getObjCLifetime() == Qualifiers::OCL_Weak)
733 Cleanup.setExprNeedsCleanups(true);
734
735 if (E->getType().isDestructedType() == QualType::DK_nontrivial_c_struct)
736 Cleanup.setExprNeedsCleanups(true);
737
738 if (!BoundsSafetyCheckUseOfCountAttrPtr(E: Res.get()))
739 return ExprError();
740
741 // C++ [conv.lval]p3:
742 // If T is cv std::nullptr_t, the result is a null pointer constant.
743 CastKind CK = T->isNullPtrType() ? CK_NullToPointer : CK_LValueToRValue;
744 Res = ImplicitCastExpr::Create(Context, T, Kind: CK, Operand: E, BasePath: nullptr, Cat: VK_PRValue,
745 FPO: CurFPFeatureOverrides());
746
747 // C11 6.3.2.1p2:
748 // ... if the lvalue has atomic type, the value has the non-atomic version
749 // of the type of the lvalue ...
750 if (const AtomicType *Atomic = T->getAs<AtomicType>()) {
751 T = Atomic->getValueType().getUnqualifiedType();
752 Res = ImplicitCastExpr::Create(Context, T, Kind: CK_AtomicToNonAtomic, Operand: Res.get(),
753 BasePath: nullptr, Cat: VK_PRValue, FPO: FPOptionsOverride());
754 }
755
756 return Res;
757}
758
759ExprResult Sema::DefaultFunctionArrayLvalueConversion(Expr *E, bool Diagnose) {
760 ExprResult Res = DefaultFunctionArrayConversion(E, Diagnose);
761 if (Res.isInvalid())
762 return ExprError();
763 Res = DefaultLvalueConversion(E: Res.get());
764 if (Res.isInvalid())
765 return ExprError();
766 return Res;
767}
768
769ExprResult Sema::CallExprUnaryConversions(Expr *E) {
770 QualType Ty = E->getType();
771 ExprResult Res = E;
772 // Only do implicit cast for a function type, but not for a pointer
773 // to function type.
774 if (Ty->isFunctionType()) {
775 Res = ImpCastExprToType(E, Type: Context.getPointerType(T: Ty),
776 CK: CK_FunctionToPointerDecay);
777 if (Res.isInvalid())
778 return ExprError();
779 }
780 Res = DefaultLvalueConversion(E: Res.get());
781 if (Res.isInvalid())
782 return ExprError();
783 return Res.get();
784}
785
786/// UsualUnaryFPConversions - Promotes floating-point types according to the
787/// current language semantics.
788ExprResult Sema::UsualUnaryFPConversions(Expr *E) {
789 QualType Ty = E->getType();
790 assert(!Ty.isNull() && "UsualUnaryFPConversions - missing type");
791
792 LangOptions::FPEvalMethodKind EvalMethod = CurFPFeatures.getFPEvalMethod();
793 if (EvalMethod != LangOptions::FEM_Source && Ty->isFloatingType() &&
794 (getLangOpts().getFPEvalMethod() !=
795 LangOptions::FPEvalMethodKind::FEM_UnsetOnCommandLine ||
796 PP.getLastFPEvalPragmaLocation().isValid())) {
797 switch (EvalMethod) {
798 default:
799 llvm_unreachable("Unrecognized float evaluation method");
800 break;
801 case LangOptions::FEM_UnsetOnCommandLine:
802 llvm_unreachable("Float evaluation method should be set by now");
803 break;
804 case LangOptions::FEM_Double:
805 if (Context.getFloatingTypeOrder(LHS: Context.DoubleTy, RHS: Ty) > 0)
806 // Widen the expression to double.
807 return Ty->isComplexType()
808 ? ImpCastExprToType(E,
809 Type: Context.getComplexType(T: Context.DoubleTy),
810 CK: CK_FloatingComplexCast)
811 : ImpCastExprToType(E, Type: Context.DoubleTy, CK: CK_FloatingCast);
812 break;
813 case LangOptions::FEM_Extended:
814 if (Context.getFloatingTypeOrder(LHS: Context.LongDoubleTy, RHS: Ty) > 0)
815 // Widen the expression to long double.
816 return Ty->isComplexType()
817 ? ImpCastExprToType(
818 E, Type: Context.getComplexType(T: Context.LongDoubleTy),
819 CK: CK_FloatingComplexCast)
820 : ImpCastExprToType(E, Type: Context.LongDoubleTy,
821 CK: CK_FloatingCast);
822 break;
823 }
824 }
825
826 // Half FP have to be promoted to float unless it is natively supported
827 if (Ty->isHalfType() && !getLangOpts().NativeHalfType)
828 return ImpCastExprToType(E, Type: Context.FloatTy, CK: CK_FloatingCast);
829
830 return E;
831}
832
833/// UsualUnaryConversions - Performs various conversions that are common to most
834/// operators (C99 6.3). The conversions of array and function types are
835/// sometimes suppressed. For example, the array->pointer conversion doesn't
836/// apply if the array is an argument to the sizeof or address (&) operators.
837/// In these instances, this routine should *not* be called.
838ExprResult Sema::UsualUnaryConversions(Expr *E) {
839 // First, convert to an r-value.
840 ExprResult Res = DefaultFunctionArrayLvalueConversion(E);
841 if (Res.isInvalid())
842 return ExprError();
843
844 // Promote floating-point types.
845 Res = UsualUnaryFPConversions(E: Res.get());
846 if (Res.isInvalid())
847 return ExprError();
848 E = Res.get();
849
850 QualType Ty = E->getType();
851 assert(!Ty.isNull() && "UsualUnaryConversions - missing type");
852
853 // Try to perform integral promotions if the object has a theoretically
854 // promotable type.
855 if (Ty->isIntegralOrUnscopedEnumerationType()) {
856 // C99 6.3.1.1p2:
857 //
858 // The following may be used in an expression wherever an int or
859 // unsigned int may be used:
860 // - an object or expression with an integer type whose integer
861 // conversion rank is less than or equal to the rank of int
862 // and unsigned int.
863 // - A bit-field of type _Bool, int, signed int, or unsigned int.
864 //
865 // If an int can represent all values of the original type, the
866 // value is converted to an int; otherwise, it is converted to an
867 // unsigned int. These are called the integer promotions. All
868 // other types are unchanged by the integer promotions.
869
870 QualType PTy = Context.isPromotableBitField(E);
871 if (!PTy.isNull()) {
872 E = ImpCastExprToType(E, Type: PTy, CK: CK_IntegralCast).get();
873 return E;
874 }
875 if (Context.isPromotableIntegerType(T: Ty)) {
876 QualType PT = Context.getPromotedIntegerType(PromotableType: Ty);
877 E = ImpCastExprToType(E, Type: PT, CK: CK_IntegralCast).get();
878 return E;
879 }
880 }
881 return E;
882}
883
884/// DefaultArgumentPromotion (C99 6.5.2.2p6). Used for function calls that
885/// do not have a prototype. Arguments that have type float or __fp16
886/// are promoted to double. All other argument types are converted by
887/// UsualUnaryConversions().
888ExprResult Sema::DefaultArgumentPromotion(Expr *E) {
889 QualType Ty = E->getType();
890 assert(!Ty.isNull() && "DefaultArgumentPromotion - missing type");
891
892 ExprResult Res = UsualUnaryConversions(E);
893 if (Res.isInvalid())
894 return ExprError();
895 E = Res.get();
896
897 // If this is a 'float' or '__fp16' (CVR qualified or typedef)
898 // promote to double.
899 // Note that default argument promotion applies only to float (and
900 // half/fp16); it does not apply to _Float16.
901 const BuiltinType *BTy = Ty->getAs<BuiltinType>();
902 if (BTy && (BTy->getKind() == BuiltinType::Half ||
903 BTy->getKind() == BuiltinType::Float)) {
904 if (getLangOpts().OpenCL &&
905 !getOpenCLOptions().isAvailableOption(Ext: "cl_khr_fp64", LO: getLangOpts())) {
906 if (BTy->getKind() == BuiltinType::Half) {
907 E = ImpCastExprToType(E, Type: Context.FloatTy, CK: CK_FloatingCast).get();
908 }
909 } else {
910 E = ImpCastExprToType(E, Type: Context.DoubleTy, CK: CK_FloatingCast).get();
911 }
912 }
913 if (BTy &&
914 getLangOpts().getExtendIntArgs() ==
915 LangOptions::ExtendArgsKind::ExtendTo64 &&
916 Context.getTargetInfo().supportsExtendIntArgs() && Ty->isIntegerType() &&
917 Context.getTypeSizeInChars(T: BTy) <
918 Context.getTypeSizeInChars(T: Context.LongLongTy)) {
919 E = (Ty->isUnsignedIntegerType())
920 ? ImpCastExprToType(E, Type: Context.UnsignedLongLongTy, CK: CK_IntegralCast)
921 .get()
922 : ImpCastExprToType(E, Type: Context.LongLongTy, CK: CK_IntegralCast).get();
923 assert(8 == Context.getTypeSizeInChars(Context.LongLongTy).getQuantity() &&
924 "Unexpected typesize for LongLongTy");
925 }
926
927 // C++ performs lvalue-to-rvalue conversion as a default argument
928 // promotion, even on class types, but note:
929 // C++11 [conv.lval]p2:
930 // When an lvalue-to-rvalue conversion occurs in an unevaluated
931 // operand or a subexpression thereof the value contained in the
932 // referenced object is not accessed. Otherwise, if the glvalue
933 // has a class type, the conversion copy-initializes a temporary
934 // of type T from the glvalue and the result of the conversion
935 // is a prvalue for the temporary.
936 // FIXME: add some way to gate this entire thing for correctness in
937 // potentially potentially evaluated contexts.
938 if (getLangOpts().CPlusPlus && E->isGLValue() && !isUnevaluatedContext()) {
939 ExprResult Temp = PerformCopyInitialization(
940 Entity: InitializedEntity::InitializeTemporary(Type: E->getType()),
941 EqualLoc: E->getExprLoc(), Init: E);
942 if (Temp.isInvalid())
943 return ExprError();
944 E = Temp.get();
945 }
946
947 // C++ [expr.call]p7, per CWG722:
948 // An argument that has (possibly cv-qualified) type std::nullptr_t is
949 // converted to void* ([conv.ptr]).
950 // (This does not apply to C23 nullptr)
951 if (getLangOpts().CPlusPlus && E->getType()->isNullPtrType())
952 E = ImpCastExprToType(E, Type: Context.VoidPtrTy, CK: CK_NullToPointer).get();
953
954 return E;
955}
956
957VarArgKind Sema::isValidVarArgType(const QualType &Ty) {
958 if (Ty->isIncompleteType()) {
959 // C++11 [expr.call]p7:
960 // After these conversions, if the argument does not have arithmetic,
961 // enumeration, pointer, pointer to member, or class type, the program
962 // is ill-formed.
963 //
964 // Since we've already performed null pointer conversion, array-to-pointer
965 // decay and function-to-pointer decay, the only such type in C++ is cv
966 // void. This also handles initializer lists as variadic arguments.
967 if (Ty->isVoidType())
968 return VarArgKind::Invalid;
969
970 if (Ty->isObjCObjectType())
971 return VarArgKind::Invalid;
972 return VarArgKind::Valid;
973 }
974
975 if (Ty.isDestructedType() == QualType::DK_nontrivial_c_struct)
976 return VarArgKind::Invalid;
977
978 if (Context.getTargetInfo().getTriple().isWasm() &&
979 Ty.isWebAssemblyReferenceType()) {
980 return VarArgKind::Invalid;
981 }
982
983 if (Ty.isCXX98PODType(Context))
984 return VarArgKind::Valid;
985
986 // C++11 [expr.call]p7:
987 // Passing a potentially-evaluated argument of class type (Clause 9)
988 // having a non-trivial copy constructor, a non-trivial move constructor,
989 // or a non-trivial destructor, with no corresponding parameter,
990 // is conditionally-supported with implementation-defined semantics.
991 if (getLangOpts().CPlusPlus11 && !Ty->isDependentType())
992 if (CXXRecordDecl *Record = Ty->getAsCXXRecordDecl())
993 if (!Record->hasNonTrivialCopyConstructor() &&
994 !Record->hasNonTrivialMoveConstructor() &&
995 !Record->hasNonTrivialDestructor())
996 return VarArgKind::ValidInCXX11;
997
998 if (getLangOpts().ObjCAutoRefCount && Ty->isObjCLifetimeType())
999 return VarArgKind::Valid;
1000
1001 if (Ty->isObjCObjectType())
1002 return VarArgKind::Invalid;
1003
1004 if (getLangOpts().HLSL && Ty->getAs<HLSLAttributedResourceType>())
1005 return VarArgKind::Valid;
1006
1007 if (getLangOpts().MSVCCompat)
1008 return VarArgKind::MSVCUndefined;
1009
1010 if (getLangOpts().HLSL && Ty->getAs<HLSLAttributedResourceType>())
1011 return VarArgKind::Valid;
1012
1013 // FIXME: In C++11, these cases are conditionally-supported, meaning we're
1014 // permitted to reject them. We should consider doing so.
1015 return VarArgKind::Undefined;
1016}
1017
1018void Sema::checkVariadicArgument(const Expr *E, VariadicCallType CT) {
1019 // Don't allow one to pass an Objective-C interface to a vararg.
1020 const QualType &Ty = E->getType();
1021 VarArgKind VAK = isValidVarArgType(Ty);
1022
1023 // Complain about passing non-POD types through varargs.
1024 switch (VAK) {
1025 case VarArgKind::ValidInCXX11:
1026 DiagRuntimeBehavior(
1027 Loc: E->getBeginLoc(), Statement: nullptr,
1028 PD: PDiag(DiagID: diag::warn_cxx98_compat_pass_non_pod_arg_to_vararg) << Ty << CT);
1029 [[fallthrough]];
1030 case VarArgKind::Valid:
1031 if (Ty->isRecordType()) {
1032 // This is unlikely to be what the user intended. If the class has a
1033 // 'c_str' member function, the user probably meant to call that.
1034 DiagRuntimeBehavior(Loc: E->getBeginLoc(), Statement: nullptr,
1035 PD: PDiag(DiagID: diag::warn_pass_class_arg_to_vararg)
1036 << Ty << CT << hasCStrMethod(E) << ".c_str()");
1037 }
1038 break;
1039
1040 case VarArgKind::Undefined:
1041 case VarArgKind::MSVCUndefined:
1042 DiagRuntimeBehavior(Loc: E->getBeginLoc(), Statement: nullptr,
1043 PD: PDiag(DiagID: diag::warn_cannot_pass_non_pod_arg_to_vararg)
1044 << getLangOpts().CPlusPlus11 << Ty << CT);
1045 break;
1046
1047 case VarArgKind::Invalid:
1048 if (Ty.isDestructedType() == QualType::DK_nontrivial_c_struct)
1049 Diag(Loc: E->getBeginLoc(),
1050 DiagID: diag::err_cannot_pass_non_trivial_c_struct_to_vararg)
1051 << Ty << CT;
1052 else if (Ty->isObjCObjectType())
1053 DiagRuntimeBehavior(Loc: E->getBeginLoc(), Statement: nullptr,
1054 PD: PDiag(DiagID: diag::err_cannot_pass_objc_interface_to_vararg)
1055 << Ty << CT);
1056 else
1057 Diag(Loc: E->getBeginLoc(), DiagID: diag::err_cannot_pass_to_vararg)
1058 << isa<InitListExpr>(Val: E) << Ty << CT;
1059 break;
1060 }
1061}
1062
1063ExprResult Sema::DefaultVariadicArgumentPromotion(Expr *E, VariadicCallType CT,
1064 FunctionDecl *FDecl) {
1065 if (const BuiltinType *PlaceholderTy = E->getType()->getAsPlaceholderType()) {
1066 // Strip the unbridged-cast placeholder expression off, if applicable.
1067 if (PlaceholderTy->getKind() == BuiltinType::ARCUnbridgedCast &&
1068 (CT == VariadicCallType::Method ||
1069 (FDecl && FDecl->hasAttr<CFAuditedTransferAttr>()))) {
1070 E = ObjC().stripARCUnbridgedCast(e: E);
1071
1072 // Otherwise, do normal placeholder checking.
1073 } else {
1074 ExprResult ExprRes = CheckPlaceholderExpr(E);
1075 if (ExprRes.isInvalid())
1076 return ExprError();
1077 E = ExprRes.get();
1078 }
1079 }
1080
1081 ExprResult ExprRes = DefaultArgumentPromotion(E);
1082 if (ExprRes.isInvalid())
1083 return ExprError();
1084
1085 // Copy blocks to the heap.
1086 if (ExprRes.get()->getType()->isBlockPointerType())
1087 maybeExtendBlockObject(E&: ExprRes);
1088
1089 E = ExprRes.get();
1090
1091 // Diagnostics regarding non-POD argument types are
1092 // emitted along with format string checking in Sema::CheckFunctionCall().
1093 if (isValidVarArgType(Ty: E->getType()) == VarArgKind::Undefined) {
1094 // Turn this into a trap.
1095 CXXScopeSpec SS;
1096 SourceLocation TemplateKWLoc;
1097 UnqualifiedId Name;
1098 Name.setIdentifier(Id: PP.getIdentifierInfo(Name: "__builtin_trap"),
1099 IdLoc: E->getBeginLoc());
1100 ExprResult TrapFn = ActOnIdExpression(S: TUScope, SS, TemplateKWLoc, Id&: Name,
1101 /*HasTrailingLParen=*/true,
1102 /*IsAddressOfOperand=*/false);
1103 if (TrapFn.isInvalid())
1104 return ExprError();
1105
1106 ExprResult Call = BuildCallExpr(S: TUScope, Fn: TrapFn.get(), LParenLoc: E->getBeginLoc(), ArgExprs: {},
1107 RParenLoc: E->getEndLoc());
1108 if (Call.isInvalid())
1109 return ExprError();
1110
1111 ExprResult Comma =
1112 ActOnBinOp(S: TUScope, TokLoc: E->getBeginLoc(), Kind: tok::comma, LHSExpr: Call.get(), RHSExpr: E);
1113 if (Comma.isInvalid())
1114 return ExprError();
1115 return Comma.get();
1116 }
1117
1118 if (!getLangOpts().CPlusPlus &&
1119 RequireCompleteType(Loc: E->getExprLoc(), T: E->getType(),
1120 DiagID: diag::err_call_incomplete_argument))
1121 return ExprError();
1122
1123 return E;
1124}
1125
1126/// Convert complex integers to complex floats and real integers to
1127/// real floats as required for complex arithmetic. Helper function of
1128/// UsualArithmeticConversions()
1129///
1130/// \return false if the integer expression is an integer type and is
1131/// successfully converted to the (complex) float type.
1132static bool handleComplexIntegerToFloatConversion(Sema &S, ExprResult &IntExpr,
1133 ExprResult &ComplexExpr,
1134 QualType IntTy,
1135 QualType ComplexTy,
1136 bool SkipCast) {
1137 if (IntTy->isComplexType() || IntTy->isRealFloatingType()) return true;
1138 if (SkipCast) return false;
1139 if (IntTy->isIntegerType()) {
1140 QualType fpTy = ComplexTy->castAs<ComplexType>()->getElementType();
1141 IntExpr = S.ImpCastExprToType(E: IntExpr.get(), Type: fpTy, CK: CK_IntegralToFloating);
1142 } else {
1143 assert(IntTy->isComplexIntegerType());
1144 IntExpr = S.ImpCastExprToType(E: IntExpr.get(), Type: ComplexTy,
1145 CK: CK_IntegralComplexToFloatingComplex);
1146 }
1147 return false;
1148}
1149
1150// This handles complex/complex, complex/float, or float/complex.
1151// When both operands are complex, the shorter operand is converted to the
1152// type of the longer, and that is the type of the result. This corresponds
1153// to what is done when combining two real floating-point operands.
1154// The fun begins when size promotion occur across type domains.
1155// From H&S 6.3.4: When one operand is complex and the other is a real
1156// floating-point type, the less precise type is converted, within it's
1157// real or complex domain, to the precision of the other type. For example,
1158// when combining a "long double" with a "double _Complex", the
1159// "double _Complex" is promoted to "long double _Complex".
1160static QualType handleComplexFloatConversion(Sema &S, ExprResult &Shorter,
1161 QualType ShorterType,
1162 QualType LongerType,
1163 bool PromotePrecision) {
1164 bool LongerIsComplex = isa<ComplexType>(Val: LongerType.getCanonicalType());
1165 QualType Result =
1166 LongerIsComplex ? LongerType : S.Context.getComplexType(T: LongerType);
1167
1168 if (PromotePrecision) {
1169 if (isa<ComplexType>(Val: ShorterType.getCanonicalType())) {
1170 Shorter =
1171 S.ImpCastExprToType(E: Shorter.get(), Type: Result, CK: CK_FloatingComplexCast);
1172 } else {
1173 if (LongerIsComplex)
1174 LongerType = LongerType->castAs<ComplexType>()->getElementType();
1175 Shorter = S.ImpCastExprToType(E: Shorter.get(), Type: LongerType, CK: CK_FloatingCast);
1176 }
1177 }
1178 return Result;
1179}
1180
1181/// Handle arithmetic conversion with complex types. Helper function of
1182/// UsualArithmeticConversions()
1183static QualType handleComplexConversion(Sema &S, ExprResult &LHS,
1184 ExprResult &RHS, QualType LHSType,
1185 QualType RHSType, bool IsCompAssign) {
1186 // Handle (complex) integer types.
1187 if (!handleComplexIntegerToFloatConversion(S, IntExpr&: RHS, ComplexExpr&: LHS, IntTy: RHSType, ComplexTy: LHSType,
1188 /*SkipCast=*/false))
1189 return LHSType;
1190 if (!handleComplexIntegerToFloatConversion(S, IntExpr&: LHS, ComplexExpr&: RHS, IntTy: LHSType, ComplexTy: RHSType,
1191 /*SkipCast=*/IsCompAssign))
1192 return RHSType;
1193
1194 // Compute the rank of the two types, regardless of whether they are complex.
1195 int Order = S.Context.getFloatingTypeOrder(LHS: LHSType, RHS: RHSType);
1196 if (Order < 0)
1197 // Promote the precision of the LHS if not an assignment.
1198 return handleComplexFloatConversion(S, Shorter&: LHS, ShorterType: LHSType, LongerType: RHSType,
1199 /*PromotePrecision=*/!IsCompAssign);
1200 // Promote the precision of the RHS unless it is already the same as the LHS.
1201 return handleComplexFloatConversion(S, Shorter&: RHS, ShorterType: RHSType, LongerType: LHSType,
1202 /*PromotePrecision=*/Order > 0);
1203}
1204
1205/// Handle arithmetic conversion from integer to float. Helper function
1206/// of UsualArithmeticConversions()
1207static QualType handleIntToFloatConversion(Sema &S, ExprResult &FloatExpr,
1208 ExprResult &IntExpr,
1209 QualType FloatTy, QualType IntTy,
1210 bool ConvertFloat, bool ConvertInt) {
1211 if (IntTy->isIntegerType()) {
1212 if (ConvertInt)
1213 // Convert intExpr to the lhs floating point type.
1214 IntExpr = S.ImpCastExprToType(E: IntExpr.get(), Type: FloatTy,
1215 CK: CK_IntegralToFloating);
1216 return FloatTy;
1217 }
1218
1219 // Convert both sides to the appropriate complex float.
1220 assert(IntTy->isComplexIntegerType());
1221 QualType result = S.Context.getComplexType(T: FloatTy);
1222
1223 // _Complex int -> _Complex float
1224 if (ConvertInt)
1225 IntExpr = S.ImpCastExprToType(E: IntExpr.get(), Type: result,
1226 CK: CK_IntegralComplexToFloatingComplex);
1227
1228 // float -> _Complex float
1229 if (ConvertFloat)
1230 FloatExpr = S.ImpCastExprToType(E: FloatExpr.get(), Type: result,
1231 CK: CK_FloatingRealToComplex);
1232
1233 return result;
1234}
1235
1236/// Handle arithmethic conversion with floating point types. Helper
1237/// function of UsualArithmeticConversions()
1238static QualType handleFloatConversion(Sema &S, ExprResult &LHS,
1239 ExprResult &RHS, QualType LHSType,
1240 QualType RHSType, bool IsCompAssign) {
1241 bool LHSFloat = LHSType->isRealFloatingType();
1242 bool RHSFloat = RHSType->isRealFloatingType();
1243
1244 // N1169 4.1.4: If one of the operands has a floating type and the other
1245 // operand has a fixed-point type, the fixed-point operand
1246 // is converted to the floating type [...]
1247 if (LHSType->isFixedPointType() || RHSType->isFixedPointType()) {
1248 if (LHSFloat)
1249 RHS = S.ImpCastExprToType(E: RHS.get(), Type: LHSType, CK: CK_FixedPointToFloating);
1250 else if (!IsCompAssign)
1251 LHS = S.ImpCastExprToType(E: LHS.get(), Type: RHSType, CK: CK_FixedPointToFloating);
1252 return LHSFloat ? LHSType : RHSType;
1253 }
1254
1255 // If we have two real floating types, convert the smaller operand
1256 // to the bigger result.
1257 if (LHSFloat && RHSFloat) {
1258 int order = S.Context.getFloatingTypeOrder(LHS: LHSType, RHS: RHSType);
1259 if (order > 0) {
1260 RHS = S.ImpCastExprToType(E: RHS.get(), Type: LHSType, CK: CK_FloatingCast);
1261 return LHSType;
1262 }
1263
1264 assert(order < 0 && "illegal float comparison");
1265 if (!IsCompAssign)
1266 LHS = S.ImpCastExprToType(E: LHS.get(), Type: RHSType, CK: CK_FloatingCast);
1267 return RHSType;
1268 }
1269
1270 if (LHSFloat) {
1271 // Half FP has to be promoted to float unless it is natively supported
1272 if (LHSType->isHalfType() && !S.getLangOpts().NativeHalfType)
1273 LHSType = S.Context.FloatTy;
1274
1275 return handleIntToFloatConversion(S, FloatExpr&: LHS, IntExpr&: RHS, FloatTy: LHSType, IntTy: RHSType,
1276 /*ConvertFloat=*/!IsCompAssign,
1277 /*ConvertInt=*/ true);
1278 }
1279 assert(RHSFloat);
1280 return handleIntToFloatConversion(S, FloatExpr&: RHS, IntExpr&: LHS, FloatTy: RHSType, IntTy: LHSType,
1281 /*ConvertFloat=*/ true,
1282 /*ConvertInt=*/!IsCompAssign);
1283}
1284
1285/// Diagnose attempts to convert between __float128, __ibm128 and
1286/// long double if there is no support for such conversion.
1287/// Helper function of UsualArithmeticConversions().
1288static bool unsupportedTypeConversion(const Sema &S, QualType LHSType,
1289 QualType RHSType) {
1290 // No issue if either is not a floating point type.
1291 if (!LHSType->isFloatingType() || !RHSType->isFloatingType())
1292 return false;
1293
1294 // No issue if both have the same 128-bit float semantics.
1295 auto *LHSComplex = LHSType->getAs<ComplexType>();
1296 auto *RHSComplex = RHSType->getAs<ComplexType>();
1297
1298 QualType LHSElem = LHSComplex ? LHSComplex->getElementType() : LHSType;
1299 QualType RHSElem = RHSComplex ? RHSComplex->getElementType() : RHSType;
1300
1301 const llvm::fltSemantics &LHSSem = S.Context.getFloatTypeSemantics(T: LHSElem);
1302 const llvm::fltSemantics &RHSSem = S.Context.getFloatTypeSemantics(T: RHSElem);
1303
1304 if ((&LHSSem != &llvm::APFloat::PPCDoubleDouble() ||
1305 &RHSSem != &llvm::APFloat::IEEEquad()) &&
1306 (&LHSSem != &llvm::APFloat::IEEEquad() ||
1307 &RHSSem != &llvm::APFloat::PPCDoubleDouble()))
1308 return false;
1309
1310 return true;
1311}
1312
1313typedef ExprResult PerformCastFn(Sema &S, Expr *operand, QualType toType);
1314
1315namespace {
1316/// These helper callbacks are placed in an anonymous namespace to
1317/// permit their use as function template parameters.
1318ExprResult doIntegralCast(Sema &S, Expr *op, QualType toType) {
1319 return S.ImpCastExprToType(E: op, Type: toType, CK: CK_IntegralCast);
1320}
1321
1322ExprResult doComplexIntegralCast(Sema &S, Expr *op, QualType toType) {
1323 return S.ImpCastExprToType(E: op, Type: S.Context.getComplexType(T: toType),
1324 CK: CK_IntegralComplexCast);
1325}
1326}
1327
1328/// Handle integer arithmetic conversions. Helper function of
1329/// UsualArithmeticConversions()
1330template <PerformCastFn doLHSCast, PerformCastFn doRHSCast>
1331static QualType handleIntegerConversion(Sema &S, ExprResult &LHS,
1332 ExprResult &RHS, QualType LHSType,
1333 QualType RHSType, bool IsCompAssign) {
1334 // The rules for this case are in C99 6.3.1.8
1335 int order = S.Context.getIntegerTypeOrder(LHS: LHSType, RHS: RHSType);
1336 bool LHSSigned = LHSType->hasSignedIntegerRepresentation();
1337 bool RHSSigned = RHSType->hasSignedIntegerRepresentation();
1338 if (LHSSigned == RHSSigned) {
1339 // Same signedness; use the higher-ranked type
1340 if (order >= 0) {
1341 RHS = (*doRHSCast)(S, RHS.get(), LHSType);
1342 return LHSType;
1343 } else if (!IsCompAssign)
1344 LHS = (*doLHSCast)(S, LHS.get(), RHSType);
1345 return RHSType;
1346 } else if (order != (LHSSigned ? 1 : -1)) {
1347 // The unsigned type has greater than or equal rank to the
1348 // signed type, so use the unsigned type
1349 if (RHSSigned) {
1350 RHS = (*doRHSCast)(S, RHS.get(), LHSType);
1351 return LHSType;
1352 } else if (!IsCompAssign)
1353 LHS = (*doLHSCast)(S, LHS.get(), RHSType);
1354 return RHSType;
1355 } else if (S.Context.getIntWidth(T: LHSType) != S.Context.getIntWidth(T: RHSType)) {
1356 // The two types are different widths; if we are here, that
1357 // means the signed type is larger than the unsigned type, so
1358 // use the signed type.
1359 if (LHSSigned) {
1360 RHS = (*doRHSCast)(S, RHS.get(), LHSType);
1361 return LHSType;
1362 } else if (!IsCompAssign)
1363 LHS = (*doLHSCast)(S, LHS.get(), RHSType);
1364 return RHSType;
1365 } else {
1366 // The signed type is higher-ranked than the unsigned type,
1367 // but isn't actually any bigger (like unsigned int and long
1368 // on most 32-bit systems). Use the unsigned type corresponding
1369 // to the signed type.
1370 QualType result =
1371 S.Context.getCorrespondingUnsignedType(T: LHSSigned ? LHSType : RHSType);
1372 RHS = (*doRHSCast)(S, RHS.get(), result);
1373 if (!IsCompAssign)
1374 LHS = (*doLHSCast)(S, LHS.get(), result);
1375 return result;
1376 }
1377}
1378
1379/// Handle conversions with GCC complex int extension. Helper function
1380/// of UsualArithmeticConversions()
1381static QualType handleComplexIntConversion(Sema &S, ExprResult &LHS,
1382 ExprResult &RHS, QualType LHSType,
1383 QualType RHSType,
1384 bool IsCompAssign) {
1385 const ComplexType *LHSComplexInt = LHSType->getAsComplexIntegerType();
1386 const ComplexType *RHSComplexInt = RHSType->getAsComplexIntegerType();
1387
1388 if (LHSComplexInt && RHSComplexInt) {
1389 QualType LHSEltType = LHSComplexInt->getElementType();
1390 QualType RHSEltType = RHSComplexInt->getElementType();
1391 QualType ScalarType =
1392 handleIntegerConversion<doComplexIntegralCast, doComplexIntegralCast>
1393 (S, LHS, RHS, LHSType: LHSEltType, RHSType: RHSEltType, IsCompAssign);
1394
1395 return S.Context.getComplexType(T: ScalarType);
1396 }
1397
1398 if (LHSComplexInt) {
1399 QualType LHSEltType = LHSComplexInt->getElementType();
1400 QualType ScalarType =
1401 handleIntegerConversion<doComplexIntegralCast, doIntegralCast>
1402 (S, LHS, RHS, LHSType: LHSEltType, RHSType, IsCompAssign);
1403 QualType ComplexType = S.Context.getComplexType(T: ScalarType);
1404 RHS = S.ImpCastExprToType(E: RHS.get(), Type: ComplexType,
1405 CK: CK_IntegralRealToComplex);
1406
1407 return ComplexType;
1408 }
1409
1410 assert(RHSComplexInt);
1411
1412 QualType RHSEltType = RHSComplexInt->getElementType();
1413 QualType ScalarType =
1414 handleIntegerConversion<doIntegralCast, doComplexIntegralCast>
1415 (S, LHS, RHS, LHSType, RHSType: RHSEltType, IsCompAssign);
1416 QualType ComplexType = S.Context.getComplexType(T: ScalarType);
1417
1418 if (!IsCompAssign)
1419 LHS = S.ImpCastExprToType(E: LHS.get(), Type: ComplexType,
1420 CK: CK_IntegralRealToComplex);
1421 return ComplexType;
1422}
1423
1424static QualType handleOverflowBehaviorTypeConversion(Sema &S, ExprResult &LHS,
1425 ExprResult &RHS,
1426 QualType LHSType,
1427 QualType RHSType,
1428 bool IsCompAssign) {
1429
1430 const auto *LhsOBT = LHSType->getAs<OverflowBehaviorType>();
1431 const auto *RhsOBT = RHSType->getAs<OverflowBehaviorType>();
1432
1433 assert(LHSType->isIntegerType() && RHSType->isIntegerType() &&
1434 "Non-integer type conversion not supported for OverflowBehaviorTypes");
1435
1436 bool LHSHasTrap =
1437 LhsOBT && LhsOBT->getBehaviorKind() ==
1438 OverflowBehaviorType::OverflowBehaviorKind::Trap;
1439 bool RHSHasTrap =
1440 RhsOBT && RhsOBT->getBehaviorKind() ==
1441 OverflowBehaviorType::OverflowBehaviorKind::Trap;
1442 bool LHSHasWrap =
1443 LhsOBT && LhsOBT->getBehaviorKind() ==
1444 OverflowBehaviorType::OverflowBehaviorKind::Wrap;
1445 bool RHSHasWrap =
1446 RhsOBT && RhsOBT->getBehaviorKind() ==
1447 OverflowBehaviorType::OverflowBehaviorKind::Wrap;
1448
1449 QualType LHSUnderlyingType = LhsOBT ? LhsOBT->getUnderlyingType() : LHSType;
1450 QualType RHSUnderlyingType = RhsOBT ? RhsOBT->getUnderlyingType() : RHSType;
1451
1452 std::optional<OverflowBehaviorType::OverflowBehaviorKind> DominantBehavior;
1453 if (LHSHasTrap || RHSHasTrap)
1454 DominantBehavior = OverflowBehaviorType::OverflowBehaviorKind::Trap;
1455 else if (LHSHasWrap || RHSHasWrap)
1456 DominantBehavior = OverflowBehaviorType::OverflowBehaviorKind::Wrap;
1457
1458 QualType LHSConvType = LHSUnderlyingType;
1459 QualType RHSConvType = RHSUnderlyingType;
1460 if (DominantBehavior) {
1461 if (!LhsOBT || LhsOBT->getBehaviorKind() != *DominantBehavior)
1462 LHSConvType = S.Context.getOverflowBehaviorType(Kind: *DominantBehavior,
1463 Wrapped: LHSUnderlyingType);
1464 else
1465 LHSConvType = LHSType;
1466
1467 if (!RhsOBT || RhsOBT->getBehaviorKind() != *DominantBehavior)
1468 RHSConvType = S.Context.getOverflowBehaviorType(Kind: *DominantBehavior,
1469 Wrapped: RHSUnderlyingType);
1470 else
1471 RHSConvType = RHSType;
1472 }
1473
1474 return handleIntegerConversion<doIntegralCast, doIntegralCast>(
1475 S, LHS, RHS, LHSType: LHSConvType, RHSType: RHSConvType, IsCompAssign);
1476}
1477
1478/// Return the rank of a given fixed point or integer type. The value itself
1479/// doesn't matter, but the values must be increasing with proper increasing
1480/// rank as described in N1169 4.1.1.
1481static unsigned GetFixedPointRank(QualType Ty) {
1482 const auto *BTy = Ty->getAs<BuiltinType>();
1483 assert(BTy && "Expected a builtin type.");
1484
1485 switch (BTy->getKind()) {
1486 case BuiltinType::ShortFract:
1487 case BuiltinType::UShortFract:
1488 case BuiltinType::SatShortFract:
1489 case BuiltinType::SatUShortFract:
1490 return 1;
1491 case BuiltinType::Fract:
1492 case BuiltinType::UFract:
1493 case BuiltinType::SatFract:
1494 case BuiltinType::SatUFract:
1495 return 2;
1496 case BuiltinType::LongFract:
1497 case BuiltinType::ULongFract:
1498 case BuiltinType::SatLongFract:
1499 case BuiltinType::SatULongFract:
1500 return 3;
1501 case BuiltinType::ShortAccum:
1502 case BuiltinType::UShortAccum:
1503 case BuiltinType::SatShortAccum:
1504 case BuiltinType::SatUShortAccum:
1505 return 4;
1506 case BuiltinType::Accum:
1507 case BuiltinType::UAccum:
1508 case BuiltinType::SatAccum:
1509 case BuiltinType::SatUAccum:
1510 return 5;
1511 case BuiltinType::LongAccum:
1512 case BuiltinType::ULongAccum:
1513 case BuiltinType::SatLongAccum:
1514 case BuiltinType::SatULongAccum:
1515 return 6;
1516 default:
1517 if (BTy->isInteger())
1518 return 0;
1519 llvm_unreachable("Unexpected fixed point or integer type");
1520 }
1521}
1522
1523/// handleFixedPointConversion - Fixed point operations between fixed
1524/// point types and integers or other fixed point types do not fall under
1525/// usual arithmetic conversion since these conversions could result in loss
1526/// of precsision (N1169 4.1.4). These operations should be calculated with
1527/// the full precision of their result type (N1169 4.1.6.2.1).
1528static QualType handleFixedPointConversion(Sema &S, QualType LHSTy,
1529 QualType RHSTy) {
1530 assert((LHSTy->isFixedPointType() || RHSTy->isFixedPointType()) &&
1531 "Expected at least one of the operands to be a fixed point type");
1532 assert((LHSTy->isFixedPointOrIntegerType() ||
1533 RHSTy->isFixedPointOrIntegerType()) &&
1534 "Special fixed point arithmetic operation conversions are only "
1535 "applied to ints or other fixed point types");
1536
1537 // If one operand has signed fixed-point type and the other operand has
1538 // unsigned fixed-point type, then the unsigned fixed-point operand is
1539 // converted to its corresponding signed fixed-point type and the resulting
1540 // type is the type of the converted operand.
1541 if (RHSTy->isSignedFixedPointType() && LHSTy->isUnsignedFixedPointType())
1542 LHSTy = S.Context.getCorrespondingSignedFixedPointType(Ty: LHSTy);
1543 else if (RHSTy->isUnsignedFixedPointType() && LHSTy->isSignedFixedPointType())
1544 RHSTy = S.Context.getCorrespondingSignedFixedPointType(Ty: RHSTy);
1545
1546 // The result type is the type with the highest rank, whereby a fixed-point
1547 // conversion rank is always greater than an integer conversion rank; if the
1548 // type of either of the operands is a saturating fixedpoint type, the result
1549 // type shall be the saturating fixed-point type corresponding to the type
1550 // with the highest rank; the resulting value is converted (taking into
1551 // account rounding and overflow) to the precision of the resulting type.
1552 // Same ranks between signed and unsigned types are resolved earlier, so both
1553 // types are either signed or both unsigned at this point.
1554 unsigned LHSTyRank = GetFixedPointRank(Ty: LHSTy);
1555 unsigned RHSTyRank = GetFixedPointRank(Ty: RHSTy);
1556
1557 QualType ResultTy = LHSTyRank > RHSTyRank ? LHSTy : RHSTy;
1558
1559 if (LHSTy->isSaturatedFixedPointType() || RHSTy->isSaturatedFixedPointType())
1560 ResultTy = S.Context.getCorrespondingSaturatedType(Ty: ResultTy);
1561
1562 return ResultTy;
1563}
1564
1565/// Check that the usual arithmetic conversions can be performed on this pair of
1566/// expressions that might be of enumeration type.
1567void Sema::checkEnumArithmeticConversions(Expr *LHS, Expr *RHS,
1568 SourceLocation Loc,
1569 ArithConvKind ACK) {
1570 // C++2a [expr.arith.conv]p1:
1571 // If one operand is of enumeration type and the other operand is of a
1572 // different enumeration type or a floating-point type, this behavior is
1573 // deprecated ([depr.arith.conv.enum]).
1574 //
1575 // Warn on this in all language modes. Produce a deprecation warning in C++20.
1576 // Eventually we will presumably reject these cases (in C++23 onwards?).
1577 QualType L = LHS->getEnumCoercedType(Ctx: Context),
1578 R = RHS->getEnumCoercedType(Ctx: Context);
1579 bool LEnum = L->isUnscopedEnumerationType(),
1580 REnum = R->isUnscopedEnumerationType();
1581 bool IsCompAssign = ACK == ArithConvKind::CompAssign;
1582 if ((!IsCompAssign && LEnum && R->isFloatingType()) ||
1583 (REnum && L->isFloatingType())) {
1584 Diag(Loc, DiagID: getLangOpts().CPlusPlus26 ? diag::err_arith_conv_enum_float_cxx26
1585 : getLangOpts().CPlusPlus20
1586 ? diag::warn_arith_conv_enum_float_cxx20
1587 : diag::warn_arith_conv_enum_float)
1588 << LHS->getSourceRange() << RHS->getSourceRange() << (int)ACK << LEnum
1589 << L << R;
1590 } else if (!IsCompAssign && LEnum && REnum &&
1591 !Context.hasSameUnqualifiedType(T1: L, T2: R)) {
1592 unsigned DiagID;
1593 // In C++ 26, usual arithmetic conversions between 2 different enum types
1594 // are ill-formed.
1595 if (getLangOpts().CPlusPlus26)
1596 DiagID = diag::warn_conv_mixed_enum_types_cxx26;
1597 else if (!L->castAsCanonical<EnumType>()->getDecl()->hasNameForLinkage() ||
1598 !R->castAsCanonical<EnumType>()->getDecl()->hasNameForLinkage()) {
1599 // If either enumeration type is unnamed, it's less likely that the
1600 // user cares about this, but this situation is still deprecated in
1601 // C++2a. Use a different warning group.
1602 DiagID = getLangOpts().CPlusPlus20
1603 ? diag::warn_arith_conv_mixed_anon_enum_types_cxx20
1604 : diag::warn_arith_conv_mixed_anon_enum_types;
1605 } else if (ACK == ArithConvKind::Conditional) {
1606 // Conditional expressions are separated out because they have
1607 // historically had a different warning flag.
1608 DiagID = getLangOpts().CPlusPlus20
1609 ? diag::warn_conditional_mixed_enum_types_cxx20
1610 : diag::warn_conditional_mixed_enum_types;
1611 } else if (ACK == ArithConvKind::Comparison) {
1612 // Comparison expressions are separated out because they have
1613 // historically had a different warning flag.
1614 DiagID = getLangOpts().CPlusPlus20
1615 ? diag::warn_comparison_mixed_enum_types_cxx20
1616 : diag::warn_comparison_mixed_enum_types;
1617 } else {
1618 DiagID = getLangOpts().CPlusPlus20
1619 ? diag::warn_arith_conv_mixed_enum_types_cxx20
1620 : diag::warn_arith_conv_mixed_enum_types;
1621 }
1622 Diag(Loc, DiagID) << LHS->getSourceRange() << RHS->getSourceRange()
1623 << (int)ACK << L << R;
1624 }
1625}
1626
1627static void CheckUnicodeArithmeticConversions(Sema &SemaRef, Expr *LHS,
1628 Expr *RHS, SourceLocation Loc,
1629 ArithConvKind ACK) {
1630 QualType LHSType = LHS->getType().getUnqualifiedType();
1631 QualType RHSType = RHS->getType().getUnqualifiedType();
1632
1633 if (!SemaRef.getLangOpts().CPlusPlus || !LHSType->isUnicodeCharacterType() ||
1634 !RHSType->isUnicodeCharacterType())
1635 return;
1636
1637 if (ACK == ArithConvKind::Comparison) {
1638 if (SemaRef.getASTContext().hasSameType(T1: LHSType, T2: RHSType))
1639 return;
1640
1641 auto IsSingleCodeUnitCP = [](const QualType &T, const llvm::APSInt &Value) {
1642 if (T->isChar8Type())
1643 return llvm::IsSingleCodeUnitUTF8Codepoint(Value.getExtValue());
1644 if (T->isChar16Type())
1645 return llvm::IsSingleCodeUnitUTF16Codepoint(Value.getExtValue());
1646 assert(T->isChar32Type());
1647 return llvm::IsSingleCodeUnitUTF32Codepoint(Value.getExtValue());
1648 };
1649
1650 Expr::EvalResult LHSRes, RHSRes;
1651 bool LHSSuccess = LHS->EvaluateAsInt(Result&: LHSRes, Ctx: SemaRef.getASTContext(),
1652 AllowSideEffects: Expr::SE_AllowSideEffects,
1653 InConstantContext: SemaRef.isConstantEvaluatedContext());
1654 bool RHSuccess = RHS->EvaluateAsInt(Result&: RHSRes, Ctx: SemaRef.getASTContext(),
1655 AllowSideEffects: Expr::SE_AllowSideEffects,
1656 InConstantContext: SemaRef.isConstantEvaluatedContext());
1657
1658 // Don't warn if the one known value is a representable
1659 // in the type of both expressions.
1660 if (LHSSuccess != RHSuccess) {
1661 Expr::EvalResult &Res = LHSSuccess ? LHSRes : RHSRes;
1662 if (IsSingleCodeUnitCP(LHSType, Res.Val.getInt()) &&
1663 IsSingleCodeUnitCP(RHSType, Res.Val.getInt()))
1664 return;
1665 }
1666
1667 if (!LHSSuccess || !RHSuccess) {
1668 SemaRef.Diag(Loc, DiagID: diag::warn_comparison_unicode_mixed_types)
1669 << LHS->getSourceRange() << RHS->getSourceRange() << LHSType
1670 << RHSType;
1671 return;
1672 }
1673
1674 llvm::APSInt LHSValue(32);
1675 LHSValue = LHSRes.Val.getInt();
1676 llvm::APSInt RHSValue(32);
1677 RHSValue = RHSRes.Val.getInt();
1678
1679 bool LHSSafe = IsSingleCodeUnitCP(LHSType, LHSValue);
1680 bool RHSSafe = IsSingleCodeUnitCP(RHSType, RHSValue);
1681 if (LHSSafe && RHSSafe)
1682 return;
1683
1684 SemaRef.Diag(Loc, DiagID: diag::warn_comparison_unicode_mixed_types_constant)
1685 << LHS->getSourceRange() << RHS->getSourceRange() << LHSType << RHSType
1686 << FormatUTFCodeUnitAsCodepoint(Value: LHSValue.getExtValue(), T: LHSType)
1687 << FormatUTFCodeUnitAsCodepoint(Value: RHSValue.getExtValue(), T: RHSType);
1688 return;
1689 }
1690
1691 if (SemaRef.getASTContext().hasSameType(T1: LHSType, T2: RHSType))
1692 return;
1693
1694 SemaRef.Diag(Loc, DiagID: diag::warn_arith_conv_mixed_unicode_types)
1695 << LHS->getSourceRange() << RHS->getSourceRange() << ACK << LHSType
1696 << RHSType;
1697}
1698
1699/// UsualArithmeticConversions - Performs various conversions that are common to
1700/// binary operators (C99 6.3.1.8). If both operands aren't arithmetic, this
1701/// routine returns the first non-arithmetic type found. The client is
1702/// responsible for emitting appropriate error diagnostics.
1703QualType Sema::UsualArithmeticConversions(ExprResult &LHS, ExprResult &RHS,
1704 SourceLocation Loc,
1705 ArithConvKind ACK) {
1706
1707 checkEnumArithmeticConversions(LHS: LHS.get(), RHS: RHS.get(), Loc, ACK);
1708
1709 CheckUnicodeArithmeticConversions(SemaRef&: *this, LHS: LHS.get(), RHS: RHS.get(), Loc, ACK);
1710
1711 if (ACK != ArithConvKind::CompAssign) {
1712 LHS = UsualUnaryConversions(E: LHS.get());
1713 if (LHS.isInvalid())
1714 return QualType();
1715 }
1716
1717 RHS = UsualUnaryConversions(E: RHS.get());
1718 if (RHS.isInvalid())
1719 return QualType();
1720
1721 // For conversion purposes, we ignore any qualifiers.
1722 // For example, "const float" and "float" are equivalent.
1723 QualType LHSType = LHS.get()->getType().getUnqualifiedType();
1724 QualType RHSType = RHS.get()->getType().getUnqualifiedType();
1725
1726 // For conversion purposes, we ignore any atomic qualifier on the LHS.
1727 if (const AtomicType *AtomicLHS = LHSType->getAs<AtomicType>())
1728 LHSType = AtomicLHS->getValueType();
1729
1730 // If both types are identical, no conversion is needed.
1731 if (Context.hasSameType(T1: LHSType, T2: RHSType))
1732 return Context.getCommonSugaredType(X: LHSType, Y: RHSType);
1733
1734 // If either side is a non-arithmetic type (e.g. a pointer), we are done.
1735 // The caller can deal with this (e.g. pointer + int).
1736 if (!LHSType->isArithmeticType() || !RHSType->isArithmeticType())
1737 return QualType();
1738
1739 // Apply unary and bitfield promotions to the LHS's type.
1740 QualType LHSUnpromotedType = LHSType;
1741 if (Context.isPromotableIntegerType(T: LHSType))
1742 LHSType = Context.getPromotedIntegerType(PromotableType: LHSType);
1743 QualType LHSBitfieldPromoteTy = Context.isPromotableBitField(E: LHS.get());
1744 if (!LHSBitfieldPromoteTy.isNull())
1745 LHSType = LHSBitfieldPromoteTy;
1746 if (LHSType != LHSUnpromotedType && ACK != ArithConvKind::CompAssign)
1747 LHS = ImpCastExprToType(E: LHS.get(), Type: LHSType, CK: CK_IntegralCast);
1748
1749 // If both types are identical, no conversion is needed.
1750 if (Context.hasSameType(T1: LHSType, T2: RHSType))
1751 return Context.getCommonSugaredType(X: LHSType, Y: RHSType);
1752
1753 // At this point, we have two different arithmetic types.
1754
1755 // Diagnose attempts to convert between __ibm128, __float128 and long double
1756 // where such conversions currently can't be handled.
1757 if (unsupportedTypeConversion(S: *this, LHSType, RHSType))
1758 return QualType();
1759
1760 // Handle complex types first (C99 6.3.1.8p1).
1761 if (LHSType->isComplexType() || RHSType->isComplexType())
1762 return handleComplexConversion(S&: *this, LHS, RHS, LHSType, RHSType,
1763 IsCompAssign: ACK == ArithConvKind::CompAssign);
1764
1765 // Now handle "real" floating types (i.e. float, double, long double).
1766 if (LHSType->isRealFloatingType() || RHSType->isRealFloatingType())
1767 return handleFloatConversion(S&: *this, LHS, RHS, LHSType, RHSType,
1768 IsCompAssign: ACK == ArithConvKind::CompAssign);
1769
1770 // Handle GCC complex int extension.
1771 if (LHSType->isComplexIntegerType() || RHSType->isComplexIntegerType())
1772 return handleComplexIntConversion(S&: *this, LHS, RHS, LHSType, RHSType,
1773 IsCompAssign: ACK == ArithConvKind::CompAssign);
1774
1775 if (LHSType->isFixedPointType() || RHSType->isFixedPointType())
1776 return handleFixedPointConversion(S&: *this, LHSTy: LHSType, RHSTy: RHSType);
1777
1778 if (LHSType->isOverflowBehaviorType() || RHSType->isOverflowBehaviorType())
1779 return handleOverflowBehaviorTypeConversion(
1780 S&: *this, LHS, RHS, LHSType, RHSType, IsCompAssign: ACK == ArithConvKind::CompAssign);
1781
1782 // Finally, we have two differing integer types.
1783 return handleIntegerConversion<doIntegralCast, doIntegralCast>(
1784 S&: *this, LHS, RHS, LHSType, RHSType, IsCompAssign: ACK == ArithConvKind::CompAssign);
1785}
1786
1787//===----------------------------------------------------------------------===//
1788// Semantic Analysis for various Expression Types
1789//===----------------------------------------------------------------------===//
1790
1791
1792ExprResult Sema::ActOnGenericSelectionExpr(
1793 SourceLocation KeyLoc, SourceLocation DefaultLoc, SourceLocation RParenLoc,
1794 bool PredicateIsExpr, void *ControllingExprOrType,
1795 ArrayRef<ParsedType> ArgTypes, ArrayRef<Expr *> ArgExprs) {
1796 unsigned NumAssocs = ArgTypes.size();
1797 assert(NumAssocs == ArgExprs.size());
1798
1799 TypeSourceInfo **Types = new TypeSourceInfo*[NumAssocs];
1800 for (unsigned i = 0; i < NumAssocs; ++i) {
1801 if (ArgTypes[i])
1802 (void) GetTypeFromParser(Ty: ArgTypes[i], TInfo: &Types[i]);
1803 else
1804 Types[i] = nullptr;
1805 }
1806
1807 // If we have a controlling type, we need to convert it from a parsed type
1808 // into a semantic type and then pass that along.
1809 if (!PredicateIsExpr) {
1810 TypeSourceInfo *ControllingType;
1811 (void)GetTypeFromParser(Ty: ParsedType::getFromOpaquePtr(P: ControllingExprOrType),
1812 TInfo: &ControllingType);
1813 assert(ControllingType && "couldn't get the type out of the parser");
1814 ControllingExprOrType = ControllingType;
1815 }
1816
1817 ExprResult ER = CreateGenericSelectionExpr(
1818 KeyLoc, DefaultLoc, RParenLoc, PredicateIsExpr, ControllingExprOrType,
1819 Types: llvm::ArrayRef(Types, NumAssocs), Exprs: ArgExprs);
1820 delete [] Types;
1821 return ER;
1822}
1823
1824// Helper function to determine type compatibility for C _Generic expressions.
1825// Multiple compatible types within the same _Generic expression is ambiguous
1826// and not valid.
1827static bool areTypesCompatibleForGeneric(ASTContext &Ctx, QualType T,
1828 QualType U) {
1829 // Try to handle special types like OverflowBehaviorTypes
1830 const auto *TOBT = T->getAs<OverflowBehaviorType>();
1831 const auto *UOBT = U.getCanonicalType()->getAs<OverflowBehaviorType>();
1832
1833 if (TOBT || UOBT) {
1834 if (TOBT && UOBT) {
1835 if (TOBT->getBehaviorKind() == UOBT->getBehaviorKind())
1836 return Ctx.typesAreCompatible(T1: TOBT->getUnderlyingType(),
1837 T2: UOBT->getUnderlyingType());
1838 return false;
1839 }
1840 return false;
1841 }
1842
1843 // We're dealing with types that don't require special handling.
1844 return Ctx.typesAreCompatible(T1: T, T2: U);
1845}
1846
1847ExprResult Sema::CreateGenericSelectionExpr(
1848 SourceLocation KeyLoc, SourceLocation DefaultLoc, SourceLocation RParenLoc,
1849 bool PredicateIsExpr, void *ControllingExprOrType,
1850 ArrayRef<TypeSourceInfo *> Types, ArrayRef<Expr *> Exprs) {
1851 unsigned NumAssocs = Types.size();
1852 assert(NumAssocs == Exprs.size());
1853 assert(ControllingExprOrType &&
1854 "Must have either a controlling expression or a controlling type");
1855
1856 Expr *ControllingExpr = nullptr;
1857 TypeSourceInfo *ControllingType = nullptr;
1858 if (PredicateIsExpr) {
1859 // Decay and strip qualifiers for the controlling expression type, and
1860 // handle placeholder type replacement. See committee discussion from WG14
1861 // DR423.
1862 EnterExpressionEvaluationContext Unevaluated(
1863 *this, Sema::ExpressionEvaluationContext::Unevaluated);
1864 ExprResult R = DefaultFunctionArrayLvalueConversion(
1865 E: reinterpret_cast<Expr *>(ControllingExprOrType));
1866 if (R.isInvalid())
1867 return ExprError();
1868 ControllingExpr = R.get();
1869 } else {
1870 // The extension form uses the type directly rather than converting it.
1871 ControllingType = reinterpret_cast<TypeSourceInfo *>(ControllingExprOrType);
1872 if (!ControllingType)
1873 return ExprError();
1874 }
1875
1876 bool TypeErrorFound = false,
1877 IsResultDependent = ControllingExpr
1878 ? ControllingExpr->isTypeDependent()
1879 : ControllingType->getType()->isDependentType(),
1880 ContainsUnexpandedParameterPack =
1881 ControllingExpr
1882 ? ControllingExpr->containsUnexpandedParameterPack()
1883 : ControllingType->getType()->containsUnexpandedParameterPack();
1884
1885 // The controlling expression is an unevaluated operand, so side effects are
1886 // likely unintended.
1887 if (!inTemplateInstantiation() && !IsResultDependent && ControllingExpr &&
1888 ControllingExpr->HasSideEffects(Ctx: Context, IncludePossibleEffects: false))
1889 Diag(Loc: ControllingExpr->getExprLoc(),
1890 DiagID: diag::warn_side_effects_unevaluated_context);
1891
1892 for (unsigned i = 0; i < NumAssocs; ++i) {
1893 if (Exprs[i]->containsUnexpandedParameterPack())
1894 ContainsUnexpandedParameterPack = true;
1895
1896 if (Types[i]) {
1897 if (Types[i]->getType()->containsUnexpandedParameterPack())
1898 ContainsUnexpandedParameterPack = true;
1899
1900 if (Types[i]->getType()->isDependentType()) {
1901 IsResultDependent = true;
1902 } else {
1903 // We relax the restriction on use of incomplete types and non-object
1904 // types with the type-based extension of _Generic. Allowing incomplete
1905 // objects means those can be used as "tags" for a type-safe way to map
1906 // to a value. Similarly, matching on function types rather than
1907 // function pointer types can be useful. However, the restriction on VM
1908 // types makes sense to retain as there are open questions about how
1909 // the selection can be made at compile time.
1910 //
1911 // C11 6.5.1.1p2 "The type name in a generic association shall specify a
1912 // complete object type other than a variably modified type."
1913 // C2y removed the requirement that an expression form must
1914 // use a complete type, though it's still as-if the type has undergone
1915 // lvalue conversion. We support this as an extension in C23 and
1916 // earlier because GCC does so.
1917 unsigned D = 0;
1918 if (ControllingExpr && Types[i]->getType()->isIncompleteType())
1919 D = LangOpts.C2y ? diag::warn_c2y_compat_assoc_type_incomplete
1920 : diag::ext_assoc_type_incomplete;
1921 else if (ControllingExpr && !Types[i]->getType()->isObjectType())
1922 D = diag::err_assoc_type_nonobject;
1923 else if (Types[i]->getType()->isVariablyModifiedType())
1924 D = diag::err_assoc_type_variably_modified;
1925 else if (ControllingExpr) {
1926 // Because the controlling expression undergoes lvalue conversion,
1927 // array conversion, and function conversion, an association which is
1928 // of array type, function type, or is qualified can never be
1929 // reached. We will warn about this so users are less surprised by
1930 // the unreachable association. However, we don't have to handle
1931 // function types; that's not an object type, so it's handled above.
1932 //
1933 // The logic is somewhat different for C++ because C++ has different
1934 // lvalue to rvalue conversion rules than C. [conv.lvalue]p1 says,
1935 // If T is a non-class type, the type of the prvalue is the cv-
1936 // unqualified version of T. Otherwise, the type of the prvalue is T.
1937 // The result of these rules is that all qualified types in an
1938 // association in C are unreachable, and in C++, only qualified non-
1939 // class types are unreachable.
1940 //
1941 // NB: this does not apply when the first operand is a type rather
1942 // than an expression, because the type form does not undergo
1943 // conversion.
1944 unsigned Reason = 0;
1945 QualType QT = Types[i]->getType();
1946 if (QT->isArrayType())
1947 Reason = 1;
1948 else if (QT.hasQualifiers() &&
1949 (!LangOpts.CPlusPlus || !QT->isRecordType()))
1950 Reason = 2;
1951
1952 if (Reason)
1953 Diag(Loc: Types[i]->getTypeLoc().getBeginLoc(),
1954 DiagID: diag::warn_unreachable_association)
1955 << QT << (Reason - 1);
1956 }
1957
1958 if (D != 0) {
1959 Diag(Loc: Types[i]->getTypeLoc().getBeginLoc(), DiagID: D)
1960 << Types[i]->getTypeLoc().getSourceRange() << Types[i]->getType();
1961 if (getDiagnostics().getDiagnosticLevel(
1962 DiagID: D, Loc: Types[i]->getTypeLoc().getBeginLoc()) >=
1963 DiagnosticsEngine::Error)
1964 TypeErrorFound = true;
1965 }
1966
1967 // C11 6.5.1.1p2 "No two generic associations in the same generic
1968 // selection shall specify compatible types."
1969 for (unsigned j = i+1; j < NumAssocs; ++j)
1970 if (Types[j] && !Types[j]->getType()->isDependentType() &&
1971 areTypesCompatibleForGeneric(Ctx&: Context, T: Types[i]->getType(),
1972 U: Types[j]->getType())) {
1973 Diag(Loc: Types[j]->getTypeLoc().getBeginLoc(),
1974 DiagID: diag::err_assoc_compatible_types)
1975 << Types[j]->getTypeLoc().getSourceRange()
1976 << Types[j]->getType()
1977 << Types[i]->getType();
1978 Diag(Loc: Types[i]->getTypeLoc().getBeginLoc(),
1979 DiagID: diag::note_compat_assoc)
1980 << Types[i]->getTypeLoc().getSourceRange()
1981 << Types[i]->getType();
1982 TypeErrorFound = true;
1983 }
1984 }
1985 }
1986 }
1987 if (TypeErrorFound)
1988 return ExprError();
1989
1990 // If we determined that the generic selection is result-dependent, don't
1991 // try to compute the result expression.
1992 if (IsResultDependent) {
1993 if (ControllingExpr)
1994 return GenericSelectionExpr::Create(Context, GenericLoc: KeyLoc, ControllingExpr,
1995 AssocTypes: Types, AssocExprs: Exprs, DefaultLoc, RParenLoc,
1996 ContainsUnexpandedParameterPack);
1997 return GenericSelectionExpr::Create(Context, GenericLoc: KeyLoc, ControllingType, AssocTypes: Types,
1998 AssocExprs: Exprs, DefaultLoc, RParenLoc,
1999 ContainsUnexpandedParameterPack);
2000 }
2001
2002 SmallVector<unsigned, 1> CompatIndices;
2003 unsigned DefaultIndex = std::numeric_limits<unsigned>::max();
2004 // Look at the canonical type of the controlling expression in case it was a
2005 // deduced type like __auto_type. However, when issuing diagnostics, use the
2006 // type the user wrote in source rather than the canonical one.
2007 for (unsigned i = 0; i < NumAssocs; ++i) {
2008 if (!Types[i])
2009 DefaultIndex = i;
2010 else {
2011 bool Compatible;
2012 QualType ControllingQT =
2013 ControllingExpr ? ControllingExpr->getType().getCanonicalType()
2014 : ControllingType->getType().getCanonicalType();
2015 QualType AssocQT = Types[i]->getType();
2016
2017 Compatible =
2018 areTypesCompatibleForGeneric(Ctx&: Context, T: ControllingQT, U: AssocQT);
2019
2020 if (Compatible)
2021 CompatIndices.push_back(Elt: i);
2022 }
2023 }
2024
2025 auto GetControllingRangeAndType = [](Expr *ControllingExpr,
2026 TypeSourceInfo *ControllingType) {
2027 // We strip parens here because the controlling expression is typically
2028 // parenthesized in macro definitions.
2029 if (ControllingExpr)
2030 ControllingExpr = ControllingExpr->IgnoreParens();
2031
2032 SourceRange SR = ControllingExpr
2033 ? ControllingExpr->getSourceRange()
2034 : ControllingType->getTypeLoc().getSourceRange();
2035 QualType QT = ControllingExpr ? ControllingExpr->getType()
2036 : ControllingType->getType();
2037
2038 return std::make_pair(x&: SR, y&: QT);
2039 };
2040
2041 // C11 6.5.1.1p2 "The controlling expression of a generic selection shall have
2042 // type compatible with at most one of the types named in its generic
2043 // association list."
2044 if (CompatIndices.size() > 1) {
2045 auto P = GetControllingRangeAndType(ControllingExpr, ControllingType);
2046 SourceRange SR = P.first;
2047 Diag(Loc: SR.getBegin(), DiagID: diag::err_generic_sel_multi_match)
2048 << SR << P.second << (unsigned)CompatIndices.size();
2049 for (unsigned I : CompatIndices) {
2050 Diag(Loc: Types[I]->getTypeLoc().getBeginLoc(),
2051 DiagID: diag::note_compat_assoc)
2052 << Types[I]->getTypeLoc().getSourceRange()
2053 << Types[I]->getType();
2054 }
2055 return ExprError();
2056 }
2057
2058 // C11 6.5.1.1p2 "If a generic selection has no default generic association,
2059 // its controlling expression shall have type compatible with exactly one of
2060 // the types named in its generic association list."
2061 if (DefaultIndex == std::numeric_limits<unsigned>::max() &&
2062 CompatIndices.size() == 0) {
2063 auto P = GetControllingRangeAndType(ControllingExpr, ControllingType);
2064 SourceRange SR = P.first;
2065 Diag(Loc: SR.getBegin(), DiagID: diag::err_generic_sel_no_match) << SR << P.second;
2066 return ExprError();
2067 }
2068
2069 // C11 6.5.1.1p3 "If a generic selection has a generic association with a
2070 // type name that is compatible with the type of the controlling expression,
2071 // then the result expression of the generic selection is the expression
2072 // in that generic association. Otherwise, the result expression of the
2073 // generic selection is the expression in the default generic association."
2074 unsigned ResultIndex =
2075 CompatIndices.size() ? CompatIndices[0] : DefaultIndex;
2076
2077 if (ControllingExpr) {
2078 return GenericSelectionExpr::Create(
2079 Context, GenericLoc: KeyLoc, ControllingExpr, AssocTypes: Types, AssocExprs: Exprs, DefaultLoc, RParenLoc,
2080 ContainsUnexpandedParameterPack, ResultIndex);
2081 }
2082 return GenericSelectionExpr::Create(
2083 Context, GenericLoc: KeyLoc, ControllingType, AssocTypes: Types, AssocExprs: Exprs, DefaultLoc, RParenLoc,
2084 ContainsUnexpandedParameterPack, ResultIndex);
2085}
2086
2087static PredefinedIdentKind getPredefinedExprKind(tok::TokenKind Kind) {
2088 switch (Kind) {
2089 default:
2090 llvm_unreachable("unexpected TokenKind");
2091 case tok::kw___func__:
2092 return PredefinedIdentKind::Func; // [C99 6.4.2.2]
2093 case tok::kw___FUNCTION__:
2094 return PredefinedIdentKind::Function;
2095 case tok::kw___FUNCDNAME__:
2096 return PredefinedIdentKind::FuncDName; // [MS]
2097 case tok::kw___FUNCSIG__:
2098 return PredefinedIdentKind::FuncSig; // [MS]
2099 case tok::kw_L__FUNCTION__:
2100 return PredefinedIdentKind::LFunction; // [MS]
2101 case tok::kw_L__FUNCSIG__:
2102 return PredefinedIdentKind::LFuncSig; // [MS]
2103 case tok::kw___PRETTY_FUNCTION__:
2104 return PredefinedIdentKind::PrettyFunction; // [GNU]
2105 }
2106}
2107
2108/// getPredefinedExprDecl - Returns Decl of a given DeclContext that can be used
2109/// to determine the value of a PredefinedExpr. This can be either a
2110/// block, lambda, captured statement, function, otherwise a nullptr.
2111static Decl *getPredefinedExprDecl(DeclContext *DC) {
2112 while (DC && !isa<BlockDecl, CapturedDecl, FunctionDecl, ObjCMethodDecl>(Val: DC))
2113 DC = DC->getParent();
2114 return cast_or_null<Decl>(Val: DC);
2115}
2116
2117/// getUDSuffixLoc - Create a SourceLocation for a ud-suffix, given the
2118/// location of the token and the offset of the ud-suffix within it.
2119static SourceLocation getUDSuffixLoc(Sema &S, SourceLocation TokLoc,
2120 unsigned Offset) {
2121 return Lexer::AdvanceToTokenCharacter(TokStart: TokLoc, Characters: Offset, SM: S.getSourceManager(),
2122 LangOpts: S.getLangOpts());
2123}
2124
2125/// BuildCookedLiteralOperatorCall - A user-defined literal was found. Look up
2126/// the corresponding cooked (non-raw) literal operator, and build a call to it.
2127static ExprResult BuildCookedLiteralOperatorCall(Sema &S, Scope *Scope,
2128 IdentifierInfo *UDSuffix,
2129 SourceLocation UDSuffixLoc,
2130 ArrayRef<Expr*> Args,
2131 SourceLocation LitEndLoc) {
2132 assert(Args.size() <= 2 && "too many arguments for literal operator");
2133
2134 QualType ArgTy[2];
2135 for (unsigned ArgIdx = 0; ArgIdx != Args.size(); ++ArgIdx) {
2136 ArgTy[ArgIdx] = Args[ArgIdx]->getType();
2137 if (ArgTy[ArgIdx]->isArrayType())
2138 ArgTy[ArgIdx] = S.Context.getArrayDecayedType(T: ArgTy[ArgIdx]);
2139 }
2140
2141 DeclarationName OpName =
2142 S.Context.DeclarationNames.getCXXLiteralOperatorName(II: UDSuffix);
2143 DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc);
2144 OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc);
2145
2146 LookupResult R(S, OpName, UDSuffixLoc, Sema::LookupOrdinaryName);
2147 if (S.LookupLiteralOperator(S: Scope, R, ArgTys: llvm::ArrayRef(ArgTy, Args.size()),
2148 /*AllowRaw*/ false, /*AllowTemplate*/ false,
2149 /*AllowStringTemplatePack*/ AllowStringTemplate: false,
2150 /*DiagnoseMissing*/ true) == Sema::LOLR_Error)
2151 return ExprError();
2152
2153 return S.BuildLiteralOperatorCall(R, SuffixInfo&: OpNameInfo, Args, LitEndLoc);
2154}
2155
2156ExprResult Sema::ActOnUnevaluatedStringLiteral(ArrayRef<Token> StringToks) {
2157 // StringToks needs backing storage as it doesn't hold array elements itself
2158 std::vector<Token> ExpandedToks;
2159 if (getLangOpts().MicrosoftExt)
2160 StringToks = ExpandedToks = ExpandFunctionLocalPredefinedMacros(Toks: StringToks);
2161
2162 StringLiteralParser Literal(StringToks, PP,
2163 StringLiteralEvalMethod::Unevaluated);
2164 if (Literal.hadError)
2165 return ExprError();
2166
2167 SmallVector<SourceLocation, 4> StringTokLocs;
2168 for (const Token &Tok : StringToks)
2169 StringTokLocs.push_back(Elt: Tok.getLocation());
2170
2171 StringLiteral *Lit = StringLiteral::Create(Ctx: Context, Str: Literal.GetString(),
2172 Kind: StringLiteralKind::Unevaluated,
2173 Pascal: false, Ty: {}, Locs: StringTokLocs);
2174
2175 if (!Literal.getUDSuffix().empty()) {
2176 SourceLocation UDSuffixLoc =
2177 getUDSuffixLoc(S&: *this, TokLoc: StringTokLocs[Literal.getUDSuffixToken()],
2178 Offset: Literal.getUDSuffixOffset());
2179 return ExprError(Diag(Loc: UDSuffixLoc, DiagID: diag::err_invalid_string_udl));
2180 }
2181
2182 return Lit;
2183}
2184
2185std::vector<Token>
2186Sema::ExpandFunctionLocalPredefinedMacros(ArrayRef<Token> Toks) {
2187 // MSVC treats some predefined identifiers (e.g. __FUNCTION__) as function
2188 // local macros that expand to string literals that may be concatenated.
2189 // These macros are expanded here (in Sema), because StringLiteralParser
2190 // (in Lex) doesn't know the enclosing function (because it hasn't been
2191 // parsed yet).
2192 assert(getLangOpts().MicrosoftExt);
2193
2194 // Note: Although function local macros are defined only inside functions,
2195 // we ensure a valid `CurrentDecl` even outside of a function. This allows
2196 // expansion of macros into empty string literals without additional checks.
2197 Decl *CurrentDecl = getPredefinedExprDecl(DC: CurContext);
2198 if (!CurrentDecl)
2199 CurrentDecl = Context.getTranslationUnitDecl();
2200
2201 std::vector<Token> ExpandedToks;
2202 ExpandedToks.reserve(n: Toks.size());
2203 for (const Token &Tok : Toks) {
2204 if (!isFunctionLocalStringLiteralMacro(K: Tok.getKind(), LO: getLangOpts())) {
2205 assert(tok::isStringLiteral(Tok.getKind()));
2206 ExpandedToks.emplace_back(args: Tok);
2207 continue;
2208 }
2209 if (isa<TranslationUnitDecl>(Val: CurrentDecl))
2210 Diag(Loc: Tok.getLocation(), DiagID: diag::ext_predef_outside_function);
2211 // Stringify predefined expression
2212 Diag(Loc: Tok.getLocation(), DiagID: diag::ext_string_literal_from_predefined)
2213 << Tok.getKind();
2214 SmallString<64> Str;
2215 llvm::raw_svector_ostream OS(Str);
2216 Token &Exp = ExpandedToks.emplace_back();
2217 Exp.startToken();
2218 if (Tok.getKind() == tok::kw_L__FUNCTION__ ||
2219 Tok.getKind() == tok::kw_L__FUNCSIG__) {
2220 OS << 'L';
2221 Exp.setKind(tok::wide_string_literal);
2222 } else {
2223 Exp.setKind(tok::string_literal);
2224 }
2225 OS << '"'
2226 << Lexer::Stringify(Str: PredefinedExpr::ComputeName(
2227 IK: getPredefinedExprKind(Kind: Tok.getKind()), CurrentDecl))
2228 << '"';
2229 PP.CreateString(Str: OS.str(), Tok&: Exp, ExpansionLocStart: Tok.getLocation(), ExpansionLocEnd: Tok.getEndLoc());
2230 }
2231 return ExpandedToks;
2232}
2233
2234ExprResult
2235Sema::ActOnStringLiteral(ArrayRef<Token> StringToks, Scope *UDLScope) {
2236 assert(!StringToks.empty() && "Must have at least one string!");
2237
2238 // StringToks needs backing storage as it doesn't hold array elements itself
2239 std::vector<Token> ExpandedToks;
2240 if (getLangOpts().MicrosoftExt)
2241 StringToks = ExpandedToks = ExpandFunctionLocalPredefinedMacros(Toks: StringToks);
2242
2243 StringLiteralParser Literal(StringToks, PP);
2244 if (Literal.hadError)
2245 return ExprError();
2246
2247 SmallVector<SourceLocation, 4> StringTokLocs;
2248 for (const Token &Tok : StringToks)
2249 StringTokLocs.push_back(Elt: Tok.getLocation());
2250
2251 QualType CharTy = Context.CharTy;
2252 StringLiteralKind Kind = StringLiteralKind::Ordinary;
2253 if (Literal.isWide()) {
2254 CharTy = Context.getWideCharType();
2255 Kind = StringLiteralKind::Wide;
2256 } else if (Literal.isUTF8()) {
2257 if (getLangOpts().Char8)
2258 CharTy = Context.Char8Ty;
2259 else if (getLangOpts().C23)
2260 CharTy = Context.UnsignedCharTy;
2261 Kind = StringLiteralKind::UTF8;
2262 } else if (Literal.isUTF16()) {
2263 CharTy = Context.Char16Ty;
2264 Kind = StringLiteralKind::UTF16;
2265 } else if (Literal.isUTF32()) {
2266 CharTy = Context.Char32Ty;
2267 Kind = StringLiteralKind::UTF32;
2268 } else if (Literal.isPascal()) {
2269 CharTy = Context.UnsignedCharTy;
2270 }
2271
2272 // Warn on u8 string literals before C++20 and C23, whose type
2273 // was an array of char before but becomes an array of char8_t.
2274 // In C++20, it cannot be used where a pointer to char is expected.
2275 // In C23, it might have an unexpected value if char was signed.
2276 if (Kind == StringLiteralKind::UTF8 &&
2277 (getLangOpts().CPlusPlus
2278 ? !getLangOpts().CPlusPlus20 && !getLangOpts().Char8
2279 : !getLangOpts().C23)) {
2280 Diag(Loc: StringTokLocs.front(), DiagID: getLangOpts().CPlusPlus
2281 ? diag::warn_cxx20_compat_utf8_string
2282 : diag::warn_c23_compat_utf8_string);
2283
2284 // Create removals for all 'u8' prefixes in the string literal(s). This
2285 // ensures C++20/C23 compatibility (but may change the program behavior when
2286 // built by non-Clang compilers for which the execution character set is
2287 // not always UTF-8).
2288 auto RemovalDiag = PDiag(DiagID: diag::note_cxx20_c23_compat_utf8_string_remove_u8);
2289 SourceLocation RemovalDiagLoc;
2290 for (const Token &Tok : StringToks) {
2291 if (Tok.getKind() == tok::utf8_string_literal) {
2292 if (RemovalDiagLoc.isInvalid())
2293 RemovalDiagLoc = Tok.getLocation();
2294 RemovalDiag << FixItHint::CreateRemoval(RemoveRange: CharSourceRange::getCharRange(
2295 B: Tok.getLocation(),
2296 E: Lexer::AdvanceToTokenCharacter(TokStart: Tok.getLocation(), Characters: 2,
2297 SM: getSourceManager(), LangOpts: getLangOpts())));
2298 }
2299 }
2300 Diag(Loc: RemovalDiagLoc, PD: RemovalDiag);
2301 }
2302
2303 QualType StrTy =
2304 Context.getStringLiteralArrayType(EltTy: CharTy, Length: Literal.GetNumStringChars());
2305
2306 // Pass &StringTokLocs[0], StringTokLocs.size() to factory!
2307 StringLiteral *Lit = StringLiteral::Create(
2308 Ctx: Context, Str: Literal.GetString(), Kind, Pascal: Literal.Pascal, Ty: StrTy, Locs: StringTokLocs);
2309 if (Literal.getUDSuffix().empty())
2310 return Lit;
2311
2312 // We're building a user-defined literal.
2313 IdentifierInfo *UDSuffix = &Context.Idents.get(Name: Literal.getUDSuffix());
2314 SourceLocation UDSuffixLoc =
2315 getUDSuffixLoc(S&: *this, TokLoc: StringTokLocs[Literal.getUDSuffixToken()],
2316 Offset: Literal.getUDSuffixOffset());
2317
2318 // Make sure we're allowed user-defined literals here.
2319 if (!UDLScope)
2320 return ExprError(Diag(Loc: UDSuffixLoc, DiagID: diag::err_invalid_string_udl));
2321
2322 // C++11 [lex.ext]p5: The literal L is treated as a call of the form
2323 // operator "" X (str, len)
2324 QualType SizeType = Context.getSizeType();
2325
2326 DeclarationName OpName =
2327 Context.DeclarationNames.getCXXLiteralOperatorName(II: UDSuffix);
2328 DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc);
2329 OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc);
2330
2331 QualType ArgTy[] = {
2332 Context.getArrayDecayedType(T: StrTy), SizeType
2333 };
2334
2335 LookupResult R(*this, OpName, UDSuffixLoc, LookupOrdinaryName);
2336 switch (LookupLiteralOperator(S: UDLScope, R, ArgTys: ArgTy,
2337 /*AllowRaw*/ false, /*AllowTemplate*/ true,
2338 /*AllowStringTemplatePack*/ AllowStringTemplate: true,
2339 /*DiagnoseMissing*/ true, StringLit: Lit)) {
2340
2341 case LOLR_Cooked: {
2342 llvm::APInt Len(Context.getIntWidth(T: SizeType), Literal.GetNumStringChars());
2343 IntegerLiteral *LenArg = IntegerLiteral::Create(C: Context, V: Len, type: SizeType,
2344 l: StringTokLocs[0]);
2345 Expr *Args[] = { Lit, LenArg };
2346
2347 return BuildLiteralOperatorCall(R, SuffixInfo&: OpNameInfo, Args, LitEndLoc: StringTokLocs.back());
2348 }
2349
2350 case LOLR_Template: {
2351 TemplateArgumentListInfo ExplicitArgs;
2352 TemplateArgument Arg(Lit, /*IsCanonical=*/false);
2353 TemplateArgumentLocInfo ArgInfo(Lit);
2354 ExplicitArgs.addArgument(Loc: TemplateArgumentLoc(Arg, ArgInfo));
2355 return BuildLiteralOperatorCall(R, SuffixInfo&: OpNameInfo, Args: {}, LitEndLoc: StringTokLocs.back(),
2356 ExplicitTemplateArgs: &ExplicitArgs);
2357 }
2358
2359 case LOLR_StringTemplatePack: {
2360 TemplateArgumentListInfo ExplicitArgs;
2361
2362 unsigned CharBits = Context.getIntWidth(T: CharTy);
2363 bool CharIsUnsigned = CharTy->isUnsignedIntegerType();
2364 llvm::APSInt Value(CharBits, CharIsUnsigned);
2365
2366 TemplateArgument TypeArg(CharTy);
2367 TemplateArgumentLocInfo TypeArgInfo(Context.getTrivialTypeSourceInfo(T: CharTy));
2368 ExplicitArgs.addArgument(Loc: TemplateArgumentLoc(TypeArg, TypeArgInfo));
2369
2370 SourceLocation Loc = StringTokLocs.back();
2371 for (unsigned I = 0, N = Lit->getLength(); I != N; ++I) {
2372 Value = Lit->getCodeUnit(i: I);
2373 TemplateArgument Arg(Context, Value, CharTy);
2374 TemplateArgumentLocInfo ArgInfo(Context, Loc.getLocWithOffset(Offset: I));
2375 ExplicitArgs.addArgument(Loc: TemplateArgumentLoc(Arg, ArgInfo));
2376 }
2377 return BuildLiteralOperatorCall(R, SuffixInfo&: OpNameInfo, Args: {}, LitEndLoc: Loc, ExplicitTemplateArgs: &ExplicitArgs);
2378 }
2379 case LOLR_Raw:
2380 case LOLR_ErrorNoDiagnostic:
2381 llvm_unreachable("unexpected literal operator lookup result");
2382 case LOLR_Error:
2383 return ExprError();
2384 }
2385 llvm_unreachable("unexpected literal operator lookup result");
2386}
2387
2388DeclRefExpr *
2389Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK,
2390 SourceLocation Loc,
2391 const CXXScopeSpec *SS) {
2392 DeclarationNameInfo NameInfo(D->getDeclName(), Loc);
2393 return BuildDeclRefExpr(D, Ty, VK, NameInfo, SS);
2394}
2395
2396DeclRefExpr *
2397Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK,
2398 const DeclarationNameInfo &NameInfo,
2399 const CXXScopeSpec *SS, NamedDecl *FoundD,
2400 SourceLocation TemplateKWLoc,
2401 const TemplateArgumentListInfo *TemplateArgs) {
2402 NestedNameSpecifierLoc NNS =
2403 SS ? SS->getWithLocInContext(Context) : NestedNameSpecifierLoc();
2404 return BuildDeclRefExpr(D, Ty, VK, NameInfo, NNS, FoundD, TemplateKWLoc,
2405 TemplateArgs);
2406}
2407
2408// CUDA/HIP: Check whether a captured reference variable is referencing a
2409// host variable in a device or host device lambda.
2410static bool isCapturingReferenceToHostVarInCUDADeviceLambda(const Sema &S,
2411 VarDecl *VD) {
2412 if (!S.getLangOpts().CUDA || !VD->hasInit())
2413 return false;
2414 assert(VD->getType()->isReferenceType());
2415
2416 // Check whether the reference variable is referencing a host variable.
2417 auto *DRE = dyn_cast<DeclRefExpr>(Val: VD->getInit());
2418 if (!DRE)
2419 return false;
2420 auto *Referee = dyn_cast<VarDecl>(Val: DRE->getDecl());
2421 if (!Referee || !Referee->hasGlobalStorage() ||
2422 Referee->hasAttr<CUDADeviceAttr>())
2423 return false;
2424
2425 // Check whether the current function is a device or host device lambda.
2426 // Check whether the reference variable is a capture by getDeclContext()
2427 // since refersToEnclosingVariableOrCapture() is not ready at this point.
2428 auto *MD = dyn_cast_or_null<CXXMethodDecl>(Val: S.CurContext);
2429 if (MD && MD->getParent()->isLambda() &&
2430 MD->getOverloadedOperator() == OO_Call && MD->hasAttr<CUDADeviceAttr>() &&
2431 VD->getDeclContext() != MD)
2432 return true;
2433
2434 return false;
2435}
2436
2437NonOdrUseReason Sema::getNonOdrUseReasonInCurrentContext(ValueDecl *D) {
2438 // A declaration named in an unevaluated operand never constitutes an odr-use.
2439 if (isUnevaluatedContext())
2440 return NOUR_Unevaluated;
2441
2442 // C++2a [basic.def.odr]p4:
2443 // A variable x whose name appears as a potentially-evaluated expression e
2444 // is odr-used by e unless [...] x is a reference that is usable in
2445 // constant expressions.
2446 // CUDA/HIP:
2447 // If a reference variable referencing a host variable is captured in a
2448 // device or host device lambda, the value of the referee must be copied
2449 // to the capture and the reference variable must be treated as odr-use
2450 // since the value of the referee is not known at compile time and must
2451 // be loaded from the captured.
2452 if (VarDecl *VD = dyn_cast<VarDecl>(Val: D)) {
2453 if (VD->getType()->isReferenceType() &&
2454 !(getLangOpts().OpenMP && OpenMP().isOpenMPCapturedDecl(D)) &&
2455 !isCapturingReferenceToHostVarInCUDADeviceLambda(S: *this, VD) &&
2456 VD->isUsableInConstantExpressions(C: Context))
2457 return NOUR_Constant;
2458 }
2459
2460 // All remaining non-variable cases constitute an odr-use. For variables, we
2461 // need to wait and see how the expression is used.
2462 return NOUR_None;
2463}
2464
2465DeclRefExpr *
2466Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK,
2467 const DeclarationNameInfo &NameInfo,
2468 NestedNameSpecifierLoc NNS, NamedDecl *FoundD,
2469 SourceLocation TemplateKWLoc,
2470 const TemplateArgumentListInfo *TemplateArgs) {
2471 bool RefersToCapturedVariable = isa<VarDecl, BindingDecl>(Val: D) &&
2472 NeedToCaptureVariable(Var: D, Loc: NameInfo.getLoc());
2473
2474 DeclRefExpr *E = DeclRefExpr::Create(
2475 Context, QualifierLoc: NNS, TemplateKWLoc, D, RefersToEnclosingVariableOrCapture: RefersToCapturedVariable, NameInfo, T: Ty,
2476 VK, FoundD, TemplateArgs, NOUR: getNonOdrUseReasonInCurrentContext(D));
2477 MarkDeclRefReferenced(E);
2478
2479 // C++ [except.spec]p17:
2480 // An exception-specification is considered to be needed when:
2481 // - in an expression, the function is the unique lookup result or
2482 // the selected member of a set of overloaded functions.
2483 //
2484 // We delay doing this until after we've built the function reference and
2485 // marked it as used so that:
2486 // a) if the function is defaulted, we get errors from defining it before /
2487 // instead of errors from computing its exception specification, and
2488 // b) if the function is a defaulted comparison, we can use the body we
2489 // build when defining it as input to the exception specification
2490 // computation rather than computing a new body.
2491 if (const auto *FPT = Ty->getAs<FunctionProtoType>()) {
2492 if (isUnresolvedExceptionSpec(ESpecType: FPT->getExceptionSpecType())) {
2493 if (const auto *NewFPT = ResolveExceptionSpec(Loc: NameInfo.getLoc(), FPT))
2494 E->setType(Context.getQualifiedType(T: NewFPT, Qs: Ty.getQualifiers()));
2495 }
2496 }
2497
2498 if (getLangOpts().ObjCWeak && isa<VarDecl>(Val: D) &&
2499 Ty.getObjCLifetime() == Qualifiers::OCL_Weak && !isUnevaluatedContext() &&
2500 !Diags.isIgnored(DiagID: diag::warn_arc_repeated_use_of_weak, Loc: E->getBeginLoc()))
2501 getCurFunction()->recordUseOfWeak(E);
2502
2503 const auto *FD = dyn_cast<FieldDecl>(Val: D);
2504 if (const auto *IFD = dyn_cast<IndirectFieldDecl>(Val: D))
2505 FD = IFD->getAnonField();
2506 if (FD) {
2507 UnusedPrivateFields.remove(X: FD);
2508 // Just in case we're building an illegal pointer-to-member.
2509 if (FD->isBitField())
2510 E->setObjectKind(OK_BitField);
2511 }
2512
2513 // C++ [expr.prim]/8: The expression [...] is a bit-field if the identifier
2514 // designates a bit-field.
2515 if (const auto *BD = dyn_cast<BindingDecl>(Val: D))
2516 if (const auto *BE = BD->getBinding())
2517 E->setObjectKind(BE->getObjectKind());
2518
2519 return E;
2520}
2521
2522void
2523Sema::DecomposeUnqualifiedId(const UnqualifiedId &Id,
2524 TemplateArgumentListInfo &Buffer,
2525 DeclarationNameInfo &NameInfo,
2526 const TemplateArgumentListInfo *&TemplateArgs) {
2527 if (Id.getKind() == UnqualifiedIdKind::IK_TemplateId) {
2528 Buffer.setLAngleLoc(Id.TemplateId->LAngleLoc);
2529 Buffer.setRAngleLoc(Id.TemplateId->RAngleLoc);
2530
2531 ASTTemplateArgsPtr TemplateArgsPtr(Id.TemplateId->getTemplateArgs(),
2532 Id.TemplateId->NumArgs);
2533 translateTemplateArguments(In: TemplateArgsPtr, Out&: Buffer);
2534
2535 TemplateName TName = Id.TemplateId->Template.get();
2536 SourceLocation TNameLoc = Id.TemplateId->TemplateNameLoc;
2537 NameInfo = Context.getNameForTemplate(Name: TName, NameLoc: TNameLoc);
2538 TemplateArgs = &Buffer;
2539 } else {
2540 NameInfo = GetNameFromUnqualifiedId(Name: Id);
2541 TemplateArgs = nullptr;
2542 }
2543}
2544
2545bool Sema::DiagnoseDependentMemberLookup(const LookupResult &R) {
2546 // During a default argument instantiation the CurContext points
2547 // to a CXXMethodDecl; but we can't apply a this-> fixit inside a
2548 // function parameter list, hence add an explicit check.
2549 bool isDefaultArgument =
2550 !CodeSynthesisContexts.empty() &&
2551 CodeSynthesisContexts.back().Kind ==
2552 CodeSynthesisContext::DefaultFunctionArgumentInstantiation;
2553 const auto *CurMethod = dyn_cast<CXXMethodDecl>(Val: CurContext);
2554 bool isInstance = CurMethod && CurMethod->isInstance() &&
2555 R.getNamingClass() == CurMethod->getParent() &&
2556 !isDefaultArgument;
2557
2558 // There are two ways we can find a class-scope declaration during template
2559 // instantiation that we did not find in the template definition: if it is a
2560 // member of a dependent base class, or if it is declared after the point of
2561 // use in the same class. Distinguish these by comparing the class in which
2562 // the member was found to the naming class of the lookup.
2563 unsigned DiagID = diag::err_found_in_dependent_base;
2564 unsigned NoteID = diag::note_member_declared_at;
2565 if (R.getRepresentativeDecl()->getDeclContext()->Equals(DC: R.getNamingClass())) {
2566 DiagID = getLangOpts().MSVCCompat ? diag::ext_found_later_in_class
2567 : diag::err_found_later_in_class;
2568 } else if (getLangOpts().MSVCCompat) {
2569 DiagID = diag::ext_found_in_dependent_base;
2570 NoteID = diag::note_dependent_member_use;
2571 }
2572
2573 if (isInstance) {
2574 // Give a code modification hint to insert 'this->'.
2575 Diag(Loc: R.getNameLoc(), DiagID)
2576 << R.getLookupName()
2577 << FixItHint::CreateInsertion(InsertionLoc: R.getNameLoc(), Code: "this->");
2578 CheckCXXThisCapture(Loc: R.getNameLoc());
2579 } else {
2580 // FIXME: Add a FixItHint to insert 'Base::' or 'Derived::' (assuming
2581 // they're not shadowed).
2582 Diag(Loc: R.getNameLoc(), DiagID) << R.getLookupName();
2583 }
2584
2585 for (const NamedDecl *D : R)
2586 Diag(Loc: D->getLocation(), DiagID: NoteID);
2587
2588 // Return true if we are inside a default argument instantiation
2589 // and the found name refers to an instance member function, otherwise
2590 // the caller will try to create an implicit member call and this is wrong
2591 // for default arguments.
2592 //
2593 // FIXME: Is this special case necessary? We could allow the caller to
2594 // diagnose this.
2595 if (isDefaultArgument && ((*R.begin())->isCXXInstanceMember())) {
2596 Diag(Loc: R.getNameLoc(), DiagID: diag::err_member_call_without_object) << 0;
2597 return true;
2598 }
2599
2600 // Tell the callee to try to recover.
2601 return false;
2602}
2603
2604bool Sema::DiagnoseEmptyLookup(Scope *S, CXXScopeSpec &SS, LookupResult &R,
2605 CorrectionCandidateCallback &CCC,
2606 TemplateArgumentListInfo *ExplicitTemplateArgs,
2607 ArrayRef<Expr *> Args, DeclContext *LookupCtx) {
2608 DeclarationName Name = R.getLookupName();
2609 SourceRange NameRange = R.getLookupNameInfo().getSourceRange();
2610
2611 unsigned diagnostic = diag::err_undeclared_var_use;
2612 unsigned diagnostic_suggest = diag::err_undeclared_var_use_suggest;
2613 if (Name.getNameKind() == DeclarationName::CXXOperatorName ||
2614 Name.getNameKind() == DeclarationName::CXXLiteralOperatorName ||
2615 Name.getNameKind() == DeclarationName::CXXConversionFunctionName) {
2616 diagnostic = diag::err_undeclared_use;
2617 diagnostic_suggest = diag::err_undeclared_use_suggest;
2618 }
2619
2620 // If the original lookup was an unqualified lookup, fake an
2621 // unqualified lookup. This is useful when (for example) the
2622 // original lookup would not have found something because it was a
2623 // dependent name.
2624 DeclContext *DC =
2625 LookupCtx ? LookupCtx : (SS.isEmpty() ? CurContext : nullptr);
2626 while (DC) {
2627 if (isa<CXXRecordDecl>(Val: DC)) {
2628 if (ExplicitTemplateArgs) {
2629 if (LookupTemplateName(
2630 R, S, SS, ObjectType: Context.getCanonicalTagType(TD: cast<CXXRecordDecl>(Val: DC)),
2631 /*EnteringContext*/ false, RequiredTemplate: TemplateNameIsRequired,
2632 /*RequiredTemplateKind*/ ATK: nullptr, /*AllowTypoCorrection*/ true))
2633 return true;
2634 } else {
2635 LookupQualifiedName(R, LookupCtx: DC);
2636 }
2637
2638 if (!R.empty()) {
2639 // Don't give errors about ambiguities in this lookup.
2640 R.suppressDiagnostics();
2641
2642 // If there's a best viable function among the results, only mention
2643 // that one in the notes.
2644 OverloadCandidateSet Candidates(R.getNameLoc(),
2645 OverloadCandidateSet::CSK_Normal);
2646 AddOverloadedCallCandidates(R, ExplicitTemplateArgs, Args, CandidateSet&: Candidates);
2647 OverloadCandidateSet::iterator Best;
2648 if (Candidates.BestViableFunction(S&: *this, Loc: R.getNameLoc(), Best) ==
2649 OR_Success) {
2650 R.clear();
2651 R.addDecl(D: Best->FoundDecl.getDecl(), AS: Best->FoundDecl.getAccess());
2652 R.resolveKind();
2653 }
2654
2655 return DiagnoseDependentMemberLookup(R);
2656 }
2657
2658 R.clear();
2659 }
2660
2661 DC = DC->getLookupParent();
2662 }
2663
2664 // We didn't find anything, so try to correct for a typo.
2665 TypoCorrection Corrected;
2666 if (S && (Corrected =
2667 CorrectTypo(Typo: R.getLookupNameInfo(), LookupKind: R.getLookupKind(), S, SS: &SS,
2668 CCC, Mode: CorrectTypoKind::ErrorRecovery, MemberContext: LookupCtx))) {
2669 std::string CorrectedStr(Corrected.getAsString(LO: getLangOpts()));
2670 bool DroppedSpecifier =
2671 Corrected.WillReplaceSpecifier() && Name.getAsString() == CorrectedStr;
2672 R.setLookupName(Corrected.getCorrection());
2673
2674 bool AcceptableWithRecovery = false;
2675 bool AcceptableWithoutRecovery = false;
2676 NamedDecl *ND = Corrected.getFoundDecl();
2677 if (ND) {
2678 if (Corrected.isOverloaded()) {
2679 OverloadCandidateSet OCS(R.getNameLoc(),
2680 OverloadCandidateSet::CSK_Normal);
2681 OverloadCandidateSet::iterator Best;
2682 for (NamedDecl *CD : Corrected) {
2683 if (FunctionTemplateDecl *FTD =
2684 dyn_cast<FunctionTemplateDecl>(Val: CD))
2685 AddTemplateOverloadCandidate(
2686 FunctionTemplate: FTD, FoundDecl: DeclAccessPair::make(D: FTD, AS: AS_none), ExplicitTemplateArgs,
2687 Args, CandidateSet&: OCS);
2688 else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Val: CD))
2689 if (!ExplicitTemplateArgs || ExplicitTemplateArgs->size() == 0)
2690 AddOverloadCandidate(Function: FD, FoundDecl: DeclAccessPair::make(D: FD, AS: AS_none),
2691 Args, CandidateSet&: OCS);
2692 }
2693 switch (OCS.BestViableFunction(S&: *this, Loc: R.getNameLoc(), Best)) {
2694 case OR_Success:
2695 ND = Best->FoundDecl;
2696 Corrected.setCorrectionDecl(ND);
2697 break;
2698 default:
2699 // FIXME: Arbitrarily pick the first declaration for the note.
2700 Corrected.setCorrectionDecl(ND);
2701 break;
2702 }
2703 }
2704 R.addDecl(D: ND);
2705 if (getLangOpts().CPlusPlus && ND->isCXXClassMember()) {
2706 CXXRecordDecl *Record =
2707 Corrected.getCorrectionSpecifier().getAsRecordDecl();
2708 if (!Record)
2709 Record = cast<CXXRecordDecl>(
2710 Val: ND->getDeclContext()->getRedeclContext());
2711 R.setNamingClass(Record);
2712 }
2713
2714 auto *UnderlyingND = ND->getUnderlyingDecl();
2715 AcceptableWithRecovery = isa<ValueDecl>(Val: UnderlyingND) ||
2716 isa<FunctionTemplateDecl>(Val: UnderlyingND);
2717 // FIXME: If we ended up with a typo for a type name or
2718 // Objective-C class name, we're in trouble because the parser
2719 // is in the wrong place to recover. Suggest the typo
2720 // correction, but don't make it a fix-it since we're not going
2721 // to recover well anyway.
2722 AcceptableWithoutRecovery = isa<TypeDecl>(Val: UnderlyingND) ||
2723 getAsTypeTemplateDecl(D: UnderlyingND) ||
2724 isa<ObjCInterfaceDecl>(Val: UnderlyingND);
2725 } else {
2726 // FIXME: We found a keyword. Suggest it, but don't provide a fix-it
2727 // because we aren't able to recover.
2728 AcceptableWithoutRecovery = true;
2729 }
2730
2731 if (AcceptableWithRecovery || AcceptableWithoutRecovery) {
2732 unsigned NoteID = Corrected.getCorrectionDeclAs<ImplicitParamDecl>()
2733 ? diag::note_implicit_param_decl
2734 : diag::note_previous_decl;
2735 if (SS.isEmpty())
2736 diagnoseTypo(Correction: Corrected, TypoDiag: PDiag(DiagID: diagnostic_suggest) << Name << NameRange,
2737 PrevNote: PDiag(DiagID: NoteID), ErrorRecovery: AcceptableWithRecovery);
2738 else
2739 diagnoseTypo(Correction: Corrected,
2740 TypoDiag: PDiag(DiagID: diag::err_no_member_suggest)
2741 << Name << computeDeclContext(SS, EnteringContext: false)
2742 << DroppedSpecifier << NameRange,
2743 PrevNote: PDiag(DiagID: NoteID), ErrorRecovery: AcceptableWithRecovery);
2744
2745 if (Corrected.WillReplaceSpecifier()) {
2746 NestedNameSpecifier NNS = Corrected.getCorrectionSpecifier();
2747 // In order to be valid, a non-empty CXXScopeSpec needs a source range.
2748 SS.MakeTrivial(Context, Qualifier: NNS,
2749 R: NNS ? NameRange.getBegin() : SourceRange());
2750 }
2751
2752 // Tell the callee whether to try to recover.
2753 return !AcceptableWithRecovery;
2754 }
2755 }
2756 R.clear();
2757
2758 // Emit a special diagnostic for failed member lookups.
2759 // FIXME: computing the declaration context might fail here (?)
2760 if (!SS.isEmpty()) {
2761 Diag(Loc: R.getNameLoc(), DiagID: diag::err_no_member)
2762 << Name << computeDeclContext(SS, EnteringContext: false) << NameRange;
2763 return true;
2764 }
2765
2766 // Give up, we can't recover.
2767 Diag(Loc: R.getNameLoc(), DiagID: diagnostic) << Name << NameRange;
2768 return true;
2769}
2770
2771/// In Microsoft mode, if we are inside a template class whose parent class has
2772/// dependent base classes, and we can't resolve an unqualified identifier, then
2773/// assume the identifier is a member of a dependent base class. We can only
2774/// recover successfully in static methods, instance methods, and other contexts
2775/// where 'this' is available. This doesn't precisely match MSVC's
2776/// instantiation model, but it's close enough.
2777static Expr *
2778recoverFromMSUnqualifiedLookup(Sema &S, ASTContext &Context,
2779 DeclarationNameInfo &NameInfo,
2780 SourceLocation TemplateKWLoc,
2781 const TemplateArgumentListInfo *TemplateArgs) {
2782 // Only try to recover from lookup into dependent bases in static methods or
2783 // contexts where 'this' is available.
2784 QualType ThisType = S.getCurrentThisType();
2785 const CXXRecordDecl *RD = nullptr;
2786 if (!ThisType.isNull())
2787 RD = ThisType->getPointeeType()->getAsCXXRecordDecl();
2788 else if (auto *MD = dyn_cast<CXXMethodDecl>(Val: S.CurContext))
2789 RD = MD->getParent();
2790 if (!RD || !RD->hasDefinition() || !RD->hasAnyDependentBases())
2791 return nullptr;
2792
2793 // Diagnose this as unqualified lookup into a dependent base class. If 'this'
2794 // is available, suggest inserting 'this->' as a fixit.
2795 SourceLocation Loc = NameInfo.getLoc();
2796 auto DB = S.Diag(Loc, DiagID: diag::ext_undeclared_unqual_id_with_dependent_base);
2797 DB << NameInfo.getName() << RD;
2798
2799 if (!ThisType.isNull()) {
2800 DB << FixItHint::CreateInsertion(InsertionLoc: Loc, Code: "this->");
2801 return CXXDependentScopeMemberExpr::Create(
2802 Ctx: Context, /*This=*/Base: nullptr, BaseType: ThisType, /*IsArrow=*/true,
2803 /*Op=*/OperatorLoc: SourceLocation(), QualifierLoc: NestedNameSpecifierLoc(), TemplateKWLoc,
2804 /*FirstQualifierFoundInScope=*/nullptr, MemberNameInfo: NameInfo, TemplateArgs);
2805 }
2806
2807 // Synthesize a fake NNS that points to the derived class. This will
2808 // perform name lookup during template instantiation.
2809 CXXScopeSpec SS;
2810 NestedNameSpecifier NNS(Context.getCanonicalTagType(TD: RD)->getTypePtr());
2811 SS.MakeTrivial(Context, Qualifier: NNS, R: SourceRange(Loc, Loc));
2812 return DependentScopeDeclRefExpr::Create(
2813 Context, QualifierLoc: SS.getWithLocInContext(Context), TemplateKWLoc, NameInfo,
2814 TemplateArgs);
2815}
2816
2817ExprResult
2818Sema::ActOnIdExpression(Scope *S, CXXScopeSpec &SS,
2819 SourceLocation TemplateKWLoc, UnqualifiedId &Id,
2820 bool HasTrailingLParen, bool IsAddressOfOperand,
2821 CorrectionCandidateCallback *CCC,
2822 bool IsInlineAsmIdentifier, Token *KeywordReplacement) {
2823 assert(!(IsAddressOfOperand && HasTrailingLParen) &&
2824 "cannot be direct & operand and have a trailing lparen");
2825 if (SS.isInvalid())
2826 return ExprError();
2827
2828 TemplateArgumentListInfo TemplateArgsBuffer;
2829
2830 // Decompose the UnqualifiedId into the following data.
2831 DeclarationNameInfo NameInfo;
2832 const TemplateArgumentListInfo *TemplateArgs;
2833 DecomposeUnqualifiedId(Id, Buffer&: TemplateArgsBuffer, NameInfo, TemplateArgs);
2834
2835 DeclarationName Name = NameInfo.getName();
2836 IdentifierInfo *II = Name.getAsIdentifierInfo();
2837 SourceLocation NameLoc = NameInfo.getLoc();
2838
2839 if (II && II->isEditorPlaceholder()) {
2840 // FIXME: When typed placeholders are supported we can create a typed
2841 // placeholder expression node.
2842 return ExprError();
2843 }
2844
2845 // This specially handles arguments of attributes appertains to a type of C
2846 // struct field such that the name lookup within a struct finds the member
2847 // name, which is not the case for other contexts in C.
2848 if (isAttrContext() && !getLangOpts().CPlusPlus && S->isClassScope()) {
2849 // See if this is reference to a field of struct.
2850 LookupResult R(*this, NameInfo, LookupMemberName);
2851 // LookupName handles a name lookup from within anonymous struct.
2852 if (LookupName(R, S)) {
2853 if (auto *VD = dyn_cast<ValueDecl>(Val: R.getFoundDecl())) {
2854 QualType type = VD->getType().getNonReferenceType();
2855 // This will eventually be translated into MemberExpr upon
2856 // the use of instantiated struct fields.
2857 return BuildDeclRefExpr(D: VD, Ty: type, VK: VK_LValue, Loc: NameLoc);
2858 }
2859 }
2860 }
2861
2862 // Perform the required lookup.
2863 LookupResult R(*this, NameInfo,
2864 (Id.getKind() == UnqualifiedIdKind::IK_ImplicitSelfParam)
2865 ? LookupObjCImplicitSelfParam
2866 : LookupOrdinaryName);
2867 if (TemplateKWLoc.isValid() || TemplateArgs) {
2868 // Lookup the template name again to correctly establish the context in
2869 // which it was found. This is really unfortunate as we already did the
2870 // lookup to determine that it was a template name in the first place. If
2871 // this becomes a performance hit, we can work harder to preserve those
2872 // results until we get here but it's likely not worth it.
2873 AssumedTemplateKind AssumedTemplate;
2874 if (LookupTemplateName(R, S, SS, /*ObjectType=*/QualType(),
2875 /*EnteringContext=*/false, RequiredTemplate: TemplateKWLoc,
2876 ATK: &AssumedTemplate))
2877 return ExprError();
2878
2879 if (R.wasNotFoundInCurrentInstantiation() || SS.isInvalid())
2880 return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo,
2881 isAddressOfOperand: IsAddressOfOperand, TemplateArgs);
2882 } else {
2883 bool IvarLookupFollowUp = II && !SS.isSet() && getCurMethodDecl();
2884 LookupParsedName(R, S, SS: &SS, /*ObjectType=*/QualType(),
2885 /*AllowBuiltinCreation=*/!IvarLookupFollowUp);
2886
2887 // If the result might be in a dependent base class, this is a dependent
2888 // id-expression.
2889 if (R.wasNotFoundInCurrentInstantiation() || SS.isInvalid())
2890 return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo,
2891 isAddressOfOperand: IsAddressOfOperand, TemplateArgs);
2892
2893 // If this reference is in an Objective-C method, then we need to do
2894 // some special Objective-C lookup, too.
2895 if (IvarLookupFollowUp) {
2896 ExprResult E(ObjC().LookupInObjCMethod(LookUp&: R, S, II, AllowBuiltinCreation: true));
2897 if (E.isInvalid())
2898 return ExprError();
2899
2900 if (Expr *Ex = E.getAs<Expr>())
2901 return Ex;
2902 }
2903 }
2904
2905 if (R.isAmbiguous())
2906 return ExprError();
2907
2908 // This could be an implicitly declared function reference if the language
2909 // mode allows it as a feature.
2910 if (R.empty() && HasTrailingLParen && II &&
2911 getLangOpts().implicitFunctionsAllowed()) {
2912 NamedDecl *D = ImplicitlyDefineFunction(Loc: NameLoc, II&: *II, S);
2913 if (D) R.addDecl(D);
2914 }
2915
2916 // Determine whether this name might be a candidate for
2917 // argument-dependent lookup.
2918 bool ADL = UseArgumentDependentLookup(SS, R, HasTrailingLParen);
2919
2920 if (R.empty() && !ADL) {
2921 if (SS.isEmpty() && getLangOpts().MSVCCompat) {
2922 if (Expr *E = recoverFromMSUnqualifiedLookup(S&: *this, Context, NameInfo,
2923 TemplateKWLoc, TemplateArgs))
2924 return E;
2925 }
2926
2927 // Don't diagnose an empty lookup for inline assembly.
2928 if (IsInlineAsmIdentifier)
2929 return ExprError();
2930
2931 // If this name wasn't predeclared and if this is not a function
2932 // call, diagnose the problem.
2933 DefaultFilterCCC DefaultValidator(II, SS.getScopeRep());
2934 DefaultValidator.IsAddressOfOperand = IsAddressOfOperand;
2935 assert((!CCC || CCC->IsAddressOfOperand == IsAddressOfOperand) &&
2936 "Typo correction callback misconfigured");
2937 if (CCC) {
2938 // Make sure the callback knows what the typo being diagnosed is.
2939 CCC->setTypoName(II);
2940 if (SS.isValid())
2941 CCC->setTypoNNS(SS.getScopeRep());
2942 }
2943 // FIXME: DiagnoseEmptyLookup produces bad diagnostics if we're looking for
2944 // a template name, but we happen to have always already looked up the name
2945 // before we get here if it must be a template name.
2946 if (DiagnoseEmptyLookup(S, SS, R, CCC&: CCC ? *CCC : DefaultValidator, ExplicitTemplateArgs: nullptr,
2947 Args: {}, LookupCtx: nullptr))
2948 return ExprError();
2949
2950 assert(!R.empty() &&
2951 "DiagnoseEmptyLookup returned false but added no results");
2952
2953 // If we found an Objective-C instance variable, let
2954 // LookupInObjCMethod build the appropriate expression to
2955 // reference the ivar.
2956 if (ObjCIvarDecl *Ivar = R.getAsSingle<ObjCIvarDecl>()) {
2957 R.clear();
2958 ExprResult E(ObjC().LookupInObjCMethod(LookUp&: R, S, II: Ivar->getIdentifier()));
2959 // In a hopelessly buggy code, Objective-C instance variable
2960 // lookup fails and no expression will be built to reference it.
2961 if (!E.isInvalid() && !E.get())
2962 return ExprError();
2963 return E;
2964 }
2965 }
2966
2967 // This is guaranteed from this point on.
2968 assert(!R.empty() || ADL);
2969
2970 // Check whether this might be a C++ implicit instance member access.
2971 // C++ [class.mfct.non-static]p3:
2972 // When an id-expression that is not part of a class member access
2973 // syntax and not used to form a pointer to member is used in the
2974 // body of a non-static member function of class X, if name lookup
2975 // resolves the name in the id-expression to a non-static non-type
2976 // member of some class C, the id-expression is transformed into a
2977 // class member access expression using (*this) as the
2978 // postfix-expression to the left of the . operator.
2979 //
2980 // But we don't actually need to do this for '&' operands if R
2981 // resolved to a function or overloaded function set, because the
2982 // expression is ill-formed if it actually works out to be a
2983 // non-static member function:
2984 //
2985 // C++ [expr.ref]p4:
2986 // Otherwise, if E1.E2 refers to a non-static member function. . .
2987 // [t]he expression can be used only as the left-hand operand of a
2988 // member function call.
2989 //
2990 // There are other safeguards against such uses, but it's important
2991 // to get this right here so that we don't end up making a
2992 // spuriously dependent expression if we're inside a dependent
2993 // instance method.
2994 if (isPotentialImplicitMemberAccess(SS, R, IsAddressOfOperand))
2995 return BuildPossibleImplicitMemberExpr(SS, TemplateKWLoc, R, TemplateArgs,
2996 S);
2997
2998 if (TemplateArgs || TemplateKWLoc.isValid()) {
2999
3000 // In C++1y, if this is a variable template id, then check it
3001 // in BuildTemplateIdExpr().
3002 // The single lookup result must be a variable template declaration.
3003 if (Id.getKind() == UnqualifiedIdKind::IK_TemplateId && Id.TemplateId &&
3004 (Id.TemplateId->Kind == TNK_Var_template ||
3005 Id.TemplateId->Kind == TNK_Concept_template)) {
3006 assert(R.getAsSingle<TemplateDecl>() &&
3007 "There should only be one declaration found.");
3008 }
3009
3010 return BuildTemplateIdExpr(SS, TemplateKWLoc, R, RequiresADL: ADL, TemplateArgs);
3011 }
3012
3013 return BuildDeclarationNameExpr(SS, R, NeedsADL: ADL);
3014}
3015
3016ExprResult Sema::BuildQualifiedDeclarationNameExpr(
3017 CXXScopeSpec &SS, const DeclarationNameInfo &NameInfo,
3018 bool IsAddressOfOperand, TypeSourceInfo **RecoveryTSI) {
3019 LookupResult R(*this, NameInfo, LookupOrdinaryName);
3020 LookupParsedName(R, /*S=*/nullptr, SS: &SS, /*ObjectType=*/QualType());
3021
3022 if (R.isAmbiguous())
3023 return ExprError();
3024
3025 if (R.wasNotFoundInCurrentInstantiation() || SS.isInvalid())
3026 return BuildDependentDeclRefExpr(SS, /*TemplateKWLoc=*/SourceLocation(),
3027 NameInfo, /*TemplateArgs=*/nullptr);
3028
3029 if (R.empty()) {
3030 // Don't diagnose problems with invalid record decl, the secondary no_member
3031 // diagnostic during template instantiation is likely bogus, e.g. if a class
3032 // is invalid because it's derived from an invalid base class, then missing
3033 // members were likely supposed to be inherited.
3034 DeclContext *DC = computeDeclContext(SS);
3035 if (const auto *CD = dyn_cast<CXXRecordDecl>(Val: DC))
3036 if (CD->isInvalidDecl() || CD->isBeingDefined())
3037 return ExprError();
3038 Diag(Loc: NameInfo.getLoc(), DiagID: diag::err_no_member)
3039 << NameInfo.getName() << DC << SS.getRange();
3040 return ExprError();
3041 }
3042
3043 if (const TypeDecl *TD = R.getAsSingle<TypeDecl>()) {
3044 QualType ET;
3045 TypeLocBuilder TLB;
3046 if (auto *TagD = dyn_cast<TagDecl>(Val: TD)) {
3047 ET = SemaRef.Context.getTagType(Keyword: ElaboratedTypeKeyword::None,
3048 Qualifier: SS.getScopeRep(), TD: TagD,
3049 /*OwnsTag=*/false);
3050 auto TL = TLB.push<TagTypeLoc>(T: ET);
3051 TL.setElaboratedKeywordLoc(SourceLocation());
3052 TL.setQualifierLoc(SS.getWithLocInContext(Context));
3053 TL.setNameLoc(NameInfo.getLoc());
3054 } else if (auto *TypedefD = dyn_cast<TypedefNameDecl>(Val: TD)) {
3055 ET = SemaRef.Context.getTypedefType(Keyword: ElaboratedTypeKeyword::None,
3056 Qualifier: SS.getScopeRep(), Decl: TypedefD);
3057 TLB.push<TypedefTypeLoc>(T: ET).set(
3058 /*ElaboratedKeywordLoc=*/SourceLocation(),
3059 QualifierLoc: SS.getWithLocInContext(Context), NameLoc: NameInfo.getLoc());
3060 } else {
3061 // FIXME: What else can appear here?
3062 ET = SemaRef.Context.getTypeDeclType(Decl: TD);
3063 TLB.pushTypeSpec(T: ET).setNameLoc(NameInfo.getLoc());
3064 assert(SS.isEmpty());
3065 }
3066
3067 // Diagnose a missing typename if this resolved unambiguously to a type in
3068 // a dependent context. If we can recover with a type, downgrade this to
3069 // a warning in Microsoft compatibility mode.
3070 unsigned DiagID = diag::err_typename_missing;
3071 if (RecoveryTSI && getLangOpts().MSVCCompat)
3072 DiagID = diag::ext_typename_missing;
3073 SourceLocation Loc = SS.getBeginLoc();
3074 auto D = Diag(Loc, DiagID);
3075 D << ET << SourceRange(Loc, NameInfo.getEndLoc());
3076
3077 // Don't recover if the caller isn't expecting us to or if we're in a SFINAE
3078 // context.
3079 if (!RecoveryTSI)
3080 return ExprError();
3081
3082 // Only issue the fixit if we're prepared to recover.
3083 D << FixItHint::CreateInsertion(InsertionLoc: Loc, Code: "typename ");
3084
3085 // Recover by pretending this was an elaborated type.
3086 *RecoveryTSI = TLB.getTypeSourceInfo(Context, T: ET);
3087
3088 return ExprEmpty();
3089 }
3090
3091 // If necessary, build an implicit class member access.
3092 if (isPotentialImplicitMemberAccess(SS, R, IsAddressOfOperand))
3093 return BuildPossibleImplicitMemberExpr(SS,
3094 /*TemplateKWLoc=*/SourceLocation(),
3095 R, /*TemplateArgs=*/nullptr,
3096 /*S=*/nullptr);
3097
3098 return BuildDeclarationNameExpr(SS, R, /*ADL=*/NeedsADL: false);
3099}
3100
3101ExprResult Sema::PerformObjectMemberConversion(Expr *From,
3102 NestedNameSpecifier Qualifier,
3103 NamedDecl *FoundDecl,
3104 NamedDecl *Member) {
3105 const auto *RD = dyn_cast<CXXRecordDecl>(Val: Member->getDeclContext());
3106 if (!RD)
3107 return From;
3108
3109 QualType DestRecordType;
3110 QualType DestType;
3111 QualType FromRecordType;
3112 QualType FromType = From->getType();
3113 bool PointerConversions = false;
3114 if (isa<FieldDecl>(Val: Member)) {
3115 DestRecordType = Context.getCanonicalTagType(TD: RD);
3116 auto FromPtrType = FromType->getAs<PointerType>();
3117 DestRecordType = Context.getAddrSpaceQualType(
3118 T: DestRecordType, AddressSpace: FromPtrType
3119 ? FromType->getPointeeType().getAddressSpace()
3120 : FromType.getAddressSpace());
3121
3122 if (FromPtrType) {
3123 DestType = Context.getPointerType(T: DestRecordType);
3124 FromRecordType = FromPtrType->getPointeeType();
3125 PointerConversions = true;
3126 } else {
3127 DestType = DestRecordType;
3128 FromRecordType = FromType;
3129 }
3130 } else if (const auto *Method = dyn_cast<CXXMethodDecl>(Val: Member)) {
3131 if (!Method->isImplicitObjectMemberFunction())
3132 return From;
3133
3134 DestType = Method->getThisType().getNonReferenceType();
3135 DestRecordType = Method->getFunctionObjectParameterType();
3136
3137 if (FromType->getAs<PointerType>()) {
3138 FromRecordType = FromType->getPointeeType();
3139 PointerConversions = true;
3140 } else {
3141 FromRecordType = FromType;
3142 DestType = DestRecordType;
3143 }
3144
3145 LangAS FromAS = FromRecordType.getAddressSpace();
3146 LangAS DestAS = DestRecordType.getAddressSpace();
3147 if (FromAS != DestAS) {
3148 QualType FromRecordTypeWithoutAS =
3149 Context.removeAddrSpaceQualType(T: FromRecordType);
3150 QualType FromTypeWithDestAS =
3151 Context.getAddrSpaceQualType(T: FromRecordTypeWithoutAS, AddressSpace: DestAS);
3152 if (PointerConversions)
3153 FromTypeWithDestAS = Context.getPointerType(T: FromTypeWithDestAS);
3154 From = ImpCastExprToType(E: From, Type: FromTypeWithDestAS,
3155 CK: CK_AddressSpaceConversion, VK: From->getValueKind())
3156 .get();
3157 }
3158 } else {
3159 // No conversion necessary.
3160 return From;
3161 }
3162
3163 if (DestType->isDependentType() || FromType->isDependentType())
3164 return From;
3165
3166 // If the unqualified types are the same, no conversion is necessary.
3167 if (Context.hasSameUnqualifiedType(T1: FromRecordType, T2: DestRecordType))
3168 return From;
3169
3170 SourceRange FromRange = From->getSourceRange();
3171 SourceLocation FromLoc = FromRange.getBegin();
3172
3173 ExprValueKind VK = From->getValueKind();
3174
3175 // C++ [class.member.lookup]p8:
3176 // [...] Ambiguities can often be resolved by qualifying a name with its
3177 // class name.
3178 //
3179 // If the member was a qualified name and the qualified referred to a
3180 // specific base subobject type, we'll cast to that intermediate type
3181 // first and then to the object in which the member is declared. That allows
3182 // one to resolve ambiguities in, e.g., a diamond-shaped hierarchy such as:
3183 //
3184 // class Base { public: int x; };
3185 // class Derived1 : public Base { };
3186 // class Derived2 : public Base { };
3187 // class VeryDerived : public Derived1, public Derived2 { void f(); };
3188 //
3189 // void VeryDerived::f() {
3190 // x = 17; // error: ambiguous base subobjects
3191 // Derived1::x = 17; // okay, pick the Base subobject of Derived1
3192 // }
3193 if (Qualifier.getKind() == NestedNameSpecifier::Kind::Type) {
3194 QualType QType = QualType(Qualifier.getAsType(), 0);
3195 assert(QType->isRecordType() && "lookup done with non-record type");
3196
3197 QualType QRecordType = QualType(QType->castAs<RecordType>(), 0);
3198
3199 // In C++98, the qualifier type doesn't actually have to be a base
3200 // type of the object type, in which case we just ignore it.
3201 // Otherwise build the appropriate casts.
3202 if (IsDerivedFrom(Loc: FromLoc, Derived: FromRecordType, Base: QRecordType)) {
3203 CXXCastPath BasePath;
3204 if (CheckDerivedToBaseConversion(Derived: FromRecordType, Base: QRecordType,
3205 Loc: FromLoc, Range: FromRange, BasePath: &BasePath))
3206 return ExprError();
3207
3208 if (PointerConversions)
3209 QType = Context.getPointerType(T: QType);
3210 From = ImpCastExprToType(E: From, Type: QType, CK: CK_UncheckedDerivedToBase,
3211 VK, BasePath: &BasePath).get();
3212
3213 FromType = QType;
3214 FromRecordType = QRecordType;
3215
3216 // If the qualifier type was the same as the destination type,
3217 // we're done.
3218 if (Context.hasSameUnqualifiedType(T1: FromRecordType, T2: DestRecordType))
3219 return From;
3220 }
3221 }
3222
3223 CXXCastPath BasePath;
3224 if (CheckDerivedToBaseConversion(Derived: FromRecordType, Base: DestRecordType,
3225 Loc: FromLoc, Range: FromRange, BasePath: &BasePath,
3226 /*IgnoreAccess=*/true))
3227 return ExprError();
3228
3229 // Propagate qualifiers to base subobjects as per:
3230 // C++ [basic.type.qualifier]p1.2:
3231 // A volatile object is [...] a subobject of a volatile object.
3232 Qualifiers FromTypeQuals = FromType.getQualifiers();
3233 FromTypeQuals.setAddressSpace(DestType.getAddressSpace());
3234 DestType = Context.getQualifiedType(T: DestType, Qs: FromTypeQuals);
3235
3236 return ImpCastExprToType(E: From, Type: DestType, CK: CK_UncheckedDerivedToBase, VK,
3237 BasePath: &BasePath);
3238}
3239
3240bool Sema::UseArgumentDependentLookup(const CXXScopeSpec &SS,
3241 const LookupResult &R,
3242 bool HasTrailingLParen) {
3243 // Only when used directly as the postfix-expression of a call.
3244 if (!HasTrailingLParen)
3245 return false;
3246
3247 // Never if a scope specifier was provided.
3248 if (SS.isNotEmpty())
3249 return false;
3250
3251 // Only in C++ or ObjC++.
3252 if (!getLangOpts().CPlusPlus)
3253 return false;
3254
3255 // Turn off ADL when we find certain kinds of declarations during
3256 // normal lookup:
3257 for (const NamedDecl *D : R) {
3258 // C++0x [basic.lookup.argdep]p3:
3259 // -- a declaration of a class member
3260 // Since using decls preserve this property, we check this on the
3261 // original decl.
3262 if (D->isCXXClassMember())
3263 return false;
3264
3265 // C++0x [basic.lookup.argdep]p3:
3266 // -- a block-scope function declaration that is not a
3267 // using-declaration
3268 // NOTE: we also trigger this for function templates (in fact, we
3269 // don't check the decl type at all, since all other decl types
3270 // turn off ADL anyway).
3271 if (isa<UsingShadowDecl>(Val: D))
3272 D = cast<UsingShadowDecl>(Val: D)->getTargetDecl();
3273 else if (D->getLexicalDeclContext()->isFunctionOrMethod())
3274 return false;
3275
3276 // C++0x [basic.lookup.argdep]p3:
3277 // -- a declaration that is neither a function or a function
3278 // template
3279 // And also for builtin functions.
3280 if (const auto *FDecl = dyn_cast<FunctionDecl>(Val: D)) {
3281 // But also builtin functions.
3282 if (FDecl->getBuiltinID() && FDecl->isImplicit())
3283 return false;
3284 } else if (!isa<FunctionTemplateDecl>(Val: D))
3285 return false;
3286 }
3287
3288 return true;
3289}
3290
3291
3292/// Diagnoses obvious problems with the use of the given declaration
3293/// as an expression. This is only actually called for lookups that
3294/// were not overloaded, and it doesn't promise that the declaration
3295/// will in fact be used.
3296static bool CheckDeclInExpr(Sema &S, SourceLocation Loc, NamedDecl *D,
3297 bool AcceptInvalid) {
3298 if (D->isInvalidDecl() && !AcceptInvalid)
3299 return true;
3300
3301 if (isa<TypedefNameDecl>(Val: D)) {
3302 S.Diag(Loc, DiagID: diag::err_unexpected_typedef) << D->getDeclName();
3303 return true;
3304 }
3305
3306 if (isa<ObjCInterfaceDecl>(Val: D)) {
3307 S.Diag(Loc, DiagID: diag::err_unexpected_interface) << D->getDeclName();
3308 return true;
3309 }
3310
3311 if (isa<NamespaceDecl>(Val: D)) {
3312 S.Diag(Loc, DiagID: diag::err_unexpected_namespace) << D->getDeclName();
3313 return true;
3314 }
3315
3316 return false;
3317}
3318
3319// Certain multiversion types should be treated as overloaded even when there is
3320// only one result.
3321static bool ShouldLookupResultBeMultiVersionOverload(const LookupResult &R) {
3322 assert(R.isSingleResult() && "Expected only a single result");
3323 const auto *FD = dyn_cast<FunctionDecl>(Val: R.getFoundDecl());
3324 return FD &&
3325 (FD->isCPUDispatchMultiVersion() || FD->isCPUSpecificMultiVersion());
3326}
3327
3328ExprResult Sema::BuildDeclarationNameExpr(const CXXScopeSpec &SS,
3329 LookupResult &R, bool NeedsADL,
3330 bool AcceptInvalidDecl) {
3331 // If this is a single, fully-resolved result and we don't need ADL,
3332 // just build an ordinary singleton decl ref.
3333 if (!NeedsADL && R.isSingleResult() &&
3334 !R.getAsSingle<FunctionTemplateDecl>() &&
3335 !ShouldLookupResultBeMultiVersionOverload(R))
3336 return BuildDeclarationNameExpr(SS, NameInfo: R.getLookupNameInfo(), D: R.getFoundDecl(),
3337 FoundD: R.getRepresentativeDecl(), TemplateArgs: nullptr,
3338 AcceptInvalidDecl);
3339
3340 // We only need to check the declaration if there's exactly one
3341 // result, because in the overloaded case the results can only be
3342 // functions and function templates.
3343 if (R.isSingleResult() && !ShouldLookupResultBeMultiVersionOverload(R) &&
3344 CheckDeclInExpr(S&: *this, Loc: R.getNameLoc(), D: R.getFoundDecl(),
3345 AcceptInvalid: AcceptInvalidDecl))
3346 return ExprError();
3347
3348 // Otherwise, just build an unresolved lookup expression. Suppress
3349 // any lookup-related diagnostics; we'll hash these out later, when
3350 // we've picked a target.
3351 R.suppressDiagnostics();
3352
3353 UnresolvedLookupExpr *ULE = UnresolvedLookupExpr::Create(
3354 Context, NamingClass: R.getNamingClass(), QualifierLoc: SS.getWithLocInContext(Context),
3355 NameInfo: R.getLookupNameInfo(), RequiresADL: NeedsADL, Begin: R.begin(), End: R.end(),
3356 /*KnownDependent=*/false, /*KnownInstantiationDependent=*/false);
3357
3358 return ULE;
3359}
3360
3361ExprResult Sema::BuildDeclarationNameExpr(
3362 const CXXScopeSpec &SS, const DeclarationNameInfo &NameInfo, NamedDecl *D,
3363 NamedDecl *FoundD, const TemplateArgumentListInfo *TemplateArgs,
3364 bool AcceptInvalidDecl) {
3365 assert(D && "Cannot refer to a NULL declaration");
3366 assert(!isa<FunctionTemplateDecl>(D) &&
3367 "Cannot refer unambiguously to a function template");
3368
3369 SourceLocation Loc = NameInfo.getLoc();
3370 if (CheckDeclInExpr(S&: *this, Loc, D, AcceptInvalid: AcceptInvalidDecl)) {
3371 // Recovery from invalid cases (e.g. D is an invalid Decl).
3372 // We use the dependent type for the RecoveryExpr to prevent bogus follow-up
3373 // diagnostics, as invalid decls use int as a fallback type.
3374 return CreateRecoveryExpr(Begin: NameInfo.getBeginLoc(), End: NameInfo.getEndLoc(), SubExprs: {});
3375 }
3376
3377 if (TemplateDecl *TD = dyn_cast<TemplateDecl>(Val: D)) {
3378 // Specifically diagnose references to class templates that are missing
3379 // a template argument list.
3380 diagnoseMissingTemplateArguments(SS, /*TemplateKeyword=*/false, TD, Loc);
3381 return ExprError();
3382 }
3383
3384 // Make sure that we're referring to a value.
3385 if (!isa<ValueDecl, UnresolvedUsingIfExistsDecl>(Val: D)) {
3386 Diag(Loc, DiagID: diag::err_ref_non_value) << D << SS.getRange();
3387 Diag(Loc: D->getLocation(), DiagID: diag::note_declared_at);
3388 return ExprError();
3389 }
3390
3391 // Check whether this declaration can be used. Note that we suppress
3392 // this check when we're going to perform argument-dependent lookup
3393 // on this function name, because this might not be the function
3394 // that overload resolution actually selects.
3395 if (DiagnoseUseOfDecl(D, Locs: Loc))
3396 return ExprError();
3397
3398 auto *VD = cast<ValueDecl>(Val: D);
3399
3400 // Only create DeclRefExpr's for valid Decl's.
3401 if (VD->isInvalidDecl() && !AcceptInvalidDecl)
3402 return ExprError();
3403
3404 // Handle members of anonymous structs and unions. If we got here,
3405 // and the reference is to a class member indirect field, then this
3406 // must be the subject of a pointer-to-member expression.
3407 if (auto *IndirectField = dyn_cast<IndirectFieldDecl>(Val: VD);
3408 IndirectField && !IndirectField->isCXXClassMember())
3409 return BuildAnonymousStructUnionMemberReference(SS, nameLoc: NameInfo.getLoc(),
3410 indirectField: IndirectField);
3411
3412 QualType type = VD->getType();
3413 if (type.isNull())
3414 return ExprError();
3415 ExprValueKind valueKind = VK_PRValue;
3416
3417 // In 'T ...V;', the type of the declaration 'V' is 'T...', but the type of
3418 // a reference to 'V' is simply (unexpanded) 'T'. The type, like the value,
3419 // is expanded by some outer '...' in the context of the use.
3420 type = type.getNonPackExpansionType();
3421
3422 switch (D->getKind()) {
3423 // Ignore all the non-ValueDecl kinds.
3424#define ABSTRACT_DECL(kind)
3425#define VALUE(type, base)
3426#define DECL(type, base) case Decl::type:
3427#include "clang/AST/DeclNodes.inc"
3428 llvm_unreachable("invalid value decl kind");
3429
3430 // These shouldn't make it here.
3431 case Decl::ObjCAtDefsField:
3432 llvm_unreachable("forming non-member reference to ivar?");
3433
3434 // Enum constants are always r-values and never references.
3435 // Unresolved using declarations are dependent.
3436 case Decl::EnumConstant:
3437 case Decl::UnresolvedUsingValue:
3438 case Decl::OMPDeclareReduction:
3439 case Decl::OMPDeclareMapper:
3440 valueKind = VK_PRValue;
3441 break;
3442
3443 // Fields and indirect fields that got here must be for
3444 // pointer-to-member expressions; we just call them l-values for
3445 // internal consistency, because this subexpression doesn't really
3446 // exist in the high-level semantics.
3447 case Decl::Field:
3448 case Decl::IndirectField:
3449 case Decl::ObjCIvar:
3450 assert((getLangOpts().CPlusPlus || isAttrContext()) &&
3451 "building reference to field in C?");
3452
3453 // These can't have reference type in well-formed programs, but
3454 // for internal consistency we do this anyway.
3455 type = type.getNonReferenceType();
3456 valueKind = VK_LValue;
3457 break;
3458
3459 // Non-type template parameters are either l-values or r-values
3460 // depending on the type.
3461 case Decl::NonTypeTemplateParm: {
3462 if (const ReferenceType *reftype = type->getAs<ReferenceType>()) {
3463 type = reftype->getPointeeType();
3464 valueKind = VK_LValue; // even if the parameter is an r-value reference
3465 break;
3466 }
3467
3468 // [expr.prim.id.unqual]p2:
3469 // If the entity is a template parameter object for a template
3470 // parameter of type T, the type of the expression is const T.
3471 // [...] The expression is an lvalue if the entity is a [...] template
3472 // parameter object.
3473 if (type->isRecordType()) {
3474 type = type.getUnqualifiedType().withConst();
3475 valueKind = VK_LValue;
3476 break;
3477 }
3478
3479 // For non-references, we need to strip qualifiers just in case
3480 // the template parameter was declared as 'const int' or whatever.
3481 valueKind = VK_PRValue;
3482 type = type.getUnqualifiedType();
3483 break;
3484 }
3485
3486 case Decl::Var:
3487 case Decl::VarTemplateSpecialization:
3488 case Decl::VarTemplatePartialSpecialization:
3489 case Decl::Decomposition:
3490 case Decl::Binding:
3491 case Decl::OMPCapturedExpr:
3492 // In C, "extern void blah;" is valid and is an r-value.
3493 if (!getLangOpts().CPlusPlus && !type.hasQualifiers() &&
3494 type->isVoidType()) {
3495 valueKind = VK_PRValue;
3496 break;
3497 }
3498 [[fallthrough]];
3499
3500 case Decl::ImplicitParam:
3501 case Decl::ParmVar: {
3502 // These are always l-values.
3503 valueKind = VK_LValue;
3504 type = type.getNonReferenceType();
3505
3506 // FIXME: Does the addition of const really only apply in
3507 // potentially-evaluated contexts? Since the variable isn't actually
3508 // captured in an unevaluated context, it seems that the answer is no.
3509 if (!isUnevaluatedContext()) {
3510 QualType CapturedType = getCapturedDeclRefType(Var: cast<ValueDecl>(Val: VD), Loc);
3511 if (!CapturedType.isNull())
3512 type = CapturedType;
3513 }
3514 break;
3515 }
3516
3517 case Decl::Function: {
3518 if (unsigned BID = cast<FunctionDecl>(Val: VD)->getBuiltinID()) {
3519 if (!Context.BuiltinInfo.isDirectlyAddressable(ID: BID)) {
3520 type = Context.BuiltinFnTy;
3521 valueKind = VK_PRValue;
3522 break;
3523 }
3524 }
3525
3526 const FunctionType *fty = type->castAs<FunctionType>();
3527
3528 // If we're referring to a function with an __unknown_anytype
3529 // result type, make the entire expression __unknown_anytype.
3530 if (fty->getReturnType() == Context.UnknownAnyTy) {
3531 type = Context.UnknownAnyTy;
3532 valueKind = VK_PRValue;
3533 break;
3534 }
3535
3536 // Functions are l-values in C++.
3537 if (getLangOpts().CPlusPlus) {
3538 valueKind = VK_LValue;
3539 break;
3540 }
3541
3542 // C99 DR 316 says that, if a function type comes from a
3543 // function definition (without a prototype), that type is only
3544 // used for checking compatibility. Therefore, when referencing
3545 // the function, we pretend that we don't have the full function
3546 // type.
3547 if (!cast<FunctionDecl>(Val: VD)->hasPrototype() && isa<FunctionProtoType>(Val: fty))
3548 type = Context.getFunctionNoProtoType(ResultTy: fty->getReturnType(),
3549 Info: fty->getExtInfo());
3550
3551 // Functions are r-values in C.
3552 valueKind = VK_PRValue;
3553 break;
3554 }
3555
3556 case Decl::CXXDeductionGuide:
3557 llvm_unreachable("building reference to deduction guide");
3558
3559 case Decl::MSProperty:
3560 case Decl::MSGuid:
3561 case Decl::TemplateParamObject:
3562 // FIXME: Should MSGuidDecl and template parameter objects be subject to
3563 // capture in OpenMP, or duplicated between host and device?
3564 valueKind = VK_LValue;
3565 break;
3566
3567 case Decl::UnnamedGlobalConstant:
3568 valueKind = VK_LValue;
3569 break;
3570
3571 case Decl::CXXMethod:
3572 // If we're referring to a method with an __unknown_anytype
3573 // result type, make the entire expression __unknown_anytype.
3574 // This should only be possible with a type written directly.
3575 if (const FunctionProtoType *proto =
3576 dyn_cast<FunctionProtoType>(Val: VD->getType()))
3577 if (proto->getReturnType() == Context.UnknownAnyTy) {
3578 type = Context.UnknownAnyTy;
3579 valueKind = VK_PRValue;
3580 break;
3581 }
3582
3583 // C++ methods are l-values if static, r-values if non-static.
3584 if (cast<CXXMethodDecl>(Val: VD)->isStatic()) {
3585 valueKind = VK_LValue;
3586 break;
3587 }
3588 [[fallthrough]];
3589
3590 case Decl::CXXConversion:
3591 case Decl::CXXDestructor:
3592 case Decl::CXXConstructor:
3593 valueKind = VK_PRValue;
3594 break;
3595 }
3596
3597 auto *E =
3598 BuildDeclRefExpr(D: VD, Ty: type, VK: valueKind, NameInfo, SS: &SS, FoundD,
3599 /*FIXME: TemplateKWLoc*/ TemplateKWLoc: SourceLocation(), TemplateArgs);
3600 // Clang AST consumers assume a DeclRefExpr refers to a valid decl. We
3601 // wrap a DeclRefExpr referring to an invalid decl with a dependent-type
3602 // RecoveryExpr to avoid follow-up semantic analysis (thus prevent bogus
3603 // diagnostics).
3604 if (VD->isInvalidDecl() && E)
3605 return CreateRecoveryExpr(Begin: E->getBeginLoc(), End: E->getEndLoc(), SubExprs: {E});
3606 return E;
3607}
3608
3609static void ConvertUTF8ToWideString(unsigned CharByteWidth, StringRef Source,
3610 SmallString<32> &Target) {
3611 Target.resize(N: CharByteWidth * (Source.size() + 1));
3612 char *ResultPtr = &Target[0];
3613 const llvm::UTF8 *ErrorPtr;
3614 bool success =
3615 llvm::ConvertUTF8toWide(WideCharWidth: CharByteWidth, Source, ResultPtr, ErrorPtr);
3616 (void)success;
3617 assert(success);
3618 Target.resize(N: ResultPtr - &Target[0]);
3619}
3620
3621ExprResult Sema::BuildPredefinedExpr(SourceLocation Loc,
3622 PredefinedIdentKind IK) {
3623 Decl *currentDecl = getPredefinedExprDecl(DC: CurContext);
3624 if (!currentDecl) {
3625 Diag(Loc, DiagID: diag::ext_predef_outside_function);
3626 currentDecl = Context.getTranslationUnitDecl();
3627 }
3628
3629 QualType ResTy;
3630 StringLiteral *SL = nullptr;
3631 if (cast<DeclContext>(Val: currentDecl)->isDependentContext())
3632 ResTy = Context.DependentTy;
3633 else {
3634 // Pre-defined identifiers are of type char[x], where x is the length of
3635 // the string.
3636 bool ForceElaboratedPrinting =
3637 IK == PredefinedIdentKind::Function && getLangOpts().MSVCCompat;
3638 auto Str =
3639 PredefinedExpr::ComputeName(IK, CurrentDecl: currentDecl, ForceElaboratedPrinting);
3640 unsigned Length = Str.length();
3641
3642 llvm::APInt LengthI(32, Length + 1);
3643 if (IK == PredefinedIdentKind::LFunction ||
3644 IK == PredefinedIdentKind::LFuncSig) {
3645 ResTy =
3646 Context.adjustStringLiteralBaseType(StrLTy: Context.WideCharTy.withConst());
3647 SmallString<32> RawChars;
3648 ConvertUTF8ToWideString(CharByteWidth: Context.getTypeSizeInChars(T: ResTy).getQuantity(),
3649 Source: Str, Target&: RawChars);
3650 ResTy = Context.getConstantArrayType(EltTy: ResTy, ArySize: LengthI, SizeExpr: nullptr,
3651 ASM: ArraySizeModifier::Normal,
3652 /*IndexTypeQuals*/ 0);
3653 SL = StringLiteral::Create(Ctx: Context, Str: RawChars, Kind: StringLiteralKind::Wide,
3654 /*Pascal*/ false, Ty: ResTy, Locs: Loc);
3655 } else {
3656 ResTy = Context.adjustStringLiteralBaseType(StrLTy: Context.CharTy.withConst());
3657 ResTy = Context.getConstantArrayType(EltTy: ResTy, ArySize: LengthI, SizeExpr: nullptr,
3658 ASM: ArraySizeModifier::Normal,
3659 /*IndexTypeQuals*/ 0);
3660 SL = StringLiteral::Create(Ctx: Context, Str, Kind: StringLiteralKind::Ordinary,
3661 /*Pascal*/ false, Ty: ResTy, Locs: Loc);
3662 }
3663 }
3664
3665 return PredefinedExpr::Create(Ctx: Context, L: Loc, FNTy: ResTy, IK, IsTransparent: LangOpts.MicrosoftExt,
3666 SL);
3667}
3668
3669ExprResult Sema::ActOnPredefinedExpr(SourceLocation Loc, tok::TokenKind Kind) {
3670 return BuildPredefinedExpr(Loc, IK: getPredefinedExprKind(Kind));
3671}
3672
3673ExprResult Sema::ActOnCharacterConstant(const Token &Tok, Scope *UDLScope) {
3674 SmallString<16> CharBuffer;
3675 bool Invalid = false;
3676 StringRef ThisTok = PP.getSpelling(Tok, Buffer&: CharBuffer, Invalid: &Invalid);
3677 if (Invalid)
3678 return ExprError();
3679
3680 CharLiteralParser Literal(ThisTok.begin(), ThisTok.end(), Tok.getLocation(),
3681 PP, Tok.getKind());
3682 if (Literal.hadError())
3683 return ExprError();
3684
3685 QualType Ty;
3686 if (Literal.isWide())
3687 Ty = Context.WideCharTy; // L'x' -> wchar_t in C and C++.
3688 else if (Literal.isUTF8() && getLangOpts().C23)
3689 Ty = Context.UnsignedCharTy; // u8'x' -> unsigned char in C23
3690 else if (Literal.isUTF8() && getLangOpts().Char8)
3691 Ty = Context.Char8Ty; // u8'x' -> char8_t when it exists.
3692 else if (Literal.isUTF16())
3693 Ty = Context.Char16Ty; // u'x' -> char16_t in C11 and C++11.
3694 else if (Literal.isUTF32())
3695 Ty = Context.Char32Ty; // U'x' -> char32_t in C11 and C++11.
3696 else if (!getLangOpts().CPlusPlus || Literal.isMultiChar())
3697 Ty = Context.IntTy; // 'x' -> int in C, 'wxyz' -> int in C++.
3698 else
3699 Ty = Context.CharTy; // 'x' -> char in C++;
3700 // u8'x' -> char in C11-C17 and in C++ without char8_t.
3701
3702 CharacterLiteralKind Kind = CharacterLiteralKind::Ascii;
3703 if (Literal.isWide())
3704 Kind = CharacterLiteralKind::Wide;
3705 else if (Literal.isUTF16())
3706 Kind = CharacterLiteralKind::UTF16;
3707 else if (Literal.isUTF32())
3708 Kind = CharacterLiteralKind::UTF32;
3709 else if (Literal.isUTF8())
3710 Kind = CharacterLiteralKind::UTF8;
3711
3712 Expr *Lit = new (Context) CharacterLiteral(Literal.getValue(), Kind, Ty,
3713 Tok.getLocation());
3714
3715 if (Literal.getUDSuffix().empty())
3716 return Lit;
3717
3718 // We're building a user-defined literal.
3719 IdentifierInfo *UDSuffix = &Context.Idents.get(Name: Literal.getUDSuffix());
3720 SourceLocation UDSuffixLoc =
3721 getUDSuffixLoc(S&: *this, TokLoc: Tok.getLocation(), Offset: Literal.getUDSuffixOffset());
3722
3723 // Make sure we're allowed user-defined literals here.
3724 if (!UDLScope)
3725 return ExprError(Diag(Loc: UDSuffixLoc, DiagID: diag::err_invalid_character_udl));
3726
3727 // C++11 [lex.ext]p6: The literal L is treated as a call of the form
3728 // operator "" X (ch)
3729 return BuildCookedLiteralOperatorCall(S&: *this, Scope: UDLScope, UDSuffix, UDSuffixLoc,
3730 Args: Lit, LitEndLoc: Tok.getLocation());
3731}
3732
3733ExprResult Sema::ActOnIntegerConstant(SourceLocation Loc, int64_t Val) {
3734 unsigned IntSize = Context.getTargetInfo().getIntWidth();
3735 return IntegerLiteral::Create(C: Context,
3736 V: llvm::APInt(IntSize, Val, /*isSigned=*/true),
3737 type: Context.IntTy, l: Loc);
3738}
3739
3740static Expr *BuildFloatingLiteral(Sema &S, NumericLiteralParser &Literal,
3741 QualType Ty, SourceLocation Loc) {
3742 const llvm::fltSemantics &Format = S.Context.getFloatTypeSemantics(T: Ty);
3743
3744 using llvm::APFloat;
3745 APFloat Val(Format);
3746
3747 llvm::RoundingMode RM = S.CurFPFeatures.getRoundingMode();
3748 if (RM == llvm::RoundingMode::Dynamic)
3749 RM = llvm::RoundingMode::NearestTiesToEven;
3750 APFloat::opStatus result = Literal.GetFloatValue(Result&: Val, RM);
3751
3752 // Overflow is always an error, but underflow is only an error if
3753 // we underflowed to zero (APFloat reports denormals as underflow).
3754 if ((result & APFloat::opOverflow) ||
3755 ((result & APFloat::opUnderflow) && Val.isZero())) {
3756 unsigned diagnostic;
3757 SmallString<20> buffer;
3758 if (result & APFloat::opOverflow) {
3759 diagnostic = diag::warn_float_overflow;
3760 APFloat::getLargest(Sem: Format).toString(Str&: buffer);
3761 } else {
3762 diagnostic = diag::warn_float_underflow;
3763 APFloat::getSmallest(Sem: Format).toString(Str&: buffer);
3764 }
3765
3766 S.Diag(Loc, DiagID: diagnostic) << Ty << buffer.str();
3767 }
3768
3769 bool isExact = (result == APFloat::opOK);
3770 return FloatingLiteral::Create(C: S.Context, V: Val, isexact: isExact, Type: Ty, L: Loc);
3771}
3772
3773bool Sema::CheckLoopHintExpr(Expr *E, SourceLocation Loc, bool AllowZero) {
3774 assert(E && "Invalid expression");
3775
3776 if (E->isValueDependent())
3777 return false;
3778
3779 QualType QT = E->getType();
3780 if (!QT->isIntegerType() || QT->isBooleanType() || QT->isCharType()) {
3781 Diag(Loc: E->getExprLoc(), DiagID: diag::err_pragma_loop_invalid_argument_type) << QT;
3782 return true;
3783 }
3784
3785 llvm::APSInt ValueAPS;
3786 ExprResult R = VerifyIntegerConstantExpression(E, Result: &ValueAPS);
3787
3788 if (R.isInvalid())
3789 return true;
3790
3791 // GCC allows the value of unroll count to be 0.
3792 // https://gcc.gnu.org/onlinedocs/gcc/Loop-Specific-Pragmas.html says
3793 // "The values of 0 and 1 block any unrolling of the loop."
3794 // The values doesn't have to be strictly positive in '#pragma GCC unroll' and
3795 // '#pragma unroll' cases.
3796 bool ValueIsPositive =
3797 AllowZero ? ValueAPS.isNonNegative() : ValueAPS.isStrictlyPositive();
3798 if (!ValueIsPositive || ValueAPS.getActiveBits() > 31) {
3799 Diag(Loc: E->getExprLoc(), DiagID: diag::err_requires_positive_value)
3800 << toString(I: ValueAPS, Radix: 10) << ValueIsPositive;
3801 return true;
3802 }
3803
3804 return false;
3805}
3806
3807ExprResult Sema::ActOnNumericConstant(const Token &Tok, Scope *UDLScope) {
3808 // Fast path for a single digit (which is quite common). A single digit
3809 // cannot have a trigraph, escaped newline, radix prefix, or suffix.
3810 if (Tok.getLength() == 1 || Tok.getKind() == tok::binary_data) {
3811 const uint8_t Val = PP.getSpellingOfSingleCharacterNumericConstant(Tok);
3812 return ActOnIntegerConstant(Loc: Tok.getLocation(), Val);
3813 }
3814
3815 SmallString<128> SpellingBuffer;
3816 // NumericLiteralParser wants to overread by one character. Add padding to
3817 // the buffer in case the token is copied to the buffer. If getSpelling()
3818 // returns a StringRef to the memory buffer, it should have a null char at
3819 // the EOF, so it is also safe.
3820 SpellingBuffer.resize(N: Tok.getLength() + 1);
3821
3822 // Get the spelling of the token, which eliminates trigraphs, etc.
3823 bool Invalid = false;
3824 StringRef TokSpelling = PP.getSpelling(Tok, Buffer&: SpellingBuffer, Invalid: &Invalid);
3825 if (Invalid)
3826 return ExprError();
3827
3828 NumericLiteralParser Literal(TokSpelling, Tok.getLocation(),
3829 PP.getSourceManager(), PP.getLangOpts(),
3830 PP.getTargetInfo(), PP.getDiagnostics());
3831 if (Literal.hadError)
3832 return ExprError();
3833
3834 if (Literal.hasUDSuffix()) {
3835 // We're building a user-defined literal.
3836 const IdentifierInfo *UDSuffix = &Context.Idents.get(Name: Literal.getUDSuffix());
3837 SourceLocation UDSuffixLoc =
3838 getUDSuffixLoc(S&: *this, TokLoc: Tok.getLocation(), Offset: Literal.getUDSuffixOffset());
3839
3840 // Make sure we're allowed user-defined literals here.
3841 if (!UDLScope)
3842 return ExprError(Diag(Loc: UDSuffixLoc, DiagID: diag::err_invalid_numeric_udl));
3843
3844 QualType CookedTy;
3845 if (Literal.isFloatingLiteral()) {
3846 // C++11 [lex.ext]p4: If S contains a literal operator with parameter type
3847 // long double, the literal is treated as a call of the form
3848 // operator "" X (f L)
3849 CookedTy = Context.LongDoubleTy;
3850 } else {
3851 // C++11 [lex.ext]p3: If S contains a literal operator with parameter type
3852 // unsigned long long, the literal is treated as a call of the form
3853 // operator "" X (n ULL)
3854 CookedTy = Context.UnsignedLongLongTy;
3855 }
3856
3857 DeclarationName OpName =
3858 Context.DeclarationNames.getCXXLiteralOperatorName(II: UDSuffix);
3859 DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc);
3860 OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc);
3861
3862 SourceLocation TokLoc = Tok.getLocation();
3863
3864 // Perform literal operator lookup to determine if we're building a raw
3865 // literal or a cooked one.
3866 LookupResult R(*this, OpName, UDSuffixLoc, LookupOrdinaryName);
3867 switch (LookupLiteralOperator(S: UDLScope, R, ArgTys: CookedTy,
3868 /*AllowRaw*/ true, /*AllowTemplate*/ true,
3869 /*AllowStringTemplatePack*/ AllowStringTemplate: false,
3870 /*DiagnoseMissing*/ !Literal.isImaginary)) {
3871 case LOLR_ErrorNoDiagnostic:
3872 // Lookup failure for imaginary constants isn't fatal, there's still the
3873 // GNU extension producing _Complex types.
3874 break;
3875 case LOLR_Error:
3876 return ExprError();
3877 case LOLR_Cooked: {
3878 Expr *Lit;
3879 if (Literal.isFloatingLiteral()) {
3880 Lit = BuildFloatingLiteral(S&: *this, Literal, Ty: CookedTy, Loc: Tok.getLocation());
3881 } else {
3882 llvm::APInt ResultVal(Context.getTargetInfo().getLongLongWidth(), 0);
3883 if (Literal.GetIntegerValue(Val&: ResultVal))
3884 Diag(Loc: Tok.getLocation(), DiagID: diag::err_integer_literal_too_large)
3885 << /* Unsigned */ 1;
3886 Lit = IntegerLiteral::Create(C: Context, V: ResultVal, type: CookedTy,
3887 l: Tok.getLocation());
3888 }
3889 return BuildLiteralOperatorCall(R, SuffixInfo&: OpNameInfo, Args: Lit, LitEndLoc: TokLoc);
3890 }
3891
3892 case LOLR_Raw: {
3893 // C++11 [lit.ext]p3, p4: If S contains a raw literal operator, the
3894 // literal is treated as a call of the form
3895 // operator "" X ("n")
3896 unsigned Length = Literal.getUDSuffixOffset();
3897 QualType StrTy = Context.getConstantArrayType(
3898 EltTy: Context.adjustStringLiteralBaseType(StrLTy: Context.CharTy.withConst()),
3899 ArySize: llvm::APInt(32, Length + 1), SizeExpr: nullptr, ASM: ArraySizeModifier::Normal, IndexTypeQuals: 0);
3900 Expr *Lit =
3901 StringLiteral::Create(Ctx: Context, Str: StringRef(TokSpelling.data(), Length),
3902 Kind: StringLiteralKind::Ordinary,
3903 /*Pascal*/ false, Ty: StrTy, Locs: TokLoc);
3904 return BuildLiteralOperatorCall(R, SuffixInfo&: OpNameInfo, Args: Lit, LitEndLoc: TokLoc);
3905 }
3906
3907 case LOLR_Template: {
3908 // C++11 [lit.ext]p3, p4: Otherwise (S contains a literal operator
3909 // template), L is treated as a call fo the form
3910 // operator "" X <'c1', 'c2', ... 'ck'>()
3911 // where n is the source character sequence c1 c2 ... ck.
3912 TemplateArgumentListInfo ExplicitArgs;
3913 unsigned CharBits = Context.getIntWidth(T: Context.CharTy);
3914 bool CharIsUnsigned = Context.CharTy->isUnsignedIntegerType();
3915 llvm::APSInt Value(CharBits, CharIsUnsigned);
3916 for (unsigned I = 0, N = Literal.getUDSuffixOffset(); I != N; ++I) {
3917 Value = TokSpelling[I];
3918 TemplateArgument Arg(Context, Value, Context.CharTy);
3919 TemplateArgumentLocInfo ArgInfo(Context, TokLoc.getLocWithOffset(Offset: I));
3920 ExplicitArgs.addArgument(Loc: TemplateArgumentLoc(Arg, ArgInfo));
3921 }
3922 return BuildLiteralOperatorCall(R, SuffixInfo&: OpNameInfo, Args: {}, LitEndLoc: TokLoc, ExplicitTemplateArgs: &ExplicitArgs);
3923 }
3924 case LOLR_StringTemplatePack:
3925 llvm_unreachable("unexpected literal operator lookup result");
3926 }
3927 }
3928
3929 Expr *Res;
3930
3931 if (Literal.isFixedPointLiteral()) {
3932 QualType Ty;
3933
3934 if (Literal.isAccum) {
3935 if (Literal.isHalf) {
3936 Ty = Context.ShortAccumTy;
3937 } else if (Literal.isLong) {
3938 Ty = Context.LongAccumTy;
3939 } else {
3940 Ty = Context.AccumTy;
3941 }
3942 } else if (Literal.isFract) {
3943 if (Literal.isHalf) {
3944 Ty = Context.ShortFractTy;
3945 } else if (Literal.isLong) {
3946 Ty = Context.LongFractTy;
3947 } else {
3948 Ty = Context.FractTy;
3949 }
3950 }
3951
3952 if (Literal.isUnsigned) Ty = Context.getCorrespondingUnsignedType(T: Ty);
3953
3954 bool isSigned = !Literal.isUnsigned;
3955 unsigned scale = Context.getFixedPointScale(Ty);
3956 unsigned bit_width = Context.getTypeInfo(T: Ty).Width;
3957
3958 llvm::APInt Val(bit_width, 0, isSigned);
3959 bool Overflowed = Literal.GetFixedPointValue(StoreVal&: Val, Scale: scale);
3960 bool ValIsZero = Val.isZero() && !Overflowed;
3961
3962 auto MaxVal = Context.getFixedPointMax(Ty).getValue();
3963 if (Literal.isFract && Val == MaxVal + 1 && !ValIsZero)
3964 // Clause 6.4.4 - The value of a constant shall be in the range of
3965 // representable values for its type, with exception for constants of a
3966 // fract type with a value of exactly 1; such a constant shall denote
3967 // the maximal value for the type.
3968 --Val;
3969 else if (Val.ugt(RHS: MaxVal) || Overflowed)
3970 Diag(Loc: Tok.getLocation(), DiagID: diag::err_too_large_for_fixed_point);
3971
3972 Res = FixedPointLiteral::CreateFromRawInt(C: Context, V: Val, type: Ty,
3973 l: Tok.getLocation(), Scale: scale);
3974 } else if (Literal.isFloatingLiteral()) {
3975 QualType Ty;
3976 if (Literal.isHalf){
3977 if (getLangOpts().HLSL ||
3978 getOpenCLOptions().isAvailableOption(Ext: "cl_khr_fp16", LO: getLangOpts()))
3979 Ty = Context.HalfTy;
3980 else {
3981 Diag(Loc: Tok.getLocation(), DiagID: diag::err_half_const_requires_fp16);
3982 return ExprError();
3983 }
3984 } else if (Literal.isFloat)
3985 Ty = Context.FloatTy;
3986 else if (Literal.isLong)
3987 Ty = !getLangOpts().HLSL ? Context.LongDoubleTy : Context.DoubleTy;
3988 else if (Literal.isFloat16)
3989 Ty = Context.Float16Ty;
3990 else if (Literal.isFloat128)
3991 Ty = Context.Float128Ty;
3992 else if (getLangOpts().HLSL)
3993 Ty = Context.FloatTy;
3994 else
3995 Ty = Context.DoubleTy;
3996
3997 Res = BuildFloatingLiteral(S&: *this, Literal, Ty, Loc: Tok.getLocation());
3998
3999 if (Ty == Context.DoubleTy) {
4000 if (getLangOpts().SinglePrecisionConstants) {
4001 if (Ty->castAs<BuiltinType>()->getKind() != BuiltinType::Float) {
4002 Res = ImpCastExprToType(E: Res, Type: Context.FloatTy, CK: CK_FloatingCast).get();
4003 }
4004 } else if (getLangOpts().OpenCL && !getOpenCLOptions().isAvailableOption(
4005 Ext: "cl_khr_fp64", LO: getLangOpts())) {
4006 // Impose single-precision float type when cl_khr_fp64 is not enabled.
4007 Diag(Loc: Tok.getLocation(), DiagID: diag::warn_double_const_requires_fp64)
4008 << (getLangOpts().getOpenCLCompatibleVersion() >= 300);
4009 Res = ImpCastExprToType(E: Res, Type: Context.FloatTy, CK: CK_FloatingCast).get();
4010 }
4011 }
4012 } else if (!Literal.isIntegerLiteral()) {
4013 return ExprError();
4014 } else {
4015 QualType Ty;
4016
4017 // 'z/uz' literals are a C++23 feature.
4018 if (Literal.isSizeT)
4019 Diag(Loc: Tok.getLocation(), DiagID: getLangOpts().CPlusPlus
4020 ? getLangOpts().CPlusPlus23
4021 ? diag::warn_cxx20_compat_size_t_suffix
4022 : diag::ext_cxx23_size_t_suffix
4023 : diag::err_cxx23_size_t_suffix);
4024
4025 // 'wb/uwb' literals are a C23 feature. We support _BitInt as a type in C++,
4026 // but we do not currently support the suffix in C++ mode because it's not
4027 // entirely clear whether WG21 will prefer this suffix to return a library
4028 // type such as std::bit_int instead of returning a _BitInt. '__wb/__uwb'
4029 // literals are a C++ extension.
4030 if (Literal.isBitInt)
4031 PP.Diag(Loc: Tok.getLocation(),
4032 DiagID: getLangOpts().CPlusPlus ? diag::ext_cxx_bitint_suffix
4033 : getLangOpts().C23 ? diag::warn_c23_compat_bitint_suffix
4034 : diag::ext_c23_bitint_suffix);
4035
4036 // Get the value in the widest-possible width. What is "widest" depends on
4037 // whether the literal is a bit-precise integer or not. For a bit-precise
4038 // integer type, try to scan the source to determine how many bits are
4039 // needed to represent the value. This may seem a bit expensive, but trying
4040 // to get the integer value from an overly-wide APInt is *extremely*
4041 // expensive, so the naive approach of assuming
4042 // llvm::IntegerType::MAX_INT_BITS is a big performance hit.
4043 unsigned BitsNeeded = Context.getTargetInfo().getIntMaxTWidth();
4044 if (Literal.isBitInt)
4045 BitsNeeded = llvm::APInt::getSufficientBitsNeeded(
4046 Str: Literal.getLiteralDigits(), Radix: Literal.getRadix());
4047 if (Literal.MicrosoftInteger) {
4048 if (Literal.MicrosoftInteger == 128 &&
4049 !Context.getTargetInfo().hasInt128Type())
4050 PP.Diag(Loc: Tok.getLocation(), DiagID: diag::err_integer_literal_too_large)
4051 << Literal.isUnsigned;
4052 BitsNeeded = Literal.MicrosoftInteger;
4053 }
4054
4055 llvm::APInt ResultVal(BitsNeeded, 0);
4056
4057 if (Literal.GetIntegerValue(Val&: ResultVal)) {
4058 // If this value didn't fit into uintmax_t, error and force to ull.
4059 Diag(Loc: Tok.getLocation(), DiagID: diag::err_integer_literal_too_large)
4060 << /* Unsigned */ 1;
4061 Ty = Context.UnsignedLongLongTy;
4062 assert(Context.getTypeSize(Ty) == ResultVal.getBitWidth() &&
4063 "long long is not intmax_t?");
4064 } else {
4065 // If this value fits into a ULL, try to figure out what else it fits into
4066 // according to the rules of C99 6.4.4.1p5.
4067
4068 // Octal, Hexadecimal, and integers with a U suffix are allowed to
4069 // be an unsigned int.
4070 bool AllowUnsigned = Literal.isUnsigned || Literal.getRadix() != 10;
4071
4072 // HLSL doesn't really have `long` or `long long`. We support the `ll`
4073 // suffix for portability of code with C++, but both `l` and `ll` are
4074 // 64-bit integer types, and we want the type of `1l` and `1ll` to be the
4075 // same.
4076 if (getLangOpts().HLSL && !Literal.isLong && Literal.isLongLong) {
4077 Literal.isLong = true;
4078 Literal.isLongLong = false;
4079 }
4080
4081 // Check from smallest to largest, picking the smallest type we can.
4082 unsigned Width = 0;
4083
4084 // Microsoft specific integer suffixes are explicitly sized.
4085 if (Literal.MicrosoftInteger) {
4086 if (Literal.MicrosoftInteger == 8 && !Literal.isUnsigned) {
4087 Width = 8;
4088 Ty = Context.CharTy;
4089 } else {
4090 Width = Literal.MicrosoftInteger;
4091 Ty = Context.getIntTypeForBitwidth(DestWidth: Width,
4092 /*Signed=*/!Literal.isUnsigned);
4093 }
4094 }
4095
4096 // Bit-precise integer literals are automagically-sized based on the
4097 // width required by the literal.
4098 if (Literal.isBitInt) {
4099 // The signed version has one more bit for the sign value. There are no
4100 // zero-width bit-precise integers, even if the literal value is 0.
4101 Width = std::max(a: ResultVal.getActiveBits(), b: 1u) +
4102 (Literal.isUnsigned ? 0u : 1u);
4103
4104 // Diagnose if the width of the constant is larger than BITINT_MAXWIDTH,
4105 // and reset the type to the largest supported width.
4106 unsigned int MaxBitIntWidth =
4107 Context.getTargetInfo().getMaxBitIntWidth();
4108 if (Width > MaxBitIntWidth) {
4109 Diag(Loc: Tok.getLocation(), DiagID: diag::err_integer_literal_too_large)
4110 << Literal.isUnsigned;
4111 Width = MaxBitIntWidth;
4112 }
4113
4114 // Reset the result value to the smaller APInt and select the correct
4115 // type to be used. Note, we zext even for signed values because the
4116 // literal itself is always an unsigned value (a preceeding - is a
4117 // unary operator, not part of the literal).
4118 ResultVal = ResultVal.zextOrTrunc(width: Width);
4119 Ty = Context.getBitIntType(Unsigned: Literal.isUnsigned, NumBits: Width);
4120 }
4121
4122 // Check C++23 size_t literals.
4123 if (Literal.isSizeT) {
4124 assert(!Literal.MicrosoftInteger &&
4125 "size_t literals can't be Microsoft literals");
4126 unsigned SizeTSize = Context.getTargetInfo().getTypeWidth(
4127 T: Context.getTargetInfo().getSizeType());
4128
4129 // Does it fit in size_t?
4130 if (ResultVal.isIntN(N: SizeTSize)) {
4131 // Does it fit in ssize_t?
4132 if (!Literal.isUnsigned && ResultVal[SizeTSize - 1] == 0)
4133 Ty = Context.getSignedSizeType();
4134 else if (AllowUnsigned)
4135 Ty = Context.getSizeType();
4136 Width = SizeTSize;
4137 }
4138 }
4139
4140 if (Ty.isNull() && !Literal.isLong && !Literal.isLongLong &&
4141 !Literal.isSizeT) {
4142 // Are int/unsigned possibilities?
4143 unsigned IntSize = Context.getTargetInfo().getIntWidth();
4144
4145 // Does it fit in a unsigned int?
4146 if (ResultVal.isIntN(N: IntSize)) {
4147 // Does it fit in a signed int?
4148 if (!Literal.isUnsigned && ResultVal[IntSize-1] == 0)
4149 Ty = Context.IntTy;
4150 else if (AllowUnsigned)
4151 Ty = Context.UnsignedIntTy;
4152 Width = IntSize;
4153 }
4154 }
4155
4156 // Are long/unsigned long possibilities?
4157 if (Ty.isNull() && !Literal.isLongLong && !Literal.isSizeT) {
4158 unsigned LongSize = Context.getTargetInfo().getLongWidth();
4159
4160 // Does it fit in a unsigned long?
4161 if (ResultVal.isIntN(N: LongSize)) {
4162 // Does it fit in a signed long?
4163 if (!Literal.isUnsigned && ResultVal[LongSize-1] == 0)
4164 Ty = Context.LongTy;
4165 else if (AllowUnsigned)
4166 Ty = Context.UnsignedLongTy;
4167 // Check according to the rules of C90 6.1.3.2p5. C++03 [lex.icon]p2
4168 // is compatible.
4169 else if (!getLangOpts().C99 && !getLangOpts().CPlusPlus11) {
4170 const unsigned LongLongSize =
4171 Context.getTargetInfo().getLongLongWidth();
4172 Diag(Loc: Tok.getLocation(),
4173 DiagID: getLangOpts().CPlusPlus
4174 ? Literal.isLong
4175 ? diag::warn_old_implicitly_unsigned_long_cxx
4176 : /*C++98 UB*/ diag::
4177 ext_old_implicitly_unsigned_long_cxx
4178 : diag::warn_old_implicitly_unsigned_long)
4179 << (LongLongSize > LongSize ? /*will have type 'long long'*/ 0
4180 : /*will be ill-formed*/ 1);
4181 Ty = Context.UnsignedLongTy;
4182 }
4183 Width = LongSize;
4184 }
4185 }
4186
4187 // Check long long if needed.
4188 if (Ty.isNull() && !Literal.isSizeT) {
4189 unsigned LongLongSize = Context.getTargetInfo().getLongLongWidth();
4190
4191 // Does it fit in a unsigned long long?
4192 if (ResultVal.isIntN(N: LongLongSize)) {
4193 // Does it fit in a signed long long?
4194 // To be compatible with MSVC, hex integer literals ending with the
4195 // LL or i64 suffix are always signed in Microsoft mode.
4196 if (!Literal.isUnsigned && (ResultVal[LongLongSize-1] == 0 ||
4197 (getLangOpts().MSVCCompat && Literal.isLongLong)))
4198 Ty = Context.LongLongTy;
4199 else if (AllowUnsigned)
4200 Ty = Context.UnsignedLongLongTy;
4201 Width = LongLongSize;
4202
4203 // 'long long' is a C99 or C++11 feature, whether the literal
4204 // explicitly specified 'long long' or we needed the extra width.
4205 if (getLangOpts().CPlusPlus)
4206 Diag(Loc: Tok.getLocation(), DiagID: getLangOpts().CPlusPlus11
4207 ? diag::warn_cxx98_compat_longlong
4208 : diag::ext_cxx11_longlong);
4209 else if (!getLangOpts().C99)
4210 Diag(Loc: Tok.getLocation(), DiagID: diag::ext_c99_longlong);
4211 }
4212 }
4213
4214 // If we still couldn't decide a type, we either have 'size_t' literal
4215 // that is out of range, or a decimal literal that does not fit in a
4216 // signed long long and has no U suffix.
4217 if (Ty.isNull()) {
4218 if (Literal.isSizeT)
4219 Diag(Loc: Tok.getLocation(), DiagID: diag::err_size_t_literal_too_large)
4220 << Literal.isUnsigned;
4221 else
4222 Diag(Loc: Tok.getLocation(),
4223 DiagID: diag::ext_integer_literal_too_large_for_signed);
4224 Ty = Context.UnsignedLongLongTy;
4225 Width = Context.getTargetInfo().getLongLongWidth();
4226 }
4227
4228 if (ResultVal.getBitWidth() != Width)
4229 ResultVal = ResultVal.trunc(width: Width);
4230 }
4231 Res = IntegerLiteral::Create(C: Context, V: ResultVal, type: Ty, l: Tok.getLocation());
4232 }
4233
4234 // If this is an imaginary literal, create the ImaginaryLiteral wrapper.
4235 if (Literal.isImaginary) {
4236 Res = new (Context) ImaginaryLiteral(Res,
4237 Context.getComplexType(T: Res->getType()));
4238
4239 // In C++, this is a GNU extension. In C, it's a C2y extension.
4240 unsigned DiagId;
4241 if (getLangOpts().CPlusPlus)
4242 DiagId = diag::ext_gnu_imaginary_constant;
4243 else if (getLangOpts().C2y)
4244 DiagId = diag::warn_c23_compat_imaginary_constant;
4245 else
4246 DiagId = diag::ext_c2y_imaginary_constant;
4247 Diag(Loc: Tok.getLocation(), DiagID: DiagId);
4248 }
4249 return Res;
4250}
4251
4252ExprResult Sema::ActOnParenExpr(SourceLocation L, SourceLocation R, Expr *E) {
4253 assert(E && "ActOnParenExpr() missing expr");
4254 QualType ExprTy = E->getType();
4255 if (getLangOpts().ProtectParens && CurFPFeatures.getAllowFPReassociate() &&
4256 !E->isLValue() && ExprTy->hasFloatingRepresentation())
4257 return BuildBuiltinCallExpr(Loc: R, Id: Builtin::BI__arithmetic_fence, CallArgs: E);
4258 return new (Context) ParenExpr(L, R, E);
4259}
4260
4261static bool CheckVecStepTraitOperandType(Sema &S, QualType T,
4262 SourceLocation Loc,
4263 SourceRange ArgRange) {
4264 // [OpenCL 1.1 6.11.12] "The vec_step built-in function takes a built-in
4265 // scalar or vector data type argument..."
4266 // Every built-in scalar type (OpenCL 1.1 6.1.1) is either an arithmetic
4267 // type (C99 6.2.5p18) or void.
4268 if (!(T->isArithmeticType() || T->isVoidType() || T->isVectorType())) {
4269 S.Diag(Loc, DiagID: diag::err_vecstep_non_scalar_vector_type)
4270 << T << ArgRange;
4271 return true;
4272 }
4273
4274 assert((T->isVoidType() || !T->isIncompleteType()) &&
4275 "Scalar types should always be complete");
4276 return false;
4277}
4278
4279static bool CheckVectorElementsTraitOperandType(Sema &S, QualType T,
4280 SourceLocation Loc,
4281 SourceRange ArgRange) {
4282 // builtin_vectorelements supports both fixed-sized and scalable vectors.
4283 if (!T->isVectorType() && !T->isSizelessVectorType())
4284 return S.Diag(Loc, DiagID: diag::err_builtin_non_vector_type)
4285 << ""
4286 << "__builtin_vectorelements" << T << ArgRange;
4287
4288 if (auto *FD = dyn_cast<FunctionDecl>(Val: S.CurContext)) {
4289 if (T->isSVESizelessBuiltinType()) {
4290 llvm::StringMap<bool> CallerFeatureMap;
4291 S.Context.getFunctionFeatureMap(FeatureMap&: CallerFeatureMap, FD);
4292 return S.ARM().checkSVETypeSupport(Ty: T, Loc, FD, FeatureMap: CallerFeatureMap);
4293 }
4294 }
4295
4296 return false;
4297}
4298
4299static bool checkPtrAuthTypeDiscriminatorOperandType(Sema &S, QualType T,
4300 SourceLocation Loc,
4301 SourceRange ArgRange) {
4302 if (S.checkPointerAuthEnabled(Loc, Range: ArgRange))
4303 return true;
4304
4305 if (!T->isFunctionType() && !T->isFunctionPointerType() &&
4306 !T->isFunctionReferenceType() && !T->isMemberFunctionPointerType()) {
4307 S.Diag(Loc, DiagID: diag::err_ptrauth_type_disc_undiscriminated) << T << ArgRange;
4308 return true;
4309 }
4310
4311 return false;
4312}
4313
4314static bool CheckExtensionTraitOperandType(Sema &S, QualType T,
4315 SourceLocation Loc,
4316 SourceRange ArgRange,
4317 UnaryExprOrTypeTrait TraitKind) {
4318 // Invalid types must be hard errors for SFINAE in C++.
4319 if (S.LangOpts.CPlusPlus)
4320 return true;
4321
4322 // C99 6.5.3.4p1:
4323 if (TraitKind == UETT_SizeOf || TraitKind == UETT_AlignOf ||
4324 TraitKind == UETT_PreferredAlignOf) {
4325
4326 // sizeof(function)/alignof(function) is allowed as an extension.
4327 if (T->isFunctionType()) {
4328 S.Diag(Loc, DiagID: diag::ext_sizeof_alignof_function_type)
4329 << getTraitSpelling(T: TraitKind) << ArgRange;
4330 return false;
4331 }
4332
4333 // Allow sizeof(void)/alignof(void) as an extension, unless in OpenCL where
4334 // this is an error (OpenCL v1.1 s6.3.k)
4335 if (T->isVoidType()) {
4336 unsigned DiagID = S.LangOpts.OpenCL ? diag::err_opencl_sizeof_alignof_type
4337 : diag::ext_sizeof_alignof_void_type;
4338 S.Diag(Loc, DiagID) << getTraitSpelling(T: TraitKind) << ArgRange;
4339 return false;
4340 }
4341 }
4342 return true;
4343}
4344
4345static bool CheckObjCTraitOperandConstraints(Sema &S, QualType T,
4346 SourceLocation Loc,
4347 SourceRange ArgRange,
4348 UnaryExprOrTypeTrait TraitKind) {
4349 // Reject sizeof(interface) and sizeof(interface<proto>) if the
4350 // runtime doesn't allow it.
4351 if (!S.LangOpts.ObjCRuntime.allowsSizeofAlignof() && T->isObjCObjectType()) {
4352 S.Diag(Loc, DiagID: diag::err_sizeof_nonfragile_interface)
4353 << T << (TraitKind == UETT_SizeOf)
4354 << ArgRange;
4355 return true;
4356 }
4357
4358 return false;
4359}
4360
4361/// Check whether E is a pointer from a decayed array type (the decayed
4362/// pointer type is equal to T) and emit a warning if it is.
4363static void warnOnSizeofOnArrayDecay(Sema &S, SourceLocation Loc, QualType T,
4364 const Expr *E) {
4365 // Don't warn if the operation changed the type.
4366 if (T != E->getType())
4367 return;
4368
4369 // Now look for array decays.
4370 const auto *ICE = dyn_cast<ImplicitCastExpr>(Val: E);
4371 if (!ICE || ICE->getCastKind() != CK_ArrayToPointerDecay)
4372 return;
4373
4374 S.Diag(Loc, DiagID: diag::warn_sizeof_array_decay) << ICE->getSourceRange()
4375 << ICE->getType()
4376 << ICE->getSubExpr()->getType();
4377}
4378
4379bool Sema::CheckUnaryExprOrTypeTraitOperand(Expr *E,
4380 UnaryExprOrTypeTrait ExprKind) {
4381 QualType ExprTy = E->getType();
4382 assert(!ExprTy->isReferenceType());
4383
4384 bool IsUnevaluatedOperand =
4385 (ExprKind == UETT_SizeOf || ExprKind == UETT_DataSizeOf ||
4386 ExprKind == UETT_AlignOf || ExprKind == UETT_PreferredAlignOf ||
4387 ExprKind == UETT_VecStep || ExprKind == UETT_CountOf);
4388 if (IsUnevaluatedOperand) {
4389 ExprResult Result = CheckUnevaluatedOperand(E);
4390 if (Result.isInvalid())
4391 return true;
4392 E = Result.get();
4393 }
4394
4395 // The operand for sizeof and alignof is in an unevaluated expression context,
4396 // so side effects could result in unintended consequences.
4397 // Exclude instantiation-dependent expressions, because 'sizeof' is sometimes
4398 // used to build SFINAE gadgets.
4399 // FIXME: Should we consider instantiation-dependent operands to 'alignof'?
4400 if (IsUnevaluatedOperand && !inTemplateInstantiation() &&
4401 !E->isInstantiationDependent() &&
4402 !E->getType()->isVariableArrayType() &&
4403 E->HasSideEffects(Ctx: Context, IncludePossibleEffects: false))
4404 Diag(Loc: E->getExprLoc(), DiagID: diag::warn_side_effects_unevaluated_context);
4405
4406 if (ExprKind == UETT_VecStep)
4407 return CheckVecStepTraitOperandType(S&: *this, T: ExprTy, Loc: E->getExprLoc(),
4408 ArgRange: E->getSourceRange());
4409
4410 if (ExprKind == UETT_VectorElements)
4411 return CheckVectorElementsTraitOperandType(S&: *this, T: ExprTy, Loc: E->getExprLoc(),
4412 ArgRange: E->getSourceRange());
4413
4414 // Explicitly list some types as extensions.
4415 if (!CheckExtensionTraitOperandType(S&: *this, T: ExprTy, Loc: E->getExprLoc(),
4416 ArgRange: E->getSourceRange(), TraitKind: ExprKind))
4417 return false;
4418
4419 // WebAssembly tables are always illegal operands to unary expressions and
4420 // type traits.
4421 if (Context.getTargetInfo().getTriple().isWasm() &&
4422 E->getType()->isWebAssemblyTableType()) {
4423 Diag(Loc: E->getExprLoc(), DiagID: diag::err_wasm_table_invalid_uett_operand)
4424 << getTraitSpelling(T: ExprKind);
4425 return true;
4426 }
4427
4428 // 'alignof' applied to an expression only requires the base element type of
4429 // the expression to be complete. 'sizeof' requires the expression's type to
4430 // be complete (and will attempt to complete it if it's an array of unknown
4431 // bound).
4432 if (ExprKind == UETT_AlignOf || ExprKind == UETT_PreferredAlignOf) {
4433 if (RequireCompleteSizedType(
4434 Loc: E->getExprLoc(), T: Context.getBaseElementType(QT: E->getType()),
4435 DiagID: diag::err_sizeof_alignof_incomplete_or_sizeless_type,
4436 Args: getTraitSpelling(T: ExprKind), Args: E->getSourceRange()))
4437 return true;
4438 } else {
4439 if (RequireCompleteSizedExprType(
4440 E, DiagID: diag::err_sizeof_alignof_incomplete_or_sizeless_type,
4441 Args: getTraitSpelling(T: ExprKind), Args: E->getSourceRange()))
4442 return true;
4443 }
4444
4445 // Completing the expression's type may have changed it.
4446 ExprTy = E->getType();
4447 assert(!ExprTy->isReferenceType());
4448
4449 if (ExprTy->isFunctionType()) {
4450 Diag(Loc: E->getExprLoc(), DiagID: diag::err_sizeof_alignof_function_type)
4451 << getTraitSpelling(T: ExprKind) << E->getSourceRange();
4452 return true;
4453 }
4454
4455 if (CheckObjCTraitOperandConstraints(S&: *this, T: ExprTy, Loc: E->getExprLoc(),
4456 ArgRange: E->getSourceRange(), TraitKind: ExprKind))
4457 return true;
4458
4459 if (ExprKind == UETT_CountOf) {
4460 // The type has to be an array type. We already checked for incomplete
4461 // types above.
4462 QualType ExprType = E->IgnoreParens()->getType();
4463 if (!ExprType->isArrayType()) {
4464 Diag(Loc: E->getExprLoc(), DiagID: diag::err_countof_arg_not_array_type) << ExprType;
4465 return true;
4466 }
4467 // FIXME: warn on _Countof on an array parameter. Not warning on it
4468 // currently because there are papers in WG14 about array types which do
4469 // not decay that could impact this behavior, so we want to see if anything
4470 // changes here before coming up with a warning group for _Countof-related
4471 // diagnostics.
4472 }
4473
4474 if (ExprKind == UETT_SizeOf) {
4475 if (const auto *DeclRef = dyn_cast<DeclRefExpr>(Val: E->IgnoreParens())) {
4476 if (const auto *PVD = dyn_cast<ParmVarDecl>(Val: DeclRef->getFoundDecl())) {
4477 QualType OType = PVD->getOriginalType();
4478 QualType Type = PVD->getType();
4479 if (Type->isPointerType() && OType->isArrayType()) {
4480 Diag(Loc: E->getExprLoc(), DiagID: diag::warn_sizeof_array_param)
4481 << Type << OType;
4482 Diag(Loc: PVD->getLocation(), DiagID: diag::note_declared_at);
4483 }
4484 }
4485 }
4486
4487 // Warn on "sizeof(array op x)" and "sizeof(x op array)", where the array
4488 // decays into a pointer and returns an unintended result. This is most
4489 // likely a typo for "sizeof(array) op x".
4490 if (const auto *BO = dyn_cast<BinaryOperator>(Val: E->IgnoreParens())) {
4491 warnOnSizeofOnArrayDecay(S&: *this, Loc: BO->getOperatorLoc(), T: BO->getType(),
4492 E: BO->getLHS());
4493 warnOnSizeofOnArrayDecay(S&: *this, Loc: BO->getOperatorLoc(), T: BO->getType(),
4494 E: BO->getRHS());
4495 }
4496 }
4497
4498 return false;
4499}
4500
4501static bool CheckAlignOfExpr(Sema &S, Expr *E, UnaryExprOrTypeTrait ExprKind) {
4502 // Cannot know anything else if the expression is dependent.
4503 if (E->isTypeDependent())
4504 return false;
4505
4506 if (E->getObjectKind() == OK_BitField) {
4507 S.Diag(Loc: E->getExprLoc(), DiagID: diag::err_sizeof_alignof_typeof_bitfield)
4508 << 1 << E->getSourceRange();
4509 return true;
4510 }
4511
4512 ValueDecl *D = nullptr;
4513 Expr *Inner = E->IgnoreParens();
4514 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Val: Inner)) {
4515 D = DRE->getDecl();
4516 } else if (MemberExpr *ME = dyn_cast<MemberExpr>(Val: Inner)) {
4517 D = ME->getMemberDecl();
4518 }
4519
4520 // If it's a field, require the containing struct to have a
4521 // complete definition so that we can compute the layout.
4522 //
4523 // This can happen in C++11 onwards, either by naming the member
4524 // in a way that is not transformed into a member access expression
4525 // (in an unevaluated operand, for instance), or by naming the member
4526 // in a trailing-return-type.
4527 //
4528 // For the record, since __alignof__ on expressions is a GCC
4529 // extension, GCC seems to permit this but always gives the
4530 // nonsensical answer 0.
4531 //
4532 // We don't really need the layout here --- we could instead just
4533 // directly check for all the appropriate alignment-lowing
4534 // attributes --- but that would require duplicating a lot of
4535 // logic that just isn't worth duplicating for such a marginal
4536 // use-case.
4537 if (FieldDecl *FD = dyn_cast_or_null<FieldDecl>(Val: D)) {
4538 // Fast path this check, since we at least know the record has a
4539 // definition if we can find a member of it.
4540 if (!FD->getParent()->isCompleteDefinition()) {
4541 S.Diag(Loc: E->getExprLoc(), DiagID: diag::err_alignof_member_of_incomplete_type)
4542 << E->getSourceRange();
4543 return true;
4544 }
4545
4546 // Otherwise, if it's a field, and the field doesn't have
4547 // reference type, then it must have a complete type (or be a
4548 // flexible array member, which we explicitly want to
4549 // white-list anyway), which makes the following checks trivial.
4550 if (!FD->getType()->isReferenceType())
4551 return false;
4552 }
4553
4554 return S.CheckUnaryExprOrTypeTraitOperand(E, ExprKind);
4555}
4556
4557bool Sema::CheckVecStepExpr(Expr *E) {
4558 E = E->IgnoreParens();
4559
4560 // Cannot know anything else if the expression is dependent.
4561 if (E->isTypeDependent())
4562 return false;
4563
4564 return CheckUnaryExprOrTypeTraitOperand(E, ExprKind: UETT_VecStep);
4565}
4566
4567static void captureVariablyModifiedType(ASTContext &Context, QualType T,
4568 CapturingScopeInfo *CSI) {
4569 assert(T->isVariablyModifiedType());
4570 assert(CSI != nullptr);
4571
4572 // We're going to walk down into the type and look for VLA expressions.
4573 do {
4574 const Type *Ty = T.getTypePtr();
4575 switch (Ty->getTypeClass()) {
4576#define TYPE(Class, Base)
4577#define ABSTRACT_TYPE(Class, Base)
4578#define NON_CANONICAL_TYPE(Class, Base)
4579#define DEPENDENT_TYPE(Class, Base) case Type::Class:
4580#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base)
4581#include "clang/AST/TypeNodes.inc"
4582 T = QualType();
4583 break;
4584 // These types are never variably-modified.
4585 case Type::Builtin:
4586 case Type::Complex:
4587 case Type::Vector:
4588 case Type::ExtVector:
4589 case Type::ConstantMatrix:
4590 case Type::Record:
4591 case Type::Enum:
4592 case Type::TemplateSpecialization:
4593 case Type::ObjCObject:
4594 case Type::ObjCInterface:
4595 case Type::ObjCObjectPointer:
4596 case Type::ObjCTypeParam:
4597 case Type::Pipe:
4598 case Type::BitInt:
4599 case Type::HLSLInlineSpirv:
4600 llvm_unreachable("type class is never variably-modified!");
4601 case Type::Adjusted:
4602 T = cast<AdjustedType>(Val: Ty)->getOriginalType();
4603 break;
4604 case Type::Decayed:
4605 T = cast<DecayedType>(Val: Ty)->getPointeeType();
4606 break;
4607 case Type::ArrayParameter:
4608 T = cast<ArrayParameterType>(Val: Ty)->getElementType();
4609 break;
4610 case Type::Pointer:
4611 T = cast<PointerType>(Val: Ty)->getPointeeType();
4612 break;
4613 case Type::BlockPointer:
4614 T = cast<BlockPointerType>(Val: Ty)->getPointeeType();
4615 break;
4616 case Type::LValueReference:
4617 case Type::RValueReference:
4618 T = cast<ReferenceType>(Val: Ty)->getPointeeType();
4619 break;
4620 case Type::MemberPointer:
4621 T = cast<MemberPointerType>(Val: Ty)->getPointeeType();
4622 break;
4623 case Type::ConstantArray:
4624 case Type::IncompleteArray:
4625 // Losing element qualification here is fine.
4626 T = cast<ArrayType>(Val: Ty)->getElementType();
4627 break;
4628 case Type::VariableArray: {
4629 // Losing element qualification here is fine.
4630 const VariableArrayType *VAT = cast<VariableArrayType>(Val: Ty);
4631
4632 // Unknown size indication requires no size computation.
4633 // Otherwise, evaluate and record it.
4634 auto Size = VAT->getSizeExpr();
4635 if (Size && !CSI->isVLATypeCaptured(VAT) &&
4636 (isa<CapturedRegionScopeInfo>(Val: CSI) || isa<LambdaScopeInfo>(Val: CSI)))
4637 CSI->addVLATypeCapture(Loc: Size->getExprLoc(), VLAType: VAT, CaptureType: Context.getSizeType());
4638
4639 T = VAT->getElementType();
4640 break;
4641 }
4642 case Type::FunctionProto:
4643 case Type::FunctionNoProto:
4644 T = cast<FunctionType>(Val: Ty)->getReturnType();
4645 break;
4646 case Type::Paren:
4647 case Type::TypeOf:
4648 case Type::UnaryTransform:
4649 case Type::Attributed:
4650 case Type::BTFTagAttributed:
4651 case Type::OverflowBehavior:
4652 case Type::HLSLAttributedResource:
4653 case Type::SubstTemplateTypeParm:
4654 case Type::MacroQualified:
4655 case Type::CountAttributed:
4656 // Keep walking after single level desugaring.
4657 T = T.getSingleStepDesugaredType(Context);
4658 break;
4659 case Type::Typedef:
4660 T = cast<TypedefType>(Val: Ty)->desugar();
4661 break;
4662 case Type::Decltype:
4663 T = cast<DecltypeType>(Val: Ty)->desugar();
4664 break;
4665 case Type::PackIndexing:
4666 T = cast<PackIndexingType>(Val: Ty)->desugar();
4667 break;
4668 case Type::Using:
4669 T = cast<UsingType>(Val: Ty)->desugar();
4670 break;
4671 case Type::Auto:
4672 case Type::DeducedTemplateSpecialization:
4673 T = cast<DeducedType>(Val: Ty)->getDeducedType();
4674 break;
4675 case Type::TypeOfExpr:
4676 T = cast<TypeOfExprType>(Val: Ty)->getUnderlyingExpr()->getType();
4677 break;
4678 case Type::Atomic:
4679 T = cast<AtomicType>(Val: Ty)->getValueType();
4680 break;
4681 case Type::PredefinedSugar:
4682 T = cast<PredefinedSugarType>(Val: Ty)->desugar();
4683 break;
4684 }
4685 } while (!T.isNull() && T->isVariablyModifiedType());
4686}
4687
4688bool Sema::CheckUnaryExprOrTypeTraitOperand(QualType ExprType,
4689 SourceLocation OpLoc,
4690 SourceRange ExprRange,
4691 UnaryExprOrTypeTrait ExprKind,
4692 StringRef KWName) {
4693 if (ExprType->isDependentType())
4694 return false;
4695
4696 // C++ [expr.sizeof]p2:
4697 // When applied to a reference or a reference type, the result
4698 // is the size of the referenced type.
4699 // C++11 [expr.alignof]p3:
4700 // When alignof is applied to a reference type, the result
4701 // shall be the alignment of the referenced type.
4702 if (const ReferenceType *Ref = ExprType->getAs<ReferenceType>())
4703 ExprType = Ref->getPointeeType();
4704
4705 // C11 6.5.3.4/3, C++11 [expr.alignof]p3:
4706 // When alignof or _Alignof is applied to an array type, the result
4707 // is the alignment of the element type.
4708 if (ExprKind == UETT_AlignOf || ExprKind == UETT_PreferredAlignOf ||
4709 ExprKind == UETT_OpenMPRequiredSimdAlign) {
4710 // If the trait is 'alignof' in C before C2y, the ability to apply the
4711 // trait to an incomplete array is an extension.
4712 if (ExprKind == UETT_AlignOf && !getLangOpts().CPlusPlus &&
4713 ExprType->isIncompleteArrayType())
4714 Diag(Loc: OpLoc, DiagID: getLangOpts().C2y
4715 ? diag::warn_c2y_compat_alignof_incomplete_array
4716 : diag::ext_c2y_alignof_incomplete_array);
4717 ExprType = Context.getBaseElementType(QT: ExprType);
4718 }
4719
4720 if (ExprKind == UETT_VecStep)
4721 return CheckVecStepTraitOperandType(S&: *this, T: ExprType, Loc: OpLoc, ArgRange: ExprRange);
4722
4723 if (ExprKind == UETT_VectorElements)
4724 return CheckVectorElementsTraitOperandType(S&: *this, T: ExprType, Loc: OpLoc,
4725 ArgRange: ExprRange);
4726
4727 if (ExprKind == UETT_PtrAuthTypeDiscriminator)
4728 return checkPtrAuthTypeDiscriminatorOperandType(S&: *this, T: ExprType, Loc: OpLoc,
4729 ArgRange: ExprRange);
4730
4731 // Explicitly list some types as extensions.
4732 if (!CheckExtensionTraitOperandType(S&: *this, T: ExprType, Loc: OpLoc, ArgRange: ExprRange,
4733 TraitKind: ExprKind))
4734 return false;
4735
4736 if (RequireCompleteSizedType(
4737 Loc: OpLoc, T: ExprType, DiagID: diag::err_sizeof_alignof_incomplete_or_sizeless_type,
4738 Args: KWName, Args: ExprRange))
4739 return true;
4740
4741 if (ExprType->isFunctionType()) {
4742 Diag(Loc: OpLoc, DiagID: diag::err_sizeof_alignof_function_type) << KWName << ExprRange;
4743 return true;
4744 }
4745
4746 if (ExprKind == UETT_CountOf) {
4747 // The type has to be an array type. We already checked for incomplete
4748 // types above.
4749 if (!ExprType->isArrayType()) {
4750 Diag(Loc: OpLoc, DiagID: diag::err_countof_arg_not_array_type) << ExprType;
4751 return true;
4752 }
4753 }
4754
4755 // WebAssembly tables are always illegal operands to unary expressions and
4756 // type traits.
4757 if (Context.getTargetInfo().getTriple().isWasm() &&
4758 ExprType->isWebAssemblyTableType()) {
4759 Diag(Loc: OpLoc, DiagID: diag::err_wasm_table_invalid_uett_operand)
4760 << getTraitSpelling(T: ExprKind);
4761 return true;
4762 }
4763
4764 if (CheckObjCTraitOperandConstraints(S&: *this, T: ExprType, Loc: OpLoc, ArgRange: ExprRange,
4765 TraitKind: ExprKind))
4766 return true;
4767
4768 if (ExprType->isVariablyModifiedType() && FunctionScopes.size() > 1) {
4769 if (auto *TT = ExprType->getAs<TypedefType>()) {
4770 for (auto I = FunctionScopes.rbegin(),
4771 E = std::prev(x: FunctionScopes.rend());
4772 I != E; ++I) {
4773 auto *CSI = dyn_cast<CapturingScopeInfo>(Val: *I);
4774 if (CSI == nullptr)
4775 break;
4776 DeclContext *DC = nullptr;
4777 if (auto *LSI = dyn_cast<LambdaScopeInfo>(Val: CSI))
4778 DC = LSI->CallOperator;
4779 else if (auto *CRSI = dyn_cast<CapturedRegionScopeInfo>(Val: CSI))
4780 DC = CRSI->TheCapturedDecl;
4781 else if (auto *BSI = dyn_cast<BlockScopeInfo>(Val: CSI))
4782 DC = BSI->TheDecl;
4783 if (DC) {
4784 if (DC->containsDecl(D: TT->getDecl()))
4785 break;
4786 captureVariablyModifiedType(Context, T: ExprType, CSI);
4787 }
4788 }
4789 }
4790 }
4791
4792 return false;
4793}
4794
4795ExprResult Sema::CreateUnaryExprOrTypeTraitExpr(TypeSourceInfo *TInfo,
4796 SourceLocation OpLoc,
4797 UnaryExprOrTypeTrait ExprKind,
4798 SourceRange R) {
4799 if (!TInfo)
4800 return ExprError();
4801
4802 QualType T = TInfo->getType();
4803
4804 if (!T->isDependentType() &&
4805 CheckUnaryExprOrTypeTraitOperand(ExprType: T, OpLoc, ExprRange: R, ExprKind,
4806 KWName: getTraitSpelling(T: ExprKind)))
4807 return ExprError();
4808
4809 // Adds overload of TransformToPotentiallyEvaluated for TypeSourceInfo to
4810 // properly deal with VLAs in nested calls of sizeof and typeof.
4811 if (currentEvaluationContext().isUnevaluated() &&
4812 currentEvaluationContext().InConditionallyConstantEvaluateContext &&
4813 (ExprKind == UETT_SizeOf || ExprKind == UETT_CountOf) &&
4814 TInfo->getType()->isVariablyModifiedType())
4815 TInfo = TransformToPotentiallyEvaluated(TInfo);
4816
4817 // It's possible that the transformation above failed.
4818 if (!TInfo)
4819 return ExprError();
4820
4821 // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t.
4822 return new (Context) UnaryExprOrTypeTraitExpr(
4823 ExprKind, TInfo, Context.getSizeType(), OpLoc, R.getEnd());
4824}
4825
4826ExprResult
4827Sema::CreateUnaryExprOrTypeTraitExpr(Expr *E, SourceLocation OpLoc,
4828 UnaryExprOrTypeTrait ExprKind) {
4829 ExprResult PE = CheckPlaceholderExpr(E);
4830 if (PE.isInvalid())
4831 return ExprError();
4832
4833 E = PE.get();
4834
4835 // Verify that the operand is valid.
4836 bool isInvalid = false;
4837 if (E->isTypeDependent()) {
4838 // Delay type-checking for type-dependent expressions.
4839 } else if (ExprKind == UETT_AlignOf || ExprKind == UETT_PreferredAlignOf) {
4840 isInvalid = CheckAlignOfExpr(S&: *this, E, ExprKind);
4841 } else if (ExprKind == UETT_VecStep) {
4842 isInvalid = CheckVecStepExpr(E);
4843 } else if (ExprKind == UETT_OpenMPRequiredSimdAlign) {
4844 Diag(Loc: E->getExprLoc(), DiagID: diag::err_openmp_default_simd_align_expr);
4845 isInvalid = true;
4846 } else if (E->refersToBitField()) { // C99 6.5.3.4p1.
4847 Diag(Loc: E->getExprLoc(), DiagID: diag::err_sizeof_alignof_typeof_bitfield) << 0;
4848 isInvalid = true;
4849 } else if (ExprKind == UETT_VectorElements || ExprKind == UETT_SizeOf ||
4850 ExprKind == UETT_CountOf) { // FIXME: __datasizeof?
4851 isInvalid = CheckUnaryExprOrTypeTraitOperand(E, ExprKind);
4852 }
4853
4854 if (isInvalid)
4855 return ExprError();
4856
4857 if ((ExprKind == UETT_SizeOf || ExprKind == UETT_CountOf) &&
4858 E->getType()->isVariableArrayType()) {
4859 PE = TransformToPotentiallyEvaluated(E);
4860 if (PE.isInvalid()) return ExprError();
4861 E = PE.get();
4862 }
4863
4864 // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t.
4865 return new (Context) UnaryExprOrTypeTraitExpr(
4866 ExprKind, E, Context.getSizeType(), OpLoc, E->getSourceRange().getEnd());
4867}
4868
4869ExprResult
4870Sema::ActOnUnaryExprOrTypeTraitExpr(SourceLocation OpLoc,
4871 UnaryExprOrTypeTrait ExprKind, bool IsType,
4872 void *TyOrEx, SourceRange ArgRange) {
4873 // If error parsing type, ignore.
4874 if (!TyOrEx) return ExprError();
4875
4876 if (IsType) {
4877 TypeSourceInfo *TInfo;
4878 (void) GetTypeFromParser(Ty: ParsedType::getFromOpaquePtr(P: TyOrEx), TInfo: &TInfo);
4879 return CreateUnaryExprOrTypeTraitExpr(TInfo, OpLoc, ExprKind, R: ArgRange);
4880 }
4881
4882 Expr *ArgEx = (Expr *)TyOrEx;
4883 ExprResult Result = CreateUnaryExprOrTypeTraitExpr(E: ArgEx, OpLoc, ExprKind);
4884 return Result;
4885}
4886
4887bool Sema::CheckAlignasTypeArgument(StringRef KWName, TypeSourceInfo *TInfo,
4888 SourceLocation OpLoc, SourceRange R) {
4889 if (!TInfo)
4890 return true;
4891 return CheckUnaryExprOrTypeTraitOperand(ExprType: TInfo->getType(), OpLoc, ExprRange: R,
4892 ExprKind: UETT_AlignOf, KWName);
4893}
4894
4895bool Sema::ActOnAlignasTypeArgument(StringRef KWName, ParsedType Ty,
4896 SourceLocation OpLoc, SourceRange R) {
4897 TypeSourceInfo *TInfo;
4898 (void)GetTypeFromParser(Ty: ParsedType::getFromOpaquePtr(P: Ty.getAsOpaquePtr()),
4899 TInfo: &TInfo);
4900 return CheckAlignasTypeArgument(KWName, TInfo, OpLoc, R);
4901}
4902
4903static QualType CheckRealImagOperand(Sema &S, ExprResult &V, SourceLocation Loc,
4904 bool IsReal) {
4905 if (V.get()->isTypeDependent())
4906 return S.Context.DependentTy;
4907
4908 // _Real and _Imag are only l-values for normal l-values.
4909 if (V.get()->getObjectKind() != OK_Ordinary) {
4910 V = S.DefaultLvalueConversion(E: V.get());
4911 if (V.isInvalid())
4912 return QualType();
4913 }
4914
4915 // These operators return the element type of a complex type.
4916 if (const ComplexType *CT = V.get()->getType()->getAs<ComplexType>())
4917 return CT->getElementType();
4918
4919 // Otherwise they pass through real integer and floating point types here.
4920 if (V.get()->getType()->isArithmeticType())
4921 return V.get()->getType();
4922
4923 // Test for placeholders.
4924 ExprResult PR = S.CheckPlaceholderExpr(E: V.get());
4925 if (PR.isInvalid()) return QualType();
4926 if (PR.get() != V.get()) {
4927 V = PR;
4928 return CheckRealImagOperand(S, V, Loc, IsReal);
4929 }
4930
4931 // Reject anything else.
4932 S.Diag(Loc, DiagID: diag::err_realimag_invalid_type) << V.get()->getType()
4933 << (IsReal ? "__real" : "__imag");
4934 return QualType();
4935}
4936
4937
4938
4939ExprResult
4940Sema::ActOnPostfixUnaryOp(Scope *S, SourceLocation OpLoc,
4941 tok::TokenKind Kind, Expr *Input) {
4942 UnaryOperatorKind Opc;
4943 switch (Kind) {
4944 default: llvm_unreachable("Unknown unary op!");
4945 case tok::plusplus: Opc = UO_PostInc; break;
4946 case tok::minusminus: Opc = UO_PostDec; break;
4947 }
4948
4949 // Since this might is a postfix expression, get rid of ParenListExprs.
4950 ExprResult Result = MaybeConvertParenListExprToParenExpr(S, ME: Input);
4951 if (Result.isInvalid()) return ExprError();
4952 Input = Result.get();
4953
4954 return BuildUnaryOp(S, OpLoc, Opc, Input);
4955}
4956
4957/// Diagnose if arithmetic on the given ObjC pointer is illegal.
4958///
4959/// \return true on error
4960static bool checkArithmeticOnObjCPointer(Sema &S,
4961 SourceLocation opLoc,
4962 Expr *op) {
4963 assert(op->getType()->isObjCObjectPointerType());
4964 if (S.LangOpts.ObjCRuntime.allowsPointerArithmetic() &&
4965 !S.LangOpts.ObjCSubscriptingLegacyRuntime)
4966 return false;
4967
4968 S.Diag(Loc: opLoc, DiagID: diag::err_arithmetic_nonfragile_interface)
4969 << op->getType()->castAs<ObjCObjectPointerType>()->getPointeeType()
4970 << op->getSourceRange();
4971 return true;
4972}
4973
4974static bool isMSPropertySubscriptExpr(Sema &S, Expr *Base) {
4975 auto *BaseNoParens = Base->IgnoreParens();
4976 if (auto *MSProp = dyn_cast<MSPropertyRefExpr>(Val: BaseNoParens))
4977 return MSProp->getPropertyDecl()->getType()->isArrayType();
4978 return isa<MSPropertySubscriptExpr>(Val: BaseNoParens);
4979}
4980
4981// Returns the type used for LHS[RHS], given one of LHS, RHS is type-dependent.
4982// Typically this is DependentTy, but can sometimes be more precise.
4983//
4984// There are cases when we could determine a non-dependent type:
4985// - LHS and RHS may have non-dependent types despite being type-dependent
4986// (e.g. unbounded array static members of the current instantiation)
4987// - one may be a dependent-sized array with known element type
4988// - one may be a dependent-typed valid index (enum in current instantiation)
4989//
4990// We *always* return a dependent type, in such cases it is DependentTy.
4991// This avoids creating type-dependent expressions with non-dependent types.
4992// FIXME: is this important to avoid? See https://reviews.llvm.org/D107275
4993static QualType getDependentArraySubscriptType(Expr *LHS, Expr *RHS,
4994 const ASTContext &Ctx) {
4995 assert(LHS->isTypeDependent() || RHS->isTypeDependent());
4996 QualType LTy = LHS->getType(), RTy = RHS->getType();
4997 QualType Result = Ctx.DependentTy;
4998 if (RTy->isIntegralOrUnscopedEnumerationType()) {
4999 if (const PointerType *PT = LTy->getAs<PointerType>())
5000 Result = PT->getPointeeType();
5001 else if (const ArrayType *AT = LTy->getAsArrayTypeUnsafe())
5002 Result = AT->getElementType();
5003 } else if (LTy->isIntegralOrUnscopedEnumerationType()) {
5004 if (const PointerType *PT = RTy->getAs<PointerType>())
5005 Result = PT->getPointeeType();
5006 else if (const ArrayType *AT = RTy->getAsArrayTypeUnsafe())
5007 Result = AT->getElementType();
5008 }
5009 // Ensure we return a dependent type.
5010 return Result->isDependentType() ? Result : Ctx.DependentTy;
5011}
5012
5013ExprResult Sema::ActOnArraySubscriptExpr(Scope *S, Expr *base,
5014 SourceLocation lbLoc,
5015 MultiExprArg ArgExprs,
5016 SourceLocation rbLoc) {
5017
5018 if (base && !base->getType().isNull() &&
5019 base->hasPlaceholderType(K: BuiltinType::ArraySection)) {
5020 auto *AS = cast<ArraySectionExpr>(Val: base);
5021 if (AS->isOMPArraySection())
5022 return OpenMP().ActOnOMPArraySectionExpr(
5023 Base: base, LBLoc: lbLoc, LowerBound: ArgExprs.front(), ColonLocFirst: SourceLocation(), ColonLocSecond: SourceLocation(),
5024 /*Length*/ nullptr,
5025 /*Stride=*/nullptr, RBLoc: rbLoc);
5026
5027 return OpenACC().ActOnArraySectionExpr(Base: base, LBLoc: lbLoc, LowerBound: ArgExprs.front(),
5028 ColonLocFirst: SourceLocation(), /*Length*/ nullptr,
5029 RBLoc: rbLoc);
5030 }
5031
5032 // Since this might be a postfix expression, get rid of ParenListExprs.
5033 if (isa<ParenListExpr>(Val: base)) {
5034 ExprResult result = MaybeConvertParenListExprToParenExpr(S, ME: base);
5035 if (result.isInvalid())
5036 return ExprError();
5037 base = result.get();
5038 }
5039
5040 // Check if base and idx form a MatrixSubscriptExpr.
5041 //
5042 // Helper to check for comma expressions, which are not allowed as indices for
5043 // matrix subscript expressions.
5044 //
5045 // In C++23, we get multiple arguments instead of a comma expression.
5046 auto CheckAndReportCommaError = [&](Expr *E) {
5047 if (ArgExprs.size() > 1 ||
5048 (isa<BinaryOperator>(Val: E) && cast<BinaryOperator>(Val: E)->isCommaOp())) {
5049 Diag(Loc: E->getExprLoc(), DiagID: diag::err_matrix_subscript_comma)
5050 << SourceRange(base->getBeginLoc(), rbLoc);
5051 return true;
5052 }
5053 return false;
5054 };
5055 // The matrix subscript operator ([][])is considered a single operator.
5056 // Separating the index expressions by parenthesis is not allowed.
5057 if (base && !base->getType().isNull() &&
5058 base->hasPlaceholderType(K: BuiltinType::IncompleteMatrixIdx) &&
5059 !isa<MatrixSubscriptExpr>(Val: base)) {
5060 Diag(Loc: base->getExprLoc(), DiagID: diag::err_matrix_separate_incomplete_index)
5061 << SourceRange(base->getBeginLoc(), rbLoc);
5062 return ExprError();
5063 }
5064 // If the base is a MatrixSubscriptExpr, try to create a new
5065 // MatrixSubscriptExpr.
5066 auto *matSubscriptE = dyn_cast<MatrixSubscriptExpr>(Val: base);
5067 if (matSubscriptE) {
5068 if (CheckAndReportCommaError(ArgExprs.front()))
5069 return ExprError();
5070
5071 assert(matSubscriptE->isIncomplete() &&
5072 "base has to be an incomplete matrix subscript");
5073 return CreateBuiltinMatrixSubscriptExpr(Base: matSubscriptE->getBase(),
5074 RowIdx: matSubscriptE->getRowIdx(),
5075 ColumnIdx: ArgExprs.front(), RBLoc: rbLoc);
5076 }
5077 if (base->getType()->isWebAssemblyTableType()) {
5078 Diag(Loc: base->getExprLoc(), DiagID: diag::err_wasm_table_art)
5079 << SourceRange(base->getBeginLoc(), rbLoc) << 3;
5080 return ExprError();
5081 }
5082
5083 CheckInvalidBuiltinCountedByRef(E: base,
5084 K: BuiltinCountedByRefKind::ArraySubscript);
5085
5086 // Handle any non-overload placeholder types in the base and index
5087 // expressions. We can't handle overloads here because the other
5088 // operand might be an overloadable type, in which case the overload
5089 // resolution for the operator overload should get the first crack
5090 // at the overload.
5091 bool IsMSPropertySubscript = false;
5092 if (base->getType()->isNonOverloadPlaceholderType()) {
5093 IsMSPropertySubscript = isMSPropertySubscriptExpr(S&: *this, Base: base);
5094 if (!IsMSPropertySubscript) {
5095 ExprResult result = CheckPlaceholderExpr(E: base);
5096 if (result.isInvalid())
5097 return ExprError();
5098 base = result.get();
5099 }
5100 }
5101
5102 // If the base is a matrix type, try to create a new MatrixSubscriptExpr.
5103 if (base->getType()->isMatrixType()) {
5104 if (CheckAndReportCommaError(ArgExprs.front()))
5105 return ExprError();
5106
5107 return CreateBuiltinMatrixSubscriptExpr(Base: base, RowIdx: ArgExprs.front(), ColumnIdx: nullptr,
5108 RBLoc: rbLoc);
5109 }
5110
5111 if (ArgExprs.size() == 1 && getLangOpts().CPlusPlus20) {
5112 Expr *idx = ArgExprs[0];
5113 if ((isa<BinaryOperator>(Val: idx) && cast<BinaryOperator>(Val: idx)->isCommaOp()) ||
5114 (isa<CXXOperatorCallExpr>(Val: idx) &&
5115 cast<CXXOperatorCallExpr>(Val: idx)->getOperator() == OO_Comma)) {
5116 Diag(Loc: idx->getExprLoc(), DiagID: diag::warn_deprecated_comma_subscript)
5117 << SourceRange(base->getBeginLoc(), rbLoc);
5118 }
5119 }
5120
5121 if (ArgExprs.size() == 1 &&
5122 ArgExprs[0]->getType()->isNonOverloadPlaceholderType()) {
5123 ExprResult result = CheckPlaceholderExpr(E: ArgExprs[0]);
5124 if (result.isInvalid())
5125 return ExprError();
5126 ArgExprs[0] = result.get();
5127 } else {
5128 if (CheckArgsForPlaceholders(args: ArgExprs))
5129 return ExprError();
5130 }
5131
5132 // Build an unanalyzed expression if either operand is type-dependent.
5133 if (getLangOpts().CPlusPlus && ArgExprs.size() == 1 &&
5134 (base->isTypeDependent() ||
5135 Expr::hasAnyTypeDependentArguments(Exprs: ArgExprs)) &&
5136 !isa<PackExpansionExpr>(Val: ArgExprs[0])) {
5137 return new (Context) ArraySubscriptExpr(
5138 base, ArgExprs.front(),
5139 getDependentArraySubscriptType(LHS: base, RHS: ArgExprs.front(), Ctx: getASTContext()),
5140 VK_LValue, OK_Ordinary, rbLoc);
5141 }
5142
5143 // MSDN, property (C++)
5144 // https://msdn.microsoft.com/en-us/library/yhfk0thd(v=vs.120).aspx
5145 // This attribute can also be used in the declaration of an empty array in a
5146 // class or structure definition. For example:
5147 // __declspec(property(get=GetX, put=PutX)) int x[];
5148 // The above statement indicates that x[] can be used with one or more array
5149 // indices. In this case, i=p->x[a][b] will be turned into i=p->GetX(a, b),
5150 // and p->x[a][b] = i will be turned into p->PutX(a, b, i);
5151 if (IsMSPropertySubscript) {
5152 if (ArgExprs.size() > 1) {
5153 Diag(Loc: base->getExprLoc(),
5154 DiagID: diag::err_ms_property_subscript_expects_single_arg);
5155 return ExprError();
5156 }
5157
5158 // Build MS property subscript expression if base is MS property reference
5159 // or MS property subscript.
5160 return new (Context)
5161 MSPropertySubscriptExpr(base, ArgExprs.front(), Context.PseudoObjectTy,
5162 VK_LValue, OK_Ordinary, rbLoc);
5163 }
5164
5165 // Use C++ overloaded-operator rules if either operand has record
5166 // type. The spec says to do this if either type is *overloadable*,
5167 // but enum types can't declare subscript operators or conversion
5168 // operators, so there's nothing interesting for overload resolution
5169 // to do if there aren't any record types involved.
5170 //
5171 // ObjC pointers have their own subscripting logic that is not tied
5172 // to overload resolution and so should not take this path.
5173 //
5174 // Issue a better diagnostic if we tried to pass multiple arguments to
5175 // a builtin subscript operator rather than diagnosing this as a generic
5176 // overload resolution failure.
5177 if (ArgExprs.size() != 1 && !base->getType()->isDependentType() &&
5178 !base->getType()->isRecordType() &&
5179 !base->getType()->isObjCObjectPointerType()) {
5180 Diag(Loc: base->getExprLoc(), DiagID: diag::err_ovl_builtin_subscript_expects_single_arg)
5181 << base->getType() << base->getSourceRange();
5182 return ExprError();
5183 }
5184
5185 if (getLangOpts().CPlusPlus && !base->getType()->isObjCObjectPointerType() &&
5186 ((base->getType()->isRecordType() ||
5187 (ArgExprs.size() != 1 || isa<PackExpansionExpr>(Val: ArgExprs[0]) ||
5188 ArgExprs[0]->getType()->isRecordType())))) {
5189 return CreateOverloadedArraySubscriptExpr(LLoc: lbLoc, RLoc: rbLoc, Base: base, Args: ArgExprs);
5190 }
5191
5192 ExprResult Res =
5193 CreateBuiltinArraySubscriptExpr(Base: base, LLoc: lbLoc, Idx: ArgExprs.front(), RLoc: rbLoc);
5194
5195 if (!Res.isInvalid() && isa<ArraySubscriptExpr>(Val: Res.get()))
5196 CheckSubscriptAccessOfNoDeref(E: cast<ArraySubscriptExpr>(Val: Res.get()));
5197
5198 return Res;
5199}
5200
5201ExprResult Sema::tryConvertExprToType(Expr *E, QualType Ty) {
5202 InitializedEntity Entity = InitializedEntity::InitializeTemporary(Type: Ty);
5203 InitializationKind Kind =
5204 InitializationKind::CreateCopy(InitLoc: E->getBeginLoc(), EqualLoc: SourceLocation());
5205 InitializationSequence InitSeq(*this, Entity, Kind, E);
5206 return InitSeq.Perform(S&: *this, Entity, Kind, Args: E);
5207}
5208
5209ExprResult Sema::CreateBuiltinMatrixSingleSubscriptExpr(Expr *Base,
5210 Expr *RowIdx,
5211 SourceLocation RBLoc) {
5212 ExprResult BaseR = CheckPlaceholderExpr(E: Base);
5213 if (BaseR.isInvalid())
5214 return BaseR;
5215 Base = BaseR.get();
5216
5217 ExprResult RowR = CheckPlaceholderExpr(E: RowIdx);
5218 if (RowR.isInvalid())
5219 return RowR;
5220 RowIdx = RowR.get();
5221
5222 // Build an unanalyzed expression if any of the operands is type-dependent.
5223 if (Base->isTypeDependent() || RowIdx->isTypeDependent())
5224 return new (Context)
5225 MatrixSingleSubscriptExpr(Base, RowIdx, Context.DependentTy, RBLoc);
5226
5227 // Check that IndexExpr is an integer expression. If it is a constant
5228 // expression, check that it is less than Dim (= the number of elements in the
5229 // corresponding dimension).
5230 auto IsIndexValid = [&](Expr *IndexExpr, unsigned Dim,
5231 bool IsColumnIdx) -> Expr * {
5232 if (!IndexExpr->getType()->isIntegerType() &&
5233 !IndexExpr->isTypeDependent()) {
5234 Diag(Loc: IndexExpr->getBeginLoc(), DiagID: diag::err_matrix_index_not_integer)
5235 << IsColumnIdx;
5236 return nullptr;
5237 }
5238
5239 if (std::optional<llvm::APSInt> Idx =
5240 IndexExpr->getIntegerConstantExpr(Ctx: Context)) {
5241 if ((*Idx < 0 || *Idx >= Dim)) {
5242 Diag(Loc: IndexExpr->getBeginLoc(), DiagID: diag::err_matrix_index_outside_range)
5243 << IsColumnIdx << Dim;
5244 return nullptr;
5245 }
5246 }
5247
5248 ExprResult ConvExpr = IndexExpr;
5249 assert(!ConvExpr.isInvalid() &&
5250 "should be able to convert any integer type to size type");
5251 return ConvExpr.get();
5252 };
5253
5254 auto *MTy = Base->getType()->getAs<ConstantMatrixType>();
5255 RowIdx = IsIndexValid(RowIdx, MTy->getNumRows(), false);
5256 if (!RowIdx)
5257 return ExprError();
5258
5259 QualType RowVecQT =
5260 Context.getExtVectorType(VectorType: MTy->getElementType(), NumElts: MTy->getNumColumns());
5261
5262 return new (Context) MatrixSingleSubscriptExpr(Base, RowIdx, RowVecQT, RBLoc);
5263}
5264
5265ExprResult Sema::CreateBuiltinMatrixSubscriptExpr(Expr *Base, Expr *RowIdx,
5266 Expr *ColumnIdx,
5267 SourceLocation RBLoc) {
5268 ExprResult BaseR = CheckPlaceholderExpr(E: Base);
5269 if (BaseR.isInvalid())
5270 return BaseR;
5271 Base = BaseR.get();
5272
5273 ExprResult RowR = CheckPlaceholderExpr(E: RowIdx);
5274 if (RowR.isInvalid())
5275 return RowR;
5276 RowIdx = RowR.get();
5277
5278 if (!ColumnIdx)
5279 return new (Context) MatrixSubscriptExpr(
5280 Base, RowIdx, ColumnIdx, Context.IncompleteMatrixIdxTy, RBLoc);
5281
5282 // Build an unanalyzed expression if any of the operands is type-dependent.
5283 if (Base->isTypeDependent() || RowIdx->isTypeDependent() ||
5284 ColumnIdx->isTypeDependent())
5285 return new (Context) MatrixSubscriptExpr(Base, RowIdx, ColumnIdx,
5286 Context.DependentTy, RBLoc);
5287
5288 ExprResult ColumnR = CheckPlaceholderExpr(E: ColumnIdx);
5289 if (ColumnR.isInvalid())
5290 return ColumnR;
5291 ColumnIdx = ColumnR.get();
5292
5293 // Check that IndexExpr is an integer expression. If it is a constant
5294 // expression, check that it is less than Dim (= the number of elements in the
5295 // corresponding dimension).
5296 auto IsIndexValid = [&](Expr *IndexExpr, unsigned Dim,
5297 bool IsColumnIdx) -> Expr * {
5298 if (!IndexExpr->getType()->isIntegerType() &&
5299 !IndexExpr->isTypeDependent()) {
5300 Diag(Loc: IndexExpr->getBeginLoc(), DiagID: diag::err_matrix_index_not_integer)
5301 << IsColumnIdx;
5302 return nullptr;
5303 }
5304
5305 if (std::optional<llvm::APSInt> Idx =
5306 IndexExpr->getIntegerConstantExpr(Ctx: Context)) {
5307 if ((*Idx < 0 || *Idx >= Dim)) {
5308 Diag(Loc: IndexExpr->getBeginLoc(), DiagID: diag::err_matrix_index_outside_range)
5309 << IsColumnIdx << Dim;
5310 return nullptr;
5311 }
5312 }
5313
5314 ExprResult ConvExpr = IndexExpr;
5315 assert(!ConvExpr.isInvalid() &&
5316 "should be able to convert any integer type to size type");
5317 return ConvExpr.get();
5318 };
5319
5320 auto *MTy = Base->getType()->getAs<ConstantMatrixType>();
5321 RowIdx = IsIndexValid(RowIdx, MTy->getNumRows(), false);
5322 ColumnIdx = IsIndexValid(ColumnIdx, MTy->getNumColumns(), true);
5323 if (!RowIdx || !ColumnIdx)
5324 return ExprError();
5325
5326 return new (Context) MatrixSubscriptExpr(Base, RowIdx, ColumnIdx,
5327 MTy->getElementType(), RBLoc);
5328}
5329
5330void Sema::CheckAddressOfNoDeref(const Expr *E) {
5331 ExpressionEvaluationContextRecord &LastRecord = ExprEvalContexts.back();
5332 const Expr *StrippedExpr = E->IgnoreParenImpCasts();
5333
5334 // For expressions like `&(*s).b`, the base is recorded and what should be
5335 // checked.
5336 const MemberExpr *Member = nullptr;
5337 while ((Member = dyn_cast<MemberExpr>(Val: StrippedExpr)) && !Member->isArrow())
5338 StrippedExpr = Member->getBase()->IgnoreParenImpCasts();
5339
5340 LastRecord.PossibleDerefs.erase(Ptr: StrippedExpr);
5341}
5342
5343void Sema::CheckSubscriptAccessOfNoDeref(const ArraySubscriptExpr *E) {
5344 if (isUnevaluatedContext())
5345 return;
5346
5347 QualType ResultTy = E->getType();
5348 ExpressionEvaluationContextRecord &LastRecord = ExprEvalContexts.back();
5349
5350 // Bail if the element is an array since it is not memory access.
5351 if (isa<ArrayType>(Val: ResultTy))
5352 return;
5353
5354 if (ResultTy->hasAttr(AK: attr::NoDeref)) {
5355 LastRecord.PossibleDerefs.insert(Ptr: E);
5356 return;
5357 }
5358
5359 // Check if the base type is a pointer to a member access of a struct
5360 // marked with noderef.
5361 const Expr *Base = E->getBase();
5362 QualType BaseTy = Base->getType();
5363 if (!(isa<ArrayType>(Val: BaseTy) || isa<PointerType>(Val: BaseTy)))
5364 // Not a pointer access
5365 return;
5366
5367 const MemberExpr *Member = nullptr;
5368 while ((Member = dyn_cast<MemberExpr>(Val: Base->IgnoreParenCasts())) &&
5369 Member->isArrow())
5370 Base = Member->getBase();
5371
5372 if (const auto *Ptr = dyn_cast<PointerType>(Val: Base->getType())) {
5373 if (Ptr->getPointeeType()->hasAttr(AK: attr::NoDeref))
5374 LastRecord.PossibleDerefs.insert(Ptr: E);
5375 }
5376}
5377
5378ExprResult
5379Sema::CreateBuiltinArraySubscriptExpr(Expr *Base, SourceLocation LLoc,
5380 Expr *Idx, SourceLocation RLoc) {
5381 Expr *LHSExp = Base;
5382 Expr *RHSExp = Idx;
5383
5384 ExprValueKind VK = VK_LValue;
5385 ExprObjectKind OK = OK_Ordinary;
5386
5387 // Per C++ core issue 1213, the result is an xvalue if either operand is
5388 // a non-lvalue array, and an lvalue otherwise.
5389 if (getLangOpts().CPlusPlus11) {
5390 for (auto *Op : {LHSExp, RHSExp}) {
5391 Op = Op->IgnoreImplicit();
5392 if (Op->getType()->isArrayType() && !Op->isLValue())
5393 VK = VK_XValue;
5394 }
5395 }
5396
5397 // Perform default conversions.
5398 if (!LHSExp->getType()->isSubscriptableVectorType()) {
5399 ExprResult Result = DefaultFunctionArrayLvalueConversion(E: LHSExp);
5400 if (Result.isInvalid())
5401 return ExprError();
5402 LHSExp = Result.get();
5403 }
5404 ExprResult Result = DefaultFunctionArrayLvalueConversion(E: RHSExp);
5405 if (Result.isInvalid())
5406 return ExprError();
5407 RHSExp = Result.get();
5408
5409 QualType LHSTy = LHSExp->getType(), RHSTy = RHSExp->getType();
5410
5411 // C99 6.5.2.1p2: the expression e1[e2] is by definition precisely equivalent
5412 // to the expression *((e1)+(e2)). This means the array "Base" may actually be
5413 // in the subscript position. As a result, we need to derive the array base
5414 // and index from the expression types.
5415 Expr *BaseExpr, *IndexExpr;
5416 QualType ResultType;
5417 if (LHSTy->isDependentType() || RHSTy->isDependentType()) {
5418 BaseExpr = LHSExp;
5419 IndexExpr = RHSExp;
5420 ResultType =
5421 getDependentArraySubscriptType(LHS: LHSExp, RHS: RHSExp, Ctx: getASTContext());
5422 } else if (const PointerType *PTy = LHSTy->getAs<PointerType>()) {
5423 BaseExpr = LHSExp;
5424 IndexExpr = RHSExp;
5425 ResultType = PTy->getPointeeType();
5426 } else if (const ObjCObjectPointerType *PTy =
5427 LHSTy->getAs<ObjCObjectPointerType>()) {
5428 BaseExpr = LHSExp;
5429 IndexExpr = RHSExp;
5430
5431 // Use custom logic if this should be the pseudo-object subscript
5432 // expression.
5433 if (!LangOpts.isSubscriptPointerArithmetic())
5434 return ObjC().BuildObjCSubscriptExpression(RB: RLoc, BaseExpr, IndexExpr,
5435 getterMethod: nullptr, setterMethod: nullptr);
5436
5437 ResultType = PTy->getPointeeType();
5438 } else if (const PointerType *PTy = RHSTy->getAs<PointerType>()) {
5439 // Handle the uncommon case of "123[Ptr]".
5440 BaseExpr = RHSExp;
5441 IndexExpr = LHSExp;
5442 ResultType = PTy->getPointeeType();
5443 } else if (const ObjCObjectPointerType *PTy =
5444 RHSTy->getAs<ObjCObjectPointerType>()) {
5445 // Handle the uncommon case of "123[Ptr]".
5446 BaseExpr = RHSExp;
5447 IndexExpr = LHSExp;
5448 ResultType = PTy->getPointeeType();
5449 if (!LangOpts.isSubscriptPointerArithmetic()) {
5450 Diag(Loc: LLoc, DiagID: diag::err_subscript_nonfragile_interface)
5451 << ResultType << BaseExpr->getSourceRange();
5452 return ExprError();
5453 }
5454 } else if (LHSTy->isSubscriptableVectorType()) {
5455 if (LHSTy->isBuiltinType() &&
5456 LHSTy->getAs<BuiltinType>()->isSveVLSBuiltinType()) {
5457 const BuiltinType *BTy = LHSTy->getAs<BuiltinType>();
5458 if (BTy->isSVEBool())
5459 return ExprError(Diag(Loc: LLoc, DiagID: diag::err_subscript_svbool_t)
5460 << LHSExp->getSourceRange()
5461 << RHSExp->getSourceRange());
5462 ResultType = BTy->getSveEltType(Ctx: Context);
5463 } else {
5464 const VectorType *VTy = LHSTy->getAs<VectorType>();
5465 ResultType = VTy->getElementType();
5466 }
5467 BaseExpr = LHSExp; // vectors: V[123]
5468 IndexExpr = RHSExp;
5469 // We apply C++ DR1213 to vector subscripting too.
5470 if (getLangOpts().CPlusPlus11 && LHSExp->isPRValue()) {
5471 ExprResult Materialized = TemporaryMaterializationConversion(E: LHSExp);
5472 if (Materialized.isInvalid())
5473 return ExprError();
5474 LHSExp = Materialized.get();
5475 }
5476 VK = LHSExp->getValueKind();
5477 if (VK != VK_PRValue)
5478 OK = OK_VectorComponent;
5479
5480 QualType BaseType = BaseExpr->getType();
5481 Qualifiers BaseQuals = BaseType.getQualifiers();
5482 Qualifiers MemberQuals = ResultType.getQualifiers();
5483 Qualifiers Combined = BaseQuals + MemberQuals;
5484 if (Combined != MemberQuals)
5485 ResultType = Context.getQualifiedType(T: ResultType, Qs: Combined);
5486 } else if (LHSTy->isArrayType()) {
5487 // If we see an array that wasn't promoted by
5488 // DefaultFunctionArrayLvalueConversion, it must be an array that
5489 // wasn't promoted because of the C90 rule that doesn't
5490 // allow promoting non-lvalue arrays. Warn, then
5491 // force the promotion here.
5492 Diag(Loc: LHSExp->getBeginLoc(), DiagID: diag::ext_subscript_non_lvalue)
5493 << LHSExp->getSourceRange();
5494 LHSExp = ImpCastExprToType(E: LHSExp, Type: Context.getArrayDecayedType(T: LHSTy),
5495 CK: CK_ArrayToPointerDecay).get();
5496 LHSTy = LHSExp->getType();
5497
5498 BaseExpr = LHSExp;
5499 IndexExpr = RHSExp;
5500 ResultType = LHSTy->castAs<PointerType>()->getPointeeType();
5501 } else if (RHSTy->isArrayType()) {
5502 // Same as previous, except for 123[f().a] case
5503 Diag(Loc: RHSExp->getBeginLoc(), DiagID: diag::ext_subscript_non_lvalue)
5504 << RHSExp->getSourceRange();
5505 RHSExp = ImpCastExprToType(E: RHSExp, Type: Context.getArrayDecayedType(T: RHSTy),
5506 CK: CK_ArrayToPointerDecay).get();
5507 RHSTy = RHSExp->getType();
5508
5509 BaseExpr = RHSExp;
5510 IndexExpr = LHSExp;
5511 ResultType = RHSTy->castAs<PointerType>()->getPointeeType();
5512 } else {
5513 return ExprError(Diag(Loc: LLoc, DiagID: diag::err_typecheck_subscript_value)
5514 << LHSExp->getSourceRange() << RHSExp->getSourceRange());
5515 }
5516 // C99 6.5.2.1p1
5517 if (!IndexExpr->getType()->isIntegerType() && !IndexExpr->isTypeDependent())
5518 return ExprError(Diag(Loc: LLoc, DiagID: diag::err_typecheck_subscript_not_integer)
5519 << IndexExpr->getSourceRange());
5520
5521 if ((IndexExpr->getType()->isSpecificBuiltinType(K: BuiltinType::Char_S) ||
5522 IndexExpr->getType()->isSpecificBuiltinType(K: BuiltinType::Char_U)) &&
5523 !IndexExpr->isTypeDependent()) {
5524 std::optional<llvm::APSInt> IntegerContantExpr =
5525 IndexExpr->getIntegerConstantExpr(Ctx: getASTContext());
5526 if (!IntegerContantExpr.has_value() ||
5527 IntegerContantExpr.value().isNegative())
5528 Diag(Loc: LLoc, DiagID: diag::warn_subscript_is_char) << IndexExpr->getSourceRange();
5529 }
5530
5531 // C99 6.5.2.1p1: "shall have type "pointer to *object* type". Similarly,
5532 // C++ [expr.sub]p1: The type "T" shall be a completely-defined object
5533 // type. Note that Functions are not objects, and that (in C99 parlance)
5534 // incomplete types are not object types.
5535 if (ResultType->isFunctionType()) {
5536 Diag(Loc: BaseExpr->getBeginLoc(), DiagID: diag::err_subscript_function_type)
5537 << ResultType << BaseExpr->getSourceRange();
5538 return ExprError();
5539 }
5540
5541 if (ResultType->isVoidType() && !getLangOpts().CPlusPlus) {
5542 // GNU extension: subscripting on pointer to void
5543 Diag(Loc: LLoc, DiagID: diag::ext_gnu_subscript_void_type)
5544 << BaseExpr->getSourceRange();
5545
5546 // C forbids expressions of unqualified void type from being l-values.
5547 // See IsCForbiddenLValueType.
5548 if (!ResultType.hasQualifiers())
5549 VK = VK_PRValue;
5550 } else if (!ResultType->isDependentType() &&
5551 !ResultType.isWebAssemblyReferenceType() &&
5552 RequireCompleteSizedType(
5553 Loc: LLoc, T: ResultType,
5554 DiagID: diag::err_subscript_incomplete_or_sizeless_type, Args: BaseExpr))
5555 return ExprError();
5556
5557 assert(VK == VK_PRValue || LangOpts.CPlusPlus ||
5558 !ResultType.isCForbiddenLValueType());
5559
5560 if (LHSExp->IgnoreParenImpCasts()->getType()->isVariablyModifiedType() &&
5561 FunctionScopes.size() > 1) {
5562 if (auto *TT =
5563 LHSExp->IgnoreParenImpCasts()->getType()->getAs<TypedefType>()) {
5564 for (auto I = FunctionScopes.rbegin(),
5565 E = std::prev(x: FunctionScopes.rend());
5566 I != E; ++I) {
5567 auto *CSI = dyn_cast<CapturingScopeInfo>(Val: *I);
5568 if (CSI == nullptr)
5569 break;
5570 DeclContext *DC = nullptr;
5571 if (auto *LSI = dyn_cast<LambdaScopeInfo>(Val: CSI))
5572 DC = LSI->CallOperator;
5573 else if (auto *CRSI = dyn_cast<CapturedRegionScopeInfo>(Val: CSI))
5574 DC = CRSI->TheCapturedDecl;
5575 else if (auto *BSI = dyn_cast<BlockScopeInfo>(Val: CSI))
5576 DC = BSI->TheDecl;
5577 if (DC) {
5578 if (DC->containsDecl(D: TT->getDecl()))
5579 break;
5580 captureVariablyModifiedType(
5581 Context, T: LHSExp->IgnoreParenImpCasts()->getType(), CSI);
5582 }
5583 }
5584 }
5585 }
5586
5587 return new (Context)
5588 ArraySubscriptExpr(LHSExp, RHSExp, ResultType, VK, OK, RLoc);
5589}
5590
5591bool Sema::CheckCXXDefaultArgExpr(SourceLocation CallLoc, FunctionDecl *FD,
5592 ParmVarDecl *Param, Expr *RewrittenInit,
5593 bool SkipImmediateInvocations) {
5594 if (Param->hasUnparsedDefaultArg()) {
5595 assert(!RewrittenInit && "Should not have a rewritten init expression yet");
5596 // If we've already cleared out the location for the default argument,
5597 // that means we're parsing it right now.
5598 if (!UnparsedDefaultArgLocs.count(Val: Param)) {
5599 Diag(Loc: Param->getBeginLoc(), DiagID: diag::err_recursive_default_argument) << FD;
5600 Diag(Loc: CallLoc, DiagID: diag::note_recursive_default_argument_used_here);
5601 Param->setInvalidDecl();
5602 return true;
5603 }
5604
5605 Diag(Loc: CallLoc, DiagID: diag::err_use_of_default_argument_to_function_declared_later)
5606 << FD << cast<CXXRecordDecl>(Val: FD->getDeclContext());
5607 Diag(Loc: UnparsedDefaultArgLocs[Param],
5608 DiagID: diag::note_default_argument_declared_here);
5609 return true;
5610 }
5611
5612 if (Param->hasUninstantiatedDefaultArg()) {
5613 assert(!RewrittenInit && "Should not have a rewitten init expression yet");
5614 if (InstantiateDefaultArgument(CallLoc, FD, Param))
5615 return true;
5616 }
5617
5618 Expr *Init = RewrittenInit ? RewrittenInit : Param->getInit();
5619 assert(Init && "default argument but no initializer?");
5620
5621 // If the default expression creates temporaries, we need to
5622 // push them to the current stack of expression temporaries so they'll
5623 // be properly destroyed.
5624 // FIXME: We should really be rebuilding the default argument with new
5625 // bound temporaries; see the comment in PR5810.
5626 // We don't need to do that with block decls, though, because
5627 // blocks in default argument expression can never capture anything.
5628 if (auto *InitWithCleanup = dyn_cast<ExprWithCleanups>(Val: Init)) {
5629 // Set the "needs cleanups" bit regardless of whether there are
5630 // any explicit objects.
5631 Cleanup.setExprNeedsCleanups(InitWithCleanup->cleanupsHaveSideEffects());
5632 // Append all the objects to the cleanup list. Right now, this
5633 // should always be a no-op, because blocks in default argument
5634 // expressions should never be able to capture anything.
5635 assert(!InitWithCleanup->getNumObjects() &&
5636 "default argument expression has capturing blocks?");
5637 }
5638 // C++ [expr.const]p15.1:
5639 // An expression or conversion is in an immediate function context if it is
5640 // potentially evaluated and [...] its innermost enclosing non-block scope
5641 // is a function parameter scope of an immediate function.
5642 EnterExpressionEvaluationContext EvalContext(
5643 *this,
5644 FD->isImmediateFunction()
5645 ? ExpressionEvaluationContext::ImmediateFunctionContext
5646 : ExpressionEvaluationContext::PotentiallyEvaluated,
5647 Param);
5648 ExprEvalContexts.back().IsCurrentlyCheckingDefaultArgumentOrInitializer =
5649 SkipImmediateInvocations;
5650 runWithSufficientStackSpace(Loc: CallLoc, Fn: [&] {
5651 MarkDeclarationsReferencedInExpr(E: Init, /*SkipLocalVariables=*/true);
5652 });
5653 return false;
5654}
5655
5656struct ImmediateCallVisitor : DynamicRecursiveASTVisitor {
5657 const ASTContext &Context;
5658 ImmediateCallVisitor(const ASTContext &Ctx) : Context(Ctx) {
5659 ShouldVisitImplicitCode = true;
5660 }
5661
5662 bool HasImmediateCalls = false;
5663
5664 bool VisitCallExpr(CallExpr *E) override {
5665 if (const FunctionDecl *FD = E->getDirectCallee())
5666 HasImmediateCalls |= FD->isImmediateFunction();
5667 return DynamicRecursiveASTVisitor::VisitStmt(S: E);
5668 }
5669
5670 bool VisitCXXConstructExpr(CXXConstructExpr *E) override {
5671 if (const FunctionDecl *FD = E->getConstructor())
5672 HasImmediateCalls |= FD->isImmediateFunction();
5673 return DynamicRecursiveASTVisitor::VisitStmt(S: E);
5674 }
5675
5676 // SourceLocExpr are not immediate invocations
5677 // but CXXDefaultInitExpr/CXXDefaultArgExpr containing a SourceLocExpr
5678 // need to be rebuilt so that they refer to the correct SourceLocation and
5679 // DeclContext.
5680 bool VisitSourceLocExpr(SourceLocExpr *E) override {
5681 HasImmediateCalls = true;
5682 return DynamicRecursiveASTVisitor::VisitStmt(S: E);
5683 }
5684
5685 // A nested lambda might have parameters with immediate invocations
5686 // in their default arguments.
5687 // The compound statement is not visited (as it does not constitute a
5688 // subexpression).
5689 // FIXME: We should consider visiting and transforming captures
5690 // with init expressions.
5691 bool VisitLambdaExpr(LambdaExpr *E) override {
5692 return VisitCXXMethodDecl(D: E->getCallOperator());
5693 }
5694
5695 bool VisitCXXDefaultArgExpr(CXXDefaultArgExpr *E) override {
5696 return TraverseStmt(S: E->getExpr());
5697 }
5698
5699 bool VisitCXXDefaultInitExpr(CXXDefaultInitExpr *E) override {
5700 return TraverseStmt(S: E->getExpr());
5701 }
5702};
5703
5704struct EnsureImmediateInvocationInDefaultArgs
5705 : TreeTransform<EnsureImmediateInvocationInDefaultArgs> {
5706 EnsureImmediateInvocationInDefaultArgs(Sema &SemaRef)
5707 : TreeTransform(SemaRef) {}
5708
5709 bool AlwaysRebuild() { return true; }
5710
5711 // Lambda can only have immediate invocations in the default
5712 // args of their parameters, which is transformed upon calling the closure.
5713 // The body is not a subexpression, so we have nothing to do.
5714 // FIXME: Immediate calls in capture initializers should be transformed.
5715 ExprResult TransformLambdaExpr(LambdaExpr *E) { return E; }
5716 ExprResult TransformBlockExpr(BlockExpr *E) { return E; }
5717
5718 // Make sure we don't rebuild the this pointer as it would
5719 // cause it to incorrectly point it to the outermost class
5720 // in the case of nested struct initialization.
5721 ExprResult TransformCXXThisExpr(CXXThisExpr *E) { return E; }
5722
5723 // Rewrite to source location to refer to the context in which they are used.
5724 ExprResult TransformSourceLocExpr(SourceLocExpr *E) {
5725 DeclContext *DC = E->getParentContext();
5726 if (DC == SemaRef.CurContext)
5727 return E;
5728
5729 // FIXME: During instantiation, because the rebuild of defaults arguments
5730 // is not always done in the context of the template instantiator,
5731 // we run the risk of producing a dependent source location
5732 // that would never be rebuilt.
5733 // This usually happens during overload resolution, or in contexts
5734 // where the value of the source location does not matter.
5735 // However, we should find a better way to deal with source location
5736 // of function templates.
5737 if (!SemaRef.CurrentInstantiationScope ||
5738 !SemaRef.CurContext->isDependentContext() || DC->isDependentContext())
5739 DC = SemaRef.CurContext;
5740
5741 return getDerived().RebuildSourceLocExpr(
5742 Kind: E->getIdentKind(), ResultTy: E->getType(), BuiltinLoc: E->getBeginLoc(), RPLoc: E->getEndLoc(), ParentContext: DC);
5743 }
5744};
5745
5746ExprResult Sema::BuildCXXDefaultArgExpr(SourceLocation CallLoc,
5747 FunctionDecl *FD, ParmVarDecl *Param,
5748 Expr *Init) {
5749 assert(Param->hasDefaultArg() && "can't build nonexistent default arg");
5750
5751 bool NestedDefaultChecking = isCheckingDefaultArgumentOrInitializer();
5752 bool NeedRebuild = needsRebuildOfDefaultArgOrInit();
5753 std::optional<ExpressionEvaluationContextRecord::InitializationContext>
5754 InitializationContext =
5755 OutermostDeclarationWithDelayedImmediateInvocations();
5756 if (!InitializationContext.has_value())
5757 InitializationContext.emplace(args&: CallLoc, args&: Param, args&: CurContext);
5758
5759 if (!Init && !Param->hasUnparsedDefaultArg()) {
5760 // Mark that we are replacing a default argument first.
5761 // If we are instantiating a template we won't have to
5762 // retransform immediate calls.
5763 // C++ [expr.const]p15.1:
5764 // An expression or conversion is in an immediate function context if it
5765 // is potentially evaluated and [...] its innermost enclosing non-block
5766 // scope is a function parameter scope of an immediate function.
5767 EnterExpressionEvaluationContext EvalContext(
5768 *this,
5769 FD->isImmediateFunction()
5770 ? ExpressionEvaluationContext::ImmediateFunctionContext
5771 : ExpressionEvaluationContext::PotentiallyEvaluated,
5772 Param);
5773
5774 if (Param->hasUninstantiatedDefaultArg()) {
5775 if (InstantiateDefaultArgument(CallLoc, FD, Param))
5776 return ExprError();
5777 }
5778 // CWG2631
5779 // An immediate invocation that is not evaluated where it appears is
5780 // evaluated and checked for whether it is a constant expression at the
5781 // point where the enclosing initializer is used in a function call.
5782 ImmediateCallVisitor V(getASTContext());
5783 if (!NestedDefaultChecking)
5784 V.TraverseDecl(D: Param);
5785
5786 // Rewrite the call argument that was created from the corresponding
5787 // parameter's default argument.
5788 if (V.HasImmediateCalls ||
5789 (NeedRebuild && isa_and_present<ExprWithCleanups>(Val: Param->getInit()))) {
5790 if (V.HasImmediateCalls)
5791 ExprEvalContexts.back().DelayedDefaultInitializationContext = {
5792 CallLoc, Param, CurContext};
5793 // Pass down lifetime extending flag, and collect temporaries in
5794 // CreateMaterializeTemporaryExpr when we rewrite the call argument.
5795 currentEvaluationContext().InLifetimeExtendingContext =
5796 parentEvaluationContext().InLifetimeExtendingContext;
5797 EnsureImmediateInvocationInDefaultArgs Immediate(*this);
5798 ExprResult Res;
5799 runWithSufficientStackSpace(Loc: CallLoc, Fn: [&] {
5800 Res = Immediate.TransformInitializer(Init: Param->getInit(),
5801 /*NotCopy=*/NotCopyInit: false);
5802 });
5803 if (Res.isInvalid())
5804 return ExprError();
5805 Res = ConvertParamDefaultArgument(Param, DefaultArg: Res.get(),
5806 EqualLoc: Res.get()->getBeginLoc());
5807 if (Res.isInvalid())
5808 return ExprError();
5809 Init = Res.get();
5810 }
5811 }
5812
5813 if (CheckCXXDefaultArgExpr(
5814 CallLoc, FD, Param, RewrittenInit: Init,
5815 /*SkipImmediateInvocations=*/NestedDefaultChecking))
5816 return ExprError();
5817
5818 return CXXDefaultArgExpr::Create(C: Context, Loc: InitializationContext->Loc, Param,
5819 RewrittenExpr: Init, UsedContext: InitializationContext->Context);
5820}
5821
5822static FieldDecl *FindFieldDeclInstantiationPattern(const ASTContext &Ctx,
5823 FieldDecl *Field) {
5824 if (FieldDecl *Pattern = Ctx.getInstantiatedFromUnnamedFieldDecl(Field))
5825 return Pattern;
5826 auto *ParentRD = cast<CXXRecordDecl>(Val: Field->getParent());
5827 CXXRecordDecl *ClassPattern = ParentRD->getTemplateInstantiationPattern();
5828 DeclContext::lookup_result Lookup =
5829 ClassPattern->lookup(Name: Field->getDeclName());
5830 auto Rng = llvm::make_filter_range(
5831 Range&: Lookup, Pred: [](auto &&L) { return isa<FieldDecl>(*L); });
5832 if (Rng.empty())
5833 return nullptr;
5834 // FIXME: this breaks clang/test/Modules/pr28812.cpp
5835 // assert(std::distance(Rng.begin(), Rng.end()) <= 1
5836 // && "Duplicated instantiation pattern for field decl");
5837 return cast<FieldDecl>(Val: *Rng.begin());
5838}
5839
5840ExprResult Sema::BuildCXXDefaultInitExpr(SourceLocation Loc, FieldDecl *Field) {
5841 assert(Field->hasInClassInitializer());
5842
5843 CXXThisScopeRAII This(*this, Field->getParent(), Qualifiers());
5844
5845 auto *ParentRD = cast<CXXRecordDecl>(Val: Field->getParent());
5846
5847 std::optional<ExpressionEvaluationContextRecord::InitializationContext>
5848 InitializationContext =
5849 OutermostDeclarationWithDelayedImmediateInvocations();
5850 if (!InitializationContext.has_value())
5851 InitializationContext.emplace(args&: Loc, args&: Field, args&: CurContext);
5852
5853 Expr *Init = nullptr;
5854
5855 bool NestedDefaultChecking = isCheckingDefaultArgumentOrInitializer();
5856 bool NeedRebuild = needsRebuildOfDefaultArgOrInit();
5857 EnterExpressionEvaluationContext EvalContext(
5858 *this, ExpressionEvaluationContext::PotentiallyEvaluated, Field);
5859
5860 if (!Field->getInClassInitializer()) {
5861 // Maybe we haven't instantiated the in-class initializer. Go check the
5862 // pattern FieldDecl to see if it has one.
5863 if (isTemplateInstantiation(Kind: ParentRD->getTemplateSpecializationKind())) {
5864 FieldDecl *Pattern =
5865 FindFieldDeclInstantiationPattern(Ctx: getASTContext(), Field);
5866 assert(Pattern && "We must have set the Pattern!");
5867 if (!Pattern->hasInClassInitializer() ||
5868 InstantiateInClassInitializer(PointOfInstantiation: Loc, Instantiation: Field, Pattern,
5869 TemplateArgs: getTemplateInstantiationArgs(D: Field))) {
5870 Field->setInvalidDecl();
5871 return ExprError();
5872 }
5873 }
5874 }
5875
5876 // CWG2631
5877 // An immediate invocation that is not evaluated where it appears is
5878 // evaluated and checked for whether it is a constant expression at the
5879 // point where the enclosing initializer is used in a [...] a constructor
5880 // definition, or an aggregate initialization.
5881 ImmediateCallVisitor V(getASTContext());
5882 if (!NestedDefaultChecking)
5883 V.TraverseDecl(D: Field);
5884
5885 // CWG1815
5886 // Support lifetime extension of temporary created by aggregate
5887 // initialization using a default member initializer. We should rebuild
5888 // the initializer in a lifetime extension context if the initializer
5889 // expression is an ExprWithCleanups. Then make sure the normal lifetime
5890 // extension code recurses into the default initializer and does lifetime
5891 // extension when warranted.
5892 bool ContainsAnyTemporaries =
5893 isa_and_present<ExprWithCleanups>(Val: Field->getInClassInitializer());
5894 if (Field->getInClassInitializer() &&
5895 !Field->getInClassInitializer()->containsErrors() &&
5896 (V.HasImmediateCalls || (NeedRebuild && ContainsAnyTemporaries))) {
5897 ExprEvalContexts.back().DelayedDefaultInitializationContext = {Loc, Field,
5898 CurContext};
5899 ExprEvalContexts.back().IsCurrentlyCheckingDefaultArgumentOrInitializer =
5900 NestedDefaultChecking;
5901 // Pass down lifetime extending flag, and collect temporaries in
5902 // CreateMaterializeTemporaryExpr when we rewrite the call argument.
5903 currentEvaluationContext().InLifetimeExtendingContext =
5904 parentEvaluationContext().InLifetimeExtendingContext;
5905 EnsureImmediateInvocationInDefaultArgs Immediate(*this);
5906 ExprResult Res;
5907 runWithSufficientStackSpace(Loc, Fn: [&] {
5908 Res = Immediate.TransformInitializer(Init: Field->getInClassInitializer(),
5909 /*CXXDirectInit=*/NotCopyInit: false);
5910 });
5911 if (!Res.isInvalid())
5912 Res = ConvertMemberDefaultInitExpression(FD: Field, InitExpr: Res.get(), InitLoc: Loc);
5913 if (Res.isInvalid()) {
5914 Field->setInvalidDecl();
5915 return ExprError();
5916 }
5917 Init = Res.get();
5918 }
5919
5920 if (Field->getInClassInitializer()) {
5921 Expr *E = Init ? Init : Field->getInClassInitializer();
5922 if (!NestedDefaultChecking)
5923 runWithSufficientStackSpace(Loc, Fn: [&] {
5924 MarkDeclarationsReferencedInExpr(E, /*SkipLocalVariables=*/false);
5925 });
5926 if (isInLifetimeExtendingContext())
5927 DiscardCleanupsInEvaluationContext();
5928 // C++11 [class.base.init]p7:
5929 // The initialization of each base and member constitutes a
5930 // full-expression.
5931 ExprResult Res = ActOnFinishFullExpr(Expr: E, /*DiscardedValue=*/false);
5932 if (Res.isInvalid()) {
5933 Field->setInvalidDecl();
5934 return ExprError();
5935 }
5936 Init = Res.get();
5937
5938 return CXXDefaultInitExpr::Create(Ctx: Context, Loc: InitializationContext->Loc,
5939 Field, UsedContext: InitializationContext->Context,
5940 RewrittenInitExpr: Init);
5941 }
5942
5943 // DR1351:
5944 // If the brace-or-equal-initializer of a non-static data member
5945 // invokes a defaulted default constructor of its class or of an
5946 // enclosing class in a potentially evaluated subexpression, the
5947 // program is ill-formed.
5948 //
5949 // This resolution is unworkable: the exception specification of the
5950 // default constructor can be needed in an unevaluated context, in
5951 // particular, in the operand of a noexcept-expression, and we can be
5952 // unable to compute an exception specification for an enclosed class.
5953 //
5954 // Any attempt to resolve the exception specification of a defaulted default
5955 // constructor before the initializer is lexically complete will ultimately
5956 // come here at which point we can diagnose it.
5957 RecordDecl *OutermostClass = ParentRD->getOuterLexicalRecordContext();
5958 Diag(Loc, DiagID: diag::err_default_member_initializer_not_yet_parsed)
5959 << OutermostClass << Field;
5960 Diag(Loc: Field->getEndLoc(),
5961 DiagID: diag::note_default_member_initializer_not_yet_parsed);
5962 // Recover by marking the field invalid, unless we're in a SFINAE context.
5963 if (!isSFINAEContext())
5964 Field->setInvalidDecl();
5965 return ExprError();
5966}
5967
5968VariadicCallType Sema::getVariadicCallType(FunctionDecl *FDecl,
5969 const FunctionProtoType *Proto,
5970 Expr *Fn) {
5971 if (Proto && Proto->isVariadic()) {
5972 if (isa_and_nonnull<CXXConstructorDecl>(Val: FDecl))
5973 return VariadicCallType::Constructor;
5974 else if (Fn && Fn->getType()->isBlockPointerType())
5975 return VariadicCallType::Block;
5976 else if (FDecl) {
5977 if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(Val: FDecl))
5978 if (Method->isInstance())
5979 return VariadicCallType::Method;
5980 } else if (Fn && Fn->getType() == Context.BoundMemberTy)
5981 return VariadicCallType::Method;
5982 return VariadicCallType::Function;
5983 }
5984 return VariadicCallType::DoesNotApply;
5985}
5986
5987namespace {
5988class FunctionCallCCC final : public FunctionCallFilterCCC {
5989public:
5990 FunctionCallCCC(Sema &SemaRef, const IdentifierInfo *FuncName,
5991 unsigned NumArgs, MemberExpr *ME)
5992 : FunctionCallFilterCCC(SemaRef, NumArgs, false, ME),
5993 FunctionName(FuncName) {}
5994
5995 bool ValidateCandidate(const TypoCorrection &candidate) override {
5996 if (!candidate.getCorrectionSpecifier() ||
5997 candidate.getCorrectionAsIdentifierInfo() != FunctionName) {
5998 return false;
5999 }
6000
6001 return FunctionCallFilterCCC::ValidateCandidate(candidate);
6002 }
6003
6004 std::unique_ptr<CorrectionCandidateCallback> clone() override {
6005 return std::make_unique<FunctionCallCCC>(args&: *this);
6006 }
6007
6008private:
6009 const IdentifierInfo *const FunctionName;
6010};
6011}
6012
6013static TypoCorrection TryTypoCorrectionForCall(Sema &S, Expr *Fn,
6014 FunctionDecl *FDecl,
6015 ArrayRef<Expr *> Args) {
6016 MemberExpr *ME = dyn_cast<MemberExpr>(Val: Fn);
6017 DeclarationName FuncName = FDecl->getDeclName();
6018 SourceLocation NameLoc = ME ? ME->getMemberLoc() : Fn->getBeginLoc();
6019
6020 FunctionCallCCC CCC(S, FuncName.getAsIdentifierInfo(), Args.size(), ME);
6021 if (TypoCorrection Corrected = S.CorrectTypo(
6022 Typo: DeclarationNameInfo(FuncName, NameLoc), LookupKind: Sema::LookupOrdinaryName,
6023 S: S.getScopeForContext(Ctx: S.CurContext), SS: nullptr, CCC,
6024 Mode: CorrectTypoKind::ErrorRecovery)) {
6025 if (NamedDecl *ND = Corrected.getFoundDecl()) {
6026 if (Corrected.isOverloaded()) {
6027 OverloadCandidateSet OCS(NameLoc, OverloadCandidateSet::CSK_Normal);
6028 OverloadCandidateSet::iterator Best;
6029 for (NamedDecl *CD : Corrected) {
6030 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Val: CD))
6031 S.AddOverloadCandidate(Function: FD, FoundDecl: DeclAccessPair::make(D: FD, AS: AS_none), Args,
6032 CandidateSet&: OCS);
6033 }
6034 switch (OCS.BestViableFunction(S, Loc: NameLoc, Best)) {
6035 case OR_Success:
6036 ND = Best->FoundDecl;
6037 Corrected.setCorrectionDecl(ND);
6038 break;
6039 default:
6040 break;
6041 }
6042 }
6043 ND = ND->getUnderlyingDecl();
6044 if (isa<ValueDecl>(Val: ND) || isa<FunctionTemplateDecl>(Val: ND))
6045 return Corrected;
6046 }
6047 }
6048 return TypoCorrection();
6049}
6050
6051// [C++26][[expr.unary.op]/p4
6052// A pointer to member is only formed when an explicit &
6053// is used and its operand is a qualified-id not enclosed in parentheses.
6054static bool isParenthetizedAndQualifiedAddressOfExpr(Expr *Fn) {
6055 if (!isa<ParenExpr>(Val: Fn))
6056 return false;
6057
6058 Fn = Fn->IgnoreParens();
6059
6060 auto *UO = dyn_cast<UnaryOperator>(Val: Fn);
6061 if (!UO || UO->getOpcode() != clang::UO_AddrOf)
6062 return false;
6063 if (auto *DRE = dyn_cast<DeclRefExpr>(Val: UO->getSubExpr()->IgnoreParens())) {
6064 return DRE->hasQualifier();
6065 }
6066 if (auto *OVL = dyn_cast<OverloadExpr>(Val: UO->getSubExpr()->IgnoreParens()))
6067 return bool(OVL->getQualifier());
6068 return false;
6069}
6070
6071bool
6072Sema::ConvertArgumentsForCall(CallExpr *Call, Expr *Fn,
6073 FunctionDecl *FDecl,
6074 const FunctionProtoType *Proto,
6075 ArrayRef<Expr *> Args,
6076 SourceLocation RParenLoc,
6077 bool IsExecConfig) {
6078 // Bail out early if calling a builtin with custom typechecking.
6079 if (FDecl)
6080 if (unsigned ID = FDecl->getBuiltinID())
6081 if (Context.BuiltinInfo.hasCustomTypechecking(ID))
6082 return false;
6083
6084 // C99 6.5.2.2p7 - the arguments are implicitly converted, as if by
6085 // assignment, to the types of the corresponding parameter, ...
6086
6087 bool AddressOf = isParenthetizedAndQualifiedAddressOfExpr(Fn);
6088 bool HasExplicitObjectParameter =
6089 !AddressOf && FDecl && FDecl->hasCXXExplicitFunctionObjectParameter();
6090 unsigned ExplicitObjectParameterOffset = HasExplicitObjectParameter ? 1 : 0;
6091 unsigned NumParams = Proto->getNumParams();
6092 bool Invalid = false;
6093 unsigned MinArgs = FDecl ? FDecl->getMinRequiredArguments() : NumParams;
6094 unsigned FnKind = Fn->getType()->isBlockPointerType()
6095 ? 1 /* block */
6096 : (IsExecConfig ? 3 /* kernel function (exec config) */
6097 : 0 /* function */);
6098
6099 // If too few arguments are available (and we don't have default
6100 // arguments for the remaining parameters), don't make the call.
6101 if (Args.size() < NumParams) {
6102 if (Args.size() < MinArgs) {
6103 TypoCorrection TC;
6104 if (FDecl && (TC = TryTypoCorrectionForCall(S&: *this, Fn, FDecl, Args))) {
6105 unsigned diag_id =
6106 MinArgs == NumParams && !Proto->isVariadic()
6107 ? diag::err_typecheck_call_too_few_args_suggest
6108 : diag::err_typecheck_call_too_few_args_at_least_suggest;
6109 diagnoseTypo(
6110 Correction: TC, TypoDiag: PDiag(DiagID: diag_id)
6111 << FnKind << MinArgs - ExplicitObjectParameterOffset
6112 << static_cast<unsigned>(Args.size()) -
6113 ExplicitObjectParameterOffset
6114 << HasExplicitObjectParameter << TC.getCorrectionRange());
6115 } else if (MinArgs - ExplicitObjectParameterOffset == 1 && FDecl &&
6116 FDecl->getParamDecl(i: ExplicitObjectParameterOffset)
6117 ->getDeclName())
6118 Diag(Loc: RParenLoc,
6119 DiagID: MinArgs == NumParams && !Proto->isVariadic()
6120 ? diag::err_typecheck_call_too_few_args_one
6121 : diag::err_typecheck_call_too_few_args_at_least_one)
6122 << FnKind << FDecl->getParamDecl(i: ExplicitObjectParameterOffset)
6123 << HasExplicitObjectParameter << Fn->getSourceRange();
6124 else
6125 Diag(Loc: RParenLoc, DiagID: MinArgs == NumParams && !Proto->isVariadic()
6126 ? diag::err_typecheck_call_too_few_args
6127 : diag::err_typecheck_call_too_few_args_at_least)
6128 << FnKind << MinArgs - ExplicitObjectParameterOffset
6129 << static_cast<unsigned>(Args.size()) -
6130 ExplicitObjectParameterOffset
6131 << HasExplicitObjectParameter << Fn->getSourceRange();
6132
6133 // Emit the location of the prototype.
6134 if (!TC && FDecl && !FDecl->getBuiltinID() && !IsExecConfig)
6135 Diag(Loc: FDecl->getLocation(), DiagID: diag::note_callee_decl)
6136 << FDecl << FDecl->getParametersSourceRange();
6137
6138 return true;
6139 }
6140 // We reserve space for the default arguments when we create
6141 // the call expression, before calling ConvertArgumentsForCall.
6142 assert((Call->getNumArgs() == NumParams) &&
6143 "We should have reserved space for the default arguments before!");
6144 }
6145
6146 // If too many are passed and not variadic, error on the extras and drop
6147 // them.
6148 if (Args.size() > NumParams) {
6149 if (!Proto->isVariadic()) {
6150 TypoCorrection TC;
6151 if (FDecl && (TC = TryTypoCorrectionForCall(S&: *this, Fn, FDecl, Args))) {
6152 unsigned diag_id =
6153 MinArgs == NumParams && !Proto->isVariadic()
6154 ? diag::err_typecheck_call_too_many_args_suggest
6155 : diag::err_typecheck_call_too_many_args_at_most_suggest;
6156 diagnoseTypo(
6157 Correction: TC, TypoDiag: PDiag(DiagID: diag_id)
6158 << FnKind << NumParams - ExplicitObjectParameterOffset
6159 << static_cast<unsigned>(Args.size()) -
6160 ExplicitObjectParameterOffset
6161 << HasExplicitObjectParameter << TC.getCorrectionRange());
6162 } else if (NumParams - ExplicitObjectParameterOffset == 1 && FDecl &&
6163 FDecl->getParamDecl(i: ExplicitObjectParameterOffset)
6164 ->getDeclName())
6165 Diag(Loc: Args[NumParams]->getBeginLoc(),
6166 DiagID: MinArgs == NumParams
6167 ? diag::err_typecheck_call_too_many_args_one
6168 : diag::err_typecheck_call_too_many_args_at_most_one)
6169 << FnKind << FDecl->getParamDecl(i: ExplicitObjectParameterOffset)
6170 << static_cast<unsigned>(Args.size()) -
6171 ExplicitObjectParameterOffset
6172 << HasExplicitObjectParameter << Fn->getSourceRange()
6173 << SourceRange(Args[NumParams]->getBeginLoc(),
6174 Args.back()->getEndLoc());
6175 else
6176 Diag(Loc: Args[NumParams]->getBeginLoc(),
6177 DiagID: MinArgs == NumParams
6178 ? diag::err_typecheck_call_too_many_args
6179 : diag::err_typecheck_call_too_many_args_at_most)
6180 << FnKind << NumParams - ExplicitObjectParameterOffset
6181 << static_cast<unsigned>(Args.size()) -
6182 ExplicitObjectParameterOffset
6183 << HasExplicitObjectParameter << Fn->getSourceRange()
6184 << SourceRange(Args[NumParams]->getBeginLoc(),
6185 Args.back()->getEndLoc());
6186
6187 // Emit the location of the prototype.
6188 if (!TC && FDecl && !FDecl->getBuiltinID() && !IsExecConfig)
6189 Diag(Loc: FDecl->getLocation(), DiagID: diag::note_callee_decl)
6190 << FDecl << FDecl->getParametersSourceRange();
6191
6192 // This deletes the extra arguments.
6193 Call->shrinkNumArgs(NewNumArgs: NumParams);
6194 return true;
6195 }
6196 }
6197 SmallVector<Expr *, 8> AllArgs;
6198 VariadicCallType CallType = getVariadicCallType(FDecl, Proto, Fn);
6199
6200 Invalid = GatherArgumentsForCall(CallLoc: Call->getExprLoc(), FDecl, Proto, FirstParam: 0, Args,
6201 AllArgs, CallType);
6202 if (Invalid)
6203 return true;
6204 unsigned TotalNumArgs = AllArgs.size();
6205 for (unsigned i = 0; i < TotalNumArgs; ++i)
6206 Call->setArg(Arg: i, ArgExpr: AllArgs[i]);
6207
6208 Call->computeDependence();
6209 return false;
6210}
6211
6212bool Sema::GatherArgumentsForCall(SourceLocation CallLoc, FunctionDecl *FDecl,
6213 const FunctionProtoType *Proto,
6214 unsigned FirstParam, ArrayRef<Expr *> Args,
6215 SmallVectorImpl<Expr *> &AllArgs,
6216 VariadicCallType CallType, bool AllowExplicit,
6217 bool IsListInitialization) {
6218 unsigned NumParams = Proto->getNumParams();
6219 bool Invalid = false;
6220 size_t ArgIx = 0;
6221 // Continue to check argument types (even if we have too few/many args).
6222 for (unsigned i = FirstParam; i < NumParams; i++) {
6223 QualType ProtoArgType = Proto->getParamType(i);
6224
6225 Expr *Arg;
6226 ParmVarDecl *Param = FDecl ? FDecl->getParamDecl(i) : nullptr;
6227 if (ArgIx < Args.size()) {
6228 Arg = Args[ArgIx++];
6229
6230 if (RequireCompleteType(Loc: Arg->getBeginLoc(), T: ProtoArgType,
6231 DiagID: diag::err_call_incomplete_argument, Args: Arg))
6232 return true;
6233
6234 // Strip the unbridged-cast placeholder expression off, if applicable.
6235 bool CFAudited = false;
6236 if (Arg->getType() == Context.ARCUnbridgedCastTy &&
6237 FDecl && FDecl->hasAttr<CFAuditedTransferAttr>() &&
6238 (!Param || !Param->hasAttr<CFConsumedAttr>()))
6239 Arg = ObjC().stripARCUnbridgedCast(e: Arg);
6240 else if (getLangOpts().ObjCAutoRefCount &&
6241 FDecl && FDecl->hasAttr<CFAuditedTransferAttr>() &&
6242 (!Param || !Param->hasAttr<CFConsumedAttr>()))
6243 CFAudited = true;
6244
6245 if (Proto->getExtParameterInfo(I: i).isNoEscape() &&
6246 ProtoArgType->isBlockPointerType())
6247 if (auto *BE = dyn_cast<BlockExpr>(Val: Arg->IgnoreParenNoopCasts(Ctx: Context)))
6248 BE->getBlockDecl()->setDoesNotEscape();
6249 if ((Proto->getExtParameterInfo(I: i).getABI() == ParameterABI::HLSLOut ||
6250 Proto->getExtParameterInfo(I: i).getABI() == ParameterABI::HLSLInOut)) {
6251 ExprResult ArgExpr = HLSL().ActOnOutParamExpr(Param, Arg);
6252 if (ArgExpr.isInvalid())
6253 return true;
6254 Arg = ArgExpr.getAs<Expr>();
6255 }
6256
6257 InitializedEntity Entity =
6258 Param ? InitializedEntity::InitializeParameter(Context, Parm: Param,
6259 Type: ProtoArgType)
6260 : InitializedEntity::InitializeParameter(
6261 Context, Type: ProtoArgType, Consumed: Proto->isParamConsumed(I: i));
6262
6263 // Remember that parameter belongs to a CF audited API.
6264 if (CFAudited)
6265 Entity.setParameterCFAudited();
6266
6267 // Warn if argument has OBT but parameter doesn't, discarding OBTs at
6268 // function boundaries is a common oversight.
6269 if (const auto *OBT = Arg->getType()->getAs<OverflowBehaviorType>();
6270 OBT && !ProtoArgType->isOverflowBehaviorType()) {
6271 bool isPedantic =
6272 OBT->isUnsignedIntegerOrEnumerationType() && OBT->isWrapKind();
6273 Diag(Loc: Arg->getExprLoc(),
6274 DiagID: isPedantic ? diag::warn_obt_discarded_at_function_boundary_pedantic
6275 : diag::warn_obt_discarded_at_function_boundary)
6276 << Arg->getType() << ProtoArgType;
6277 }
6278
6279 ExprResult ArgE = PerformCopyInitialization(
6280 Entity, EqualLoc: SourceLocation(), Init: Arg, TopLevelOfInitList: IsListInitialization, AllowExplicit);
6281 if (ArgE.isInvalid())
6282 return true;
6283
6284 Arg = ArgE.getAs<Expr>();
6285 } else {
6286 assert(Param && "can't use default arguments without a known callee");
6287
6288 ExprResult ArgExpr = BuildCXXDefaultArgExpr(CallLoc, FD: FDecl, Param);
6289 if (ArgExpr.isInvalid())
6290 return true;
6291
6292 Arg = ArgExpr.getAs<Expr>();
6293 }
6294
6295 // Check for array bounds violations for each argument to the call. This
6296 // check only triggers warnings when the argument isn't a more complex Expr
6297 // with its own checking, such as a BinaryOperator.
6298 CheckArrayAccess(E: Arg);
6299
6300 // Check for violations of C99 static array rules (C99 6.7.5.3p7).
6301 CheckStaticArrayArgument(CallLoc, Param, ArgExpr: Arg);
6302
6303 AllArgs.push_back(Elt: Arg);
6304 }
6305
6306 // If this is a variadic call, handle args passed through "...".
6307 if (CallType != VariadicCallType::DoesNotApply) {
6308 // Assume that extern "C" functions with variadic arguments that
6309 // return __unknown_anytype aren't *really* variadic.
6310 if (Proto->getReturnType() == Context.UnknownAnyTy && FDecl &&
6311 FDecl->isExternC()) {
6312 for (Expr *A : Args.slice(N: ArgIx)) {
6313 QualType paramType; // ignored
6314 ExprResult arg = checkUnknownAnyArg(callLoc: CallLoc, result: A, paramType);
6315 Invalid |= arg.isInvalid();
6316 AllArgs.push_back(Elt: arg.get());
6317 }
6318
6319 // Otherwise do argument promotion, (C99 6.5.2.2p7).
6320 } else {
6321 for (Expr *A : Args.slice(N: ArgIx)) {
6322 ExprResult Arg = DefaultVariadicArgumentPromotion(E: A, CT: CallType, FDecl);
6323 Invalid |= Arg.isInvalid();
6324 AllArgs.push_back(Elt: Arg.get());
6325 }
6326 }
6327
6328 // Check for array bounds violations.
6329 for (Expr *A : Args.slice(N: ArgIx))
6330 CheckArrayAccess(E: A);
6331 }
6332 return Invalid;
6333}
6334
6335static void DiagnoseCalleeStaticArrayParam(Sema &S, ParmVarDecl *PVD) {
6336 TypeLoc TL = PVD->getTypeSourceInfo()->getTypeLoc();
6337 if (DecayedTypeLoc DTL = TL.getAs<DecayedTypeLoc>())
6338 TL = DTL.getOriginalLoc();
6339 if (ArrayTypeLoc ATL = TL.getAs<ArrayTypeLoc>())
6340 S.Diag(Loc: PVD->getLocation(), DiagID: diag::note_callee_static_array)
6341 << ATL.getLocalSourceRange();
6342}
6343
6344void
6345Sema::CheckStaticArrayArgument(SourceLocation CallLoc,
6346 ParmVarDecl *Param,
6347 const Expr *ArgExpr) {
6348 // Static array parameters are not supported in C++.
6349 if (!Param || getLangOpts().CPlusPlus)
6350 return;
6351
6352 QualType OrigTy = Param->getOriginalType();
6353
6354 const ArrayType *AT = Context.getAsArrayType(T: OrigTy);
6355 if (!AT || AT->getSizeModifier() != ArraySizeModifier::Static)
6356 return;
6357
6358 if (ArgExpr->isNullPointerConstant(Ctx&: Context,
6359 NPC: Expr::NPC_NeverValueDependent)) {
6360 Diag(Loc: CallLoc, DiagID: diag::warn_null_arg) << ArgExpr->getSourceRange();
6361 DiagnoseCalleeStaticArrayParam(S&: *this, PVD: Param);
6362 return;
6363 }
6364
6365 const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(Val: AT);
6366 if (!CAT)
6367 return;
6368
6369 const ConstantArrayType *ArgCAT =
6370 Context.getAsConstantArrayType(T: ArgExpr->IgnoreParenCasts()->getType());
6371 if (!ArgCAT)
6372 return;
6373
6374 if (getASTContext().hasSameUnqualifiedType(T1: CAT->getElementType(),
6375 T2: ArgCAT->getElementType())) {
6376 if (ArgCAT->getSize().ult(RHS: CAT->getSize())) {
6377 Diag(Loc: CallLoc, DiagID: diag::warn_static_array_too_small)
6378 << ArgExpr->getSourceRange() << (unsigned)ArgCAT->getZExtSize()
6379 << (unsigned)CAT->getZExtSize() << 0;
6380 DiagnoseCalleeStaticArrayParam(S&: *this, PVD: Param);
6381 }
6382 return;
6383 }
6384
6385 std::optional<CharUnits> ArgSize =
6386 getASTContext().getTypeSizeInCharsIfKnown(Ty: ArgCAT);
6387 std::optional<CharUnits> ParmSize =
6388 getASTContext().getTypeSizeInCharsIfKnown(Ty: CAT);
6389 if (ArgSize && ParmSize && *ArgSize < *ParmSize) {
6390 Diag(Loc: CallLoc, DiagID: diag::warn_static_array_too_small)
6391 << ArgExpr->getSourceRange() << (unsigned)ArgSize->getQuantity()
6392 << (unsigned)ParmSize->getQuantity() << 1;
6393 DiagnoseCalleeStaticArrayParam(S&: *this, PVD: Param);
6394 }
6395}
6396
6397/// Given a function expression of unknown-any type, try to rebuild it
6398/// to have a function type.
6399static ExprResult rebuildUnknownAnyFunction(Sema &S, Expr *fn);
6400
6401/// Is the given type a placeholder that we need to lower out
6402/// immediately during argument processing?
6403static bool isPlaceholderToRemoveAsArg(QualType type) {
6404 // Placeholders are never sugared.
6405 const BuiltinType *placeholder = dyn_cast<BuiltinType>(Val&: type);
6406 if (!placeholder) return false;
6407
6408 switch (placeholder->getKind()) {
6409 // Ignore all the non-placeholder types.
6410#define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
6411 case BuiltinType::Id:
6412#include "clang/Basic/OpenCLImageTypes.def"
6413#define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \
6414 case BuiltinType::Id:
6415#include "clang/Basic/OpenCLExtensionTypes.def"
6416 // In practice we'll never use this, since all SVE types are sugared
6417 // via TypedefTypes rather than exposed directly as BuiltinTypes.
6418#define SVE_TYPE(Name, Id, SingletonId) \
6419 case BuiltinType::Id:
6420#include "clang/Basic/AArch64ACLETypes.def"
6421#define PPC_VECTOR_TYPE(Name, Id, Size) \
6422 case BuiltinType::Id:
6423#include "clang/Basic/PPCTypes.def"
6424#define RVV_TYPE(Name, Id, SingletonId) case BuiltinType::Id:
6425#include "clang/Basic/RISCVVTypes.def"
6426#define WASM_TYPE(Name, Id, SingletonId) case BuiltinType::Id:
6427#include "clang/Basic/WebAssemblyReferenceTypes.def"
6428#define AMDGPU_TYPE(Name, Id, SingletonId, Width, Align) case BuiltinType::Id:
6429#include "clang/Basic/AMDGPUTypes.def"
6430#define HLSL_INTANGIBLE_TYPE(Name, Id, SingletonId) case BuiltinType::Id:
6431#include "clang/Basic/HLSLIntangibleTypes.def"
6432#define PLACEHOLDER_TYPE(ID, SINGLETON_ID)
6433#define BUILTIN_TYPE(ID, SINGLETON_ID) case BuiltinType::ID:
6434#include "clang/AST/BuiltinTypes.def"
6435 return false;
6436
6437 case BuiltinType::UnresolvedTemplate:
6438 // We cannot lower out overload sets; they might validly be resolved
6439 // by the call machinery.
6440 case BuiltinType::Overload:
6441 return false;
6442
6443 // Unbridged casts in ARC can be handled in some call positions and
6444 // should be left in place.
6445 case BuiltinType::ARCUnbridgedCast:
6446 return false;
6447
6448 // Pseudo-objects should be converted as soon as possible.
6449 case BuiltinType::PseudoObject:
6450 return true;
6451
6452 // The debugger mode could theoretically but currently does not try
6453 // to resolve unknown-typed arguments based on known parameter types.
6454 case BuiltinType::UnknownAny:
6455 return true;
6456
6457 // These are always invalid as call arguments and should be reported.
6458 case BuiltinType::BoundMember:
6459 case BuiltinType::BuiltinFn:
6460 case BuiltinType::IncompleteMatrixIdx:
6461 case BuiltinType::ArraySection:
6462 case BuiltinType::OMPArrayShaping:
6463 case BuiltinType::OMPIterator:
6464 return true;
6465
6466 }
6467 llvm_unreachable("bad builtin type kind");
6468}
6469
6470bool Sema::CheckArgsForPlaceholders(MultiExprArg args) {
6471 // Apply this processing to all the arguments at once instead of
6472 // dying at the first failure.
6473 bool hasInvalid = false;
6474 for (size_t i = 0, e = args.size(); i != e; i++) {
6475 if (isPlaceholderToRemoveAsArg(type: args[i]->getType())) {
6476 ExprResult result = CheckPlaceholderExpr(E: args[i]);
6477 if (result.isInvalid()) hasInvalid = true;
6478 else args[i] = result.get();
6479 }
6480 }
6481 return hasInvalid;
6482}
6483
6484/// If a builtin function has a pointer argument with no explicit address
6485/// space, then it should be able to accept a pointer to any address
6486/// space as input. In order to do this, we need to replace the
6487/// standard builtin declaration with one that uses the same address space
6488/// as the call.
6489///
6490/// \returns nullptr If this builtin is not a candidate for a rewrite i.e.
6491/// it does not contain any pointer arguments without
6492/// an address space qualifer. Otherwise the rewritten
6493/// FunctionDecl is returned.
6494/// TODO: Handle pointer return types.
6495static FunctionDecl *rewriteBuiltinFunctionDecl(Sema *Sema, ASTContext &Context,
6496 FunctionDecl *FDecl,
6497 MultiExprArg ArgExprs) {
6498
6499 QualType DeclType = FDecl->getType();
6500 const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(Val&: DeclType);
6501
6502 if (!Context.BuiltinInfo.hasPtrArgsOrResult(ID: FDecl->getBuiltinID()) || !FT ||
6503 ArgExprs.size() < FT->getNumParams())
6504 return nullptr;
6505
6506 bool NeedsNewDecl = false;
6507 unsigned i = 0;
6508 SmallVector<QualType, 8> OverloadParams;
6509
6510 {
6511 // The lvalue conversions in this loop are only for type resolution and
6512 // don't actually occur.
6513 EnterExpressionEvaluationContext Unevaluated(
6514 *Sema, Sema::ExpressionEvaluationContext::Unevaluated);
6515 Sema::SFINAETrap Trap(*Sema, /*ForValidityCheck=*/true);
6516
6517 for (QualType ParamType : FT->param_types()) {
6518
6519 // Convert array arguments to pointer to simplify type lookup.
6520 ExprResult ArgRes =
6521 Sema->DefaultFunctionArrayLvalueConversion(E: ArgExprs[i++]);
6522 if (ArgRes.isInvalid())
6523 return nullptr;
6524 Expr *Arg = ArgRes.get();
6525 QualType ArgType = Arg->getType();
6526 if (!ParamType->isPointerType() ||
6527 ParamType->getPointeeType().hasAddressSpace() ||
6528 !ArgType->isPointerType() ||
6529 !ArgType->getPointeeType().hasAddressSpace() ||
6530 isPtrSizeAddressSpace(AS: ArgType->getPointeeType().getAddressSpace())) {
6531 OverloadParams.push_back(Elt: ParamType);
6532 continue;
6533 }
6534
6535 QualType PointeeType = ParamType->getPointeeType();
6536 NeedsNewDecl = true;
6537 LangAS AS = ArgType->getPointeeType().getAddressSpace();
6538
6539 PointeeType = Context.getAddrSpaceQualType(T: PointeeType, AddressSpace: AS);
6540 OverloadParams.push_back(Elt: Context.getPointerType(T: PointeeType));
6541 }
6542 }
6543
6544 if (!NeedsNewDecl)
6545 return nullptr;
6546
6547 FunctionProtoType::ExtProtoInfo EPI;
6548 EPI.Variadic = FT->isVariadic();
6549 QualType OverloadTy = Context.getFunctionType(ResultTy: FT->getReturnType(),
6550 Args: OverloadParams, EPI);
6551 DeclContext *Parent = FDecl->getParent();
6552 FunctionDecl *OverloadDecl = FunctionDecl::Create(
6553 C&: Context, DC: Parent, StartLoc: FDecl->getLocation(), NLoc: FDecl->getLocation(),
6554 N: FDecl->getIdentifier(), T: OverloadTy,
6555 /*TInfo=*/nullptr, SC: SC_Extern, UsesFPIntrin: Sema->getCurFPFeatures().isFPConstrained(),
6556 isInlineSpecified: false,
6557 /*hasPrototype=*/hasWrittenPrototype: true);
6558 SmallVector<ParmVarDecl*, 16> Params;
6559 FT = cast<FunctionProtoType>(Val&: OverloadTy);
6560 for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i) {
6561 QualType ParamType = FT->getParamType(i);
6562 ParmVarDecl *Parm =
6563 ParmVarDecl::Create(C&: Context, DC: OverloadDecl, StartLoc: SourceLocation(),
6564 IdLoc: SourceLocation(), Id: nullptr, T: ParamType,
6565 /*TInfo=*/nullptr, S: SC_None, DefArg: nullptr);
6566 Parm->setScopeInfo(scopeDepth: 0, parameterIndex: i);
6567 Params.push_back(Elt: Parm);
6568 }
6569 OverloadDecl->setParams(Params);
6570 // We cannot merge host/device attributes of redeclarations. They have to
6571 // be consistent when created.
6572 if (Sema->LangOpts.CUDA) {
6573 if (FDecl->hasAttr<CUDAHostAttr>())
6574 OverloadDecl->addAttr(A: CUDAHostAttr::CreateImplicit(Ctx&: Context));
6575 if (FDecl->hasAttr<CUDADeviceAttr>())
6576 OverloadDecl->addAttr(A: CUDADeviceAttr::CreateImplicit(Ctx&: Context));
6577 }
6578 Sema->mergeDeclAttributes(New: OverloadDecl, Old: FDecl);
6579 return OverloadDecl;
6580}
6581
6582static void checkDirectCallValidity(Sema &S, const Expr *Fn,
6583 FunctionDecl *Callee,
6584 MultiExprArg ArgExprs) {
6585 // `Callee` (when called with ArgExprs) may be ill-formed. enable_if (and
6586 // similar attributes) really don't like it when functions are called with an
6587 // invalid number of args.
6588 if (S.TooManyArguments(NumParams: Callee->getNumParams(), NumArgs: ArgExprs.size(),
6589 /*PartialOverloading=*/false) &&
6590 !Callee->isVariadic())
6591 return;
6592 if (Callee->getMinRequiredArguments() > ArgExprs.size())
6593 return;
6594
6595 if (const EnableIfAttr *Attr =
6596 S.CheckEnableIf(Function: Callee, CallLoc: Fn->getBeginLoc(), Args: ArgExprs, MissingImplicitThis: true)) {
6597 S.Diag(Loc: Fn->getBeginLoc(),
6598 DiagID: isa<CXXMethodDecl>(Val: Callee)
6599 ? diag::err_ovl_no_viable_member_function_in_call
6600 : diag::err_ovl_no_viable_function_in_call)
6601 << Callee << Callee->getSourceRange();
6602 S.Diag(Loc: Callee->getLocation(),
6603 DiagID: diag::note_ovl_candidate_disabled_by_function_cond_attr)
6604 << Attr->getCond()->getSourceRange() << Attr->getMessage();
6605 return;
6606 }
6607}
6608
6609static bool enclosingClassIsRelatedToClassInWhichMembersWereFound(
6610 const UnresolvedMemberExpr *const UME, Sema &S) {
6611
6612 const auto GetFunctionLevelDCIfCXXClass =
6613 [](Sema &S) -> const CXXRecordDecl * {
6614 const DeclContext *const DC = S.getFunctionLevelDeclContext();
6615 if (!DC || !DC->getParent())
6616 return nullptr;
6617
6618 // If the call to some member function was made from within a member
6619 // function body 'M' return return 'M's parent.
6620 if (const auto *MD = dyn_cast<CXXMethodDecl>(Val: DC))
6621 return MD->getParent()->getCanonicalDecl();
6622 // else the call was made from within a default member initializer of a
6623 // class, so return the class.
6624 if (const auto *RD = dyn_cast<CXXRecordDecl>(Val: DC))
6625 return RD->getCanonicalDecl();
6626 return nullptr;
6627 };
6628 // If our DeclContext is neither a member function nor a class (in the
6629 // case of a lambda in a default member initializer), we can't have an
6630 // enclosing 'this'.
6631
6632 const CXXRecordDecl *const CurParentClass = GetFunctionLevelDCIfCXXClass(S);
6633 if (!CurParentClass)
6634 return false;
6635
6636 // The naming class for implicit member functions call is the class in which
6637 // name lookup starts.
6638 const CXXRecordDecl *const NamingClass =
6639 UME->getNamingClass()->getCanonicalDecl();
6640 assert(NamingClass && "Must have naming class even for implicit access");
6641
6642 // If the unresolved member functions were found in a 'naming class' that is
6643 // related (either the same or derived from) to the class that contains the
6644 // member function that itself contained the implicit member access.
6645
6646 return CurParentClass == NamingClass ||
6647 CurParentClass->isDerivedFrom(Base: NamingClass);
6648}
6649
6650static void
6651tryImplicitlyCaptureThisIfImplicitMemberFunctionAccessWithDependentArgs(
6652 Sema &S, const UnresolvedMemberExpr *const UME, SourceLocation CallLoc) {
6653
6654 if (!UME)
6655 return;
6656
6657 LambdaScopeInfo *const CurLSI = S.getCurLambda();
6658 // Only try and implicitly capture 'this' within a C++ Lambda if it hasn't
6659 // already been captured, or if this is an implicit member function call (if
6660 // it isn't, an attempt to capture 'this' should already have been made).
6661 if (!CurLSI || CurLSI->ImpCaptureStyle == CurLSI->ImpCap_None ||
6662 !UME->isImplicitAccess() || CurLSI->isCXXThisCaptured())
6663 return;
6664
6665 // Check if the naming class in which the unresolved members were found is
6666 // related (same as or is a base of) to the enclosing class.
6667
6668 if (!enclosingClassIsRelatedToClassInWhichMembersWereFound(UME, S))
6669 return;
6670
6671
6672 DeclContext *EnclosingFunctionCtx = S.CurContext->getParent()->getParent();
6673 // If the enclosing function is not dependent, then this lambda is
6674 // capture ready, so if we can capture this, do so.
6675 if (!EnclosingFunctionCtx->isDependentContext()) {
6676 // If the current lambda and all enclosing lambdas can capture 'this' -
6677 // then go ahead and capture 'this' (since our unresolved overload set
6678 // contains at least one non-static member function).
6679 if (!S.CheckCXXThisCapture(Loc: CallLoc, /*Explcit*/ Explicit: false, /*Diagnose*/ BuildAndDiagnose: false))
6680 S.CheckCXXThisCapture(Loc: CallLoc);
6681 } else if (S.CurContext->isDependentContext()) {
6682 // ... since this is an implicit member reference, that might potentially
6683 // involve a 'this' capture, mark 'this' for potential capture in
6684 // enclosing lambdas.
6685 if (CurLSI->ImpCaptureStyle != CurLSI->ImpCap_None)
6686 CurLSI->addPotentialThisCapture(Loc: CallLoc);
6687 }
6688}
6689
6690// Once a call is fully resolved, warn for unqualified calls to specific
6691// C++ standard functions, like move and forward.
6692static void DiagnosedUnqualifiedCallsToStdFunctions(Sema &S,
6693 const CallExpr *Call) {
6694 // We are only checking unary move and forward so exit early here.
6695 if (Call->getNumArgs() != 1)
6696 return;
6697
6698 const Expr *E = Call->getCallee()->IgnoreParenImpCasts();
6699 if (!E || isa<UnresolvedLookupExpr>(Val: E))
6700 return;
6701 const DeclRefExpr *DRE = dyn_cast_if_present<DeclRefExpr>(Val: E);
6702 if (!DRE || !DRE->getLocation().isValid())
6703 return;
6704
6705 if (DRE->getQualifier())
6706 return;
6707
6708 const FunctionDecl *FD = Call->getDirectCallee();
6709 if (!FD)
6710 return;
6711
6712 // Only warn for some functions deemed more frequent or problematic.
6713 unsigned BuiltinID = FD->getBuiltinID();
6714 if (BuiltinID != Builtin::BImove && BuiltinID != Builtin::BIforward)
6715 return;
6716
6717 S.Diag(Loc: DRE->getLocation(), DiagID: diag::warn_unqualified_call_to_std_cast_function)
6718 << FD->getQualifiedNameAsString()
6719 << FixItHint::CreateInsertion(InsertionLoc: DRE->getLocation(), Code: "std::");
6720}
6721
6722ExprResult Sema::ActOnCallExpr(Scope *Scope, Expr *Fn, SourceLocation LParenLoc,
6723 MultiExprArg ArgExprs, SourceLocation RParenLoc,
6724 Expr *ExecConfig) {
6725 ExprResult Call =
6726 BuildCallExpr(S: Scope, Fn, LParenLoc, ArgExprs, RParenLoc, ExecConfig,
6727 /*IsExecConfig=*/false, /*AllowRecovery=*/true);
6728 if (Call.isInvalid())
6729 return Call;
6730
6731 // Diagnose uses of the C++20 "ADL-only template-id call" feature in earlier
6732 // language modes.
6733 if (const auto *ULE = dyn_cast<UnresolvedLookupExpr>(Val: Fn);
6734 ULE && ULE->hasExplicitTemplateArgs() && ULE->decls().empty()) {
6735 DiagCompat(Loc: Fn->getExprLoc(), CompatDiagId: diag_compat::adl_only_template_id)
6736 << ULE->getName();
6737 }
6738
6739 if (LangOpts.OpenMP)
6740 Call = OpenMP().ActOnOpenMPCall(Call, Scope, LParenLoc, ArgExprs, RParenLoc,
6741 ExecConfig);
6742 if (LangOpts.CPlusPlus) {
6743 if (const auto *CE = dyn_cast<CallExpr>(Val: Call.get()))
6744 DiagnosedUnqualifiedCallsToStdFunctions(S&: *this, Call: CE);
6745
6746 // If we previously found that the id-expression of this call refers to a
6747 // consteval function but the call is dependent, we should not treat is an
6748 // an invalid immediate call.
6749 if (auto *DRE = dyn_cast<DeclRefExpr>(Val: Fn->IgnoreParens());
6750 DRE && Call.get()->isValueDependent()) {
6751 currentEvaluationContext().ReferenceToConsteval.erase(Ptr: DRE);
6752 }
6753 }
6754 return Call;
6755}
6756
6757// Any type that could be used to form a callable expression
6758static bool MayBeFunctionType(const ASTContext &Context, const Expr *E) {
6759 QualType T = E->getType();
6760 if (T->isDependentType())
6761 return true;
6762
6763 if (T == Context.BoundMemberTy || T == Context.UnknownAnyTy ||
6764 T == Context.BuiltinFnTy || T == Context.OverloadTy ||
6765 T->isFunctionType() || T->isFunctionReferenceType() ||
6766 T->isMemberFunctionPointerType() || T->isFunctionPointerType() ||
6767 T->isBlockPointerType() || T->isRecordType())
6768 return true;
6769
6770 return isa<CallExpr, DeclRefExpr, MemberExpr, CXXPseudoDestructorExpr,
6771 OverloadExpr, UnresolvedMemberExpr, UnaryOperator>(Val: E);
6772}
6773
6774ExprResult Sema::BuildCallExpr(Scope *Scope, Expr *Fn, SourceLocation LParenLoc,
6775 MultiExprArg ArgExprs, SourceLocation RParenLoc,
6776 Expr *ExecConfig, bool IsExecConfig,
6777 bool AllowRecovery) {
6778 // Since this might be a postfix expression, get rid of ParenListExprs.
6779 ExprResult Result = MaybeConvertParenListExprToParenExpr(S: Scope, ME: Fn);
6780 if (Result.isInvalid()) return ExprError();
6781 Fn = Result.get();
6782
6783 // The __builtin_amdgcn_is_invocable builtin is special, and will be resolved
6784 // later, when we check boolean conditions, for now we merely forward it
6785 // without any additional checking.
6786 if (Fn->getType() == Context.BuiltinFnTy && ArgExprs.size() == 1 &&
6787 ArgExprs[0]->getType() == Context.BuiltinFnTy) {
6788 const auto *FD = cast<FunctionDecl>(Val: Fn->getReferencedDeclOfCallee());
6789
6790 if (FD->getName() == "__builtin_amdgcn_is_invocable") {
6791 QualType FnPtrTy = Context.getPointerType(T: FD->getType());
6792 Expr *R = ImpCastExprToType(E: Fn, Type: FnPtrTy, CK: CK_BuiltinFnToFnPtr).get();
6793 return CallExpr::Create(
6794 Ctx: Context, Fn: R, Args: ArgExprs, Ty: Context.AMDGPUFeaturePredicateTy,
6795 VK: ExprValueKind::VK_PRValue, RParenLoc, FPFeatures: FPOptionsOverride());
6796 }
6797 }
6798
6799 if (CheckArgsForPlaceholders(args: ArgExprs))
6800 return ExprError();
6801
6802 // The result of __builtin_counted_by_ref cannot be used as a function
6803 // argument. It allows leaking and modification of bounds safety information.
6804 for (const Expr *Arg : ArgExprs)
6805 if (CheckInvalidBuiltinCountedByRef(E: Arg,
6806 K: BuiltinCountedByRefKind::FunctionArg))
6807 return ExprError();
6808
6809 if (getLangOpts().CPlusPlus) {
6810 // If this is a pseudo-destructor expression, build the call immediately.
6811 if (isa<CXXPseudoDestructorExpr>(Val: Fn)) {
6812 if (!ArgExprs.empty()) {
6813 // Pseudo-destructor calls should not have any arguments.
6814 Diag(Loc: Fn->getBeginLoc(), DiagID: diag::err_pseudo_dtor_call_with_args)
6815 << FixItHint::CreateRemoval(
6816 RemoveRange: SourceRange(ArgExprs.front()->getBeginLoc(),
6817 ArgExprs.back()->getEndLoc()));
6818 }
6819
6820 return CallExpr::Create(Ctx: Context, Fn, /*Args=*/{}, Ty: Context.VoidTy,
6821 VK: VK_PRValue, RParenLoc, FPFeatures: CurFPFeatureOverrides());
6822 }
6823 if (Fn->getType() == Context.PseudoObjectTy) {
6824 ExprResult result = CheckPlaceholderExpr(E: Fn);
6825 if (result.isInvalid()) return ExprError();
6826 Fn = result.get();
6827 }
6828
6829 // Determine whether this is a dependent call inside a C++ template,
6830 // in which case we won't do any semantic analysis now.
6831 if (Fn->isTypeDependent() || Expr::hasAnyTypeDependentArguments(Exprs: ArgExprs)) {
6832 if (ExecConfig) {
6833 return CUDAKernelCallExpr::Create(Ctx: Context, Fn,
6834 Config: cast<CallExpr>(Val: ExecConfig), Args: ArgExprs,
6835 Ty: Context.DependentTy, VK: VK_PRValue,
6836 RP: RParenLoc, FPFeatures: CurFPFeatureOverrides());
6837 } else {
6838
6839 tryImplicitlyCaptureThisIfImplicitMemberFunctionAccessWithDependentArgs(
6840 S&: *this, UME: dyn_cast<UnresolvedMemberExpr>(Val: Fn->IgnoreParens()),
6841 CallLoc: Fn->getBeginLoc());
6842
6843 // If the type of the function itself is not dependent
6844 // check that it is a reasonable as a function, as type deduction
6845 // later assume the CallExpr has a sensible TYPE.
6846 if (!MayBeFunctionType(Context, E: Fn))
6847 return ExprError(
6848 Diag(Loc: LParenLoc, DiagID: diag::err_typecheck_call_not_function)
6849 << Fn->getType() << Fn->getSourceRange());
6850
6851 return CallExpr::Create(Ctx: Context, Fn, Args: ArgExprs, Ty: Context.DependentTy,
6852 VK: VK_PRValue, RParenLoc, FPFeatures: CurFPFeatureOverrides());
6853 }
6854 }
6855
6856 // Determine whether this is a call to an object (C++ [over.call.object]).
6857 if (Fn->getType()->isRecordType())
6858 return BuildCallToObjectOfClassType(S: Scope, Object: Fn, LParenLoc, Args: ArgExprs,
6859 RParenLoc);
6860
6861 if (Fn->getType() == Context.UnknownAnyTy) {
6862 ExprResult result = rebuildUnknownAnyFunction(S&: *this, fn: Fn);
6863 if (result.isInvalid()) return ExprError();
6864 Fn = result.get();
6865 }
6866
6867 if (Fn->getType() == Context.BoundMemberTy) {
6868 return BuildCallToMemberFunction(S: Scope, MemExpr: Fn, LParenLoc, Args: ArgExprs,
6869 RParenLoc, ExecConfig, IsExecConfig,
6870 AllowRecovery);
6871 }
6872 }
6873
6874 // Check for overloaded calls. This can happen even in C due to extensions.
6875 if (Fn->getType() == Context.OverloadTy) {
6876 OverloadExpr::FindResult find = OverloadExpr::find(E: Fn);
6877
6878 // We aren't supposed to apply this logic if there's an '&' involved.
6879 if (!find.HasFormOfMemberPointer || find.IsAddressOfOperandWithParen) {
6880 if (Expr::hasAnyTypeDependentArguments(Exprs: ArgExprs))
6881 return CallExpr::Create(Ctx: Context, Fn, Args: ArgExprs, Ty: Context.DependentTy,
6882 VK: VK_PRValue, RParenLoc, FPFeatures: CurFPFeatureOverrides());
6883 OverloadExpr *ovl = find.Expression;
6884 if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(Val: ovl))
6885 return BuildOverloadedCallExpr(
6886 S: Scope, Fn, ULE, LParenLoc, Args: ArgExprs, RParenLoc, ExecConfig,
6887 /*AllowTypoCorrection=*/true, CalleesAddressIsTaken: find.IsAddressOfOperand);
6888 return BuildCallToMemberFunction(S: Scope, MemExpr: Fn, LParenLoc, Args: ArgExprs,
6889 RParenLoc, ExecConfig, IsExecConfig,
6890 AllowRecovery);
6891 }
6892 }
6893
6894 // If we're directly calling a function, get the appropriate declaration.
6895 if (Fn->getType() == Context.UnknownAnyTy) {
6896 ExprResult result = rebuildUnknownAnyFunction(S&: *this, fn: Fn);
6897 if (result.isInvalid()) return ExprError();
6898 Fn = result.get();
6899 }
6900
6901 Expr *NakedFn = Fn->IgnoreParens();
6902
6903 bool CallingNDeclIndirectly = false;
6904 NamedDecl *NDecl = nullptr;
6905 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(Val: NakedFn)) {
6906 if (UnOp->getOpcode() == UO_AddrOf) {
6907 CallingNDeclIndirectly = true;
6908 NakedFn = UnOp->getSubExpr()->IgnoreParens();
6909 }
6910 }
6911
6912 if (auto *DRE = dyn_cast<DeclRefExpr>(Val: NakedFn)) {
6913 NDecl = DRE->getDecl();
6914
6915 FunctionDecl *FDecl = dyn_cast<FunctionDecl>(Val: NDecl);
6916 if (FDecl && FDecl->getBuiltinID()) {
6917 const llvm::Triple &Triple = Context.getTargetInfo().getTriple();
6918 if (Triple.isSPIRV() && Triple.getVendor() == llvm::Triple::AMD) {
6919 if (Context.BuiltinInfo.isTSBuiltin(ID: FDecl->getBuiltinID()) &&
6920 !Context.BuiltinInfo.isAuxBuiltinID(ID: FDecl->getBuiltinID())) {
6921 AMDGPU().AddPotentiallyUnguardedBuiltinUser(FD: cast<FunctionDecl>(
6922 Val: getFunctionLevelDeclContext(/*AllowLambda=*/true)));
6923 }
6924 }
6925
6926 // Rewrite the function decl for this builtin by replacing parameters
6927 // with no explicit address space with the address space of the arguments
6928 // in ArgExprs.
6929 if ((FDecl =
6930 rewriteBuiltinFunctionDecl(Sema: this, Context, FDecl, ArgExprs))) {
6931 NDecl = FDecl;
6932 Fn = DeclRefExpr::Create(
6933 Context, QualifierLoc: DRE->getQualifierLoc(), TemplateKWLoc: SourceLocation(), D: FDecl, RefersToEnclosingVariableOrCapture: false,
6934 NameLoc: SourceLocation(), T: Fn->getType() /* BuiltinFnTy */,
6935 VK: Fn->getValueKind(), FoundD: FDecl, TemplateArgs: nullptr, NOUR: DRE->isNonOdrUse());
6936 }
6937 }
6938 } else if (auto *ME = dyn_cast<MemberExpr>(Val: NakedFn))
6939 NDecl = ME->getMemberDecl();
6940
6941 if (FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(Val: NDecl)) {
6942 if (CallingNDeclIndirectly && !checkAddressOfFunctionIsAvailable(
6943 Function: FD, /*Complain=*/true, Loc: Fn->getBeginLoc()))
6944 return ExprError();
6945
6946 checkDirectCallValidity(S&: *this, Fn, Callee: FD, ArgExprs);
6947
6948 // If this expression is a call to a builtin function in HIP compilation,
6949 // allow a pointer-type argument to default address space to be passed as a
6950 // pointer-type parameter to a non-default address space. If Arg is declared
6951 // in the default address space and Param is declared in a non-default
6952 // address space, perform an implicit address space cast to the parameter
6953 // type.
6954 if (getLangOpts().HIP && FD && FD->getBuiltinID()) {
6955 for (unsigned Idx = 0; Idx < ArgExprs.size() && Idx < FD->param_size();
6956 ++Idx) {
6957 ParmVarDecl *Param = FD->getParamDecl(i: Idx);
6958 if (!ArgExprs[Idx] || !Param || !Param->getType()->isPointerType() ||
6959 !ArgExprs[Idx]->getType()->isPointerType())
6960 continue;
6961
6962 auto ParamAS = Param->getType()->getPointeeType().getAddressSpace();
6963 auto ArgTy = ArgExprs[Idx]->getType();
6964 auto ArgPtTy = ArgTy->getPointeeType();
6965 auto ArgAS = ArgPtTy.getAddressSpace();
6966
6967 // Add address space cast if target address spaces are different
6968 bool NeedImplicitASC =
6969 ParamAS != LangAS::Default && // Pointer params in generic AS don't need special handling.
6970 ( ArgAS == LangAS::Default || // We do allow implicit conversion from generic AS
6971 // or from specific AS which has target AS matching that of Param.
6972 getASTContext().getTargetAddressSpace(AS: ArgAS) == getASTContext().getTargetAddressSpace(AS: ParamAS));
6973 if (!NeedImplicitASC)
6974 continue;
6975
6976 // First, ensure that the Arg is an RValue.
6977 if (ArgExprs[Idx]->isGLValue()) {
6978 ExprResult Res = DefaultLvalueConversion(E: ArgExprs[Idx]);
6979 if (Res.isInvalid())
6980 return ExprError();
6981 ArgExprs[Idx] = Res.get();
6982 }
6983
6984 // Construct a new arg type with address space of Param
6985 Qualifiers ArgPtQuals = ArgPtTy.getQualifiers();
6986 ArgPtQuals.setAddressSpace(ParamAS);
6987 auto NewArgPtTy =
6988 Context.getQualifiedType(T: ArgPtTy.getUnqualifiedType(), Qs: ArgPtQuals);
6989 auto NewArgTy =
6990 Context.getQualifiedType(T: Context.getPointerType(T: NewArgPtTy),
6991 Qs: ArgTy.getQualifiers());
6992
6993 // Finally perform an implicit address space cast
6994 ArgExprs[Idx] = ImpCastExprToType(E: ArgExprs[Idx], Type: NewArgTy,
6995 CK: CK_AddressSpaceConversion)
6996 .get();
6997 }
6998 }
6999 }
7000
7001 if (Context.isDependenceAllowed() &&
7002 (Fn->isTypeDependent() || Expr::hasAnyTypeDependentArguments(Exprs: ArgExprs))) {
7003 assert(!getLangOpts().CPlusPlus);
7004 assert((Fn->containsErrors() ||
7005 llvm::any_of(ArgExprs,
7006 [](clang::Expr *E) { return E->containsErrors(); })) &&
7007 "should only occur in error-recovery path.");
7008 return CallExpr::Create(Ctx: Context, Fn, Args: ArgExprs, Ty: Context.DependentTy,
7009 VK: VK_PRValue, RParenLoc, FPFeatures: CurFPFeatureOverrides());
7010 }
7011 return BuildResolvedCallExpr(Fn, NDecl, LParenLoc, Arg: ArgExprs, RParenLoc,
7012 Config: ExecConfig, IsExecConfig);
7013}
7014
7015Expr *Sema::BuildBuiltinCallExpr(SourceLocation Loc, Builtin::ID Id,
7016 MultiExprArg CallArgs) {
7017 std::string Name = Context.BuiltinInfo.getName(ID: Id);
7018 LookupResult R(*this, &Context.Idents.get(Name), Loc,
7019 Sema::LookupOrdinaryName);
7020 LookupName(R, S: TUScope, /*AllowBuiltinCreation=*/true);
7021
7022 auto *BuiltInDecl = R.getAsSingle<FunctionDecl>();
7023 assert(BuiltInDecl && "failed to find builtin declaration");
7024
7025 ExprResult DeclRef =
7026 BuildDeclRefExpr(D: BuiltInDecl, Ty: BuiltInDecl->getType(), VK: VK_LValue, Loc);
7027 assert(DeclRef.isUsable() && "Builtin reference cannot fail");
7028
7029 ExprResult Call =
7030 BuildCallExpr(/*Scope=*/nullptr, Fn: DeclRef.get(), LParenLoc: Loc, ArgExprs: CallArgs, RParenLoc: Loc);
7031
7032 assert(!Call.isInvalid() && "Call to builtin cannot fail!");
7033 return Call.get();
7034}
7035
7036ExprResult Sema::ActOnAsTypeExpr(Expr *E, ParsedType ParsedDestTy,
7037 SourceLocation BuiltinLoc,
7038 SourceLocation RParenLoc) {
7039 QualType DstTy = GetTypeFromParser(Ty: ParsedDestTy);
7040 return BuildAsTypeExpr(E, DestTy: DstTy, BuiltinLoc, RParenLoc);
7041}
7042
7043ExprResult Sema::BuildAsTypeExpr(Expr *E, QualType DestTy,
7044 SourceLocation BuiltinLoc,
7045 SourceLocation RParenLoc) {
7046 ExprValueKind VK = VK_PRValue;
7047 ExprObjectKind OK = OK_Ordinary;
7048 QualType SrcTy = E->getType();
7049 if (!SrcTy->isDependentType() &&
7050 Context.getTypeSize(T: DestTy) != Context.getTypeSize(T: SrcTy))
7051 return ExprError(
7052 Diag(Loc: BuiltinLoc, DiagID: diag::err_invalid_astype_of_different_size)
7053 << DestTy << SrcTy << E->getSourceRange());
7054 return new (Context) AsTypeExpr(E, DestTy, VK, OK, BuiltinLoc, RParenLoc);
7055}
7056
7057ExprResult Sema::ActOnConvertVectorExpr(Expr *E, ParsedType ParsedDestTy,
7058 SourceLocation BuiltinLoc,
7059 SourceLocation RParenLoc) {
7060 TypeSourceInfo *TInfo;
7061 GetTypeFromParser(Ty: ParsedDestTy, TInfo: &TInfo);
7062 return ConvertVectorExpr(E, TInfo, BuiltinLoc, RParenLoc);
7063}
7064
7065ExprResult Sema::BuildResolvedCallExpr(Expr *Fn, NamedDecl *NDecl,
7066 SourceLocation LParenLoc,
7067 ArrayRef<Expr *> Args,
7068 SourceLocation RParenLoc, Expr *Config,
7069 bool IsExecConfig, ADLCallKind UsesADL) {
7070 FunctionDecl *FDecl = dyn_cast_or_null<FunctionDecl>(Val: NDecl);
7071 unsigned BuiltinID = (FDecl ? FDecl->getBuiltinID() : 0);
7072
7073 auto IsSJLJ = [&] {
7074 switch (BuiltinID) {
7075 case Builtin::BI__builtin_longjmp:
7076 case Builtin::BI__builtin_setjmp:
7077 case Builtin::BI__sigsetjmp:
7078 case Builtin::BI_longjmp:
7079 case Builtin::BI_setjmp:
7080 case Builtin::BIlongjmp:
7081 case Builtin::BIsetjmp:
7082 case Builtin::BIsiglongjmp:
7083 case Builtin::BIsigsetjmp:
7084 return true;
7085 default:
7086 return false;
7087 }
7088 };
7089
7090 // Forbid any call to setjmp/longjmp and friends inside a '_Defer' statement.
7091 if (!CurrentDefer.empty() && IsSJLJ()) {
7092 // Note: If we ever start supporting '_Defer' in C++ we'll have to check
7093 // for more than just blocks (e.g. lambdas, nested classes...).
7094 Scope *DeferParent = CurrentDefer.back().first;
7095 Scope *Block = CurScope->getBlockParent();
7096 if (DeferParent->Contains(rhs: *CurScope) &&
7097 (!Block || !DeferParent->Contains(rhs: *Block)))
7098 Diag(Loc: Fn->getExprLoc(), DiagID: diag::err_defer_invalid_sjlj) << FDecl;
7099 }
7100
7101 // Functions with 'interrupt' attribute cannot be called directly.
7102 if (FDecl) {
7103 if (FDecl->hasAttr<AnyX86InterruptAttr>()) {
7104 Diag(Loc: Fn->getExprLoc(), DiagID: diag::err_anyx86_interrupt_called);
7105 return ExprError();
7106 }
7107 if (FDecl->hasAttr<ARMInterruptAttr>()) {
7108 Diag(Loc: Fn->getExprLoc(), DiagID: diag::err_arm_interrupt_called);
7109 return ExprError();
7110 }
7111 }
7112
7113 // X86 interrupt handlers may only call routines with attribute
7114 // no_caller_saved_registers since there is no efficient way to
7115 // save and restore the non-GPR state.
7116 if (auto *Caller = getCurFunctionDecl()) {
7117 if (Caller->hasAttr<AnyX86InterruptAttr>() ||
7118 Caller->hasAttr<AnyX86NoCallerSavedRegistersAttr>()) {
7119 const TargetInfo &TI = Context.getTargetInfo();
7120 bool HasNonGPRRegisters =
7121 TI.hasFeature(Feature: "sse") || TI.hasFeature(Feature: "x87") || TI.hasFeature(Feature: "mmx");
7122 if (HasNonGPRRegisters &&
7123 (!FDecl || !FDecl->hasAttr<AnyX86NoCallerSavedRegistersAttr>())) {
7124 Diag(Loc: Fn->getExprLoc(), DiagID: diag::warn_anyx86_excessive_regsave)
7125 << (Caller->hasAttr<AnyX86InterruptAttr>() ? 0 : 1);
7126 if (FDecl)
7127 Diag(Loc: FDecl->getLocation(), DiagID: diag::note_callee_decl) << FDecl;
7128 }
7129 }
7130 }
7131
7132 // Extract the return type from the builtin function pointer type.
7133 QualType ResultTy;
7134 if (BuiltinID)
7135 ResultTy = FDecl->getCallResultType();
7136 else
7137 ResultTy = Context.BoolTy;
7138
7139 // Promote the function operand.
7140 // We special-case function promotion here because we only allow promoting
7141 // builtin functions to function pointers in the callee of a call.
7142 ExprResult Result;
7143 if (BuiltinID &&
7144 Fn->getType()->isSpecificBuiltinType(K: BuiltinType::BuiltinFn)) {
7145 // FIXME Several builtins still have setType in
7146 // Sema::CheckBuiltinFunctionCall. One should review their definitions in
7147 // Builtins.td to ensure they are correct before removing setType calls.
7148 QualType FnPtrTy = Context.getPointerType(T: FDecl->getType());
7149 Result = ImpCastExprToType(E: Fn, Type: FnPtrTy, CK: CK_BuiltinFnToFnPtr).get();
7150 } else
7151 Result = CallExprUnaryConversions(E: Fn);
7152 if (Result.isInvalid())
7153 return ExprError();
7154 Fn = Result.get();
7155
7156 // Check for a valid function type, but only if it is not a builtin which
7157 // requires custom type checking. These will be handled by
7158 // CheckBuiltinFunctionCall below just after creation of the call expression.
7159 const FunctionType *FuncT = nullptr;
7160 if (!BuiltinID || !Context.BuiltinInfo.hasCustomTypechecking(ID: BuiltinID)) {
7161 retry:
7162 if (const PointerType *PT = Fn->getType()->getAs<PointerType>()) {
7163 // C99 6.5.2.2p1 - "The expression that denotes the called function shall
7164 // have type pointer to function".
7165 FuncT = PT->getPointeeType()->getAs<FunctionType>();
7166 if (!FuncT)
7167 return ExprError(Diag(Loc: LParenLoc, DiagID: diag::err_typecheck_call_not_function)
7168 << Fn->getType() << Fn->getSourceRange());
7169 } else if (const BlockPointerType *BPT =
7170 Fn->getType()->getAs<BlockPointerType>()) {
7171 FuncT = BPT->getPointeeType()->castAs<FunctionType>();
7172 } else {
7173 // Handle calls to expressions of unknown-any type.
7174 if (Fn->getType() == Context.UnknownAnyTy) {
7175 ExprResult rewrite = rebuildUnknownAnyFunction(S&: *this, fn: Fn);
7176 if (rewrite.isInvalid())
7177 return ExprError();
7178 Fn = rewrite.get();
7179 goto retry;
7180 }
7181
7182 return ExprError(Diag(Loc: LParenLoc, DiagID: diag::err_typecheck_call_not_function)
7183 << Fn->getType() << Fn->getSourceRange());
7184 }
7185 }
7186
7187 // Get the number of parameters in the function prototype, if any.
7188 // We will allocate space for max(Args.size(), NumParams) arguments
7189 // in the call expression.
7190 const auto *Proto = dyn_cast_or_null<FunctionProtoType>(Val: FuncT);
7191 unsigned NumParams = Proto ? Proto->getNumParams() : 0;
7192
7193 CallExpr *TheCall;
7194 if (Config) {
7195 assert(UsesADL == ADLCallKind::NotADL &&
7196 "CUDAKernelCallExpr should not use ADL");
7197 TheCall = CUDAKernelCallExpr::Create(Ctx: Context, Fn, Config: cast<CallExpr>(Val: Config),
7198 Args, Ty: ResultTy, VK: VK_PRValue, RP: RParenLoc,
7199 FPFeatures: CurFPFeatureOverrides(), MinNumArgs: NumParams);
7200 } else {
7201 TheCall =
7202 CallExpr::Create(Ctx: Context, Fn, Args, Ty: ResultTy, VK: VK_PRValue, RParenLoc,
7203 FPFeatures: CurFPFeatureOverrides(), MinNumArgs: NumParams, UsesADL);
7204 }
7205
7206 // Bail out early if calling a builtin with custom type checking.
7207 if (BuiltinID && Context.BuiltinInfo.hasCustomTypechecking(ID: BuiltinID)) {
7208 ExprResult E = CheckBuiltinFunctionCall(FDecl, BuiltinID, TheCall);
7209 if (!E.isInvalid() && Context.BuiltinInfo.isImmediate(ID: BuiltinID))
7210 E = CheckForImmediateInvocation(E, Decl: FDecl);
7211 return E;
7212 }
7213
7214 if (getLangOpts().CUDA) {
7215 if (Config) {
7216 // CUDA: Kernel calls must be to global functions
7217 if (FDecl && !FDecl->hasAttr<CUDAGlobalAttr>())
7218 return ExprError(Diag(Loc: LParenLoc,DiagID: diag::err_kern_call_not_global_function)
7219 << FDecl << Fn->getSourceRange());
7220
7221 // CUDA: Kernel function must have 'void' return type
7222 if (!FuncT->getReturnType()->isVoidType() &&
7223 !FuncT->getReturnType()->getAs<AutoType>() &&
7224 !FuncT->getReturnType()->isInstantiationDependentType())
7225 return ExprError(Diag(Loc: LParenLoc, DiagID: diag::err_kern_type_not_void_return)
7226 << Fn->getType() << Fn->getSourceRange());
7227 } else {
7228 // CUDA: Calls to global functions must be configured
7229 if (FDecl && FDecl->hasAttr<CUDAGlobalAttr>())
7230 return ExprError(Diag(Loc: LParenLoc, DiagID: diag::err_global_call_not_config)
7231 << FDecl << Fn->getSourceRange());
7232 }
7233 }
7234
7235 // Check for a valid return type
7236 if (CheckCallReturnType(ReturnType: FuncT->getReturnType(), Loc: Fn->getBeginLoc(), CE: TheCall,
7237 FD: FDecl))
7238 return ExprError();
7239
7240 // We know the result type of the call, set it.
7241 TheCall->setType(FuncT->getCallResultType(Context));
7242 TheCall->setValueKind(Expr::getValueKindForType(T: FuncT->getReturnType()));
7243
7244 // WebAssembly tables can't be used as arguments.
7245 if (Context.getTargetInfo().getTriple().isWasm()) {
7246 for (const Expr *Arg : Args) {
7247 if (Arg && Arg->getType()->isWebAssemblyTableType()) {
7248 return ExprError(Diag(Loc: Arg->getExprLoc(),
7249 DiagID: diag::err_wasm_table_as_function_parameter));
7250 }
7251 }
7252 }
7253
7254 if (Proto) {
7255 if (ConvertArgumentsForCall(Call: TheCall, Fn, FDecl, Proto, Args, RParenLoc,
7256 IsExecConfig))
7257 return ExprError();
7258 } else {
7259 assert(isa<FunctionNoProtoType>(FuncT) && "Unknown FunctionType!");
7260
7261 if (FDecl) {
7262 // Check if we have too few/too many template arguments, based
7263 // on our knowledge of the function definition.
7264 const FunctionDecl *Def = nullptr;
7265 if (FDecl->hasBody(Definition&: Def) && Args.size() != Def->param_size()) {
7266 Proto = Def->getType()->getAs<FunctionProtoType>();
7267 if (!Proto || !(Proto->isVariadic() && Args.size() >= Def->param_size()))
7268 Diag(Loc: RParenLoc, DiagID: diag::warn_call_wrong_number_of_arguments)
7269 << (Args.size() > Def->param_size()) << FDecl << Fn->getSourceRange();
7270 }
7271
7272 // If the function we're calling isn't a function prototype, but we have
7273 // a function prototype from a prior declaratiom, use that prototype.
7274 if (!FDecl->hasPrototype())
7275 Proto = FDecl->getType()->getAs<FunctionProtoType>();
7276 }
7277
7278 // If we still haven't found a prototype to use but there are arguments to
7279 // the call, diagnose this as calling a function without a prototype.
7280 // However, if we found a function declaration, check to see if
7281 // -Wdeprecated-non-prototype was disabled where the function was declared.
7282 // If so, we will silence the diagnostic here on the assumption that this
7283 // interface is intentional and the user knows what they're doing. We will
7284 // also silence the diagnostic if there is a function declaration but it
7285 // was implicitly defined (the user already gets diagnostics about the
7286 // creation of the implicit function declaration, so the additional warning
7287 // is not helpful).
7288 if (!Proto && !Args.empty() &&
7289 (!FDecl || (!FDecl->isImplicit() &&
7290 !Diags.isIgnored(DiagID: diag::warn_strict_uses_without_prototype,
7291 Loc: FDecl->getLocation()))))
7292 Diag(Loc: LParenLoc, DiagID: diag::warn_strict_uses_without_prototype)
7293 << (FDecl != nullptr) << FDecl;
7294
7295 // Promote the arguments (C99 6.5.2.2p6).
7296 for (unsigned i = 0, e = Args.size(); i != e; i++) {
7297 Expr *Arg = Args[i];
7298
7299 if (Proto && i < Proto->getNumParams()) {
7300 InitializedEntity Entity = InitializedEntity::InitializeParameter(
7301 Context, Type: Proto->getParamType(i), Consumed: Proto->isParamConsumed(I: i));
7302 ExprResult ArgE =
7303 PerformCopyInitialization(Entity, EqualLoc: SourceLocation(), Init: Arg);
7304 if (ArgE.isInvalid())
7305 return true;
7306
7307 Arg = ArgE.getAs<Expr>();
7308
7309 } else {
7310 ExprResult ArgE = DefaultArgumentPromotion(E: Arg);
7311
7312 if (ArgE.isInvalid())
7313 return true;
7314
7315 Arg = ArgE.getAs<Expr>();
7316 }
7317
7318 if (RequireCompleteType(Loc: Arg->getBeginLoc(), T: Arg->getType(),
7319 DiagID: diag::err_call_incomplete_argument, Args: Arg))
7320 return ExprError();
7321
7322 TheCall->setArg(Arg: i, ArgExpr: Arg);
7323 }
7324 TheCall->computeDependence();
7325 }
7326
7327 if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(Val: FDecl))
7328 if (Method->isImplicitObjectMemberFunction())
7329 return ExprError(Diag(Loc: LParenLoc, DiagID: diag::err_member_call_without_object)
7330 << Fn->getSourceRange() << 0);
7331
7332 // Check for sentinels
7333 if (NDecl)
7334 DiagnoseSentinelCalls(D: NDecl, Loc: LParenLoc, Args);
7335
7336 // Warn for unions passing across security boundary (CMSE).
7337 if (FuncT != nullptr && FuncT->getCmseNSCallAttr()) {
7338 for (unsigned i = 0, e = Args.size(); i != e; i++) {
7339 if (const auto *RT =
7340 dyn_cast<RecordType>(Val: Args[i]->getType().getCanonicalType())) {
7341 if (RT->getDecl()->isOrContainsUnion())
7342 Diag(Loc: Args[i]->getBeginLoc(), DiagID: diag::warn_cmse_nonsecure_union)
7343 << 0 << i;
7344 }
7345 }
7346 }
7347
7348 // Do special checking on direct calls to functions.
7349 if (FDecl) {
7350 if (CheckFunctionCall(FDecl, TheCall, Proto))
7351 return ExprError();
7352
7353 checkFortifiedBuiltinMemoryFunction(FD: FDecl, TheCall);
7354
7355 if (BuiltinID)
7356 return CheckBuiltinFunctionCall(FDecl, BuiltinID, TheCall);
7357 } else if (NDecl) {
7358 if (CheckPointerCall(NDecl, TheCall, Proto))
7359 return ExprError();
7360 } else {
7361 if (CheckOtherCall(TheCall, Proto))
7362 return ExprError();
7363 }
7364
7365 return CheckForImmediateInvocation(E: MaybeBindToTemporary(E: TheCall), Decl: FDecl);
7366}
7367
7368ExprResult
7369Sema::ActOnCompoundLiteral(SourceLocation LParenLoc, ParsedType Ty,
7370 SourceLocation RParenLoc, Expr *InitExpr) {
7371 assert(Ty && "ActOnCompoundLiteral(): missing type");
7372 assert(InitExpr && "ActOnCompoundLiteral(): missing expression");
7373
7374 TypeSourceInfo *TInfo;
7375 QualType literalType = GetTypeFromParser(Ty, TInfo: &TInfo);
7376 if (!TInfo)
7377 TInfo = Context.getTrivialTypeSourceInfo(T: literalType);
7378
7379 return BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc, LiteralExpr: InitExpr);
7380}
7381
7382ExprResult
7383Sema::BuildCompoundLiteralExpr(SourceLocation LParenLoc, TypeSourceInfo *TInfo,
7384 SourceLocation RParenLoc, Expr *LiteralExpr) {
7385 QualType literalType = TInfo->getType();
7386
7387 if (literalType->isArrayType()) {
7388 if (RequireCompleteSizedType(
7389 Loc: LParenLoc, T: Context.getBaseElementType(QT: literalType),
7390 DiagID: diag::err_array_incomplete_or_sizeless_type,
7391 Args: SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd())))
7392 return ExprError();
7393 if (literalType->isVariableArrayType()) {
7394 // C23 6.7.10p4: An entity of variable length array type shall not be
7395 // initialized except by an empty initializer.
7396 //
7397 // The C extension warnings are issued from ParseBraceInitializer() and
7398 // do not need to be issued here. However, we continue to issue an error
7399 // in the case there are initializers or we are compiling C++. We allow
7400 // use of VLAs in C++, but it's not clear we want to allow {} to zero
7401 // init a VLA in C++ in all cases (such as with non-trivial constructors).
7402 // FIXME: should we allow this construct in C++ when it makes sense to do
7403 // so?
7404 //
7405 // But: C99-C23 6.5.2.5 Compound literals constraint 1: The type name
7406 // shall specify an object type or an array of unknown size, but not a
7407 // variable length array type. This seems odd, as it allows 'int a[size] =
7408 // {}', but forbids 'int *a = (int[size]){}'. As this is what the standard
7409 // says, this is what's implemented here for C (except for the extension
7410 // that permits constant foldable size arrays)
7411
7412 auto diagID = LangOpts.CPlusPlus
7413 ? diag::err_variable_object_no_init
7414 : diag::err_compound_literal_with_vla_type;
7415 if (!tryToFixVariablyModifiedVarType(TInfo, T&: literalType, Loc: LParenLoc,
7416 FailedFoldDiagID: diagID))
7417 return ExprError();
7418 }
7419 } else if (!literalType->isDependentType() &&
7420 RequireCompleteType(Loc: LParenLoc, T: literalType,
7421 DiagID: diag::err_typecheck_decl_incomplete_type,
7422 Args: SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd())))
7423 return ExprError();
7424
7425 InitializedEntity Entity
7426 = InitializedEntity::InitializeCompoundLiteralInit(TSI: TInfo);
7427 InitializationKind Kind
7428 = InitializationKind::CreateCStyleCast(StartLoc: LParenLoc,
7429 TypeRange: SourceRange(LParenLoc, RParenLoc),
7430 /*InitList=*/true);
7431 InitializationSequence InitSeq(*this, Entity, Kind, LiteralExpr);
7432 ExprResult Result = InitSeq.Perform(S&: *this, Entity, Kind, Args: LiteralExpr,
7433 ResultType: &literalType);
7434 if (Result.isInvalid())
7435 return ExprError();
7436 LiteralExpr = Result.get();
7437
7438 // We treat the compound literal as being at file scope if it's not in a
7439 // function or method body, or within the function's prototype scope. This
7440 // means the following compound literal is not at file scope:
7441 // void func(char *para[(int [1]){ 0 }[0]);
7442 const Scope *S = getCurScope();
7443 bool IsFileScope = !CurContext->isFunctionOrMethod() &&
7444 !S->isInCFunctionScope() &&
7445 (!S || !S->isFunctionPrototypeScope());
7446
7447 // In C, compound literals are l-values for some reason.
7448 // For GCC compatibility, in C++, file-scope array compound literals with
7449 // constant initializers are also l-values, and compound literals are
7450 // otherwise prvalues.
7451 //
7452 // (GCC also treats C++ list-initialized file-scope array prvalues with
7453 // constant initializers as l-values, but that's non-conforming, so we don't
7454 // follow it there.)
7455 //
7456 // FIXME: It would be better to handle the lvalue cases as materializing and
7457 // lifetime-extending a temporary object, but our materialized temporaries
7458 // representation only supports lifetime extension from a variable, not "out
7459 // of thin air".
7460 // FIXME: For C++, we might want to instead lifetime-extend only if a pointer
7461 // is bound to the result of applying array-to-pointer decay to the compound
7462 // literal.
7463 // FIXME: GCC supports compound literals of reference type, which should
7464 // obviously have a value kind derived from the kind of reference involved.
7465 ExprValueKind VK =
7466 (getLangOpts().CPlusPlus && !(IsFileScope && literalType->isArrayType()))
7467 ? VK_PRValue
7468 : VK_LValue;
7469
7470 // C99 6.5.2.5
7471 // "If the compound literal occurs outside the body of a function, the
7472 // initializer list shall consist of constant expressions."
7473 if (IsFileScope)
7474 if (auto ILE = dyn_cast<InitListExpr>(Val: LiteralExpr))
7475 for (unsigned i = 0, j = ILE->getNumInits(); i != j; i++) {
7476 Expr *Init = ILE->getInit(Init: i);
7477 if (!Init->isTypeDependent() && !Init->isValueDependent() &&
7478 !Init->isConstantInitializer(Ctx&: Context)) {
7479 Diag(Loc: Init->getExprLoc(), DiagID: diag::err_init_element_not_constant)
7480 << Init->getSourceBitField();
7481 return ExprError();
7482 }
7483
7484 ILE->setInit(Init: i, expr: ConstantExpr::Create(Context, E: Init));
7485 }
7486
7487 auto *E = new (Context) CompoundLiteralExpr(LParenLoc, TInfo, literalType, VK,
7488 LiteralExpr, IsFileScope);
7489 if (IsFileScope) {
7490 if (!LiteralExpr->isTypeDependent() &&
7491 !LiteralExpr->isValueDependent() &&
7492 !literalType->isDependentType()) // C99 6.5.2.5p3
7493 if (CheckForConstantInitializer(Init: LiteralExpr))
7494 return ExprError();
7495 } else if (literalType.getAddressSpace() != LangAS::opencl_private &&
7496 literalType.getAddressSpace() != LangAS::Default) {
7497 // Embedded-C extensions to C99 6.5.2.5:
7498 // "If the compound literal occurs inside the body of a function, the
7499 // type name shall not be qualified by an address-space qualifier."
7500 Diag(Loc: LParenLoc, DiagID: diag::err_compound_literal_with_address_space)
7501 << SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd());
7502 return ExprError();
7503 }
7504
7505 if (!IsFileScope && !getLangOpts().CPlusPlus) {
7506 // Compound literals that have automatic storage duration are destroyed at
7507 // the end of the scope in C; in C++, they're just temporaries.
7508
7509 // Emit diagnostics if it is or contains a C union type that is non-trivial
7510 // to destruct.
7511 if (E->getType().hasNonTrivialToPrimitiveDestructCUnion())
7512 checkNonTrivialCUnion(QT: E->getType(), Loc: E->getExprLoc(),
7513 UseContext: NonTrivialCUnionContext::CompoundLiteral,
7514 NonTrivialKind: NTCUK_Destruct);
7515
7516 // Diagnose jumps that enter or exit the lifetime of the compound literal.
7517 if (literalType.isDestructedType()) {
7518 Cleanup.setExprNeedsCleanups(true);
7519 ExprCleanupObjects.push_back(Elt: E);
7520 getCurFunction()->setHasBranchProtectedScope();
7521 }
7522 }
7523
7524 if (E->getType().hasNonTrivialToPrimitiveDefaultInitializeCUnion() ||
7525 E->getType().hasNonTrivialToPrimitiveCopyCUnion())
7526 checkNonTrivialCUnionInInitializer(Init: E->getInitializer(),
7527 Loc: E->getInitializer()->getExprLoc());
7528
7529 return MaybeBindToTemporary(E);
7530}
7531
7532ExprResult
7533Sema::ActOnInitList(SourceLocation LBraceLoc, MultiExprArg InitArgList,
7534 SourceLocation RBraceLoc) {
7535 // Only produce each kind of designated initialization diagnostic once.
7536 SourceLocation FirstDesignator;
7537 bool DiagnosedArrayDesignator = false;
7538 bool DiagnosedNestedDesignator = false;
7539 bool DiagnosedMixedDesignator = false;
7540
7541 // Check that any designated initializers are syntactically valid in the
7542 // current language mode.
7543 for (unsigned I = 0, E = InitArgList.size(); I != E; ++I) {
7544 if (auto *DIE = dyn_cast<DesignatedInitExpr>(Val: InitArgList[I])) {
7545 if (FirstDesignator.isInvalid())
7546 FirstDesignator = DIE->getBeginLoc();
7547
7548 if (!getLangOpts().CPlusPlus)
7549 break;
7550
7551 if (!DiagnosedNestedDesignator && DIE->size() > 1) {
7552 DiagnosedNestedDesignator = true;
7553 Diag(Loc: DIE->getBeginLoc(), DiagID: diag::ext_designated_init_nested)
7554 << DIE->getDesignatorsSourceRange();
7555 }
7556
7557 for (auto &Desig : DIE->designators()) {
7558 if (!Desig.isFieldDesignator() && !DiagnosedArrayDesignator) {
7559 DiagnosedArrayDesignator = true;
7560 Diag(Loc: Desig.getBeginLoc(), DiagID: diag::ext_designated_init_array)
7561 << Desig.getSourceRange();
7562 }
7563 }
7564
7565 if (!DiagnosedMixedDesignator &&
7566 !isa<DesignatedInitExpr>(Val: InitArgList[0])) {
7567 DiagnosedMixedDesignator = true;
7568 Diag(Loc: DIE->getBeginLoc(), DiagID: diag::ext_designated_init_mixed)
7569 << DIE->getSourceRange();
7570 Diag(Loc: InitArgList[0]->getBeginLoc(), DiagID: diag::note_designated_init_mixed)
7571 << InitArgList[0]->getSourceRange();
7572 }
7573 } else if (getLangOpts().CPlusPlus && !DiagnosedMixedDesignator &&
7574 isa<DesignatedInitExpr>(Val: InitArgList[0])) {
7575 DiagnosedMixedDesignator = true;
7576 auto *DIE = cast<DesignatedInitExpr>(Val: InitArgList[0]);
7577 Diag(Loc: DIE->getBeginLoc(), DiagID: diag::ext_designated_init_mixed)
7578 << DIE->getSourceRange();
7579 Diag(Loc: InitArgList[I]->getBeginLoc(), DiagID: diag::note_designated_init_mixed)
7580 << InitArgList[I]->getSourceRange();
7581 }
7582 }
7583
7584 if (FirstDesignator.isValid()) {
7585 // Only diagnose designated initiaization as a C++20 extension if we didn't
7586 // already diagnose use of (non-C++20) C99 designator syntax.
7587 if (getLangOpts().CPlusPlus && !DiagnosedArrayDesignator &&
7588 !DiagnosedNestedDesignator && !DiagnosedMixedDesignator) {
7589 Diag(Loc: FirstDesignator, DiagID: getLangOpts().CPlusPlus20
7590 ? diag::warn_cxx17_compat_designated_init
7591 : diag::ext_cxx_designated_init);
7592 } else if (!getLangOpts().CPlusPlus && !getLangOpts().C99) {
7593 Diag(Loc: FirstDesignator, DiagID: diag::ext_designated_init);
7594 }
7595 }
7596
7597 return BuildInitList(LBraceLoc, InitArgList, RBraceLoc);
7598}
7599
7600ExprResult
7601Sema::BuildInitList(SourceLocation LBraceLoc, MultiExprArg InitArgList,
7602 SourceLocation RBraceLoc) {
7603 // Semantic analysis for initializers is done by ActOnDeclarator() and
7604 // CheckInitializer() - it requires knowledge of the object being initialized.
7605
7606 // Immediately handle non-overload placeholders. Overloads can be
7607 // resolved contextually, but everything else here can't.
7608 for (unsigned I = 0, E = InitArgList.size(); I != E; ++I) {
7609 if (InitArgList[I]->getType()->isNonOverloadPlaceholderType()) {
7610 ExprResult result = CheckPlaceholderExpr(E: InitArgList[I]);
7611
7612 // Ignore failures; dropping the entire initializer list because
7613 // of one failure would be terrible for indexing/etc.
7614 if (result.isInvalid()) continue;
7615
7616 InitArgList[I] = result.get();
7617 }
7618 }
7619
7620 InitListExpr *E =
7621 new (Context) InitListExpr(Context, LBraceLoc, InitArgList, RBraceLoc);
7622 E->setType(Context.VoidTy); // FIXME: just a place holder for now.
7623 return E;
7624}
7625
7626void Sema::maybeExtendBlockObject(ExprResult &E) {
7627 assert(E.get()->getType()->isBlockPointerType());
7628 assert(E.get()->isPRValue());
7629
7630 // Only do this in an r-value context.
7631 if (!getLangOpts().ObjCAutoRefCount) return;
7632
7633 E = ImplicitCastExpr::Create(
7634 Context, T: E.get()->getType(), Kind: CK_ARCExtendBlockObject, Operand: E.get(),
7635 /*base path*/ BasePath: nullptr, Cat: VK_PRValue, FPO: FPOptionsOverride());
7636 Cleanup.setExprNeedsCleanups(true);
7637}
7638
7639CastKind Sema::PrepareScalarCast(ExprResult &Src, QualType DestTy) {
7640 // Both Src and Dest are scalar types, i.e. arithmetic or pointer.
7641 // Also, callers should have filtered out the invalid cases with
7642 // pointers. Everything else should be possible.
7643
7644 QualType SrcTy = Src.get()->getType();
7645 if (Context.hasSameUnqualifiedType(T1: SrcTy, T2: DestTy))
7646 return CK_NoOp;
7647
7648 switch (Type::ScalarTypeKind SrcKind = SrcTy->getScalarTypeKind()) {
7649 case Type::STK_MemberPointer:
7650 llvm_unreachable("member pointer type in C");
7651
7652 case Type::STK_CPointer:
7653 case Type::STK_BlockPointer:
7654 case Type::STK_ObjCObjectPointer:
7655 switch (DestTy->getScalarTypeKind()) {
7656 case Type::STK_CPointer: {
7657 LangAS SrcAS = SrcTy->getPointeeType().getAddressSpace();
7658 LangAS DestAS = DestTy->getPointeeType().getAddressSpace();
7659 if (SrcAS != DestAS)
7660 return CK_AddressSpaceConversion;
7661 if (Context.hasCvrSimilarType(T1: SrcTy, T2: DestTy))
7662 return CK_NoOp;
7663 return CK_BitCast;
7664 }
7665 case Type::STK_BlockPointer:
7666 return (SrcKind == Type::STK_BlockPointer
7667 ? CK_BitCast : CK_AnyPointerToBlockPointerCast);
7668 case Type::STK_ObjCObjectPointer:
7669 if (SrcKind == Type::STK_ObjCObjectPointer)
7670 return CK_BitCast;
7671 if (SrcKind == Type::STK_CPointer)
7672 return CK_CPointerToObjCPointerCast;
7673 maybeExtendBlockObject(E&: Src);
7674 return CK_BlockPointerToObjCPointerCast;
7675 case Type::STK_Bool:
7676 return CK_PointerToBoolean;
7677 case Type::STK_Integral:
7678 return CK_PointerToIntegral;
7679 case Type::STK_Floating:
7680 case Type::STK_FloatingComplex:
7681 case Type::STK_IntegralComplex:
7682 case Type::STK_MemberPointer:
7683 case Type::STK_FixedPoint:
7684 llvm_unreachable("illegal cast from pointer");
7685 }
7686 llvm_unreachable("Should have returned before this");
7687
7688 case Type::STK_FixedPoint:
7689 switch (DestTy->getScalarTypeKind()) {
7690 case Type::STK_FixedPoint:
7691 return CK_FixedPointCast;
7692 case Type::STK_Bool:
7693 return CK_FixedPointToBoolean;
7694 case Type::STK_Integral:
7695 return CK_FixedPointToIntegral;
7696 case Type::STK_Floating:
7697 return CK_FixedPointToFloating;
7698 case Type::STK_IntegralComplex:
7699 case Type::STK_FloatingComplex:
7700 Diag(Loc: Src.get()->getExprLoc(),
7701 DiagID: diag::err_unimplemented_conversion_with_fixed_point_type)
7702 << DestTy;
7703 return CK_IntegralCast;
7704 case Type::STK_CPointer:
7705 case Type::STK_ObjCObjectPointer:
7706 case Type::STK_BlockPointer:
7707 case Type::STK_MemberPointer:
7708 llvm_unreachable("illegal cast to pointer type");
7709 }
7710 llvm_unreachable("Should have returned before this");
7711
7712 case Type::STK_Bool: // casting from bool is like casting from an integer
7713 case Type::STK_Integral:
7714 switch (DestTy->getScalarTypeKind()) {
7715 case Type::STK_CPointer:
7716 case Type::STK_ObjCObjectPointer:
7717 case Type::STK_BlockPointer:
7718 if (Src.get()->isNullPointerConstant(Ctx&: Context,
7719 NPC: Expr::NPC_ValueDependentIsNull))
7720 return CK_NullToPointer;
7721 return CK_IntegralToPointer;
7722 case Type::STK_Bool:
7723 return CK_IntegralToBoolean;
7724 case Type::STK_Integral:
7725 return CK_IntegralCast;
7726 case Type::STK_Floating:
7727 return CK_IntegralToFloating;
7728 case Type::STK_IntegralComplex:
7729 Src = ImpCastExprToType(E: Src.get(),
7730 Type: DestTy->castAs<ComplexType>()->getElementType(),
7731 CK: CK_IntegralCast);
7732 return CK_IntegralRealToComplex;
7733 case Type::STK_FloatingComplex:
7734 Src = ImpCastExprToType(E: Src.get(),
7735 Type: DestTy->castAs<ComplexType>()->getElementType(),
7736 CK: CK_IntegralToFloating);
7737 return CK_FloatingRealToComplex;
7738 case Type::STK_MemberPointer:
7739 llvm_unreachable("member pointer type in C");
7740 case Type::STK_FixedPoint:
7741 return CK_IntegralToFixedPoint;
7742 }
7743 llvm_unreachable("Should have returned before this");
7744
7745 case Type::STK_Floating:
7746 switch (DestTy->getScalarTypeKind()) {
7747 case Type::STK_Floating:
7748 return CK_FloatingCast;
7749 case Type::STK_Bool:
7750 return CK_FloatingToBoolean;
7751 case Type::STK_Integral:
7752 return CK_FloatingToIntegral;
7753 case Type::STK_FloatingComplex:
7754 Src = ImpCastExprToType(E: Src.get(),
7755 Type: DestTy->castAs<ComplexType>()->getElementType(),
7756 CK: CK_FloatingCast);
7757 return CK_FloatingRealToComplex;
7758 case Type::STK_IntegralComplex:
7759 Src = ImpCastExprToType(E: Src.get(),
7760 Type: DestTy->castAs<ComplexType>()->getElementType(),
7761 CK: CK_FloatingToIntegral);
7762 return CK_IntegralRealToComplex;
7763 case Type::STK_CPointer:
7764 case Type::STK_ObjCObjectPointer:
7765 case Type::STK_BlockPointer:
7766 llvm_unreachable("valid float->pointer cast?");
7767 case Type::STK_MemberPointer:
7768 llvm_unreachable("member pointer type in C");
7769 case Type::STK_FixedPoint:
7770 return CK_FloatingToFixedPoint;
7771 }
7772 llvm_unreachable("Should have returned before this");
7773
7774 case Type::STK_FloatingComplex:
7775 switch (DestTy->getScalarTypeKind()) {
7776 case Type::STK_FloatingComplex:
7777 return CK_FloatingComplexCast;
7778 case Type::STK_IntegralComplex:
7779 return CK_FloatingComplexToIntegralComplex;
7780 case Type::STK_Floating: {
7781 QualType ET = SrcTy->castAs<ComplexType>()->getElementType();
7782 if (Context.hasSameType(T1: ET, T2: DestTy))
7783 return CK_FloatingComplexToReal;
7784 Src = ImpCastExprToType(E: Src.get(), Type: ET, CK: CK_FloatingComplexToReal);
7785 return CK_FloatingCast;
7786 }
7787 case Type::STK_Bool:
7788 return CK_FloatingComplexToBoolean;
7789 case Type::STK_Integral:
7790 Src = ImpCastExprToType(E: Src.get(),
7791 Type: SrcTy->castAs<ComplexType>()->getElementType(),
7792 CK: CK_FloatingComplexToReal);
7793 return CK_FloatingToIntegral;
7794 case Type::STK_CPointer:
7795 case Type::STK_ObjCObjectPointer:
7796 case Type::STK_BlockPointer:
7797 llvm_unreachable("valid complex float->pointer cast?");
7798 case Type::STK_MemberPointer:
7799 llvm_unreachable("member pointer type in C");
7800 case Type::STK_FixedPoint:
7801 Diag(Loc: Src.get()->getExprLoc(),
7802 DiagID: diag::err_unimplemented_conversion_with_fixed_point_type)
7803 << SrcTy;
7804 return CK_IntegralCast;
7805 }
7806 llvm_unreachable("Should have returned before this");
7807
7808 case Type::STK_IntegralComplex:
7809 switch (DestTy->getScalarTypeKind()) {
7810 case Type::STK_FloatingComplex:
7811 return CK_IntegralComplexToFloatingComplex;
7812 case Type::STK_IntegralComplex:
7813 return CK_IntegralComplexCast;
7814 case Type::STK_Integral: {
7815 QualType ET = SrcTy->castAs<ComplexType>()->getElementType();
7816 if (Context.hasSameType(T1: ET, T2: DestTy))
7817 return CK_IntegralComplexToReal;
7818 Src = ImpCastExprToType(E: Src.get(), Type: ET, CK: CK_IntegralComplexToReal);
7819 return CK_IntegralCast;
7820 }
7821 case Type::STK_Bool:
7822 return CK_IntegralComplexToBoolean;
7823 case Type::STK_Floating:
7824 Src = ImpCastExprToType(E: Src.get(),
7825 Type: SrcTy->castAs<ComplexType>()->getElementType(),
7826 CK: CK_IntegralComplexToReal);
7827 return CK_IntegralToFloating;
7828 case Type::STK_CPointer:
7829 case Type::STK_ObjCObjectPointer:
7830 case Type::STK_BlockPointer:
7831 llvm_unreachable("valid complex int->pointer cast?");
7832 case Type::STK_MemberPointer:
7833 llvm_unreachable("member pointer type in C");
7834 case Type::STK_FixedPoint:
7835 Diag(Loc: Src.get()->getExprLoc(),
7836 DiagID: diag::err_unimplemented_conversion_with_fixed_point_type)
7837 << SrcTy;
7838 return CK_IntegralCast;
7839 }
7840 llvm_unreachable("Should have returned before this");
7841 }
7842
7843 llvm_unreachable("Unhandled scalar cast");
7844}
7845
7846static bool breakDownVectorType(QualType type, uint64_t &len,
7847 QualType &eltType) {
7848 // Vectors are simple.
7849 if (const VectorType *vecType = type->getAs<VectorType>()) {
7850 len = vecType->getNumElements();
7851 eltType = vecType->getElementType();
7852 assert(eltType->isScalarType() || eltType->isMFloat8Type());
7853 return true;
7854 }
7855
7856 // We allow lax conversion to and from non-vector types, but only if
7857 // they're real types (i.e. non-complex, non-pointer scalar types).
7858 if (!type->isRealType()) return false;
7859
7860 len = 1;
7861 eltType = type;
7862 return true;
7863}
7864
7865bool Sema::isValidSveBitcast(QualType srcTy, QualType destTy) {
7866 assert(srcTy->isVectorType() || destTy->isVectorType());
7867
7868 auto ValidScalableConversion = [](QualType FirstType, QualType SecondType) {
7869 if (!FirstType->isSVESizelessBuiltinType())
7870 return false;
7871
7872 const auto *VecTy = SecondType->getAs<VectorType>();
7873 return VecTy && VecTy->getVectorKind() == VectorKind::SveFixedLengthData;
7874 };
7875
7876 return ValidScalableConversion(srcTy, destTy) ||
7877 ValidScalableConversion(destTy, srcTy);
7878}
7879
7880bool Sema::areMatrixTypesOfTheSameDimension(QualType srcTy, QualType destTy) {
7881 if (!destTy->isMatrixType() || !srcTy->isMatrixType())
7882 return false;
7883
7884 const ConstantMatrixType *matSrcType = srcTy->getAs<ConstantMatrixType>();
7885 const ConstantMatrixType *matDestType = destTy->getAs<ConstantMatrixType>();
7886
7887 return matSrcType->getNumRows() == matDestType->getNumRows() &&
7888 matSrcType->getNumColumns() == matDestType->getNumColumns();
7889}
7890
7891bool Sema::areVectorTypesSameSize(QualType SrcTy, QualType DestTy) {
7892 assert(DestTy->isVectorType() || SrcTy->isVectorType());
7893
7894 uint64_t SrcLen, DestLen;
7895 QualType SrcEltTy, DestEltTy;
7896 if (!breakDownVectorType(type: SrcTy, len&: SrcLen, eltType&: SrcEltTy))
7897 return false;
7898 if (!breakDownVectorType(type: DestTy, len&: DestLen, eltType&: DestEltTy))
7899 return false;
7900
7901 // ASTContext::getTypeSize will return the size rounded up to a
7902 // power of 2, so instead of using that, we need to use the raw
7903 // element size multiplied by the element count.
7904 uint64_t SrcEltSize = Context.getTypeSize(T: SrcEltTy);
7905 uint64_t DestEltSize = Context.getTypeSize(T: DestEltTy);
7906
7907 return (SrcLen * SrcEltSize == DestLen * DestEltSize);
7908}
7909
7910bool Sema::anyAltivecTypes(QualType SrcTy, QualType DestTy) {
7911 assert((DestTy->isVectorType() || SrcTy->isVectorType()) &&
7912 "expected at least one type to be a vector here");
7913
7914 bool IsSrcTyAltivec =
7915 SrcTy->isVectorType() && ((SrcTy->castAs<VectorType>()->getVectorKind() ==
7916 VectorKind::AltiVecVector) ||
7917 (SrcTy->castAs<VectorType>()->getVectorKind() ==
7918 VectorKind::AltiVecBool) ||
7919 (SrcTy->castAs<VectorType>()->getVectorKind() ==
7920 VectorKind::AltiVecPixel));
7921
7922 bool IsDestTyAltivec = DestTy->isVectorType() &&
7923 ((DestTy->castAs<VectorType>()->getVectorKind() ==
7924 VectorKind::AltiVecVector) ||
7925 (DestTy->castAs<VectorType>()->getVectorKind() ==
7926 VectorKind::AltiVecBool) ||
7927 (DestTy->castAs<VectorType>()->getVectorKind() ==
7928 VectorKind::AltiVecPixel));
7929
7930 return (IsSrcTyAltivec || IsDestTyAltivec);
7931}
7932
7933bool Sema::areLaxCompatibleVectorTypes(QualType srcTy, QualType destTy) {
7934 assert(destTy->isVectorType() || srcTy->isVectorType());
7935
7936 // Disallow lax conversions between scalars and ExtVectors (these
7937 // conversions are allowed for other vector types because common headers
7938 // depend on them). Most scalar OP ExtVector cases are handled by the
7939 // splat path anyway, which does what we want (convert, not bitcast).
7940 // What this rules out for ExtVectors is crazy things like char4*float.
7941 if (srcTy->isScalarType() && destTy->isExtVectorType()) return false;
7942 if (destTy->isScalarType() && srcTy->isExtVectorType()) return false;
7943
7944 return areVectorTypesSameSize(SrcTy: srcTy, DestTy: destTy);
7945}
7946
7947bool Sema::isLaxVectorConversion(QualType srcTy, QualType destTy) {
7948 assert(destTy->isVectorType() || srcTy->isVectorType());
7949
7950 switch (Context.getLangOpts().getLaxVectorConversions()) {
7951 case LangOptions::LaxVectorConversionKind::None:
7952 return false;
7953
7954 case LangOptions::LaxVectorConversionKind::Integer:
7955 if (!srcTy->isIntegralOrEnumerationType()) {
7956 auto *Vec = srcTy->getAs<VectorType>();
7957 if (!Vec || !Vec->getElementType()->isIntegralOrEnumerationType())
7958 return false;
7959 }
7960 if (!destTy->isIntegralOrEnumerationType()) {
7961 auto *Vec = destTy->getAs<VectorType>();
7962 if (!Vec || !Vec->getElementType()->isIntegralOrEnumerationType())
7963 return false;
7964 }
7965 // OK, integer (vector) -> integer (vector) bitcast.
7966 break;
7967
7968 case LangOptions::LaxVectorConversionKind::All:
7969 break;
7970 }
7971
7972 return areLaxCompatibleVectorTypes(srcTy, destTy);
7973}
7974
7975bool Sema::CheckMatrixCast(SourceRange R, QualType DestTy, QualType SrcTy,
7976 CastKind &Kind) {
7977 if (SrcTy->isMatrixType() && DestTy->isMatrixType()) {
7978 if (!areMatrixTypesOfTheSameDimension(srcTy: SrcTy, destTy: DestTy)) {
7979 return Diag(Loc: R.getBegin(), DiagID: diag::err_invalid_conversion_between_matrixes)
7980 << DestTy << SrcTy << R;
7981 }
7982 } else if (SrcTy->isMatrixType()) {
7983 return Diag(Loc: R.getBegin(),
7984 DiagID: diag::err_invalid_conversion_between_matrix_and_type)
7985 << SrcTy << DestTy << R;
7986 } else if (DestTy->isMatrixType()) {
7987 return Diag(Loc: R.getBegin(),
7988 DiagID: diag::err_invalid_conversion_between_matrix_and_type)
7989 << DestTy << SrcTy << R;
7990 }
7991
7992 Kind = CK_MatrixCast;
7993 return false;
7994}
7995
7996bool Sema::CheckVectorCast(SourceRange R, QualType VectorTy, QualType Ty,
7997 CastKind &Kind) {
7998 assert(VectorTy->isVectorType() && "Not a vector type!");
7999
8000 if (Ty->isVectorType() || Ty->isIntegralType(Ctx: Context)) {
8001 if (!areLaxCompatibleVectorTypes(srcTy: Ty, destTy: VectorTy))
8002 return Diag(Loc: R.getBegin(),
8003 DiagID: Ty->isVectorType() ?
8004 diag::err_invalid_conversion_between_vectors :
8005 diag::err_invalid_conversion_between_vector_and_integer)
8006 << VectorTy << Ty << R;
8007 } else
8008 return Diag(Loc: R.getBegin(),
8009 DiagID: diag::err_invalid_conversion_between_vector_and_scalar)
8010 << VectorTy << Ty << R;
8011
8012 Kind = CK_BitCast;
8013 return false;
8014}
8015
8016ExprResult Sema::prepareVectorSplat(QualType VectorTy, Expr *SplattedExpr) {
8017 QualType DestElemTy = VectorTy->castAs<VectorType>()->getElementType();
8018
8019 if (DestElemTy == SplattedExpr->getType())
8020 return SplattedExpr;
8021
8022 assert(DestElemTy->isFloatingType() ||
8023 DestElemTy->isIntegralOrEnumerationType());
8024
8025 CastKind CK;
8026 if (VectorTy->isExtVectorType() && SplattedExpr->getType()->isBooleanType()) {
8027 // OpenCL requires that we convert `true` boolean expressions to -1, but
8028 // only when splatting vectors.
8029 if (DestElemTy->isFloatingType()) {
8030 // To avoid having to have a CK_BooleanToSignedFloating cast kind, we cast
8031 // in two steps: boolean to signed integral, then to floating.
8032 ExprResult CastExprRes = ImpCastExprToType(E: SplattedExpr, Type: Context.IntTy,
8033 CK: CK_BooleanToSignedIntegral);
8034 SplattedExpr = CastExprRes.get();
8035 CK = CK_IntegralToFloating;
8036 } else {
8037 CK = CK_BooleanToSignedIntegral;
8038 }
8039 } else {
8040 ExprResult CastExprRes = SplattedExpr;
8041 CK = PrepareScalarCast(Src&: CastExprRes, DestTy: DestElemTy);
8042 if (CastExprRes.isInvalid())
8043 return ExprError();
8044 SplattedExpr = CastExprRes.get();
8045 }
8046 return ImpCastExprToType(E: SplattedExpr, Type: DestElemTy, CK);
8047}
8048
8049ExprResult Sema::prepareMatrixSplat(QualType MatrixTy, Expr *SplattedExpr) {
8050 QualType DestElemTy = MatrixTy->castAs<MatrixType>()->getElementType();
8051
8052 if (DestElemTy == SplattedExpr->getType())
8053 return SplattedExpr;
8054
8055 assert(DestElemTy->isFloatingType() ||
8056 DestElemTy->isIntegralOrEnumerationType());
8057
8058 ExprResult CastExprRes = SplattedExpr;
8059 CastKind CK = PrepareScalarCast(Src&: CastExprRes, DestTy: DestElemTy);
8060 if (CastExprRes.isInvalid())
8061 return ExprError();
8062 SplattedExpr = CastExprRes.get();
8063
8064 return ImpCastExprToType(E: SplattedExpr, Type: DestElemTy, CK);
8065}
8066
8067ExprResult Sema::CheckExtVectorCast(SourceRange R, QualType DestTy,
8068 Expr *CastExpr, CastKind &Kind) {
8069 assert(DestTy->isExtVectorType() && "Not an extended vector type!");
8070
8071 QualType SrcTy = CastExpr->getType();
8072
8073 // If SrcTy is a VectorType, the total size must match to explicitly cast to
8074 // an ExtVectorType.
8075 // In OpenCL, casts between vectors of different types are not allowed.
8076 // (See OpenCL 6.2).
8077 if (SrcTy->isVectorType()) {
8078 if (!areLaxCompatibleVectorTypes(srcTy: SrcTy, destTy: DestTy) ||
8079 (getLangOpts().OpenCL &&
8080 !Context.hasSameUnqualifiedType(T1: DestTy, T2: SrcTy) &&
8081 !Context.areCompatibleVectorTypes(FirstVec: DestTy, SecondVec: SrcTy))) {
8082 Diag(Loc: R.getBegin(),DiagID: diag::err_invalid_conversion_between_ext_vectors)
8083 << DestTy << SrcTy << R;
8084 return ExprError();
8085 }
8086 Kind = CK_BitCast;
8087 return CastExpr;
8088 }
8089
8090 // All non-pointer scalars can be cast to ExtVector type. The appropriate
8091 // conversion will take place first from scalar to elt type, and then
8092 // splat from elt type to vector.
8093 if (SrcTy->isPointerType())
8094 return Diag(Loc: R.getBegin(),
8095 DiagID: diag::err_invalid_conversion_between_vector_and_scalar)
8096 << DestTy << SrcTy << R;
8097
8098 Kind = CK_VectorSplat;
8099 return prepareVectorSplat(VectorTy: DestTy, SplattedExpr: CastExpr);
8100}
8101
8102/// Check that a call to alloc_size function specifies sufficient space for the
8103/// destination type.
8104static void CheckSufficientAllocSize(Sema &S, QualType DestType,
8105 const Expr *E) {
8106 QualType SourceType = E->getType();
8107 if (!DestType->isPointerType() || !SourceType->isPointerType() ||
8108 DestType == SourceType)
8109 return;
8110
8111 const auto *CE = dyn_cast<CallExpr>(Val: E->IgnoreParenCasts());
8112 if (!CE)
8113 return;
8114
8115 // Find the total size allocated by the function call.
8116 if (!CE->getCalleeAllocSizeAttr())
8117 return;
8118 std::optional<llvm::APInt> AllocSize =
8119 CE->evaluateBytesReturnedByAllocSizeCall(Ctx: S.Context);
8120 // Allocations of size zero are permitted as a special case. They are usually
8121 // done intentionally.
8122 if (!AllocSize || AllocSize->isZero())
8123 return;
8124 auto Size = CharUnits::fromQuantity(Quantity: AllocSize->getZExtValue());
8125
8126 QualType TargetType = DestType->getPointeeType();
8127 // Find the destination size. As a special case function types have size of
8128 // one byte to match the sizeof operator behavior.
8129 auto LhsSize = TargetType->isFunctionType()
8130 ? CharUnits::One()
8131 : S.Context.getTypeSizeInCharsIfKnown(Ty: TargetType);
8132 if (LhsSize && Size < LhsSize)
8133 S.Diag(Loc: E->getExprLoc(), DiagID: diag::warn_alloc_size)
8134 << Size.getQuantity() << TargetType << LhsSize->getQuantity();
8135}
8136
8137ExprResult
8138Sema::ActOnCastExpr(Scope *S, SourceLocation LParenLoc,
8139 Declarator &D, ParsedType &Ty,
8140 SourceLocation RParenLoc, Expr *CastExpr) {
8141 assert(!D.isInvalidType() && (CastExpr != nullptr) &&
8142 "ActOnCastExpr(): missing type or expr");
8143
8144 TypeSourceInfo *castTInfo = GetTypeForDeclaratorCast(D, FromTy: CastExpr->getType());
8145 if (D.isInvalidType())
8146 return ExprError();
8147
8148 if (getLangOpts().CPlusPlus) {
8149 // Check that there are no default arguments (C++ only).
8150 CheckExtraCXXDefaultArguments(D);
8151 }
8152
8153 checkUnusedDeclAttributes(D);
8154
8155 QualType castType = castTInfo->getType();
8156 Ty = CreateParsedType(T: castType, TInfo: castTInfo);
8157
8158 bool isVectorLiteral = false;
8159
8160 // Check for an altivec or OpenCL literal,
8161 // i.e. all the elements are integer constants.
8162 ParenExpr *PE = dyn_cast<ParenExpr>(Val: CastExpr);
8163 ParenListExpr *PLE = dyn_cast<ParenListExpr>(Val: CastExpr);
8164 if ((getLangOpts().AltiVec || getLangOpts().ZVector || getLangOpts().OpenCL)
8165 && castType->isVectorType() && (PE || PLE)) {
8166 if (PLE && PLE->getNumExprs() == 0) {
8167 Diag(Loc: PLE->getExprLoc(), DiagID: diag::err_altivec_empty_initializer);
8168 return ExprError();
8169 }
8170 if (PE || PLE->getNumExprs() == 1) {
8171 Expr *E = (PE ? PE->getSubExpr() : PLE->getExpr(Init: 0));
8172 if (!E->isTypeDependent() && !E->getType()->isVectorType())
8173 isVectorLiteral = true;
8174 }
8175 else
8176 isVectorLiteral = true;
8177 }
8178
8179 // If this is a vector initializer, '(' type ')' '(' init, ..., init ')'
8180 // then handle it as such.
8181 if (isVectorLiteral)
8182 return BuildVectorLiteral(LParenLoc, RParenLoc, E: CastExpr, TInfo: castTInfo);
8183
8184 // If the Expr being casted is a ParenListExpr, handle it specially.
8185 // This is not an AltiVec-style cast, so turn the ParenListExpr into a
8186 // sequence of BinOp comma operators.
8187 if (isa<ParenListExpr>(Val: CastExpr)) {
8188 ExprResult Result = MaybeConvertParenListExprToParenExpr(S, ME: CastExpr);
8189 if (Result.isInvalid()) return ExprError();
8190 CastExpr = Result.get();
8191 }
8192
8193 if (getLangOpts().CPlusPlus && !castType->isVoidType())
8194 Diag(Loc: LParenLoc, DiagID: diag::warn_old_style_cast) << CastExpr->getSourceRange();
8195
8196 ObjC().CheckTollFreeBridgeCast(castType, castExpr: CastExpr);
8197
8198 ObjC().CheckObjCBridgeRelatedCast(castType, castExpr: CastExpr);
8199
8200 DiscardMisalignedMemberAddress(T: castType.getTypePtr(), E: CastExpr);
8201
8202 CheckSufficientAllocSize(S&: *this, DestType: castType, E: CastExpr);
8203
8204 return BuildCStyleCastExpr(LParenLoc, Ty: castTInfo, RParenLoc, Op: CastExpr);
8205}
8206
8207ExprResult Sema::BuildVectorLiteral(SourceLocation LParenLoc,
8208 SourceLocation RParenLoc, Expr *E,
8209 TypeSourceInfo *TInfo) {
8210 assert((isa<ParenListExpr>(E) || isa<ParenExpr>(E)) &&
8211 "Expected paren or paren list expression");
8212
8213 Expr **exprs;
8214 unsigned numExprs;
8215 Expr *subExpr;
8216 SourceLocation LiteralLParenLoc, LiteralRParenLoc;
8217 if (ParenListExpr *PE = dyn_cast<ParenListExpr>(Val: E)) {
8218 LiteralLParenLoc = PE->getLParenLoc();
8219 LiteralRParenLoc = PE->getRParenLoc();
8220 exprs = PE->getExprs();
8221 numExprs = PE->getNumExprs();
8222 } else { // isa<ParenExpr> by assertion at function entrance
8223 LiteralLParenLoc = cast<ParenExpr>(Val: E)->getLParen();
8224 LiteralRParenLoc = cast<ParenExpr>(Val: E)->getRParen();
8225 subExpr = cast<ParenExpr>(Val: E)->getSubExpr();
8226 exprs = &subExpr;
8227 numExprs = 1;
8228 }
8229
8230 QualType Ty = TInfo->getType();
8231 assert(Ty->isVectorType() && "Expected vector type");
8232
8233 SmallVector<Expr *, 8> initExprs;
8234 const VectorType *VTy = Ty->castAs<VectorType>();
8235 unsigned numElems = VTy->getNumElements();
8236
8237 // '(...)' form of vector initialization in AltiVec: the number of
8238 // initializers must be one or must match the size of the vector.
8239 // If a single value is specified in the initializer then it will be
8240 // replicated to all the components of the vector
8241 if (CheckAltivecInitFromScalar(R: E->getSourceRange(), VecTy: Ty,
8242 SrcTy: VTy->getElementType()))
8243 return ExprError();
8244 if (ShouldSplatAltivecScalarInCast(VecTy: VTy)) {
8245 // The number of initializers must be one or must match the size of the
8246 // vector. If a single value is specified in the initializer then it will
8247 // be replicated to all the components of the vector
8248 if (numExprs == 1) {
8249 QualType ElemTy = VTy->getElementType();
8250 ExprResult Literal = DefaultLvalueConversion(E: exprs[0]);
8251 if (Literal.isInvalid())
8252 return ExprError();
8253 Literal = ImpCastExprToType(E: Literal.get(), Type: ElemTy,
8254 CK: PrepareScalarCast(Src&: Literal, DestTy: ElemTy));
8255 return BuildCStyleCastExpr(LParenLoc, Ty: TInfo, RParenLoc, Op: Literal.get());
8256 }
8257 else if (numExprs < numElems) {
8258 Diag(Loc: E->getExprLoc(),
8259 DiagID: diag::err_incorrect_number_of_vector_initializers);
8260 return ExprError();
8261 }
8262 else
8263 initExprs.append(in_start: exprs, in_end: exprs + numExprs);
8264 }
8265 else {
8266 // For OpenCL, when the number of initializers is a single value,
8267 // it will be replicated to all components of the vector.
8268 if (getLangOpts().OpenCL && VTy->getVectorKind() == VectorKind::Generic &&
8269 numExprs == 1) {
8270 QualType SrcTy = exprs[0]->getType();
8271 if (!SrcTy->isArithmeticType()) {
8272 Diag(Loc: exprs[0]->getBeginLoc(), DiagID: diag::err_typecheck_convert_incompatible)
8273 << Ty << SrcTy << AssignmentAction::Initializing << /*elidable=*/0
8274 << /*c_style=*/0 << /*cast_kind=*/"" << exprs[0]->getSourceRange();
8275 return ExprError();
8276 }
8277 QualType ElemTy = VTy->getElementType();
8278 ExprResult Literal = DefaultLvalueConversion(E: exprs[0]);
8279 if (Literal.isInvalid())
8280 return ExprError();
8281 Literal = ImpCastExprToType(E: Literal.get(), Type: ElemTy,
8282 CK: PrepareScalarCast(Src&: Literal, DestTy: ElemTy));
8283 return BuildCStyleCastExpr(LParenLoc, Ty: TInfo, RParenLoc, Op: Literal.get());
8284 }
8285
8286 initExprs.append(in_start: exprs, in_end: exprs + numExprs);
8287 }
8288 // FIXME: This means that pretty-printing the final AST will produce curly
8289 // braces instead of the original commas.
8290 InitListExpr *initE = new (Context) InitListExpr(Context, LiteralLParenLoc,
8291 initExprs, LiteralRParenLoc);
8292 initE->setType(Ty);
8293 return BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc, LiteralExpr: initE);
8294}
8295
8296ExprResult
8297Sema::MaybeConvertParenListExprToParenExpr(Scope *S, Expr *OrigExpr) {
8298 ParenListExpr *E = dyn_cast<ParenListExpr>(Val: OrigExpr);
8299 if (!E)
8300 return OrigExpr;
8301
8302 ExprResult Result(E->getExpr(Init: 0));
8303
8304 for (unsigned i = 1, e = E->getNumExprs(); i != e && !Result.isInvalid(); ++i)
8305 Result = ActOnBinOp(S, TokLoc: E->getExprLoc(), Kind: tok::comma, LHSExpr: Result.get(),
8306 RHSExpr: E->getExpr(Init: i));
8307
8308 if (Result.isInvalid()) return ExprError();
8309
8310 return ActOnParenExpr(L: E->getLParenLoc(), R: E->getRParenLoc(), E: Result.get());
8311}
8312
8313ExprResult Sema::ActOnParenListExpr(SourceLocation L,
8314 SourceLocation R,
8315 MultiExprArg Val) {
8316 return ParenListExpr::Create(Ctx: Context, LParenLoc: L, Exprs: Val, RParenLoc: R);
8317}
8318
8319ExprResult Sema::ActOnCXXParenListInitExpr(ArrayRef<Expr *> Args, QualType T,
8320 unsigned NumUserSpecifiedExprs,
8321 SourceLocation InitLoc,
8322 SourceLocation LParenLoc,
8323 SourceLocation RParenLoc) {
8324 return CXXParenListInitExpr::Create(C&: Context, Args, T, NumUserSpecifiedExprs,
8325 InitLoc, LParenLoc, RParenLoc);
8326}
8327
8328bool Sema::DiagnoseConditionalForNull(const Expr *LHSExpr, const Expr *RHSExpr,
8329 SourceLocation QuestionLoc) {
8330 const Expr *NullExpr = LHSExpr;
8331 const Expr *NonPointerExpr = RHSExpr;
8332 Expr::NullPointerConstantKind NullKind =
8333 NullExpr->isNullPointerConstant(Ctx&: Context,
8334 NPC: Expr::NPC_ValueDependentIsNotNull);
8335
8336 if (NullKind == Expr::NPCK_NotNull) {
8337 NullExpr = RHSExpr;
8338 NonPointerExpr = LHSExpr;
8339 NullKind =
8340 NullExpr->isNullPointerConstant(Ctx&: Context,
8341 NPC: Expr::NPC_ValueDependentIsNotNull);
8342 }
8343
8344 if (NullKind == Expr::NPCK_NotNull)
8345 return false;
8346
8347 if (NullKind == Expr::NPCK_ZeroExpression)
8348 return false;
8349
8350 if (NullKind == Expr::NPCK_ZeroLiteral) {
8351 // In this case, check to make sure that we got here from a "NULL"
8352 // string in the source code.
8353 NullExpr = NullExpr->IgnoreParenImpCasts();
8354 SourceLocation loc = NullExpr->getExprLoc();
8355 if (!findMacroSpelling(loc, name: "NULL"))
8356 return false;
8357 }
8358
8359 int DiagType = (NullKind == Expr::NPCK_CXX11_nullptr);
8360 Diag(Loc: QuestionLoc, DiagID: diag::err_typecheck_cond_incompatible_operands_null)
8361 << NonPointerExpr->getType() << DiagType
8362 << NonPointerExpr->getSourceRange();
8363 return true;
8364}
8365
8366/// Return false if the condition expression is valid, true otherwise.
8367static bool checkCondition(Sema &S, const Expr *Cond,
8368 SourceLocation QuestionLoc) {
8369 QualType CondTy = Cond->getType();
8370
8371 // OpenCL v1.1 s6.3.i says the condition cannot be a floating point type.
8372 if (S.getLangOpts().OpenCL && CondTy->isFloatingType()) {
8373 S.Diag(Loc: QuestionLoc, DiagID: diag::err_typecheck_cond_expect_nonfloat)
8374 << CondTy << Cond->getSourceRange();
8375 return true;
8376 }
8377
8378 // C99 6.5.15p2
8379 if (CondTy->isScalarType()) return false;
8380
8381 S.Diag(Loc: QuestionLoc, DiagID: diag::err_typecheck_cond_expect_scalar)
8382 << CondTy << Cond->getSourceRange();
8383 return true;
8384}
8385
8386/// Return false if the NullExpr can be promoted to PointerTy,
8387/// true otherwise.
8388static bool checkConditionalNullPointer(Sema &S, ExprResult &NullExpr,
8389 QualType PointerTy) {
8390 if ((!PointerTy->isAnyPointerType() && !PointerTy->isBlockPointerType()) ||
8391 !NullExpr.get()->isNullPointerConstant(Ctx&: S.Context,
8392 NPC: Expr::NPC_ValueDependentIsNull))
8393 return true;
8394
8395 NullExpr = S.ImpCastExprToType(E: NullExpr.get(), Type: PointerTy, CK: CK_NullToPointer);
8396 return false;
8397}
8398
8399/// Checks compatibility between two pointers and return the resulting
8400/// type.
8401static QualType checkConditionalPointerCompatibility(Sema &S, ExprResult &LHS,
8402 ExprResult &RHS,
8403 SourceLocation Loc) {
8404 QualType LHSTy = LHS.get()->getType();
8405 QualType RHSTy = RHS.get()->getType();
8406
8407 if (S.Context.hasSameType(T1: LHSTy, T2: RHSTy)) {
8408 // Two identical pointers types are always compatible.
8409 return S.Context.getCommonSugaredType(X: LHSTy, Y: RHSTy);
8410 }
8411
8412 QualType lhptee, rhptee;
8413
8414 // Get the pointee types.
8415 bool IsBlockPointer = false;
8416 if (const BlockPointerType *LHSBTy = LHSTy->getAs<BlockPointerType>()) {
8417 lhptee = LHSBTy->getPointeeType();
8418 rhptee = RHSTy->castAs<BlockPointerType>()->getPointeeType();
8419 IsBlockPointer = true;
8420 } else {
8421 lhptee = LHSTy->castAs<PointerType>()->getPointeeType();
8422 rhptee = RHSTy->castAs<PointerType>()->getPointeeType();
8423 }
8424
8425 // C99 6.5.15p6: If both operands are pointers to compatible types or to
8426 // differently qualified versions of compatible types, the result type is
8427 // a pointer to an appropriately qualified version of the composite
8428 // type.
8429
8430 // Only CVR-qualifiers exist in the standard, and the differently-qualified
8431 // clause doesn't make sense for our extensions. E.g. address space 2 should
8432 // be incompatible with address space 3: they may live on different devices or
8433 // anything.
8434 Qualifiers lhQual = lhptee.getQualifiers();
8435 Qualifiers rhQual = rhptee.getQualifiers();
8436
8437 LangAS ResultAddrSpace = LangAS::Default;
8438 LangAS LAddrSpace = lhQual.getAddressSpace();
8439 LangAS RAddrSpace = rhQual.getAddressSpace();
8440
8441 // OpenCL v1.1 s6.5 - Conversion between pointers to distinct address
8442 // spaces is disallowed.
8443 if (lhQual.isAddressSpaceSupersetOf(other: rhQual, Ctx: S.getASTContext()))
8444 ResultAddrSpace = LAddrSpace;
8445 else if (rhQual.isAddressSpaceSupersetOf(other: lhQual, Ctx: S.getASTContext()))
8446 ResultAddrSpace = RAddrSpace;
8447 else {
8448 S.Diag(Loc, DiagID: diag::err_typecheck_op_on_nonoverlapping_address_space_pointers)
8449 << LHSTy << RHSTy << 2 << LHS.get()->getSourceRange()
8450 << RHS.get()->getSourceRange();
8451 return QualType();
8452 }
8453
8454 unsigned MergedCVRQual = lhQual.getCVRQualifiers() | rhQual.getCVRQualifiers();
8455 auto LHSCastKind = CK_BitCast, RHSCastKind = CK_BitCast;
8456 lhQual.removeCVRQualifiers();
8457 rhQual.removeCVRQualifiers();
8458
8459 if (!lhQual.getPointerAuth().isEquivalent(Other: rhQual.getPointerAuth())) {
8460 S.Diag(Loc, DiagID: diag::err_typecheck_cond_incompatible_ptrauth)
8461 << LHSTy << RHSTy << LHS.get()->getSourceRange()
8462 << RHS.get()->getSourceRange();
8463 return QualType();
8464 }
8465
8466 // OpenCL v2.0 specification doesn't extend compatibility of type qualifiers
8467 // (C99 6.7.3) for address spaces. We assume that the check should behave in
8468 // the same manner as it's defined for CVR qualifiers, so for OpenCL two
8469 // qual types are compatible iff
8470 // * corresponded types are compatible
8471 // * CVR qualifiers are equal
8472 // * address spaces are equal
8473 // Thus for conditional operator we merge CVR and address space unqualified
8474 // pointees and if there is a composite type we return a pointer to it with
8475 // merged qualifiers.
8476 LHSCastKind =
8477 LAddrSpace == ResultAddrSpace ? CK_BitCast : CK_AddressSpaceConversion;
8478 RHSCastKind =
8479 RAddrSpace == ResultAddrSpace ? CK_BitCast : CK_AddressSpaceConversion;
8480 lhQual.removeAddressSpace();
8481 rhQual.removeAddressSpace();
8482
8483 lhptee = S.Context.getQualifiedType(T: lhptee.getUnqualifiedType(), Qs: lhQual);
8484 rhptee = S.Context.getQualifiedType(T: rhptee.getUnqualifiedType(), Qs: rhQual);
8485
8486 QualType CompositeTy = S.Context.mergeTypes(
8487 lhptee, rhptee, /*OfBlockPointer=*/false, /*Unqualified=*/false,
8488 /*BlockReturnType=*/false, /*IsConditionalOperator=*/true);
8489
8490 if (CompositeTy.isNull()) {
8491 // In this situation, we assume void* type. No especially good
8492 // reason, but this is what gcc does, and we do have to pick
8493 // to get a consistent AST.
8494 QualType incompatTy;
8495 incompatTy = S.Context.getPointerType(
8496 T: S.Context.getAddrSpaceQualType(T: S.Context.VoidTy, AddressSpace: ResultAddrSpace));
8497 LHS = S.ImpCastExprToType(E: LHS.get(), Type: incompatTy, CK: LHSCastKind);
8498 RHS = S.ImpCastExprToType(E: RHS.get(), Type: incompatTy, CK: RHSCastKind);
8499
8500 // FIXME: For OpenCL the warning emission and cast to void* leaves a room
8501 // for casts between types with incompatible address space qualifiers.
8502 // For the following code the compiler produces casts between global and
8503 // local address spaces of the corresponded innermost pointees:
8504 // local int *global *a;
8505 // global int *global *b;
8506 // a = (0 ? a : b); // see C99 6.5.16.1.p1.
8507 S.Diag(Loc, DiagID: diag::ext_typecheck_cond_incompatible_pointers)
8508 << LHSTy << RHSTy << LHS.get()->getSourceRange()
8509 << RHS.get()->getSourceRange();
8510
8511 return incompatTy;
8512 }
8513
8514 // The pointer types are compatible.
8515 // In case of OpenCL ResultTy should have the address space qualifier
8516 // which is a superset of address spaces of both the 2nd and the 3rd
8517 // operands of the conditional operator.
8518 QualType ResultTy = [&, ResultAddrSpace]() {
8519 if (S.getLangOpts().OpenCL) {
8520 Qualifiers CompositeQuals = CompositeTy.getQualifiers();
8521 CompositeQuals.setAddressSpace(ResultAddrSpace);
8522 return S.Context
8523 .getQualifiedType(T: CompositeTy.getUnqualifiedType(), Qs: CompositeQuals)
8524 .withCVRQualifiers(CVR: MergedCVRQual);
8525 }
8526 return CompositeTy.withCVRQualifiers(CVR: MergedCVRQual);
8527 }();
8528 if (IsBlockPointer)
8529 ResultTy = S.Context.getBlockPointerType(T: ResultTy);
8530 else
8531 ResultTy = S.Context.getPointerType(T: ResultTy);
8532
8533 LHS = S.ImpCastExprToType(E: LHS.get(), Type: ResultTy, CK: LHSCastKind);
8534 RHS = S.ImpCastExprToType(E: RHS.get(), Type: ResultTy, CK: RHSCastKind);
8535 return ResultTy;
8536}
8537
8538/// Return the resulting type when the operands are both block pointers.
8539static QualType checkConditionalBlockPointerCompatibility(Sema &S,
8540 ExprResult &LHS,
8541 ExprResult &RHS,
8542 SourceLocation Loc) {
8543 QualType LHSTy = LHS.get()->getType();
8544 QualType RHSTy = RHS.get()->getType();
8545
8546 if (!LHSTy->isBlockPointerType() || !RHSTy->isBlockPointerType()) {
8547 if (LHSTy->isVoidPointerType() || RHSTy->isVoidPointerType()) {
8548 QualType destType = S.Context.getPointerType(T: S.Context.VoidTy);
8549 LHS = S.ImpCastExprToType(E: LHS.get(), Type: destType, CK: CK_BitCast);
8550 RHS = S.ImpCastExprToType(E: RHS.get(), Type: destType, CK: CK_BitCast);
8551 return destType;
8552 }
8553 S.Diag(Loc, DiagID: diag::err_typecheck_cond_incompatible_operands)
8554 << LHSTy << RHSTy << LHS.get()->getSourceRange()
8555 << RHS.get()->getSourceRange();
8556 return QualType();
8557 }
8558
8559 // We have 2 block pointer types.
8560 return checkConditionalPointerCompatibility(S, LHS, RHS, Loc);
8561}
8562
8563/// Return the resulting type when the operands are both pointers.
8564static QualType
8565checkConditionalObjectPointersCompatibility(Sema &S, ExprResult &LHS,
8566 ExprResult &RHS,
8567 SourceLocation Loc) {
8568 // get the pointer types
8569 QualType LHSTy = LHS.get()->getType();
8570 QualType RHSTy = RHS.get()->getType();
8571
8572 // get the "pointed to" types
8573 QualType lhptee = LHSTy->castAs<PointerType>()->getPointeeType();
8574 QualType rhptee = RHSTy->castAs<PointerType>()->getPointeeType();
8575
8576 // ignore qualifiers on void (C99 6.5.15p3, clause 6)
8577 if (lhptee->isVoidType() && rhptee->isIncompleteOrObjectType()) {
8578 // Figure out necessary qualifiers (C99 6.5.15p6)
8579 QualType destPointee
8580 = S.Context.getQualifiedType(T: lhptee, Qs: rhptee.getQualifiers());
8581 QualType destType = S.Context.getPointerType(T: destPointee);
8582 // Add qualifiers if necessary.
8583 LHS = S.ImpCastExprToType(E: LHS.get(), Type: destType, CK: CK_NoOp);
8584 // Promote to void*.
8585 RHS = S.ImpCastExprToType(E: RHS.get(), Type: destType, CK: CK_BitCast);
8586 return destType;
8587 }
8588 if (rhptee->isVoidType() && lhptee->isIncompleteOrObjectType()) {
8589 QualType destPointee
8590 = S.Context.getQualifiedType(T: rhptee, Qs: lhptee.getQualifiers());
8591 QualType destType = S.Context.getPointerType(T: destPointee);
8592 // Add qualifiers if necessary.
8593 RHS = S.ImpCastExprToType(E: RHS.get(), Type: destType, CK: CK_NoOp);
8594 // Promote to void*.
8595 LHS = S.ImpCastExprToType(E: LHS.get(), Type: destType, CK: CK_BitCast);
8596 return destType;
8597 }
8598
8599 return checkConditionalPointerCompatibility(S, LHS, RHS, Loc);
8600}
8601
8602/// Return false if the first expression is not an integer and the second
8603/// expression is not a pointer, true otherwise.
8604static bool checkPointerIntegerMismatch(Sema &S, ExprResult &Int,
8605 Expr* PointerExpr, SourceLocation Loc,
8606 bool IsIntFirstExpr) {
8607 if (!PointerExpr->getType()->isPointerType() ||
8608 !Int.get()->getType()->isIntegerType())
8609 return false;
8610
8611 Expr *Expr1 = IsIntFirstExpr ? Int.get() : PointerExpr;
8612 Expr *Expr2 = IsIntFirstExpr ? PointerExpr : Int.get();
8613
8614 S.Diag(Loc, DiagID: diag::ext_typecheck_cond_pointer_integer_mismatch)
8615 << Expr1->getType() << Expr2->getType()
8616 << Expr1->getSourceRange() << Expr2->getSourceRange();
8617 Int = S.ImpCastExprToType(E: Int.get(), Type: PointerExpr->getType(),
8618 CK: CK_IntegralToPointer);
8619 return true;
8620}
8621
8622/// Simple conversion between integer and floating point types.
8623///
8624/// Used when handling the OpenCL conditional operator where the
8625/// condition is a vector while the other operands are scalar.
8626///
8627/// OpenCL v1.1 s6.3.i and s6.11.6 together require that the scalar
8628/// types are either integer or floating type. Between the two
8629/// operands, the type with the higher rank is defined as the "result
8630/// type". The other operand needs to be promoted to the same type. No
8631/// other type promotion is allowed. We cannot use
8632/// UsualArithmeticConversions() for this purpose, since it always
8633/// promotes promotable types.
8634static QualType OpenCLArithmeticConversions(Sema &S, ExprResult &LHS,
8635 ExprResult &RHS,
8636 SourceLocation QuestionLoc) {
8637 LHS = S.DefaultFunctionArrayLvalueConversion(E: LHS.get());
8638 if (LHS.isInvalid())
8639 return QualType();
8640 RHS = S.DefaultFunctionArrayLvalueConversion(E: RHS.get());
8641 if (RHS.isInvalid())
8642 return QualType();
8643
8644 // For conversion purposes, we ignore any qualifiers.
8645 // For example, "const float" and "float" are equivalent.
8646 QualType LHSType =
8647 S.Context.getCanonicalType(T: LHS.get()->getType()).getUnqualifiedType();
8648 QualType RHSType =
8649 S.Context.getCanonicalType(T: RHS.get()->getType()).getUnqualifiedType();
8650
8651 if (!LHSType->isIntegerType() && !LHSType->isRealFloatingType()) {
8652 S.Diag(Loc: QuestionLoc, DiagID: diag::err_typecheck_cond_expect_int_float)
8653 << LHSType << LHS.get()->getSourceRange();
8654 return QualType();
8655 }
8656
8657 if (!RHSType->isIntegerType() && !RHSType->isRealFloatingType()) {
8658 S.Diag(Loc: QuestionLoc, DiagID: diag::err_typecheck_cond_expect_int_float)
8659 << RHSType << RHS.get()->getSourceRange();
8660 return QualType();
8661 }
8662
8663 // If both types are identical, no conversion is needed.
8664 if (LHSType == RHSType)
8665 return LHSType;
8666
8667 // Now handle "real" floating types (i.e. float, double, long double).
8668 if (LHSType->isRealFloatingType() || RHSType->isRealFloatingType())
8669 return handleFloatConversion(S, LHS, RHS, LHSType, RHSType,
8670 /*IsCompAssign = */ false);
8671
8672 // Finally, we have two differing integer types.
8673 return handleIntegerConversion<doIntegralCast, doIntegralCast>
8674 (S, LHS, RHS, LHSType, RHSType, /*IsCompAssign = */ false);
8675}
8676
8677/// Convert scalar operands to a vector that matches the
8678/// condition in length.
8679///
8680/// Used when handling the OpenCL conditional operator where the
8681/// condition is a vector while the other operands are scalar.
8682///
8683/// We first compute the "result type" for the scalar operands
8684/// according to OpenCL v1.1 s6.3.i. Both operands are then converted
8685/// into a vector of that type where the length matches the condition
8686/// vector type. s6.11.6 requires that the element types of the result
8687/// and the condition must have the same number of bits.
8688static QualType
8689OpenCLConvertScalarsToVectors(Sema &S, ExprResult &LHS, ExprResult &RHS,
8690 QualType CondTy, SourceLocation QuestionLoc) {
8691 QualType ResTy = OpenCLArithmeticConversions(S, LHS, RHS, QuestionLoc);
8692 if (ResTy.isNull()) return QualType();
8693
8694 const VectorType *CV = CondTy->getAs<VectorType>();
8695 assert(CV);
8696
8697 // Determine the vector result type
8698 unsigned NumElements = CV->getNumElements();
8699 QualType VectorTy = S.Context.getExtVectorType(VectorType: ResTy, NumElts: NumElements);
8700
8701 // Ensure that all types have the same number of bits
8702 if (S.Context.getTypeSize(T: CV->getElementType())
8703 != S.Context.getTypeSize(T: ResTy)) {
8704 // Since VectorTy is created internally, it does not pretty print
8705 // with an OpenCL name. Instead, we just print a description.
8706 std::string EleTyName = ResTy.getUnqualifiedType().getAsString();
8707 SmallString<64> Str;
8708 llvm::raw_svector_ostream OS(Str);
8709 OS << "(vector of " << NumElements << " '" << EleTyName << "' values)";
8710 S.Diag(Loc: QuestionLoc, DiagID: diag::err_conditional_vector_element_size)
8711 << CondTy << OS.str();
8712 return QualType();
8713 }
8714
8715 // Convert operands to the vector result type
8716 LHS = S.ImpCastExprToType(E: LHS.get(), Type: VectorTy, CK: CK_VectorSplat);
8717 RHS = S.ImpCastExprToType(E: RHS.get(), Type: VectorTy, CK: CK_VectorSplat);
8718
8719 return VectorTy;
8720}
8721
8722/// Return false if this is a valid OpenCL condition vector
8723static bool checkOpenCLConditionVector(Sema &S, Expr *Cond,
8724 SourceLocation QuestionLoc) {
8725 // OpenCL v1.1 s6.11.6 says the elements of the vector must be of
8726 // integral type.
8727 const VectorType *CondTy = Cond->getType()->getAs<VectorType>();
8728 assert(CondTy);
8729 QualType EleTy = CondTy->getElementType();
8730 if (EleTy->isIntegerType()) return false;
8731
8732 S.Diag(Loc: QuestionLoc, DiagID: diag::err_typecheck_cond_expect_nonfloat)
8733 << Cond->getType() << Cond->getSourceRange();
8734 return true;
8735}
8736
8737/// Return false if the vector condition type and the vector
8738/// result type are compatible.
8739///
8740/// OpenCL v1.1 s6.11.6 requires that both vector types have the same
8741/// number of elements, and their element types have the same number
8742/// of bits.
8743static bool checkVectorResult(Sema &S, QualType CondTy, QualType VecResTy,
8744 SourceLocation QuestionLoc) {
8745 const VectorType *CV = CondTy->getAs<VectorType>();
8746 const VectorType *RV = VecResTy->getAs<VectorType>();
8747 assert(CV && RV);
8748
8749 if (CV->getNumElements() != RV->getNumElements()) {
8750 S.Diag(Loc: QuestionLoc, DiagID: diag::err_conditional_vector_size)
8751 << CondTy << VecResTy;
8752 return true;
8753 }
8754
8755 QualType CVE = CV->getElementType();
8756 QualType RVE = RV->getElementType();
8757
8758 // Boolean vectors are permitted outside of OpenCL mode.
8759 if (S.Context.getTypeSize(T: CVE) != S.Context.getTypeSize(T: RVE) &&
8760 (!CVE->isBooleanType() || S.LangOpts.OpenCL)) {
8761 S.Diag(Loc: QuestionLoc, DiagID: diag::err_conditional_vector_element_size)
8762 << CondTy << VecResTy;
8763 return true;
8764 }
8765
8766 return false;
8767}
8768
8769/// Return the resulting type for the conditional operator in
8770/// OpenCL (aka "ternary selection operator", OpenCL v1.1
8771/// s6.3.i) when the condition is a vector type.
8772static QualType
8773OpenCLCheckVectorConditional(Sema &S, ExprResult &Cond,
8774 ExprResult &LHS, ExprResult &RHS,
8775 SourceLocation QuestionLoc) {
8776 Cond = S.DefaultFunctionArrayLvalueConversion(E: Cond.get());
8777 if (Cond.isInvalid())
8778 return QualType();
8779 QualType CondTy = Cond.get()->getType();
8780
8781 if (checkOpenCLConditionVector(S, Cond: Cond.get(), QuestionLoc))
8782 return QualType();
8783
8784 // If either operand is a vector then find the vector type of the
8785 // result as specified in OpenCL v1.1 s6.3.i.
8786 if (LHS.get()->getType()->isVectorType() ||
8787 RHS.get()->getType()->isVectorType()) {
8788 bool IsBoolVecLang =
8789 !S.getLangOpts().OpenCL && !S.getLangOpts().OpenCLCPlusPlus;
8790 QualType VecResTy =
8791 S.CheckVectorOperands(LHS, RHS, Loc: QuestionLoc,
8792 /*isCompAssign*/ IsCompAssign: false,
8793 /*AllowBothBool*/ true,
8794 /*AllowBoolConversions*/ AllowBoolConversion: false,
8795 /*AllowBooleanOperation*/ AllowBoolOperation: IsBoolVecLang,
8796 /*ReportInvalid*/ true);
8797 if (VecResTy.isNull())
8798 return QualType();
8799 // The result type must match the condition type as specified in
8800 // OpenCL v1.1 s6.11.6.
8801 if (checkVectorResult(S, CondTy, VecResTy, QuestionLoc))
8802 return QualType();
8803 return VecResTy;
8804 }
8805
8806 // Both operands are scalar.
8807 return OpenCLConvertScalarsToVectors(S, LHS, RHS, CondTy, QuestionLoc);
8808}
8809
8810/// Return true if the Expr is block type
8811static bool checkBlockType(Sema &S, const Expr *E) {
8812 if (E->getType()->isBlockPointerType()) {
8813 S.Diag(Loc: E->getExprLoc(), DiagID: diag::err_opencl_ternary_with_block);
8814 return true;
8815 }
8816
8817 if (const CallExpr *CE = dyn_cast<CallExpr>(Val: E)) {
8818 QualType Ty = CE->getCallee()->getType();
8819 if (Ty->isBlockPointerType()) {
8820 S.Diag(Loc: E->getExprLoc(), DiagID: diag::err_opencl_ternary_with_block);
8821 return true;
8822 }
8823 }
8824 return false;
8825}
8826
8827/// Note that LHS is not null here, even if this is the gnu "x ?: y" extension.
8828/// In that case, LHS = cond.
8829/// C99 6.5.15
8830QualType Sema::CheckConditionalOperands(ExprResult &Cond, ExprResult &LHS,
8831 ExprResult &RHS, ExprValueKind &VK,
8832 ExprObjectKind &OK,
8833 SourceLocation QuestionLoc) {
8834
8835 ExprResult LHSResult = CheckPlaceholderExpr(E: LHS.get());
8836 if (!LHSResult.isUsable()) return QualType();
8837 LHS = LHSResult;
8838
8839 ExprResult RHSResult = CheckPlaceholderExpr(E: RHS.get());
8840 if (!RHSResult.isUsable()) return QualType();
8841 RHS = RHSResult;
8842
8843 // C++ is sufficiently different to merit its own checker.
8844 if (getLangOpts().CPlusPlus)
8845 return CXXCheckConditionalOperands(cond&: Cond, lhs&: LHS, rhs&: RHS, VK, OK, questionLoc: QuestionLoc);
8846
8847 VK = VK_PRValue;
8848 OK = OK_Ordinary;
8849
8850 if (Context.isDependenceAllowed() &&
8851 (Cond.get()->isTypeDependent() || LHS.get()->isTypeDependent() ||
8852 RHS.get()->isTypeDependent())) {
8853 assert(!getLangOpts().CPlusPlus);
8854 assert((Cond.get()->containsErrors() || LHS.get()->containsErrors() ||
8855 RHS.get()->containsErrors()) &&
8856 "should only occur in error-recovery path.");
8857 return Context.DependentTy;
8858 }
8859
8860 // The OpenCL operator with a vector condition is sufficiently
8861 // different to merit its own checker.
8862 if ((getLangOpts().OpenCL && Cond.get()->getType()->isVectorType()) ||
8863 Cond.get()->getType()->isExtVectorType())
8864 return OpenCLCheckVectorConditional(S&: *this, Cond, LHS, RHS, QuestionLoc);
8865
8866 // First, check the condition.
8867 Cond = UsualUnaryConversions(E: Cond.get());
8868 if (Cond.isInvalid())
8869 return QualType();
8870 if (checkCondition(S&: *this, Cond: Cond.get(), QuestionLoc))
8871 return QualType();
8872
8873 // Handle vectors.
8874 if (LHS.get()->getType()->isVectorType() ||
8875 RHS.get()->getType()->isVectorType())
8876 return CheckVectorOperands(LHS, RHS, Loc: QuestionLoc, /*isCompAssign*/ IsCompAssign: false,
8877 /*AllowBothBool*/ true,
8878 /*AllowBoolConversions*/ AllowBoolConversion: false,
8879 /*AllowBooleanOperation*/ AllowBoolOperation: false,
8880 /*ReportInvalid*/ true);
8881
8882 QualType ResTy = UsualArithmeticConversions(LHS, RHS, Loc: QuestionLoc,
8883 ACK: ArithConvKind::Conditional);
8884 if (LHS.isInvalid() || RHS.isInvalid())
8885 return QualType();
8886
8887 // WebAssembly tables are not allowed as conditional LHS or RHS.
8888 QualType LHSTy = LHS.get()->getType();
8889 QualType RHSTy = RHS.get()->getType();
8890 if (LHSTy->isWebAssemblyTableType() || RHSTy->isWebAssemblyTableType()) {
8891 Diag(Loc: QuestionLoc, DiagID: diag::err_wasm_table_conditional_expression)
8892 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
8893 return QualType();
8894 }
8895
8896 // Diagnose attempts to convert between __ibm128, __float128 and long double
8897 // where such conversions currently can't be handled.
8898 if (unsupportedTypeConversion(S: *this, LHSType: LHSTy, RHSType: RHSTy)) {
8899 Diag(Loc: QuestionLoc,
8900 DiagID: diag::err_typecheck_cond_incompatible_operands) << LHSTy << RHSTy
8901 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
8902 return QualType();
8903 }
8904
8905 // OpenCL v2.0 s6.12.5 - Blocks cannot be used as expressions of the ternary
8906 // selection operator (?:).
8907 if (getLangOpts().OpenCL &&
8908 ((int)checkBlockType(S&: *this, E: LHS.get()) | (int)checkBlockType(S&: *this, E: RHS.get()))) {
8909 return QualType();
8910 }
8911
8912 // If both operands have arithmetic type, do the usual arithmetic conversions
8913 // to find a common type: C99 6.5.15p3,5.
8914 if (LHSTy->isArithmeticType() && RHSTy->isArithmeticType()) {
8915 // Disallow invalid arithmetic conversions, such as those between bit-
8916 // precise integers types of different sizes, or between a bit-precise
8917 // integer and another type.
8918 if (ResTy.isNull() && (LHSTy->isBitIntType() || RHSTy->isBitIntType())) {
8919 Diag(Loc: QuestionLoc, DiagID: diag::err_typecheck_cond_incompatible_operands)
8920 << LHSTy << RHSTy << LHS.get()->getSourceRange()
8921 << RHS.get()->getSourceRange();
8922 return QualType();
8923 }
8924
8925 LHS = ImpCastExprToType(E: LHS.get(), Type: ResTy, CK: PrepareScalarCast(Src&: LHS, DestTy: ResTy));
8926 RHS = ImpCastExprToType(E: RHS.get(), Type: ResTy, CK: PrepareScalarCast(Src&: RHS, DestTy: ResTy));
8927
8928 return ResTy;
8929 }
8930
8931 // If both operands are the same structure or union type, the result is that
8932 // type.
8933 // FIXME: Type of conditional expression must be complete in C mode.
8934 if (LHSTy->isRecordType() &&
8935 Context.hasSameUnqualifiedType(T1: LHSTy, T2: RHSTy)) // C99 6.5.15p3
8936 return Context.getCommonSugaredType(X: LHSTy.getUnqualifiedType(),
8937 Y: RHSTy.getUnqualifiedType());
8938
8939 // C99 6.5.15p5: "If both operands have void type, the result has void type."
8940 // The following || allows only one side to be void (a GCC-ism).
8941 if (LHSTy->isVoidType() || RHSTy->isVoidType()) {
8942 if (LHSTy->isVoidType() && RHSTy->isVoidType()) {
8943 // UsualArithmeticConversions already handled the case where both sides
8944 // are the same type.
8945 } else if (RHSTy->isVoidType()) {
8946 ResTy = RHSTy;
8947 Diag(Loc: RHS.get()->getBeginLoc(), DiagID: diag::ext_typecheck_cond_one_void)
8948 << RHS.get()->getSourceRange();
8949 } else {
8950 ResTy = LHSTy;
8951 Diag(Loc: LHS.get()->getBeginLoc(), DiagID: diag::ext_typecheck_cond_one_void)
8952 << LHS.get()->getSourceRange();
8953 }
8954 LHS = ImpCastExprToType(E: LHS.get(), Type: ResTy, CK: CK_ToVoid);
8955 RHS = ImpCastExprToType(E: RHS.get(), Type: ResTy, CK: CK_ToVoid);
8956 return ResTy;
8957 }
8958
8959 // C23 6.5.15p7:
8960 // ... if both the second and third operands have nullptr_t type, the
8961 // result also has that type.
8962 if (LHSTy->isNullPtrType() && Context.hasSameType(T1: LHSTy, T2: RHSTy))
8963 return ResTy;
8964
8965 // C99 6.5.15p6 - "if one operand is a null pointer constant, the result has
8966 // the type of the other operand."
8967 if (!checkConditionalNullPointer(S&: *this, NullExpr&: RHS, PointerTy: LHSTy)) return LHSTy;
8968 if (!checkConditionalNullPointer(S&: *this, NullExpr&: LHS, PointerTy: RHSTy)) return RHSTy;
8969
8970 // All objective-c pointer type analysis is done here.
8971 QualType compositeType =
8972 ObjC().FindCompositeObjCPointerType(LHS, RHS, QuestionLoc);
8973 if (LHS.isInvalid() || RHS.isInvalid())
8974 return QualType();
8975 if (!compositeType.isNull())
8976 return compositeType;
8977
8978
8979 // Handle block pointer types.
8980 if (LHSTy->isBlockPointerType() || RHSTy->isBlockPointerType())
8981 return checkConditionalBlockPointerCompatibility(S&: *this, LHS, RHS,
8982 Loc: QuestionLoc);
8983
8984 // Check constraints for C object pointers types (C99 6.5.15p3,6).
8985 if (LHSTy->isPointerType() && RHSTy->isPointerType())
8986 return checkConditionalObjectPointersCompatibility(S&: *this, LHS, RHS,
8987 Loc: QuestionLoc);
8988
8989 // GCC compatibility: soften pointer/integer mismatch. Note that
8990 // null pointers have been filtered out by this point.
8991 if (checkPointerIntegerMismatch(S&: *this, Int&: LHS, PointerExpr: RHS.get(), Loc: QuestionLoc,
8992 /*IsIntFirstExpr=*/true))
8993 return RHSTy;
8994 if (checkPointerIntegerMismatch(S&: *this, Int&: RHS, PointerExpr: LHS.get(), Loc: QuestionLoc,
8995 /*IsIntFirstExpr=*/false))
8996 return LHSTy;
8997
8998 // Emit a better diagnostic if one of the expressions is a null pointer
8999 // constant and the other is not a pointer type. In this case, the user most
9000 // likely forgot to take the address of the other expression.
9001 if (DiagnoseConditionalForNull(LHSExpr: LHS.get(), RHSExpr: RHS.get(), QuestionLoc))
9002 return QualType();
9003
9004 // Finally, if the LHS and RHS types are canonically the same type, we can
9005 // use the common sugared type.
9006 if (Context.hasSameType(T1: LHSTy, T2: RHSTy))
9007 return Context.getCommonSugaredType(X: LHSTy, Y: RHSTy);
9008
9009 // Otherwise, the operands are not compatible.
9010 Diag(Loc: QuestionLoc, DiagID: diag::err_typecheck_cond_incompatible_operands)
9011 << LHSTy << RHSTy << LHS.get()->getSourceRange()
9012 << RHS.get()->getSourceRange();
9013 return QualType();
9014}
9015
9016/// SuggestParentheses - Emit a note with a fixit hint that wraps
9017/// ParenRange in parentheses.
9018static void SuggestParentheses(Sema &Self, SourceLocation Loc,
9019 const PartialDiagnostic &Note,
9020 SourceRange ParenRange) {
9021 SourceLocation EndLoc = Self.getLocForEndOfToken(Loc: ParenRange.getEnd());
9022 if (ParenRange.getBegin().isFileID() && ParenRange.getEnd().isFileID() &&
9023 EndLoc.isValid()) {
9024 Self.Diag(Loc, PD: Note)
9025 << FixItHint::CreateInsertion(InsertionLoc: ParenRange.getBegin(), Code: "(")
9026 << FixItHint::CreateInsertion(InsertionLoc: EndLoc, Code: ")");
9027 } else {
9028 // We can't display the parentheses, so just show the bare note.
9029 Self.Diag(Loc, PD: Note) << ParenRange;
9030 }
9031}
9032
9033static bool IsArithmeticOp(BinaryOperatorKind Opc) {
9034 return BinaryOperator::isAdditiveOp(Opc) ||
9035 BinaryOperator::isMultiplicativeOp(Opc) ||
9036 BinaryOperator::isShiftOp(Opc) || Opc == BO_And || Opc == BO_Or;
9037 // This only checks for bitwise-or and bitwise-and, but not bitwise-xor and
9038 // not any of the logical operators. Bitwise-xor is commonly used as a
9039 // logical-xor because there is no logical-xor operator. The logical
9040 // operators, including uses of xor, have a high false positive rate for
9041 // precedence warnings.
9042}
9043
9044/// IsArithmeticBinaryExpr - Returns true if E is an arithmetic binary
9045/// expression, either using a built-in or overloaded operator,
9046/// and sets *OpCode to the opcode and *RHSExprs to the right-hand side
9047/// expression.
9048static bool IsArithmeticBinaryExpr(const Expr *E, BinaryOperatorKind *Opcode,
9049 const Expr **RHSExprs) {
9050 // Don't strip parenthesis: we should not warn if E is in parenthesis.
9051 E = E->IgnoreImpCasts();
9052 E = E->IgnoreConversionOperatorSingleStep();
9053 E = E->IgnoreImpCasts();
9054 if (const auto *MTE = dyn_cast<MaterializeTemporaryExpr>(Val: E)) {
9055 E = MTE->getSubExpr();
9056 E = E->IgnoreImpCasts();
9057 }
9058
9059 // Built-in binary operator.
9060 if (const auto *OP = dyn_cast<BinaryOperator>(Val: E);
9061 OP && IsArithmeticOp(Opc: OP->getOpcode())) {
9062 *Opcode = OP->getOpcode();
9063 *RHSExprs = OP->getRHS();
9064 return true;
9065 }
9066
9067 // Overloaded operator.
9068 if (const auto *Call = dyn_cast<CXXOperatorCallExpr>(Val: E)) {
9069 if (Call->getNumArgs() != 2)
9070 return false;
9071
9072 // Make sure this is really a binary operator that is safe to pass into
9073 // BinaryOperator::getOverloadedOpcode(), e.g. it's not a subscript op.
9074 OverloadedOperatorKind OO = Call->getOperator();
9075 if (OO < OO_Plus || OO > OO_Arrow ||
9076 OO == OO_PlusPlus || OO == OO_MinusMinus)
9077 return false;
9078
9079 BinaryOperatorKind OpKind = BinaryOperator::getOverloadedOpcode(OO);
9080 if (IsArithmeticOp(Opc: OpKind)) {
9081 *Opcode = OpKind;
9082 *RHSExprs = Call->getArg(Arg: 1);
9083 return true;
9084 }
9085 }
9086
9087 return false;
9088}
9089
9090/// ExprLooksBoolean - Returns true if E looks boolean, i.e. it has boolean type
9091/// or is a logical expression such as (x==y) which has int type, but is
9092/// commonly interpreted as boolean.
9093static bool ExprLooksBoolean(const Expr *E) {
9094 E = E->IgnoreParenImpCasts();
9095
9096 if (E->getType()->isBooleanType())
9097 return true;
9098 if (const auto *OP = dyn_cast<BinaryOperator>(Val: E))
9099 return OP->isComparisonOp() || OP->isLogicalOp();
9100 if (const auto *OP = dyn_cast<UnaryOperator>(Val: E))
9101 return OP->getOpcode() == UO_LNot;
9102 if (E->getType()->isPointerType())
9103 return true;
9104 // FIXME: What about overloaded operator calls returning "unspecified boolean
9105 // type"s (commonly pointer-to-members)?
9106
9107 return false;
9108}
9109
9110/// DiagnoseConditionalPrecedence - Emit a warning when a conditional operator
9111/// and binary operator are mixed in a way that suggests the programmer assumed
9112/// the conditional operator has higher precedence, for example:
9113/// "int x = a + someBinaryCondition ? 1 : 2".
9114static void DiagnoseConditionalPrecedence(Sema &Self, SourceLocation OpLoc,
9115 Expr *Condition, const Expr *LHSExpr,
9116 const Expr *RHSExpr) {
9117 BinaryOperatorKind CondOpcode;
9118 const Expr *CondRHS;
9119
9120 if (!IsArithmeticBinaryExpr(E: Condition, Opcode: &CondOpcode, RHSExprs: &CondRHS))
9121 return;
9122 if (!ExprLooksBoolean(E: CondRHS))
9123 return;
9124
9125 // The condition is an arithmetic binary expression, with a right-
9126 // hand side that looks boolean, so warn.
9127
9128 unsigned DiagID = BinaryOperator::isBitwiseOp(Opc: CondOpcode)
9129 ? diag::warn_precedence_bitwise_conditional
9130 : diag::warn_precedence_conditional;
9131
9132 Self.Diag(Loc: OpLoc, DiagID)
9133 << Condition->getSourceRange()
9134 << BinaryOperator::getOpcodeStr(Op: CondOpcode);
9135
9136 SuggestParentheses(
9137 Self, Loc: OpLoc,
9138 Note: Self.PDiag(DiagID: diag::note_precedence_silence)
9139 << BinaryOperator::getOpcodeStr(Op: CondOpcode),
9140 ParenRange: SourceRange(Condition->getBeginLoc(), Condition->getEndLoc()));
9141
9142 SuggestParentheses(Self, Loc: OpLoc,
9143 Note: Self.PDiag(DiagID: diag::note_precedence_conditional_first),
9144 ParenRange: SourceRange(CondRHS->getBeginLoc(), RHSExpr->getEndLoc()));
9145}
9146
9147/// Compute the nullability of a conditional expression.
9148static QualType computeConditionalNullability(QualType ResTy, bool IsBin,
9149 QualType LHSTy, QualType RHSTy,
9150 ASTContext &Ctx) {
9151 if (!ResTy->isAnyPointerType())
9152 return ResTy;
9153
9154 auto GetNullability = [](QualType Ty) {
9155 std::optional<NullabilityKind> Kind = Ty->getNullability();
9156 if (Kind) {
9157 // For our purposes, treat _Nullable_result as _Nullable.
9158 if (*Kind == NullabilityKind::NullableResult)
9159 return NullabilityKind::Nullable;
9160 return *Kind;
9161 }
9162 return NullabilityKind::Unspecified;
9163 };
9164
9165 auto LHSKind = GetNullability(LHSTy), RHSKind = GetNullability(RHSTy);
9166 NullabilityKind MergedKind;
9167
9168 // Compute nullability of a binary conditional expression.
9169 if (IsBin) {
9170 if (LHSKind == NullabilityKind::NonNull)
9171 MergedKind = NullabilityKind::NonNull;
9172 else
9173 MergedKind = RHSKind;
9174 // Compute nullability of a normal conditional expression.
9175 } else {
9176 if (LHSKind == NullabilityKind::Nullable ||
9177 RHSKind == NullabilityKind::Nullable)
9178 MergedKind = NullabilityKind::Nullable;
9179 else if (LHSKind == NullabilityKind::NonNull)
9180 MergedKind = RHSKind;
9181 else if (RHSKind == NullabilityKind::NonNull)
9182 MergedKind = LHSKind;
9183 else
9184 MergedKind = NullabilityKind::Unspecified;
9185 }
9186
9187 // Return if ResTy already has the correct nullability.
9188 if (GetNullability(ResTy) == MergedKind)
9189 return ResTy;
9190
9191 // Strip all nullability from ResTy.
9192 while (ResTy->getNullability())
9193 ResTy = ResTy.getSingleStepDesugaredType(Context: Ctx);
9194
9195 // Create a new AttributedType with the new nullability kind.
9196 return Ctx.getAttributedType(nullability: MergedKind, modifiedType: ResTy, equivalentType: ResTy);
9197}
9198
9199ExprResult Sema::ActOnConditionalOp(SourceLocation QuestionLoc,
9200 SourceLocation ColonLoc,
9201 Expr *CondExpr, Expr *LHSExpr,
9202 Expr *RHSExpr) {
9203 // If this is the gnu "x ?: y" extension, analyze the types as though the LHS
9204 // was the condition.
9205 OpaqueValueExpr *opaqueValue = nullptr;
9206 Expr *commonExpr = nullptr;
9207 if (!LHSExpr) {
9208 commonExpr = CondExpr;
9209 // Lower out placeholder types first. This is important so that we don't
9210 // try to capture a placeholder. This happens in few cases in C++; such
9211 // as Objective-C++'s dictionary subscripting syntax.
9212 if (commonExpr->hasPlaceholderType()) {
9213 ExprResult result = CheckPlaceholderExpr(E: commonExpr);
9214 if (!result.isUsable()) return ExprError();
9215 commonExpr = result.get();
9216 }
9217 // We usually want to apply unary conversions *before* saving, except
9218 // in the special case of a C++ l-value conditional.
9219 if (!(getLangOpts().CPlusPlus
9220 && !commonExpr->isTypeDependent()
9221 && commonExpr->getValueKind() == RHSExpr->getValueKind()
9222 && commonExpr->isGLValue()
9223 && commonExpr->isOrdinaryOrBitFieldObject()
9224 && RHSExpr->isOrdinaryOrBitFieldObject()
9225 && Context.hasSameType(T1: commonExpr->getType(), T2: RHSExpr->getType()))) {
9226 ExprResult commonRes = UsualUnaryConversions(E: commonExpr);
9227 if (commonRes.isInvalid())
9228 return ExprError();
9229 commonExpr = commonRes.get();
9230 }
9231
9232 // If the common expression is a class or array prvalue, materialize it
9233 // so that we can safely refer to it multiple times.
9234 if (commonExpr->isPRValue() && (commonExpr->getType()->isRecordType() ||
9235 commonExpr->getType()->isArrayType())) {
9236 ExprResult MatExpr = TemporaryMaterializationConversion(E: commonExpr);
9237 if (MatExpr.isInvalid())
9238 return ExprError();
9239 commonExpr = MatExpr.get();
9240 }
9241
9242 opaqueValue = new (Context) OpaqueValueExpr(commonExpr->getExprLoc(),
9243 commonExpr->getType(),
9244 commonExpr->getValueKind(),
9245 commonExpr->getObjectKind(),
9246 commonExpr);
9247 LHSExpr = CondExpr = opaqueValue;
9248 }
9249
9250 QualType LHSTy = LHSExpr->getType(), RHSTy = RHSExpr->getType();
9251 ExprValueKind VK = VK_PRValue;
9252 ExprObjectKind OK = OK_Ordinary;
9253 ExprResult Cond = CondExpr, LHS = LHSExpr, RHS = RHSExpr;
9254 QualType result = CheckConditionalOperands(Cond, LHS, RHS,
9255 VK, OK, QuestionLoc);
9256 if (result.isNull() || Cond.isInvalid() || LHS.isInvalid() ||
9257 RHS.isInvalid())
9258 return ExprError();
9259
9260 DiagnoseConditionalPrecedence(Self&: *this, OpLoc: QuestionLoc, Condition: Cond.get(), LHSExpr: LHS.get(),
9261 RHSExpr: RHS.get());
9262
9263 CheckBoolLikeConversion(E: Cond.get(), CC: QuestionLoc);
9264
9265 result = computeConditionalNullability(ResTy: result, IsBin: commonExpr, LHSTy, RHSTy,
9266 Ctx&: Context);
9267
9268 if (!commonExpr)
9269 return new (Context)
9270 ConditionalOperator(Cond.get(), QuestionLoc, LHS.get(), ColonLoc,
9271 RHS.get(), result, VK, OK);
9272
9273 return new (Context) BinaryConditionalOperator(
9274 commonExpr, opaqueValue, Cond.get(), LHS.get(), RHS.get(), QuestionLoc,
9275 ColonLoc, result, VK, OK);
9276}
9277
9278bool Sema::IsInvalidSMECallConversion(QualType FromType, QualType ToType) {
9279 unsigned FromAttributes = 0, ToAttributes = 0;
9280 if (const auto *FromFn =
9281 dyn_cast<FunctionProtoType>(Val: Context.getCanonicalType(T: FromType)))
9282 FromAttributes =
9283 FromFn->getAArch64SMEAttributes() & FunctionType::SME_AttributeMask;
9284 if (const auto *ToFn =
9285 dyn_cast<FunctionProtoType>(Val: Context.getCanonicalType(T: ToType)))
9286 ToAttributes =
9287 ToFn->getAArch64SMEAttributes() & FunctionType::SME_AttributeMask;
9288
9289 return FromAttributes != ToAttributes;
9290}
9291
9292// checkPointerTypesForAssignment - This is a very tricky routine (despite
9293// being closely modeled after the C99 spec:-). The odd characteristic of this
9294// routine is it effectively iqnores the qualifiers on the top level pointee.
9295// This circumvents the usual type rules specified in 6.2.7p1 & 6.7.5.[1-3].
9296// FIXME: add a couple examples in this comment.
9297static AssignConvertType checkPointerTypesForAssignment(Sema &S,
9298 QualType LHSType,
9299 QualType RHSType,
9300 SourceLocation Loc) {
9301 assert(LHSType.isCanonical() && "LHS not canonicalized!");
9302 assert(RHSType.isCanonical() && "RHS not canonicalized!");
9303
9304 // get the "pointed to" type (ignoring qualifiers at the top level)
9305 const Type *lhptee, *rhptee;
9306 Qualifiers lhq, rhq;
9307 std::tie(args&: lhptee, args&: lhq) =
9308 cast<PointerType>(Val&: LHSType)->getPointeeType().split().asPair();
9309 std::tie(args&: rhptee, args&: rhq) =
9310 cast<PointerType>(Val&: RHSType)->getPointeeType().split().asPair();
9311
9312 AssignConvertType ConvTy = AssignConvertType::Compatible;
9313
9314 // C99 6.5.16.1p1: This following citation is common to constraints
9315 // 3 & 4 (below). ...and the type *pointed to* by the left has all the
9316 // qualifiers of the type *pointed to* by the right;
9317
9318 // As a special case, 'non-__weak A *' -> 'non-__weak const *' is okay.
9319 if (lhq.getObjCLifetime() != rhq.getObjCLifetime() &&
9320 lhq.compatiblyIncludesObjCLifetime(other: rhq)) {
9321 // Ignore lifetime for further calculation.
9322 lhq.removeObjCLifetime();
9323 rhq.removeObjCLifetime();
9324 }
9325
9326 if (!lhq.compatiblyIncludes(other: rhq, Ctx: S.getASTContext())) {
9327 // Treat address-space mismatches as fatal.
9328 if (!lhq.isAddressSpaceSupersetOf(other: rhq, Ctx: S.getASTContext()))
9329 return AssignConvertType::IncompatiblePointerDiscardsQualifiers;
9330
9331 // It's okay to add or remove GC or lifetime qualifiers when converting to
9332 // and from void*.
9333 else if (lhq.withoutObjCGCAttr().withoutObjCLifetime().compatiblyIncludes(
9334 other: rhq.withoutObjCGCAttr().withoutObjCLifetime(),
9335 Ctx: S.getASTContext()) &&
9336 (lhptee->isVoidType() || rhptee->isVoidType()))
9337 ; // keep old
9338
9339 // Treat lifetime mismatches as fatal.
9340 else if (lhq.getObjCLifetime() != rhq.getObjCLifetime())
9341 ConvTy = AssignConvertType::IncompatiblePointerDiscardsQualifiers;
9342
9343 // Treat pointer-auth mismatches as fatal.
9344 else if (!lhq.getPointerAuth().isEquivalent(Other: rhq.getPointerAuth()))
9345 ConvTy = AssignConvertType::IncompatiblePointerDiscardsQualifiers;
9346
9347 // For GCC/MS compatibility, other qualifier mismatches are treated
9348 // as still compatible in C.
9349 else
9350 ConvTy = AssignConvertType::CompatiblePointerDiscardsQualifiers;
9351 }
9352
9353 // C99 6.5.16.1p1 (constraint 4): If one operand is a pointer to an object or
9354 // incomplete type and the other is a pointer to a qualified or unqualified
9355 // version of void...
9356 if (lhptee->isVoidType()) {
9357 if (rhptee->isIncompleteOrObjectType())
9358 return ConvTy;
9359
9360 // As an extension, we allow cast to/from void* to function pointer.
9361 assert(rhptee->isFunctionType());
9362 return AssignConvertType::FunctionVoidPointer;
9363 }
9364
9365 if (rhptee->isVoidType()) {
9366 // In C, void * to another pointer type is compatible, but we want to note
9367 // that there will be an implicit conversion happening here.
9368 if (lhptee->isIncompleteOrObjectType())
9369 return ConvTy == AssignConvertType::Compatible &&
9370 !S.getLangOpts().CPlusPlus
9371 ? AssignConvertType::CompatibleVoidPtrToNonVoidPtr
9372 : ConvTy;
9373
9374 // As an extension, we allow cast to/from void* to function pointer.
9375 assert(lhptee->isFunctionType());
9376 return AssignConvertType::FunctionVoidPointer;
9377 }
9378
9379 if (!S.Diags.isIgnored(
9380 DiagID: diag::warn_typecheck_convert_incompatible_function_pointer_strict,
9381 Loc) &&
9382 RHSType->isFunctionPointerType() && LHSType->isFunctionPointerType() &&
9383 !S.TryFunctionConversion(FromType: RHSType, ToType: LHSType, ResultTy&: RHSType))
9384 return AssignConvertType::IncompatibleFunctionPointerStrict;
9385
9386 // C99 6.5.16.1p1 (constraint 3): both operands are pointers to qualified or
9387 // unqualified versions of compatible types, ...
9388 QualType ltrans = QualType(lhptee, 0), rtrans = QualType(rhptee, 0);
9389
9390 if (ltrans->isOverflowBehaviorType() || rtrans->isOverflowBehaviorType()) {
9391 if (!S.Context.hasSameType(T1: ltrans, T2: rtrans)) {
9392 QualType LUnderlying =
9393 ltrans->isOverflowBehaviorType()
9394 ? ltrans->castAs<OverflowBehaviorType>()->getUnderlyingType()
9395 : ltrans;
9396 QualType RUnderlying =
9397 rtrans->isOverflowBehaviorType()
9398 ? rtrans->castAs<OverflowBehaviorType>()->getUnderlyingType()
9399 : rtrans;
9400
9401 if (S.Context.hasSameType(T1: LUnderlying, T2: RUnderlying))
9402 return AssignConvertType::IncompatiblePointerDiscardsOverflowBehavior;
9403
9404 ltrans = LUnderlying;
9405 rtrans = RUnderlying;
9406 }
9407 }
9408
9409 if (!S.Context.typesAreCompatible(T1: ltrans, T2: rtrans)) {
9410 // Check if the pointee types are compatible ignoring the sign.
9411 // We explicitly check for char so that we catch "char" vs
9412 // "unsigned char" on systems where "char" is unsigned.
9413 if (lhptee->isCharType())
9414 ltrans = S.Context.UnsignedCharTy;
9415 else if (lhptee->hasSignedIntegerRepresentation())
9416 ltrans = S.Context.getCorrespondingUnsignedType(T: ltrans);
9417
9418 if (rhptee->isCharType())
9419 rtrans = S.Context.UnsignedCharTy;
9420 else if (rhptee->hasSignedIntegerRepresentation())
9421 rtrans = S.Context.getCorrespondingUnsignedType(T: rtrans);
9422
9423 if (ltrans == rtrans) {
9424 // Types are compatible ignoring the sign. Qualifier incompatibility
9425 // takes priority over sign incompatibility because the sign
9426 // warning can be disabled.
9427 if (!S.IsAssignConvertCompatible(ConvTy))
9428 return ConvTy;
9429
9430 return AssignConvertType::IncompatiblePointerSign;
9431 }
9432
9433 // If we are a multi-level pointer, it's possible that our issue is simply
9434 // one of qualification - e.g. char ** -> const char ** is not allowed. If
9435 // the eventual target type is the same and the pointers have the same
9436 // level of indirection, this must be the issue.
9437 if (isa<PointerType>(Val: lhptee) && isa<PointerType>(Val: rhptee)) {
9438 do {
9439 std::tie(args&: lhptee, args&: lhq) =
9440 cast<PointerType>(Val: lhptee)->getPointeeType().split().asPair();
9441 std::tie(args&: rhptee, args&: rhq) =
9442 cast<PointerType>(Val: rhptee)->getPointeeType().split().asPair();
9443
9444 // Inconsistent address spaces at this point is invalid, even if the
9445 // address spaces would be compatible.
9446 // FIXME: This doesn't catch address space mismatches for pointers of
9447 // different nesting levels, like:
9448 // __local int *** a;
9449 // int ** b = a;
9450 // It's not clear how to actually determine when such pointers are
9451 // invalidly incompatible.
9452 if (lhq.getAddressSpace() != rhq.getAddressSpace())
9453 return AssignConvertType::
9454 IncompatibleNestedPointerAddressSpaceMismatch;
9455
9456 } while (isa<PointerType>(Val: lhptee) && isa<PointerType>(Val: rhptee));
9457
9458 if (lhptee == rhptee)
9459 return AssignConvertType::IncompatibleNestedPointerQualifiers;
9460 }
9461
9462 // General pointer incompatibility takes priority over qualifiers.
9463 if (RHSType->isFunctionPointerType() && LHSType->isFunctionPointerType())
9464 return AssignConvertType::IncompatibleFunctionPointer;
9465 return AssignConvertType::IncompatiblePointer;
9466 }
9467 // Note: in C++, typesAreCompatible(ltrans, rtrans) will have guaranteed
9468 // hasSameType, so we can skip further checks.
9469 const auto *LFT = ltrans->getAs<FunctionType>();
9470 const auto *RFT = rtrans->getAs<FunctionType>();
9471 if (!S.getLangOpts().CPlusPlus && LFT && RFT) {
9472 // The invocation of IsFunctionConversion below will try to transform rtrans
9473 // to obtain an exact match for ltrans. This should not fail because of
9474 // mismatches in result type and parameter types, they were already checked
9475 // by typesAreCompatible above. So we will recreate rtrans (or where
9476 // appropriate ltrans) using the result type and parameter types from ltrans
9477 // (respectively rtrans), but keeping its ExtInfo/ExtProtoInfo.
9478 const auto *LFPT = dyn_cast<FunctionProtoType>(Val: LFT);
9479 const auto *RFPT = dyn_cast<FunctionProtoType>(Val: RFT);
9480 if (LFPT && RFPT) {
9481 rtrans = S.Context.getFunctionType(ResultTy: LFPT->getReturnType(),
9482 Args: LFPT->getParamTypes(),
9483 EPI: RFPT->getExtProtoInfo());
9484 } else if (LFPT) {
9485 FunctionProtoType::ExtProtoInfo EPI;
9486 EPI.ExtInfo = RFT->getExtInfo();
9487 rtrans = S.Context.getFunctionType(ResultTy: LFPT->getReturnType(),
9488 Args: LFPT->getParamTypes(), EPI);
9489 } else if (RFPT) {
9490 // In this case, we want to retain rtrans as a FunctionProtoType, to keep
9491 // all of its ExtProtoInfo. Transform ltrans instead.
9492 FunctionProtoType::ExtProtoInfo EPI;
9493 EPI.ExtInfo = LFT->getExtInfo();
9494 ltrans = S.Context.getFunctionType(ResultTy: RFPT->getReturnType(),
9495 Args: RFPT->getParamTypes(), EPI);
9496 } else {
9497 rtrans = S.Context.getFunctionNoProtoType(ResultTy: LFT->getReturnType(),
9498 Info: RFT->getExtInfo());
9499 }
9500 if (!S.Context.hasSameUnqualifiedType(T1: rtrans, T2: ltrans) &&
9501 !S.IsFunctionConversion(FromType: rtrans, ToType: ltrans))
9502 return AssignConvertType::IncompatibleFunctionPointer;
9503 }
9504 return ConvTy;
9505}
9506
9507/// checkBlockPointerTypesForAssignment - This routine determines whether two
9508/// block pointer types are compatible or whether a block and normal pointer
9509/// are compatible. It is more restrict than comparing two function pointer
9510// types.
9511static AssignConvertType checkBlockPointerTypesForAssignment(Sema &S,
9512 QualType LHSType,
9513 QualType RHSType) {
9514 assert(LHSType.isCanonical() && "LHS not canonicalized!");
9515 assert(RHSType.isCanonical() && "RHS not canonicalized!");
9516
9517 QualType lhptee, rhptee;
9518
9519 // get the "pointed to" type (ignoring qualifiers at the top level)
9520 lhptee = cast<BlockPointerType>(Val&: LHSType)->getPointeeType();
9521 rhptee = cast<BlockPointerType>(Val&: RHSType)->getPointeeType();
9522
9523 // In C++, the types have to match exactly.
9524 if (S.getLangOpts().CPlusPlus)
9525 return AssignConvertType::IncompatibleBlockPointer;
9526
9527 AssignConvertType ConvTy = AssignConvertType::Compatible;
9528
9529 // For blocks we enforce that qualifiers are identical.
9530 Qualifiers LQuals = lhptee.getLocalQualifiers();
9531 Qualifiers RQuals = rhptee.getLocalQualifiers();
9532 if (S.getLangOpts().OpenCL) {
9533 LQuals.removeAddressSpace();
9534 RQuals.removeAddressSpace();
9535 }
9536 if (LQuals != RQuals)
9537 ConvTy = AssignConvertType::CompatiblePointerDiscardsQualifiers;
9538
9539 // FIXME: OpenCL doesn't define the exact compile time semantics for a block
9540 // assignment.
9541 // The current behavior is similar to C++ lambdas. A block might be
9542 // assigned to a variable iff its return type and parameters are compatible
9543 // (C99 6.2.7) with the corresponding return type and parameters of the LHS of
9544 // an assignment. Presumably it should behave in way that a function pointer
9545 // assignment does in C, so for each parameter and return type:
9546 // * CVR and address space of LHS should be a superset of CVR and address
9547 // space of RHS.
9548 // * unqualified types should be compatible.
9549 if (S.getLangOpts().OpenCL) {
9550 if (!S.Context.typesAreBlockPointerCompatible(
9551 S.Context.getQualifiedType(T: LHSType.getUnqualifiedType(), Qs: LQuals),
9552 S.Context.getQualifiedType(T: RHSType.getUnqualifiedType(), Qs: RQuals)))
9553 return AssignConvertType::IncompatibleBlockPointer;
9554 } else if (!S.Context.typesAreBlockPointerCompatible(LHSType, RHSType))
9555 return AssignConvertType::IncompatibleBlockPointer;
9556
9557 return ConvTy;
9558}
9559
9560/// checkObjCPointerTypesForAssignment - Compares two objective-c pointer types
9561/// for assignment compatibility.
9562static AssignConvertType checkObjCPointerTypesForAssignment(Sema &S,
9563 QualType LHSType,
9564 QualType RHSType) {
9565 assert(LHSType.isCanonical() && "LHS was not canonicalized!");
9566 assert(RHSType.isCanonical() && "RHS was not canonicalized!");
9567
9568 if (LHSType->isObjCBuiltinType()) {
9569 // Class is not compatible with ObjC object pointers.
9570 if (LHSType->isObjCClassType() && !RHSType->isObjCBuiltinType() &&
9571 !RHSType->isObjCQualifiedClassType())
9572 return AssignConvertType::IncompatiblePointer;
9573 return AssignConvertType::Compatible;
9574 }
9575 if (RHSType->isObjCBuiltinType()) {
9576 if (RHSType->isObjCClassType() && !LHSType->isObjCBuiltinType() &&
9577 !LHSType->isObjCQualifiedClassType())
9578 return AssignConvertType::IncompatiblePointer;
9579 return AssignConvertType::Compatible;
9580 }
9581 QualType lhptee = LHSType->castAs<ObjCObjectPointerType>()->getPointeeType();
9582 QualType rhptee = RHSType->castAs<ObjCObjectPointerType>()->getPointeeType();
9583
9584 if (!lhptee.isAtLeastAsQualifiedAs(other: rhptee, Ctx: S.getASTContext()) &&
9585 // make an exception for id<P>
9586 !LHSType->isObjCQualifiedIdType())
9587 return AssignConvertType::CompatiblePointerDiscardsQualifiers;
9588
9589 if (S.Context.typesAreCompatible(T1: LHSType, T2: RHSType))
9590 return AssignConvertType::Compatible;
9591 if (LHSType->isObjCQualifiedIdType() || RHSType->isObjCQualifiedIdType())
9592 return AssignConvertType::IncompatibleObjCQualifiedId;
9593 return AssignConvertType::IncompatiblePointer;
9594}
9595
9596AssignConvertType Sema::CheckAssignmentConstraints(SourceLocation Loc,
9597 QualType LHSType,
9598 QualType RHSType) {
9599 // Fake up an opaque expression. We don't actually care about what
9600 // cast operations are required, so if CheckAssignmentConstraints
9601 // adds casts to this they'll be wasted, but fortunately that doesn't
9602 // usually happen on valid code.
9603 OpaqueValueExpr RHSExpr(Loc, RHSType, VK_PRValue);
9604 ExprResult RHSPtr = &RHSExpr;
9605 CastKind K;
9606
9607 return CheckAssignmentConstraints(LHSType, RHS&: RHSPtr, Kind&: K, /*ConvertRHS=*/false);
9608}
9609
9610/// This helper function returns true if QT is a vector type that has element
9611/// type ElementType.
9612static bool isVector(QualType QT, QualType ElementType) {
9613 if (const VectorType *VT = QT->getAs<VectorType>())
9614 return VT->getElementType().getCanonicalType() == ElementType;
9615 return false;
9616}
9617
9618/// CheckAssignmentConstraints (C99 6.5.16) - This routine currently
9619/// has code to accommodate several GCC extensions when type checking
9620/// pointers. Here are some objectionable examples that GCC considers warnings:
9621///
9622/// int a, *pint;
9623/// short *pshort;
9624/// struct foo *pfoo;
9625///
9626/// pint = pshort; // warning: assignment from incompatible pointer type
9627/// a = pint; // warning: assignment makes integer from pointer without a cast
9628/// pint = a; // warning: assignment makes pointer from integer without a cast
9629/// pint = pfoo; // warning: assignment from incompatible pointer type
9630///
9631/// As a result, the code for dealing with pointers is more complex than the
9632/// C99 spec dictates.
9633///
9634/// Sets 'Kind' for any result kind except Incompatible.
9635AssignConvertType Sema::CheckAssignmentConstraints(QualType LHSType,
9636 ExprResult &RHS,
9637 CastKind &Kind,
9638 bool ConvertRHS) {
9639 QualType RHSType = RHS.get()->getType();
9640 QualType OrigLHSType = LHSType;
9641
9642 // Get canonical types. We're not formatting these types, just comparing
9643 // them.
9644 LHSType = Context.getCanonicalType(T: LHSType).getUnqualifiedType();
9645 RHSType = Context.getCanonicalType(T: RHSType).getUnqualifiedType();
9646
9647 // Common case: no conversion required.
9648 if (LHSType == RHSType) {
9649 Kind = CK_NoOp;
9650 return AssignConvertType::Compatible;
9651 }
9652
9653 // If the LHS has an __auto_type, there are no additional type constraints
9654 // to be worried about.
9655 if (const auto *AT = dyn_cast<AutoType>(Val&: LHSType)) {
9656 if (AT->isGNUAutoType()) {
9657 Kind = CK_NoOp;
9658 return AssignConvertType::Compatible;
9659 }
9660 }
9661
9662 auto OBTResult = Context.checkOBTAssignmentCompatibility(LHS: LHSType, RHS: RHSType);
9663 switch (OBTResult) {
9664 case ASTContext::OBTAssignResult::IncompatibleKinds:
9665 Kind = CK_NoOp;
9666 return AssignConvertType::IncompatibleOBTKinds;
9667 case ASTContext::OBTAssignResult::Discards:
9668 Kind = LHSType->isBooleanType() ? CK_IntegralToBoolean : CK_IntegralCast;
9669 return AssignConvertType::CompatibleOBTDiscards;
9670 case ASTContext::OBTAssignResult::Compatible:
9671 case ASTContext::OBTAssignResult::NotApplicable:
9672 break;
9673 }
9674
9675 // Check for incompatible OBT types in pointer pointee types
9676 if (LHSType->isPointerType() && RHSType->isPointerType()) {
9677 QualType LHSPointee = LHSType->getPointeeType();
9678 QualType RHSPointee = RHSType->getPointeeType();
9679 if ((LHSPointee->isOverflowBehaviorType() ||
9680 RHSPointee->isOverflowBehaviorType()) &&
9681 !Context.areCompatibleOverflowBehaviorTypes(LHS: LHSPointee, RHS: RHSPointee)) {
9682 Kind = CK_NoOp;
9683 return AssignConvertType::IncompatibleOBTKinds;
9684 }
9685 }
9686
9687 // If we have an atomic type, try a non-atomic assignment, then just add an
9688 // atomic qualification step.
9689 if (const AtomicType *AtomicTy = dyn_cast<AtomicType>(Val&: LHSType)) {
9690 AssignConvertType Result =
9691 CheckAssignmentConstraints(LHSType: AtomicTy->getValueType(), RHS, Kind);
9692 if (!IsAssignConvertCompatible(ConvTy: Result))
9693 return Result;
9694 if (Kind != CK_NoOp && ConvertRHS)
9695 RHS = ImpCastExprToType(E: RHS.get(), Type: AtomicTy->getValueType(), CK: Kind);
9696 Kind = CK_NonAtomicToAtomic;
9697 return Result;
9698 }
9699
9700 // If the left-hand side is a reference type, then we are in a
9701 // (rare!) case where we've allowed the use of references in C,
9702 // e.g., as a parameter type in a built-in function. In this case,
9703 // just make sure that the type referenced is compatible with the
9704 // right-hand side type. The caller is responsible for adjusting
9705 // LHSType so that the resulting expression does not have reference
9706 // type.
9707 if (const ReferenceType *LHSTypeRef = LHSType->getAs<ReferenceType>()) {
9708 if (Context.typesAreCompatible(T1: LHSTypeRef->getPointeeType(), T2: RHSType)) {
9709 Kind = CK_LValueBitCast;
9710 return AssignConvertType::Compatible;
9711 }
9712 return AssignConvertType::Incompatible;
9713 }
9714
9715 // Allow scalar to ExtVector assignments, assignment to bool, and assignments
9716 // of an ExtVector type to the same ExtVector type.
9717 if (auto *LHSExtType = LHSType->getAs<ExtVectorType>()) {
9718 if (auto *RHSExtType = RHSType->getAs<ExtVectorType>()) {
9719 // Implicit conversions require the same number of elements.
9720 if (LHSExtType->getNumElements() != RHSExtType->getNumElements())
9721 return AssignConvertType::Incompatible;
9722
9723 if (LHSType->isExtVectorBoolType() &&
9724 RHSExtType->getElementType()->isIntegerType()) {
9725 Kind = CK_IntegralToBoolean;
9726 return AssignConvertType::Compatible;
9727 }
9728 // In OpenCL, allow compatible vector types (e.g. half to _Float16)
9729 if (Context.getLangOpts().OpenCL &&
9730 Context.areCompatibleVectorTypes(FirstVec: LHSType, SecondVec: RHSType)) {
9731 Kind = CK_BitCast;
9732 return AssignConvertType::Compatible;
9733 }
9734 return AssignConvertType::Incompatible;
9735 }
9736 if (RHSType->isArithmeticType()) {
9737 // CK_VectorSplat does T -> vector T, so first cast to the element type.
9738 if (ConvertRHS)
9739 RHS = prepareVectorSplat(VectorTy: LHSType, SplattedExpr: RHS.get());
9740 Kind = CK_VectorSplat;
9741 return AssignConvertType::Compatible;
9742 }
9743 }
9744
9745 // Conversions to or from vector type.
9746 if (LHSType->isVectorType() || RHSType->isVectorType()) {
9747 if (LHSType->isVectorType() && RHSType->isVectorType()) {
9748 // Allow assignments of an AltiVec vector type to an equivalent GCC
9749 // vector type and vice versa
9750 if (Context.areCompatibleVectorTypes(FirstVec: LHSType, SecondVec: RHSType)) {
9751 Kind = CK_BitCast;
9752 return AssignConvertType::Compatible;
9753 }
9754
9755 // If we are allowing lax vector conversions, and LHS and RHS are both
9756 // vectors, the total size only needs to be the same. This is a bitcast;
9757 // no bits are changed but the result type is different.
9758 if (isLaxVectorConversion(srcTy: RHSType, destTy: LHSType)) {
9759 // The default for lax vector conversions with Altivec vectors will
9760 // change, so if we are converting between vector types where
9761 // at least one is an Altivec vector, emit a warning.
9762 if (Context.getTargetInfo().getTriple().isPPC() &&
9763 anyAltivecTypes(SrcTy: RHSType, DestTy: LHSType) &&
9764 !Context.areCompatibleVectorTypes(FirstVec: RHSType, SecondVec: LHSType))
9765 Diag(Loc: RHS.get()->getExprLoc(), DiagID: diag::warn_deprecated_lax_vec_conv_all)
9766 << RHSType << LHSType;
9767 Kind = CK_BitCast;
9768 return AssignConvertType::IncompatibleVectors;
9769 }
9770 }
9771
9772 // When the RHS comes from another lax conversion (e.g. binops between
9773 // scalars and vectors) the result is canonicalized as a vector. When the
9774 // LHS is also a vector, the lax is allowed by the condition above. Handle
9775 // the case where LHS is a scalar.
9776 if (LHSType->isScalarType()) {
9777 const VectorType *VecType = RHSType->getAs<VectorType>();
9778 if (VecType && VecType->getNumElements() == 1 &&
9779 isLaxVectorConversion(srcTy: RHSType, destTy: LHSType)) {
9780 if (Context.getTargetInfo().getTriple().isPPC() &&
9781 (VecType->getVectorKind() == VectorKind::AltiVecVector ||
9782 VecType->getVectorKind() == VectorKind::AltiVecBool ||
9783 VecType->getVectorKind() == VectorKind::AltiVecPixel))
9784 Diag(Loc: RHS.get()->getExprLoc(), DiagID: diag::warn_deprecated_lax_vec_conv_all)
9785 << RHSType << LHSType;
9786 ExprResult *VecExpr = &RHS;
9787 *VecExpr = ImpCastExprToType(E: VecExpr->get(), Type: LHSType, CK: CK_BitCast);
9788 Kind = CK_BitCast;
9789 return AssignConvertType::Compatible;
9790 }
9791 }
9792
9793 // Allow assignments between fixed-length and sizeless SVE vectors.
9794 if ((LHSType->isSVESizelessBuiltinType() && RHSType->isVectorType()) ||
9795 (LHSType->isVectorType() && RHSType->isSVESizelessBuiltinType()))
9796 if (ARM().areCompatibleSveTypes(FirstType: LHSType, SecondType: RHSType) ||
9797 ARM().areLaxCompatibleSveTypes(FirstType: LHSType, SecondType: RHSType)) {
9798 Kind = CK_BitCast;
9799 return AssignConvertType::Compatible;
9800 }
9801
9802 // Allow assignments between fixed-length and sizeless RVV vectors.
9803 if ((LHSType->isRVVSizelessBuiltinType() && RHSType->isVectorType()) ||
9804 (LHSType->isVectorType() && RHSType->isRVVSizelessBuiltinType())) {
9805 if (Context.areCompatibleRVVTypes(FirstType: LHSType, SecondType: RHSType) ||
9806 Context.areLaxCompatibleRVVTypes(FirstType: LHSType, SecondType: RHSType)) {
9807 Kind = CK_BitCast;
9808 return AssignConvertType::Compatible;
9809 }
9810 }
9811
9812 return AssignConvertType::Incompatible;
9813 }
9814
9815 // Diagnose attempts to convert between __ibm128, __float128 and long double
9816 // where such conversions currently can't be handled.
9817 if (unsupportedTypeConversion(S: *this, LHSType, RHSType))
9818 return AssignConvertType::Incompatible;
9819
9820 // Disallow assigning a _Complex to a real type in C++ mode since it simply
9821 // discards the imaginary part.
9822 if (getLangOpts().CPlusPlus && RHSType->getAs<ComplexType>() &&
9823 !LHSType->getAs<ComplexType>())
9824 return AssignConvertType::Incompatible;
9825
9826 // Arithmetic conversions.
9827 if (LHSType->isArithmeticType() && RHSType->isArithmeticType() &&
9828 !(getLangOpts().CPlusPlus && LHSType->isEnumeralType())) {
9829 if (ConvertRHS)
9830 Kind = PrepareScalarCast(Src&: RHS, DestTy: LHSType);
9831 return AssignConvertType::Compatible;
9832 }
9833
9834 // Conversions to normal pointers.
9835 if (const PointerType *LHSPointer = dyn_cast<PointerType>(Val&: LHSType)) {
9836 // U* -> T*
9837 if (isa<PointerType>(Val: RHSType)) {
9838 LangAS AddrSpaceL = LHSPointer->getPointeeType().getAddressSpace();
9839 LangAS AddrSpaceR = RHSType->getPointeeType().getAddressSpace();
9840 if (AddrSpaceL != AddrSpaceR)
9841 Kind = CK_AddressSpaceConversion;
9842 else if (Context.hasCvrSimilarType(T1: RHSType, T2: LHSType))
9843 Kind = CK_NoOp;
9844 else
9845 Kind = CK_BitCast;
9846 return checkPointerTypesForAssignment(S&: *this, LHSType, RHSType,
9847 Loc: RHS.get()->getBeginLoc());
9848 }
9849
9850 // int -> T*
9851 if (RHSType->isIntegerType()) {
9852 Kind = CK_IntegralToPointer; // FIXME: null?
9853 return AssignConvertType::IntToPointer;
9854 }
9855
9856 // C pointers are not compatible with ObjC object pointers,
9857 // with two exceptions:
9858 if (isa<ObjCObjectPointerType>(Val: RHSType)) {
9859 // - conversions to void*
9860 if (LHSPointer->getPointeeType()->isVoidType()) {
9861 Kind = CK_BitCast;
9862 return AssignConvertType::Compatible;
9863 }
9864
9865 // - conversions from 'Class' to the redefinition type
9866 if (RHSType->isObjCClassType() &&
9867 Context.hasSameType(T1: LHSType,
9868 T2: Context.getObjCClassRedefinitionType())) {
9869 Kind = CK_BitCast;
9870 return AssignConvertType::Compatible;
9871 }
9872
9873 Kind = CK_BitCast;
9874 return AssignConvertType::IncompatiblePointer;
9875 }
9876
9877 // U^ -> void*
9878 if (RHSType->getAs<BlockPointerType>()) {
9879 if (LHSPointer->getPointeeType()->isVoidType()) {
9880 LangAS AddrSpaceL = LHSPointer->getPointeeType().getAddressSpace();
9881 LangAS AddrSpaceR = RHSType->getAs<BlockPointerType>()
9882 ->getPointeeType()
9883 .getAddressSpace();
9884 Kind =
9885 AddrSpaceL != AddrSpaceR ? CK_AddressSpaceConversion : CK_BitCast;
9886 return AssignConvertType::Compatible;
9887 }
9888 }
9889
9890 return AssignConvertType::Incompatible;
9891 }
9892
9893 // Conversions to block pointers.
9894 if (isa<BlockPointerType>(Val: LHSType)) {
9895 // U^ -> T^
9896 if (RHSType->isBlockPointerType()) {
9897 LangAS AddrSpaceL = LHSType->getAs<BlockPointerType>()
9898 ->getPointeeType()
9899 .getAddressSpace();
9900 LangAS AddrSpaceR = RHSType->getAs<BlockPointerType>()
9901 ->getPointeeType()
9902 .getAddressSpace();
9903 Kind = AddrSpaceL != AddrSpaceR ? CK_AddressSpaceConversion : CK_BitCast;
9904 return checkBlockPointerTypesForAssignment(S&: *this, LHSType, RHSType);
9905 }
9906
9907 // int or null -> T^
9908 if (RHSType->isIntegerType()) {
9909 Kind = CK_IntegralToPointer; // FIXME: null
9910 return AssignConvertType::IntToBlockPointer;
9911 }
9912
9913 // id -> T^
9914 if (getLangOpts().ObjC && RHSType->isObjCIdType()) {
9915 Kind = CK_AnyPointerToBlockPointerCast;
9916 return AssignConvertType::Compatible;
9917 }
9918
9919 // void* -> T^
9920 if (const PointerType *RHSPT = RHSType->getAs<PointerType>())
9921 if (RHSPT->getPointeeType()->isVoidType()) {
9922 Kind = CK_AnyPointerToBlockPointerCast;
9923 return AssignConvertType::Compatible;
9924 }
9925
9926 return AssignConvertType::Incompatible;
9927 }
9928
9929 // Conversions to Objective-C pointers.
9930 if (isa<ObjCObjectPointerType>(Val: LHSType)) {
9931 // A* -> B*
9932 if (RHSType->isObjCObjectPointerType()) {
9933 Kind = CK_BitCast;
9934 AssignConvertType result =
9935 checkObjCPointerTypesForAssignment(S&: *this, LHSType, RHSType);
9936 if (getLangOpts().allowsNonTrivialObjCLifetimeQualifiers() &&
9937 result == AssignConvertType::Compatible &&
9938 !ObjC().CheckObjCARCUnavailableWeakConversion(castType: OrigLHSType, ExprType: RHSType))
9939 result = AssignConvertType::IncompatibleObjCWeakRef;
9940 return result;
9941 }
9942
9943 // int or null -> A*
9944 if (RHSType->isIntegerType()) {
9945 Kind = CK_IntegralToPointer; // FIXME: null
9946 return AssignConvertType::IntToPointer;
9947 }
9948
9949 // In general, C pointers are not compatible with ObjC object pointers,
9950 // with two exceptions:
9951 if (isa<PointerType>(Val: RHSType)) {
9952 Kind = CK_CPointerToObjCPointerCast;
9953
9954 // - conversions from 'void*'
9955 if (RHSType->isVoidPointerType()) {
9956 return AssignConvertType::Compatible;
9957 }
9958
9959 // - conversions to 'Class' from its redefinition type
9960 if (LHSType->isObjCClassType() &&
9961 Context.hasSameType(T1: RHSType,
9962 T2: Context.getObjCClassRedefinitionType())) {
9963 return AssignConvertType::Compatible;
9964 }
9965
9966 return AssignConvertType::IncompatiblePointer;
9967 }
9968
9969 // Only under strict condition T^ is compatible with an Objective-C pointer.
9970 if (RHSType->isBlockPointerType() &&
9971 LHSType->isBlockCompatibleObjCPointerType(ctx&: Context)) {
9972 if (ConvertRHS)
9973 maybeExtendBlockObject(E&: RHS);
9974 Kind = CK_BlockPointerToObjCPointerCast;
9975 return AssignConvertType::Compatible;
9976 }
9977
9978 return AssignConvertType::Incompatible;
9979 }
9980
9981 // Conversion to nullptr_t (C23 only)
9982 if (getLangOpts().C23 && LHSType->isNullPtrType() &&
9983 RHS.get()->isNullPointerConstant(Ctx&: Context,
9984 NPC: Expr::NPC_ValueDependentIsNull)) {
9985 // null -> nullptr_t
9986 Kind = CK_NullToPointer;
9987 return AssignConvertType::Compatible;
9988 }
9989
9990 // Conversions from pointers that are not covered by the above.
9991 if (isa<PointerType>(Val: RHSType)) {
9992 // T* -> _Bool
9993 if (LHSType == Context.BoolTy) {
9994 Kind = CK_PointerToBoolean;
9995 return AssignConvertType::Compatible;
9996 }
9997
9998 // T* -> int
9999 if (LHSType->isIntegerType()) {
10000 Kind = CK_PointerToIntegral;
10001 return AssignConvertType::PointerToInt;
10002 }
10003
10004 return AssignConvertType::Incompatible;
10005 }
10006
10007 // Conversions from Objective-C pointers that are not covered by the above.
10008 if (isa<ObjCObjectPointerType>(Val: RHSType)) {
10009 // T* -> _Bool
10010 if (LHSType == Context.BoolTy) {
10011 Kind = CK_PointerToBoolean;
10012 return AssignConvertType::Compatible;
10013 }
10014
10015 // T* -> int
10016 if (LHSType->isIntegerType()) {
10017 Kind = CK_PointerToIntegral;
10018 return AssignConvertType::PointerToInt;
10019 }
10020
10021 return AssignConvertType::Incompatible;
10022 }
10023
10024 // struct A -> struct B
10025 if (isa<TagType>(Val: LHSType) && isa<TagType>(Val: RHSType)) {
10026 if (Context.typesAreCompatible(T1: LHSType, T2: RHSType)) {
10027 Kind = CK_NoOp;
10028 return AssignConvertType::Compatible;
10029 }
10030 }
10031
10032 if (LHSType->isSamplerT() && RHSType->isIntegerType()) {
10033 Kind = CK_IntToOCLSampler;
10034 return AssignConvertType::Compatible;
10035 }
10036
10037 return AssignConvertType::Incompatible;
10038}
10039
10040/// Constructs a transparent union from an expression that is
10041/// used to initialize the transparent union.
10042static void ConstructTransparentUnion(Sema &S, ASTContext &C,
10043 ExprResult &EResult, QualType UnionType,
10044 FieldDecl *Field) {
10045 // Build an initializer list that designates the appropriate member
10046 // of the transparent union.
10047 Expr *E = EResult.get();
10048 InitListExpr *Initializer = new (C) InitListExpr(C, SourceLocation(),
10049 E, SourceLocation());
10050 Initializer->setType(UnionType);
10051 Initializer->setInitializedFieldInUnion(Field);
10052
10053 // Build a compound literal constructing a value of the transparent
10054 // union type from this initializer list.
10055 TypeSourceInfo *unionTInfo = C.getTrivialTypeSourceInfo(T: UnionType);
10056 EResult = new (C) CompoundLiteralExpr(SourceLocation(), unionTInfo, UnionType,
10057 VK_PRValue, Initializer, false);
10058}
10059
10060AssignConvertType
10061Sema::CheckTransparentUnionArgumentConstraints(QualType ArgType,
10062 ExprResult &RHS) {
10063 QualType RHSType = RHS.get()->getType();
10064
10065 // If the ArgType is a Union type, we want to handle a potential
10066 // transparent_union GCC extension.
10067 const RecordType *UT = ArgType->getAsUnionType();
10068 if (!UT)
10069 return AssignConvertType::Incompatible;
10070
10071 RecordDecl *UD = UT->getDecl()->getDefinitionOrSelf();
10072 if (!UD->hasAttr<TransparentUnionAttr>())
10073 return AssignConvertType::Incompatible;
10074
10075 // The field to initialize within the transparent union.
10076 FieldDecl *InitField = nullptr;
10077 // It's compatible if the expression matches any of the fields.
10078 for (auto *it : UD->fields()) {
10079 if (it->getType()->isPointerType()) {
10080 // If the transparent union contains a pointer type, we allow:
10081 // 1) void pointer
10082 // 2) null pointer constant
10083 if (RHSType->isPointerType())
10084 if (RHSType->castAs<PointerType>()->getPointeeType()->isVoidType()) {
10085 RHS = ImpCastExprToType(E: RHS.get(), Type: it->getType(), CK: CK_BitCast);
10086 InitField = it;
10087 break;
10088 }
10089
10090 if (RHS.get()->isNullPointerConstant(Ctx&: Context,
10091 NPC: Expr::NPC_ValueDependentIsNull)) {
10092 RHS = ImpCastExprToType(E: RHS.get(), Type: it->getType(),
10093 CK: CK_NullToPointer);
10094 InitField = it;
10095 break;
10096 }
10097 }
10098
10099 CastKind Kind;
10100 if (CheckAssignmentConstraints(LHSType: it->getType(), RHS, Kind) ==
10101 AssignConvertType::Compatible) {
10102 RHS = ImpCastExprToType(E: RHS.get(), Type: it->getType(), CK: Kind);
10103 InitField = it;
10104 break;
10105 }
10106 }
10107
10108 if (!InitField)
10109 return AssignConvertType::Incompatible;
10110
10111 ConstructTransparentUnion(S&: *this, C&: Context, EResult&: RHS, UnionType: ArgType, Field: InitField);
10112 return AssignConvertType::Compatible;
10113}
10114
10115AssignConvertType Sema::CheckSingleAssignmentConstraints(QualType LHSType,
10116 ExprResult &CallerRHS,
10117 bool Diagnose,
10118 bool DiagnoseCFAudited,
10119 bool ConvertRHS) {
10120 // We need to be able to tell the caller whether we diagnosed a problem, if
10121 // they ask us to issue diagnostics.
10122 assert((ConvertRHS || !Diagnose) && "can't indicate whether we diagnosed");
10123
10124 // If ConvertRHS is false, we want to leave the caller's RHS untouched. Sadly,
10125 // we can't avoid *all* modifications at the moment, so we need some somewhere
10126 // to put the updated value.
10127 ExprResult LocalRHS = CallerRHS;
10128 ExprResult &RHS = ConvertRHS ? CallerRHS : LocalRHS;
10129
10130 if (const auto *LHSPtrType = LHSType->getAs<PointerType>()) {
10131 if (const auto *RHSPtrType = RHS.get()->getType()->getAs<PointerType>()) {
10132 if (RHSPtrType->getPointeeType()->hasAttr(AK: attr::NoDeref) &&
10133 !LHSPtrType->getPointeeType()->hasAttr(AK: attr::NoDeref)) {
10134 Diag(Loc: RHS.get()->getExprLoc(),
10135 DiagID: diag::warn_noderef_to_dereferenceable_pointer)
10136 << RHS.get()->getSourceRange();
10137 }
10138 }
10139 }
10140
10141 if (getLangOpts().CPlusPlus) {
10142 if (!LHSType->isRecordType() && !LHSType->isAtomicType()) {
10143 // C++ 5.17p3: If the left operand is not of class type, the
10144 // expression is implicitly converted (C++ 4) to the
10145 // cv-unqualified type of the left operand.
10146 QualType RHSType = RHS.get()->getType();
10147 if (Diagnose) {
10148 RHS = PerformImplicitConversion(From: RHS.get(), ToType: LHSType.getUnqualifiedType(),
10149 Action: AssignmentAction::Assigning);
10150 } else {
10151 ImplicitConversionSequence ICS =
10152 TryImplicitConversion(From: RHS.get(), ToType: LHSType.getUnqualifiedType(),
10153 /*SuppressUserConversions=*/false,
10154 AllowExplicit: AllowedExplicit::None,
10155 /*InOverloadResolution=*/false,
10156 /*CStyle=*/false,
10157 /*AllowObjCWritebackConversion=*/false);
10158 if (ICS.isFailure())
10159 return AssignConvertType::Incompatible;
10160 RHS = PerformImplicitConversion(From: RHS.get(), ToType: LHSType.getUnqualifiedType(),
10161 ICS, Action: AssignmentAction::Assigning);
10162 }
10163 if (RHS.isInvalid())
10164 return AssignConvertType::Incompatible;
10165 AssignConvertType result = AssignConvertType::Compatible;
10166 if (getLangOpts().allowsNonTrivialObjCLifetimeQualifiers() &&
10167 !ObjC().CheckObjCARCUnavailableWeakConversion(castType: LHSType, ExprType: RHSType))
10168 result = AssignConvertType::IncompatibleObjCWeakRef;
10169
10170 // Check if OBT is being discarded during assignment
10171 // The RHS may have propagated OBT, but if LHS doesn't have it, warn
10172 if (RHSType->isOverflowBehaviorType() &&
10173 !LHSType->isOverflowBehaviorType()) {
10174 result = AssignConvertType::CompatibleOBTDiscards;
10175 }
10176
10177 return result;
10178 }
10179
10180 // FIXME: Currently, we fall through and treat C++ classes like C
10181 // structures.
10182 // FIXME: We also fall through for atomics; not sure what should
10183 // happen there, though.
10184 } else if (RHS.get()->getType() == Context.OverloadTy) {
10185 // As a set of extensions to C, we support overloading on functions. These
10186 // functions need to be resolved here.
10187 DeclAccessPair DAP;
10188 if (FunctionDecl *FD = ResolveAddressOfOverloadedFunction(
10189 AddressOfExpr: RHS.get(), TargetType: LHSType, /*Complain=*/false, Found&: DAP))
10190 RHS = FixOverloadedFunctionReference(E: RHS.get(), FoundDecl: DAP, Fn: FD);
10191 else
10192 return AssignConvertType::Incompatible;
10193 }
10194
10195 // This check seems unnatural, however it is necessary to ensure the proper
10196 // conversion of functions/arrays. If the conversion were done for all
10197 // DeclExpr's (created by ActOnIdExpression), it would mess up the unary
10198 // expressions that suppress this implicit conversion (&, sizeof). This needs
10199 // to happen before we check for null pointer conversions because C does not
10200 // undergo the same implicit conversions as C++ does above (by the calls to
10201 // TryImplicitConversion() and PerformImplicitConversion()) which insert the
10202 // lvalue to rvalue cast before checking for null pointer constraints. This
10203 // addresses code like: nullptr_t val; int *ptr; ptr = val;
10204 //
10205 // Suppress this for references: C++ 8.5.3p5.
10206 if (!LHSType->isReferenceType()) {
10207 // FIXME: We potentially allocate here even if ConvertRHS is false.
10208 RHS = DefaultFunctionArrayLvalueConversion(E: RHS.get(), Diagnose);
10209 if (RHS.isInvalid())
10210 return AssignConvertType::Incompatible;
10211 }
10212
10213 // The constraints are expressed in terms of the atomic, qualified, or
10214 // unqualified type of the LHS.
10215 QualType LHSTypeAfterConversion = LHSType.getAtomicUnqualifiedType();
10216
10217 // C99 6.5.16.1p1: the left operand is a pointer and the right is
10218 // a null pointer constant <C23>or its type is nullptr_t;</C23>.
10219 if ((LHSTypeAfterConversion->isPointerType() ||
10220 LHSTypeAfterConversion->isObjCObjectPointerType() ||
10221 LHSTypeAfterConversion->isBlockPointerType()) &&
10222 ((getLangOpts().C23 && RHS.get()->getType()->isNullPtrType()) ||
10223 RHS.get()->isNullPointerConstant(Ctx&: Context,
10224 NPC: Expr::NPC_ValueDependentIsNull))) {
10225 AssignConvertType Ret = AssignConvertType::Compatible;
10226 if (Diagnose || ConvertRHS) {
10227 CastKind Kind;
10228 CXXCastPath Path;
10229 CheckPointerConversion(From: RHS.get(), ToType: LHSType, Kind, BasePath&: Path,
10230 /*IgnoreBaseAccess=*/false, Diagnose);
10231
10232 // If there is a conversion of some kind, check to see what kind of
10233 // pointer conversion happened so we can diagnose a C++ compatibility
10234 // diagnostic if the conversion is invalid. This only matters if the RHS
10235 // is some kind of void pointer. We have a carve-out when the RHS is from
10236 // a macro expansion because the use of a macro may indicate different
10237 // code between C and C++. Consider: char *s = NULL; where NULL is
10238 // defined as (void *)0 in C (which would be invalid in C++), but 0 in
10239 // C++, which is valid in C++.
10240 if (Kind != CK_NoOp && !getLangOpts().CPlusPlus &&
10241 !RHS.get()->getBeginLoc().isMacroID()) {
10242 QualType CanRHS =
10243 RHS.get()->getType().getCanonicalType().getUnqualifiedType();
10244 QualType CanLHS = LHSType.getCanonicalType().getUnqualifiedType();
10245 if (CanRHS->isVoidPointerType() && CanLHS->isPointerType()) {
10246 Ret = checkPointerTypesForAssignment(S&: *this, LHSType: CanLHS, RHSType: CanRHS,
10247 Loc: RHS.get()->getExprLoc());
10248 // Anything that's not considered perfectly compatible would be
10249 // incompatible in C++.
10250 if (Ret != AssignConvertType::Compatible)
10251 Ret = AssignConvertType::CompatibleVoidPtrToNonVoidPtr;
10252 }
10253 }
10254
10255 if (ConvertRHS)
10256 RHS = ImpCastExprToType(E: RHS.get(), Type: LHSType, CK: Kind, VK: VK_PRValue, BasePath: &Path);
10257 }
10258 return Ret;
10259 }
10260 // C23 6.5.16.1p1: the left operand has type atomic, qualified, or
10261 // unqualified bool, and the right operand is a pointer or its type is
10262 // nullptr_t.
10263 if (getLangOpts().C23 && LHSType->isBooleanType() &&
10264 RHS.get()->getType()->isNullPtrType()) {
10265 // NB: T* -> _Bool is handled in CheckAssignmentConstraints, this only
10266 // only handles nullptr -> _Bool due to needing an extra conversion
10267 // step.
10268 // We model this by converting from nullptr -> void * and then let the
10269 // conversion from void * -> _Bool happen naturally.
10270 if (Diagnose || ConvertRHS) {
10271 CastKind Kind;
10272 CXXCastPath Path;
10273 CheckPointerConversion(From: RHS.get(), ToType: Context.VoidPtrTy, Kind, BasePath&: Path,
10274 /*IgnoreBaseAccess=*/false, Diagnose);
10275 if (ConvertRHS)
10276 RHS = ImpCastExprToType(E: RHS.get(), Type: Context.VoidPtrTy, CK: Kind, VK: VK_PRValue,
10277 BasePath: &Path);
10278 }
10279 }
10280
10281 // OpenCL queue_t type assignment.
10282 if (LHSType->isQueueT() && RHS.get()->isNullPointerConstant(
10283 Ctx&: Context, NPC: Expr::NPC_ValueDependentIsNull)) {
10284 RHS = ImpCastExprToType(E: RHS.get(), Type: LHSType, CK: CK_NullToPointer);
10285 return AssignConvertType::Compatible;
10286 }
10287
10288 CastKind Kind;
10289 AssignConvertType result =
10290 CheckAssignmentConstraints(LHSType, RHS, Kind, ConvertRHS);
10291
10292 // If assigning a void * created by an allocation function call to some other
10293 // type, check that the allocated size is sufficient for that type.
10294 if (result != AssignConvertType::Incompatible &&
10295 RHS.get()->getType()->isVoidPointerType())
10296 CheckSufficientAllocSize(S&: *this, DestType: LHSType, E: RHS.get());
10297
10298 // C99 6.5.16.1p2: The value of the right operand is converted to the
10299 // type of the assignment expression.
10300 // CheckAssignmentConstraints allows the left-hand side to be a reference,
10301 // so that we can use references in built-in functions even in C.
10302 // The getNonReferenceType() call makes sure that the resulting expression
10303 // does not have reference type.
10304 if (result != AssignConvertType::Incompatible &&
10305 RHS.get()->getType() != LHSType) {
10306 QualType Ty = LHSType.getNonLValueExprType(Context);
10307 Expr *E = RHS.get();
10308
10309 // Check for various Objective-C errors. If we are not reporting
10310 // diagnostics and just checking for errors, e.g., during overload
10311 // resolution, return Incompatible to indicate the failure.
10312 if (getLangOpts().allowsNonTrivialObjCLifetimeQualifiers() &&
10313 ObjC().CheckObjCConversion(castRange: SourceRange(), castType: Ty, op&: E,
10314 CCK: CheckedConversionKind::Implicit, Diagnose,
10315 DiagnoseCFAudited) != SemaObjC::ACR_okay) {
10316 if (!Diagnose)
10317 return AssignConvertType::Incompatible;
10318 }
10319 if (getLangOpts().ObjC &&
10320 (ObjC().CheckObjCBridgeRelatedConversions(Loc: E->getBeginLoc(), DestType: LHSType,
10321 SrcType: E->getType(), SrcExpr&: E, Diagnose) ||
10322 ObjC().CheckConversionToObjCLiteral(DstType: LHSType, SrcExpr&: E, Diagnose))) {
10323 if (!Diagnose)
10324 return AssignConvertType::Incompatible;
10325 // Replace the expression with a corrected version and continue so we
10326 // can find further errors.
10327 RHS = E;
10328 return AssignConvertType::Compatible;
10329 }
10330
10331 if (ConvertRHS)
10332 RHS = ImpCastExprToType(E, Type: Ty, CK: Kind);
10333 }
10334
10335 return result;
10336}
10337
10338namespace {
10339/// The original operand to an operator, prior to the application of the usual
10340/// arithmetic conversions and converting the arguments of a builtin operator
10341/// candidate.
10342struct OriginalOperand {
10343 explicit OriginalOperand(Expr *Op) : Orig(Op), Conversion(nullptr) {
10344 if (auto *MTE = dyn_cast<MaterializeTemporaryExpr>(Val: Op))
10345 Op = MTE->getSubExpr();
10346 if (auto *BTE = dyn_cast<CXXBindTemporaryExpr>(Val: Op))
10347 Op = BTE->getSubExpr();
10348 if (auto *ICE = dyn_cast<ImplicitCastExpr>(Val: Op)) {
10349 Orig = ICE->getSubExprAsWritten();
10350 Conversion = ICE->getConversionFunction();
10351 }
10352 }
10353
10354 QualType getType() const { return Orig->getType(); }
10355
10356 Expr *Orig;
10357 NamedDecl *Conversion;
10358};
10359}
10360
10361QualType Sema::InvalidOperands(SourceLocation Loc, ExprResult &LHS,
10362 ExprResult &RHS) {
10363 OriginalOperand OrigLHS(LHS.get()), OrigRHS(RHS.get());
10364
10365 Diag(Loc, DiagID: diag::err_typecheck_invalid_operands)
10366 << OrigLHS.getType() << OrigRHS.getType()
10367 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
10368
10369 // If a user-defined conversion was applied to either of the operands prior
10370 // to applying the built-in operator rules, tell the user about it.
10371 if (OrigLHS.Conversion) {
10372 Diag(Loc: OrigLHS.Conversion->getLocation(),
10373 DiagID: diag::note_typecheck_invalid_operands_converted)
10374 << 0 << LHS.get()->getType();
10375 }
10376 if (OrigRHS.Conversion) {
10377 Diag(Loc: OrigRHS.Conversion->getLocation(),
10378 DiagID: diag::note_typecheck_invalid_operands_converted)
10379 << 1 << RHS.get()->getType();
10380 }
10381
10382 return QualType();
10383}
10384
10385QualType Sema::InvalidLogicalVectorOperands(SourceLocation Loc, ExprResult &LHS,
10386 ExprResult &RHS) {
10387 QualType LHSType = LHS.get()->IgnoreImpCasts()->getType();
10388 QualType RHSType = RHS.get()->IgnoreImpCasts()->getType();
10389
10390 bool LHSNatVec = LHSType->isVectorType();
10391 bool RHSNatVec = RHSType->isVectorType();
10392
10393 if (!(LHSNatVec && RHSNatVec)) {
10394 Expr *Vector = LHSNatVec ? LHS.get() : RHS.get();
10395 Expr *NonVector = !LHSNatVec ? LHS.get() : RHS.get();
10396 Diag(Loc, DiagID: diag::err_typecheck_logical_vector_expr_gnu_cpp_restrict)
10397 << 0 << Vector->getType() << NonVector->IgnoreImpCasts()->getType()
10398 << Vector->getSourceRange();
10399 return QualType();
10400 }
10401
10402 Diag(Loc, DiagID: diag::err_typecheck_logical_vector_expr_gnu_cpp_restrict)
10403 << 1 << LHSType << RHSType << LHS.get()->getSourceRange()
10404 << RHS.get()->getSourceRange();
10405
10406 return QualType();
10407}
10408
10409/// Try to convert a value of non-vector type to a vector type by converting
10410/// the type to the element type of the vector and then performing a splat.
10411/// If the language is OpenCL, we only use conversions that promote scalar
10412/// rank; for C, Obj-C, and C++ we allow any real scalar conversion except
10413/// for float->int.
10414///
10415/// OpenCL V2.0 6.2.6.p2:
10416/// An error shall occur if any scalar operand type has greater rank
10417/// than the type of the vector element.
10418///
10419/// \param scalar - if non-null, actually perform the conversions
10420/// \return true if the operation fails (but without diagnosing the failure)
10421static bool tryVectorConvertAndSplat(Sema &S, ExprResult *scalar,
10422 QualType scalarTy,
10423 QualType vectorEltTy,
10424 QualType vectorTy,
10425 unsigned &DiagID) {
10426 // The conversion to apply to the scalar before splatting it,
10427 // if necessary.
10428 CastKind scalarCast = CK_NoOp;
10429
10430 if (vectorEltTy->isBooleanType() && scalarTy->isIntegralType(Ctx: S.Context)) {
10431 scalarCast = CK_IntegralToBoolean;
10432 } else if (vectorEltTy->isIntegralType(Ctx: S.Context)) {
10433 if (S.getLangOpts().OpenCL && (scalarTy->isRealFloatingType() ||
10434 (scalarTy->isIntegerType() &&
10435 S.Context.getIntegerTypeOrder(LHS: vectorEltTy, RHS: scalarTy) < 0))) {
10436 DiagID = diag::err_opencl_scalar_type_rank_greater_than_vector_type;
10437 return true;
10438 }
10439 if (!scalarTy->isIntegralType(Ctx: S.Context))
10440 return true;
10441 scalarCast = CK_IntegralCast;
10442 } else if (vectorEltTy->isRealFloatingType()) {
10443 if (scalarTy->isRealFloatingType()) {
10444 if (S.getLangOpts().OpenCL &&
10445 S.Context.getFloatingTypeOrder(LHS: vectorEltTy, RHS: scalarTy) < 0) {
10446 DiagID = diag::err_opencl_scalar_type_rank_greater_than_vector_type;
10447 return true;
10448 }
10449 scalarCast = CK_FloatingCast;
10450 }
10451 else if (scalarTy->isIntegralType(Ctx: S.Context))
10452 scalarCast = CK_IntegralToFloating;
10453 else
10454 return true;
10455 } else {
10456 return true;
10457 }
10458
10459 // Adjust scalar if desired.
10460 if (scalar) {
10461 if (scalarCast != CK_NoOp)
10462 *scalar = S.ImpCastExprToType(E: scalar->get(), Type: vectorEltTy, CK: scalarCast);
10463 *scalar = S.ImpCastExprToType(E: scalar->get(), Type: vectorTy, CK: CK_VectorSplat);
10464 }
10465 return false;
10466}
10467
10468/// Convert vector E to a vector with the same number of elements but different
10469/// element type.
10470static ExprResult convertVector(Expr *E, QualType ElementType, Sema &S) {
10471 const auto *VecTy = E->getType()->getAs<VectorType>();
10472 assert(VecTy && "Expression E must be a vector");
10473 QualType NewVecTy =
10474 VecTy->isExtVectorType()
10475 ? S.Context.getExtVectorType(VectorType: ElementType, NumElts: VecTy->getNumElements())
10476 : S.Context.getVectorType(VectorType: ElementType, NumElts: VecTy->getNumElements(),
10477 VecKind: VecTy->getVectorKind());
10478
10479 // Look through the implicit cast. Return the subexpression if its type is
10480 // NewVecTy.
10481 if (auto *ICE = dyn_cast<ImplicitCastExpr>(Val: E))
10482 if (ICE->getSubExpr()->getType() == NewVecTy)
10483 return ICE->getSubExpr();
10484
10485 auto Cast = ElementType->isIntegerType() ? CK_IntegralCast : CK_FloatingCast;
10486 return S.ImpCastExprToType(E, Type: NewVecTy, CK: Cast);
10487}
10488
10489/// Test if a (constant) integer Int can be casted to another integer type
10490/// IntTy without losing precision.
10491static bool canConvertIntToOtherIntTy(Sema &S, ExprResult *Int,
10492 QualType OtherIntTy) {
10493 Expr *E = Int->get();
10494 if (E->containsErrors() || E->isInstantiationDependent())
10495 return false;
10496
10497 QualType IntTy = Int->get()->getType().getUnqualifiedType();
10498
10499 // Reject cases where the value of the Int is unknown as that would
10500 // possibly cause truncation, but accept cases where the scalar can be
10501 // demoted without loss of precision.
10502 Expr::EvalResult EVResult;
10503 bool CstInt = Int->get()->EvaluateAsInt(Result&: EVResult, Ctx: S.Context);
10504 int Order = S.Context.getIntegerTypeOrder(LHS: OtherIntTy, RHS: IntTy);
10505 bool IntSigned = IntTy->hasSignedIntegerRepresentation();
10506 bool OtherIntSigned = OtherIntTy->hasSignedIntegerRepresentation();
10507
10508 if (CstInt) {
10509 // If the scalar is constant and is of a higher order and has more active
10510 // bits that the vector element type, reject it.
10511 llvm::APSInt Result = EVResult.Val.getInt();
10512 unsigned NumBits = IntSigned
10513 ? (Result.isNegative() ? Result.getSignificantBits()
10514 : Result.getActiveBits())
10515 : Result.getActiveBits();
10516 if (Order < 0 && S.Context.getIntWidth(T: OtherIntTy) < NumBits)
10517 return true;
10518
10519 // If the signedness of the scalar type and the vector element type
10520 // differs and the number of bits is greater than that of the vector
10521 // element reject it.
10522 return (IntSigned != OtherIntSigned &&
10523 NumBits > S.Context.getIntWidth(T: OtherIntTy));
10524 }
10525
10526 // Reject cases where the value of the scalar is not constant and it's
10527 // order is greater than that of the vector element type.
10528 return (Order < 0);
10529}
10530
10531/// Test if a (constant) integer Int can be casted to floating point type
10532/// FloatTy without losing precision.
10533static bool canConvertIntTyToFloatTy(Sema &S, ExprResult *Int,
10534 QualType FloatTy) {
10535 if (Int->get()->containsErrors())
10536 return false;
10537
10538 QualType IntTy = Int->get()->getType().getUnqualifiedType();
10539
10540 // Determine if the integer constant can be expressed as a floating point
10541 // number of the appropriate type.
10542 Expr::EvalResult EVResult;
10543 bool CstInt = Int->get()->EvaluateAsInt(Result&: EVResult, Ctx: S.Context);
10544
10545 uint64_t Bits = 0;
10546 if (CstInt) {
10547 // Reject constants that would be truncated if they were converted to
10548 // the floating point type. Test by simple to/from conversion.
10549 // FIXME: Ideally the conversion to an APFloat and from an APFloat
10550 // could be avoided if there was a convertFromAPInt method
10551 // which could signal back if implicit truncation occurred.
10552 llvm::APSInt Result = EVResult.Val.getInt();
10553 llvm::APFloat Float(S.Context.getFloatTypeSemantics(T: FloatTy));
10554 Float.convertFromAPInt(Input: Result, IsSigned: IntTy->hasSignedIntegerRepresentation(),
10555 RM: llvm::APFloat::rmTowardZero);
10556 llvm::APSInt ConvertBack(S.Context.getIntWidth(T: IntTy),
10557 !IntTy->hasSignedIntegerRepresentation());
10558 bool Ignored = false;
10559 Float.convertToInteger(Result&: ConvertBack, RM: llvm::APFloat::rmNearestTiesToEven,
10560 IsExact: &Ignored);
10561 if (Result != ConvertBack)
10562 return true;
10563 } else {
10564 // Reject types that cannot be fully encoded into the mantissa of
10565 // the float.
10566 Bits = S.Context.getTypeSize(T: IntTy);
10567 unsigned FloatPrec = llvm::APFloat::semanticsPrecision(
10568 S.Context.getFloatTypeSemantics(T: FloatTy));
10569 if (Bits > FloatPrec)
10570 return true;
10571 }
10572
10573 return false;
10574}
10575
10576/// Attempt to convert and splat Scalar into a vector whose types matches
10577/// Vector following GCC conversion rules. The rule is that implicit
10578/// conversion can occur when Scalar can be casted to match Vector's element
10579/// type without causing truncation of Scalar.
10580static bool tryGCCVectorConvertAndSplat(Sema &S, ExprResult *Scalar,
10581 ExprResult *Vector) {
10582 QualType ScalarTy = Scalar->get()->getType().getUnqualifiedType();
10583 QualType VectorTy = Vector->get()->getType().getUnqualifiedType();
10584 QualType VectorEltTy;
10585
10586 if (const auto *VT = VectorTy->getAs<VectorType>()) {
10587 assert(!isa<ExtVectorType>(VT) &&
10588 "ExtVectorTypes should not be handled here!");
10589 VectorEltTy = VT->getElementType();
10590 } else if (VectorTy->isSveVLSBuiltinType()) {
10591 VectorEltTy =
10592 VectorTy->castAs<BuiltinType>()->getSveEltType(Ctx: S.getASTContext());
10593 } else {
10594 llvm_unreachable("Only Fixed-Length and SVE Vector types are handled here");
10595 }
10596
10597 // Reject cases where the vector element type or the scalar element type are
10598 // not integral or floating point types.
10599 if (!VectorEltTy->isArithmeticType() || !ScalarTy->isArithmeticType())
10600 return true;
10601
10602 // The conversion to apply to the scalar before splatting it,
10603 // if necessary.
10604 CastKind ScalarCast = CK_NoOp;
10605
10606 // Accept cases where the vector elements are integers and the scalar is
10607 // an integer.
10608 // FIXME: Notionally if the scalar was a floating point value with a precise
10609 // integral representation, we could cast it to an appropriate integer
10610 // type and then perform the rest of the checks here. GCC will perform
10611 // this conversion in some cases as determined by the input language.
10612 // We should accept it on a language independent basis.
10613 if (VectorEltTy->isIntegralType(Ctx: S.Context) &&
10614 ScalarTy->isIntegralType(Ctx: S.Context) &&
10615 S.Context.getIntegerTypeOrder(LHS: VectorEltTy, RHS: ScalarTy)) {
10616
10617 if (canConvertIntToOtherIntTy(S, Int: Scalar, OtherIntTy: VectorEltTy))
10618 return true;
10619
10620 ScalarCast = CK_IntegralCast;
10621 } else if (VectorEltTy->isIntegralType(Ctx: S.Context) &&
10622 ScalarTy->isRealFloatingType()) {
10623 if (S.Context.getTypeSize(T: VectorEltTy) == S.Context.getTypeSize(T: ScalarTy))
10624 ScalarCast = CK_FloatingToIntegral;
10625 else
10626 return true;
10627 } else if (VectorEltTy->isRealFloatingType()) {
10628 if (ScalarTy->isRealFloatingType()) {
10629
10630 // Reject cases where the scalar type is not a constant and has a higher
10631 // Order than the vector element type.
10632 llvm::APFloat Result(0.0);
10633
10634 // Determine whether this is a constant scalar. In the event that the
10635 // value is dependent (and thus cannot be evaluated by the constant
10636 // evaluator), skip the evaluation. This will then diagnose once the
10637 // expression is instantiated.
10638 bool CstScalar = Scalar->get()->isValueDependent() ||
10639 Scalar->get()->EvaluateAsFloat(Result, Ctx: S.Context);
10640 int Order = S.Context.getFloatingTypeOrder(LHS: VectorEltTy, RHS: ScalarTy);
10641 if (!CstScalar && Order < 0)
10642 return true;
10643
10644 // If the scalar cannot be safely casted to the vector element type,
10645 // reject it.
10646 if (CstScalar) {
10647 bool Truncated = false;
10648 Result.convert(ToSemantics: S.Context.getFloatTypeSemantics(T: VectorEltTy),
10649 RM: llvm::APFloat::rmNearestTiesToEven, losesInfo: &Truncated);
10650 if (Truncated)
10651 return true;
10652 }
10653
10654 ScalarCast = CK_FloatingCast;
10655 } else if (ScalarTy->isIntegralType(Ctx: S.Context)) {
10656 if (canConvertIntTyToFloatTy(S, Int: Scalar, FloatTy: VectorEltTy))
10657 return true;
10658
10659 ScalarCast = CK_IntegralToFloating;
10660 } else
10661 return true;
10662 } else if (ScalarTy->isEnumeralType())
10663 return true;
10664
10665 // Adjust scalar if desired.
10666 if (ScalarCast != CK_NoOp)
10667 *Scalar = S.ImpCastExprToType(E: Scalar->get(), Type: VectorEltTy, CK: ScalarCast);
10668 *Scalar = S.ImpCastExprToType(E: Scalar->get(), Type: VectorTy, CK: CK_VectorSplat);
10669 return false;
10670}
10671
10672QualType Sema::CheckVectorOperands(ExprResult &LHS, ExprResult &RHS,
10673 SourceLocation Loc, bool IsCompAssign,
10674 bool AllowBothBool,
10675 bool AllowBoolConversions,
10676 bool AllowBoolOperation,
10677 bool ReportInvalid) {
10678 if (!IsCompAssign) {
10679 LHS = DefaultFunctionArrayLvalueConversion(E: LHS.get());
10680 if (LHS.isInvalid())
10681 return QualType();
10682 }
10683 RHS = DefaultFunctionArrayLvalueConversion(E: RHS.get());
10684 if (RHS.isInvalid())
10685 return QualType();
10686
10687 // For conversion purposes, we ignore any qualifiers.
10688 // For example, "const float" and "float" are equivalent.
10689 QualType LHSType = LHS.get()->getType().getUnqualifiedType();
10690 QualType RHSType = RHS.get()->getType().getUnqualifiedType();
10691
10692 const VectorType *LHSVecType = LHSType->getAs<VectorType>();
10693 const VectorType *RHSVecType = RHSType->getAs<VectorType>();
10694 assert(LHSVecType || RHSVecType);
10695
10696 if (getLangOpts().HLSL)
10697 return HLSL().handleVectorBinOpConversion(LHS, RHS, LHSType, RHSType,
10698 IsCompAssign);
10699
10700 // Any operation with MFloat8 type is only possible with C intrinsics
10701 if ((LHSVecType && LHSVecType->getElementType()->isMFloat8Type()) ||
10702 (RHSVecType && RHSVecType->getElementType()->isMFloat8Type()))
10703 return InvalidOperands(Loc, LHS, RHS);
10704
10705 // AltiVec-style "vector bool op vector bool" combinations are allowed
10706 // for some operators but not others.
10707 if (!AllowBothBool && LHSVecType &&
10708 LHSVecType->getVectorKind() == VectorKind::AltiVecBool && RHSVecType &&
10709 RHSVecType->getVectorKind() == VectorKind::AltiVecBool)
10710 return ReportInvalid ? InvalidOperands(Loc, LHS, RHS) : QualType();
10711
10712 // This operation may not be performed on boolean vectors.
10713 if (!AllowBoolOperation &&
10714 (LHSType->isExtVectorBoolType() || RHSType->isExtVectorBoolType()))
10715 return ReportInvalid ? InvalidOperands(Loc, LHS, RHS) : QualType();
10716
10717 // If the vector types are identical, return.
10718 if (Context.hasSameType(T1: LHSType, T2: RHSType))
10719 return Context.getCommonSugaredType(X: LHSType, Y: RHSType);
10720
10721 // If we have compatible AltiVec and GCC vector types, use the AltiVec type.
10722 if (LHSVecType && RHSVecType &&
10723 Context.areCompatibleVectorTypes(FirstVec: LHSType, SecondVec: RHSType)) {
10724 if (isa<ExtVectorType>(Val: LHSVecType)) {
10725 RHS = ImpCastExprToType(E: RHS.get(), Type: LHSType, CK: CK_BitCast);
10726 return LHSType;
10727 }
10728
10729 if (!IsCompAssign)
10730 LHS = ImpCastExprToType(E: LHS.get(), Type: RHSType, CK: CK_BitCast);
10731 return RHSType;
10732 }
10733
10734 // AllowBoolConversions says that bool and non-bool AltiVec vectors
10735 // can be mixed, with the result being the non-bool type. The non-bool
10736 // operand must have integer element type.
10737 if (AllowBoolConversions && LHSVecType && RHSVecType &&
10738 LHSVecType->getNumElements() == RHSVecType->getNumElements() &&
10739 (Context.getTypeSize(T: LHSVecType->getElementType()) ==
10740 Context.getTypeSize(T: RHSVecType->getElementType()))) {
10741 if (LHSVecType->getVectorKind() == VectorKind::AltiVecVector &&
10742 LHSVecType->getElementType()->isIntegerType() &&
10743 RHSVecType->getVectorKind() == VectorKind::AltiVecBool) {
10744 RHS = ImpCastExprToType(E: RHS.get(), Type: LHSType, CK: CK_BitCast);
10745 return LHSType;
10746 }
10747 if (!IsCompAssign &&
10748 LHSVecType->getVectorKind() == VectorKind::AltiVecBool &&
10749 RHSVecType->getVectorKind() == VectorKind::AltiVecVector &&
10750 RHSVecType->getElementType()->isIntegerType()) {
10751 LHS = ImpCastExprToType(E: LHS.get(), Type: RHSType, CK: CK_BitCast);
10752 return RHSType;
10753 }
10754 }
10755
10756 // Expressions containing fixed-length and sizeless SVE/RVV vectors are
10757 // invalid since the ambiguity can affect the ABI.
10758 auto IsSveRVVConversion = [](QualType FirstType, QualType SecondType,
10759 unsigned &SVEorRVV) {
10760 const VectorType *VecType = SecondType->getAs<VectorType>();
10761 SVEorRVV = 0;
10762 if (FirstType->isSizelessBuiltinType() && VecType) {
10763 if (VecType->getVectorKind() == VectorKind::SveFixedLengthData ||
10764 VecType->getVectorKind() == VectorKind::SveFixedLengthPredicate)
10765 return true;
10766 if (VecType->getVectorKind() == VectorKind::RVVFixedLengthData ||
10767 VecType->getVectorKind() == VectorKind::RVVFixedLengthMask ||
10768 VecType->getVectorKind() == VectorKind::RVVFixedLengthMask_1 ||
10769 VecType->getVectorKind() == VectorKind::RVVFixedLengthMask_2 ||
10770 VecType->getVectorKind() == VectorKind::RVVFixedLengthMask_4) {
10771 SVEorRVV = 1;
10772 return true;
10773 }
10774 }
10775
10776 return false;
10777 };
10778
10779 unsigned SVEorRVV;
10780 if (IsSveRVVConversion(LHSType, RHSType, SVEorRVV) ||
10781 IsSveRVVConversion(RHSType, LHSType, SVEorRVV)) {
10782 Diag(Loc, DiagID: diag::err_typecheck_sve_rvv_ambiguous)
10783 << SVEorRVV << LHSType << RHSType;
10784 return QualType();
10785 }
10786
10787 // Expressions containing GNU and SVE or RVV (fixed or sizeless) vectors are
10788 // invalid since the ambiguity can affect the ABI.
10789 auto IsSveRVVGnuConversion = [](QualType FirstType, QualType SecondType,
10790 unsigned &SVEorRVV) {
10791 const VectorType *FirstVecType = FirstType->getAs<VectorType>();
10792 const VectorType *SecondVecType = SecondType->getAs<VectorType>();
10793
10794 SVEorRVV = 0;
10795 if (FirstVecType && SecondVecType) {
10796 if (FirstVecType->getVectorKind() == VectorKind::Generic) {
10797 if (SecondVecType->getVectorKind() == VectorKind::SveFixedLengthData ||
10798 SecondVecType->getVectorKind() ==
10799 VectorKind::SveFixedLengthPredicate)
10800 return true;
10801 if (SecondVecType->getVectorKind() == VectorKind::RVVFixedLengthData ||
10802 SecondVecType->getVectorKind() == VectorKind::RVVFixedLengthMask ||
10803 SecondVecType->getVectorKind() ==
10804 VectorKind::RVVFixedLengthMask_1 ||
10805 SecondVecType->getVectorKind() ==
10806 VectorKind::RVVFixedLengthMask_2 ||
10807 SecondVecType->getVectorKind() ==
10808 VectorKind::RVVFixedLengthMask_4) {
10809 SVEorRVV = 1;
10810 return true;
10811 }
10812 }
10813 return false;
10814 }
10815
10816 if (SecondVecType &&
10817 SecondVecType->getVectorKind() == VectorKind::Generic) {
10818 if (FirstType->isSVESizelessBuiltinType())
10819 return true;
10820 if (FirstType->isRVVSizelessBuiltinType()) {
10821 SVEorRVV = 1;
10822 return true;
10823 }
10824 }
10825
10826 return false;
10827 };
10828
10829 if (IsSveRVVGnuConversion(LHSType, RHSType, SVEorRVV) ||
10830 IsSveRVVGnuConversion(RHSType, LHSType, SVEorRVV)) {
10831 Diag(Loc, DiagID: diag::err_typecheck_sve_rvv_gnu_ambiguous)
10832 << SVEorRVV << LHSType << RHSType;
10833 return QualType();
10834 }
10835
10836 // If there's a vector type and a scalar, try to convert the scalar to
10837 // the vector element type and splat.
10838 unsigned DiagID = diag::err_typecheck_vector_not_convertable;
10839 if (!RHSVecType) {
10840 if (isa<ExtVectorType>(Val: LHSVecType)) {
10841 if (!tryVectorConvertAndSplat(S&: *this, scalar: &RHS, scalarTy: RHSType,
10842 vectorEltTy: LHSVecType->getElementType(), vectorTy: LHSType,
10843 DiagID))
10844 return LHSType;
10845 } else {
10846 if (!tryGCCVectorConvertAndSplat(S&: *this, Scalar: &RHS, Vector: &LHS))
10847 return LHSType;
10848 }
10849 }
10850 if (!LHSVecType) {
10851 if (isa<ExtVectorType>(Val: RHSVecType)) {
10852 if (!tryVectorConvertAndSplat(S&: *this, scalar: (IsCompAssign ? nullptr : &LHS),
10853 scalarTy: LHSType, vectorEltTy: RHSVecType->getElementType(),
10854 vectorTy: RHSType, DiagID))
10855 return RHSType;
10856 } else {
10857 if (LHS.get()->isLValue() ||
10858 !tryGCCVectorConvertAndSplat(S&: *this, Scalar: &LHS, Vector: &RHS))
10859 return RHSType;
10860 }
10861 }
10862
10863 // FIXME: The code below also handles conversion between vectors and
10864 // non-scalars, we should break this down into fine grained specific checks
10865 // and emit proper diagnostics.
10866 QualType VecType = LHSVecType ? LHSType : RHSType;
10867 const VectorType *VT = LHSVecType ? LHSVecType : RHSVecType;
10868 QualType OtherType = LHSVecType ? RHSType : LHSType;
10869 ExprResult *OtherExpr = LHSVecType ? &RHS : &LHS;
10870 if (isLaxVectorConversion(srcTy: OtherType, destTy: VecType)) {
10871 if (Context.getTargetInfo().getTriple().isPPC() &&
10872 anyAltivecTypes(SrcTy: RHSType, DestTy: LHSType) &&
10873 !Context.areCompatibleVectorTypes(FirstVec: RHSType, SecondVec: LHSType))
10874 Diag(Loc, DiagID: diag::warn_deprecated_lax_vec_conv_all) << RHSType << LHSType;
10875 // If we're allowing lax vector conversions, only the total (data) size
10876 // needs to be the same. For non compound assignment, if one of the types is
10877 // scalar, the result is always the vector type.
10878 if (!IsCompAssign) {
10879 *OtherExpr = ImpCastExprToType(E: OtherExpr->get(), Type: VecType, CK: CK_BitCast);
10880 return VecType;
10881 // In a compound assignment, lhs += rhs, 'lhs' is a lvalue src, forbidding
10882 // any implicit cast. Here, the 'rhs' should be implicit casted to 'lhs'
10883 // type. Note that this is already done by non-compound assignments in
10884 // CheckAssignmentConstraints. If it's a scalar type, only bitcast for
10885 // <1 x T> -> T. The result is also a vector type.
10886 } else if (OtherType->isExtVectorType() || OtherType->isVectorType() ||
10887 (OtherType->isScalarType() && VT->getNumElements() == 1)) {
10888 ExprResult *RHSExpr = &RHS;
10889 *RHSExpr = ImpCastExprToType(E: RHSExpr->get(), Type: LHSType, CK: CK_BitCast);
10890 return VecType;
10891 }
10892 }
10893
10894 // Okay, the expression is invalid.
10895
10896 // If there's a non-vector, non-real operand, diagnose that.
10897 if ((!RHSVecType && !RHSType->isRealType()) ||
10898 (!LHSVecType && !LHSType->isRealType())) {
10899 Diag(Loc, DiagID: diag::err_typecheck_vector_not_convertable_non_scalar)
10900 << LHSType << RHSType
10901 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
10902 return QualType();
10903 }
10904
10905 // OpenCL V1.1 6.2.6.p1:
10906 // If the operands are of more than one vector type, then an error shall
10907 // occur. Implicit conversions between vector types are not permitted, per
10908 // section 6.2.1.
10909 if (getLangOpts().OpenCL &&
10910 RHSVecType && isa<ExtVectorType>(Val: RHSVecType) &&
10911 LHSVecType && isa<ExtVectorType>(Val: LHSVecType)) {
10912 Diag(Loc, DiagID: diag::err_opencl_implicit_vector_conversion) << LHSType
10913 << RHSType;
10914 return QualType();
10915 }
10916
10917
10918 // If there is a vector type that is not a ExtVector and a scalar, we reach
10919 // this point if scalar could not be converted to the vector's element type
10920 // without truncation.
10921 if ((RHSVecType && !isa<ExtVectorType>(Val: RHSVecType)) ||
10922 (LHSVecType && !isa<ExtVectorType>(Val: LHSVecType))) {
10923 QualType Scalar = LHSVecType ? RHSType : LHSType;
10924 QualType Vector = LHSVecType ? LHSType : RHSType;
10925 unsigned ScalarOrVector = LHSVecType && RHSVecType ? 1 : 0;
10926 Diag(Loc,
10927 DiagID: diag::err_typecheck_vector_not_convertable_implict_truncation)
10928 << ScalarOrVector << Scalar << Vector;
10929
10930 return QualType();
10931 }
10932
10933 // Otherwise, use the generic diagnostic.
10934 Diag(Loc, DiagID)
10935 << LHSType << RHSType
10936 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
10937 return QualType();
10938}
10939
10940QualType Sema::CheckSizelessVectorOperands(ExprResult &LHS, ExprResult &RHS,
10941 SourceLocation Loc,
10942 bool IsCompAssign,
10943 ArithConvKind OperationKind) {
10944 if (!IsCompAssign) {
10945 LHS = DefaultFunctionArrayLvalueConversion(E: LHS.get());
10946 if (LHS.isInvalid())
10947 return QualType();
10948 }
10949 RHS = DefaultFunctionArrayLvalueConversion(E: RHS.get());
10950 if (RHS.isInvalid())
10951 return QualType();
10952
10953 QualType LHSType = LHS.get()->getType().getUnqualifiedType();
10954 QualType RHSType = RHS.get()->getType().getUnqualifiedType();
10955
10956 const BuiltinType *LHSBuiltinTy = LHSType->getAs<BuiltinType>();
10957 const BuiltinType *RHSBuiltinTy = RHSType->getAs<BuiltinType>();
10958
10959 unsigned DiagID = diag::err_typecheck_invalid_operands;
10960 if ((OperationKind == ArithConvKind::Arithmetic) &&
10961 ((LHSBuiltinTy && LHSBuiltinTy->isSVEBool()) ||
10962 (RHSBuiltinTy && RHSBuiltinTy->isSVEBool()))) {
10963 Diag(Loc, DiagID) << LHSType << RHSType << LHS.get()->getSourceRange()
10964 << RHS.get()->getSourceRange();
10965 return QualType();
10966 }
10967
10968 if (Context.hasSameType(T1: LHSType, T2: RHSType))
10969 return LHSType;
10970
10971 if (LHSType->isSveVLSBuiltinType() && !RHSType->isSveVLSBuiltinType()) {
10972 if (!tryGCCVectorConvertAndSplat(S&: *this, Scalar: &RHS, Vector: &LHS))
10973 return LHSType;
10974 }
10975 if (RHSType->isSveVLSBuiltinType() && !LHSType->isSveVLSBuiltinType()) {
10976 if (LHS.get()->isLValue() ||
10977 !tryGCCVectorConvertAndSplat(S&: *this, Scalar: &LHS, Vector: &RHS))
10978 return RHSType;
10979 }
10980
10981 if ((!LHSType->isSveVLSBuiltinType() && !LHSType->isRealType()) ||
10982 (!RHSType->isSveVLSBuiltinType() && !RHSType->isRealType())) {
10983 Diag(Loc, DiagID: diag::err_typecheck_vector_not_convertable_non_scalar)
10984 << LHSType << RHSType << LHS.get()->getSourceRange()
10985 << RHS.get()->getSourceRange();
10986 return QualType();
10987 }
10988
10989 if (LHSType->isSveVLSBuiltinType() && RHSType->isSveVLSBuiltinType() &&
10990 Context.getBuiltinVectorTypeInfo(VecTy: LHSBuiltinTy).EC !=
10991 Context.getBuiltinVectorTypeInfo(VecTy: RHSBuiltinTy).EC) {
10992 Diag(Loc, DiagID: diag::err_typecheck_vector_lengths_not_equal)
10993 << LHSType << RHSType << LHS.get()->getSourceRange()
10994 << RHS.get()->getSourceRange();
10995 return QualType();
10996 }
10997
10998 if (LHSType->isSveVLSBuiltinType() || RHSType->isSveVLSBuiltinType()) {
10999 QualType Scalar = LHSType->isSveVLSBuiltinType() ? RHSType : LHSType;
11000 QualType Vector = LHSType->isSveVLSBuiltinType() ? LHSType : RHSType;
11001 bool ScalarOrVector =
11002 LHSType->isSveVLSBuiltinType() && RHSType->isSveVLSBuiltinType();
11003
11004 Diag(Loc, DiagID: diag::err_typecheck_vector_not_convertable_implict_truncation)
11005 << ScalarOrVector << Scalar << Vector;
11006
11007 return QualType();
11008 }
11009
11010 Diag(Loc, DiagID) << LHSType << RHSType << LHS.get()->getSourceRange()
11011 << RHS.get()->getSourceRange();
11012 return QualType();
11013}
11014
11015// checkArithmeticNull - Detect when a NULL constant is used improperly in an
11016// expression. These are mainly cases where the null pointer is used as an
11017// integer instead of a pointer.
11018static void checkArithmeticNull(Sema &S, ExprResult &LHS, ExprResult &RHS,
11019 SourceLocation Loc, bool IsCompare) {
11020 // The canonical way to check for a GNU null is with isNullPointerConstant,
11021 // but we use a bit of a hack here for speed; this is a relatively
11022 // hot path, and isNullPointerConstant is slow.
11023 bool LHSNull = isa<GNUNullExpr>(Val: LHS.get()->IgnoreParenImpCasts());
11024 bool RHSNull = isa<GNUNullExpr>(Val: RHS.get()->IgnoreParenImpCasts());
11025
11026 QualType NonNullType = LHSNull ? RHS.get()->getType() : LHS.get()->getType();
11027
11028 // Avoid analyzing cases where the result will either be invalid (and
11029 // diagnosed as such) or entirely valid and not something to warn about.
11030 if ((!LHSNull && !RHSNull) || NonNullType->isBlockPointerType() ||
11031 NonNullType->isMemberPointerType() || NonNullType->isFunctionType())
11032 return;
11033
11034 // Comparison operations would not make sense with a null pointer no matter
11035 // what the other expression is.
11036 if (!IsCompare) {
11037 S.Diag(Loc, DiagID: diag::warn_null_in_arithmetic_operation)
11038 << (LHSNull ? LHS.get()->getSourceRange() : SourceRange())
11039 << (RHSNull ? RHS.get()->getSourceRange() : SourceRange());
11040 return;
11041 }
11042
11043 // The rest of the operations only make sense with a null pointer
11044 // if the other expression is a pointer.
11045 if (LHSNull == RHSNull || NonNullType->isAnyPointerType() ||
11046 NonNullType->canDecayToPointerType())
11047 return;
11048
11049 S.Diag(Loc, DiagID: diag::warn_null_in_comparison_operation)
11050 << LHSNull /* LHS is NULL */ << NonNullType
11051 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
11052}
11053
11054static void DetectPrecisionLossInComplexDivision(Sema &S, QualType DivisorTy,
11055 SourceLocation OpLoc) {
11056 // If the divisor is real, then this is real/real or complex/real division.
11057 // Either way there can be no precision loss.
11058 auto *CT = DivisorTy->getAs<ComplexType>();
11059 if (!CT)
11060 return;
11061
11062 QualType ElementType = CT->getElementType().getCanonicalType();
11063 bool IsComplexRangePromoted = S.getLangOpts().getComplexRange() ==
11064 LangOptions::ComplexRangeKind::CX_Promoted;
11065 if (!ElementType->isFloatingType() || !IsComplexRangePromoted)
11066 return;
11067
11068 ASTContext &Ctx = S.getASTContext();
11069 QualType HigherElementType = Ctx.GetHigherPrecisionFPType(ElementType);
11070 const llvm::fltSemantics &ElementTypeSemantics =
11071 Ctx.getFloatTypeSemantics(T: ElementType);
11072 const llvm::fltSemantics &HigherElementTypeSemantics =
11073 Ctx.getFloatTypeSemantics(T: HigherElementType);
11074
11075 if ((llvm::APFloat::semanticsMaxExponent(ElementTypeSemantics) * 2 + 1 >
11076 llvm::APFloat::semanticsMaxExponent(HigherElementTypeSemantics)) ||
11077 (HigherElementType == Ctx.LongDoubleTy &&
11078 !Ctx.getTargetInfo().hasLongDoubleType())) {
11079 // Retain the location of the first use of higher precision type.
11080 if (!S.LocationOfExcessPrecisionNotSatisfied.isValid())
11081 S.LocationOfExcessPrecisionNotSatisfied = OpLoc;
11082 for (auto &[Type, Num] : S.ExcessPrecisionNotSatisfied) {
11083 if (Type == HigherElementType) {
11084 Num++;
11085 return;
11086 }
11087 }
11088 S.ExcessPrecisionNotSatisfied.push_back(x: std::make_pair(
11089 x&: HigherElementType, y: S.ExcessPrecisionNotSatisfied.size()));
11090 }
11091}
11092
11093static void DiagnoseDivisionSizeofPointerOrArray(Sema &S, Expr *LHS, Expr *RHS,
11094 SourceLocation Loc) {
11095 const auto *LUE = dyn_cast<UnaryExprOrTypeTraitExpr>(Val: LHS);
11096 const auto *RUE = dyn_cast<UnaryExprOrTypeTraitExpr>(Val: RHS);
11097 if (!LUE || !RUE)
11098 return;
11099 if (LUE->getKind() != UETT_SizeOf || LUE->isArgumentType() ||
11100 RUE->getKind() != UETT_SizeOf)
11101 return;
11102
11103 const Expr *LHSArg = LUE->getArgumentExpr()->IgnoreParens();
11104 QualType LHSTy = LHSArg->getType();
11105 QualType RHSTy;
11106
11107 if (RUE->isArgumentType())
11108 RHSTy = RUE->getArgumentType().getNonReferenceType();
11109 else
11110 RHSTy = RUE->getArgumentExpr()->IgnoreParens()->getType();
11111
11112 if (LHSTy->isPointerType() && !RHSTy->isPointerType()) {
11113 if (!S.Context.hasSameUnqualifiedType(T1: LHSTy->getPointeeType(), T2: RHSTy))
11114 return;
11115
11116 S.Diag(Loc, DiagID: diag::warn_division_sizeof_ptr) << LHS << LHS->getSourceRange();
11117 if (const auto *DRE = dyn_cast<DeclRefExpr>(Val: LHSArg)) {
11118 if (const ValueDecl *LHSArgDecl = DRE->getDecl())
11119 S.Diag(Loc: LHSArgDecl->getLocation(), DiagID: diag::note_pointer_declared_here)
11120 << LHSArgDecl;
11121 }
11122 } else if (const auto *ArrayTy = S.Context.getAsArrayType(T: LHSTy)) {
11123 QualType ArrayElemTy = ArrayTy->getElementType();
11124 if (ArrayElemTy != S.Context.getBaseElementType(VAT: ArrayTy) ||
11125 ArrayElemTy->isDependentType() || RHSTy->isDependentType() ||
11126 RHSTy->isReferenceType() || ArrayElemTy->isCharType() ||
11127 S.Context.getTypeSize(T: ArrayElemTy) == S.Context.getTypeSize(T: RHSTy))
11128 return;
11129 S.Diag(Loc, DiagID: diag::warn_division_sizeof_array)
11130 << LHSArg->getSourceRange() << ArrayElemTy << RHSTy;
11131 if (const auto *DRE = dyn_cast<DeclRefExpr>(Val: LHSArg)) {
11132 if (const ValueDecl *LHSArgDecl = DRE->getDecl())
11133 S.Diag(Loc: LHSArgDecl->getLocation(), DiagID: diag::note_array_declared_here)
11134 << LHSArgDecl;
11135 }
11136
11137 S.Diag(Loc, DiagID: diag::note_precedence_silence) << RHS;
11138 }
11139}
11140
11141static void DiagnoseBadDivideOrRemainderValues(Sema& S, ExprResult &LHS,
11142 ExprResult &RHS,
11143 SourceLocation Loc, bool IsDiv) {
11144 // Check for division/remainder by zero.
11145 Expr::EvalResult RHSValue;
11146 if (!RHS.get()->isValueDependent() &&
11147 RHS.get()->EvaluateAsInt(Result&: RHSValue, Ctx: S.Context) &&
11148 RHSValue.Val.getInt() == 0)
11149 S.DiagRuntimeBehavior(Loc, Statement: RHS.get(),
11150 PD: S.PDiag(DiagID: diag::warn_remainder_division_by_zero)
11151 << IsDiv << RHS.get()->getSourceRange());
11152}
11153
11154static void diagnoseScopedEnums(Sema &S, const SourceLocation Loc,
11155 const ExprResult &LHS, const ExprResult &RHS,
11156 BinaryOperatorKind Opc) {
11157 if (!LHS.isUsable() || !RHS.isUsable())
11158 return;
11159 const Expr *LHSExpr = LHS.get();
11160 const Expr *RHSExpr = RHS.get();
11161 const QualType LHSType = LHSExpr->getType();
11162 const QualType RHSType = RHSExpr->getType();
11163 const bool LHSIsScoped = LHSType->isScopedEnumeralType();
11164 const bool RHSIsScoped = RHSType->isScopedEnumeralType();
11165 if (!LHSIsScoped && !RHSIsScoped)
11166 return;
11167 if (BinaryOperator::isAssignmentOp(Opc) && LHSIsScoped)
11168 return;
11169 if (!LHSIsScoped && !LHSType->isIntegralOrUnscopedEnumerationType())
11170 return;
11171 if (!RHSIsScoped && !RHSType->isIntegralOrUnscopedEnumerationType())
11172 return;
11173 auto DiagnosticHelper = [&S](const Expr *expr, const QualType type) {
11174 SourceLocation BeginLoc = expr->getBeginLoc();
11175 QualType IntType = type->castAs<EnumType>()
11176 ->getDecl()
11177 ->getDefinitionOrSelf()
11178 ->getIntegerType();
11179 std::string InsertionString = "static_cast<" + IntType.getAsString() + ">(";
11180 S.Diag(Loc: BeginLoc, DiagID: diag::note_no_implicit_conversion_for_scoped_enum)
11181 << FixItHint::CreateInsertion(InsertionLoc: BeginLoc, Code: InsertionString)
11182 << FixItHint::CreateInsertion(InsertionLoc: expr->getEndLoc(), Code: ")");
11183 };
11184 if (LHSIsScoped) {
11185 DiagnosticHelper(LHSExpr, LHSType);
11186 }
11187 if (RHSIsScoped) {
11188 DiagnosticHelper(RHSExpr, RHSType);
11189 }
11190}
11191
11192QualType Sema::CheckMultiplyDivideOperands(ExprResult &LHS, ExprResult &RHS,
11193 SourceLocation Loc,
11194 BinaryOperatorKind Opc) {
11195 bool IsCompAssign = Opc == BO_MulAssign || Opc == BO_DivAssign;
11196 bool IsDiv = Opc == BO_Div || Opc == BO_DivAssign;
11197
11198 checkArithmeticNull(S&: *this, LHS, RHS, Loc, /*IsCompare=*/false);
11199
11200 QualType LHSTy = LHS.get()->getType();
11201 QualType RHSTy = RHS.get()->getType();
11202 if (LHSTy->isVectorType() || RHSTy->isVectorType())
11203 return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign,
11204 /*AllowBothBool*/ getLangOpts().AltiVec,
11205 /*AllowBoolConversions*/ false,
11206 /*AllowBooleanOperation*/ AllowBoolOperation: false,
11207 /*ReportInvalid*/ true);
11208 if (LHSTy->isSveVLSBuiltinType() || RHSTy->isSveVLSBuiltinType())
11209 return CheckSizelessVectorOperands(LHS, RHS, Loc, IsCompAssign,
11210 OperationKind: ArithConvKind::Arithmetic);
11211 if (!IsDiv &&
11212 (LHSTy->isConstantMatrixType() || RHSTy->isConstantMatrixType()))
11213 return CheckMatrixMultiplyOperands(LHS, RHS, Loc, IsCompAssign);
11214 // For division, only matrix-by-scalar is supported. Other combinations with
11215 // matrix types are invalid.
11216 if (IsDiv && LHSTy->isConstantMatrixType() && RHSTy->isArithmeticType())
11217 return CheckMatrixElementwiseOperands(LHS, RHS, Loc, IsCompAssign);
11218
11219 QualType compType = UsualArithmeticConversions(
11220 LHS, RHS, Loc,
11221 ACK: IsCompAssign ? ArithConvKind::CompAssign : ArithConvKind::Arithmetic);
11222 if (LHS.isInvalid() || RHS.isInvalid())
11223 return QualType();
11224
11225 if (compType.isNull() || !compType->isArithmeticType()) {
11226 QualType ResultTy = InvalidOperands(Loc, LHS, RHS);
11227 diagnoseScopedEnums(S&: *this, Loc, LHS, RHS, Opc);
11228 return ResultTy;
11229 }
11230 if (IsDiv) {
11231 DetectPrecisionLossInComplexDivision(S&: *this, DivisorTy: RHS.get()->getType(), OpLoc: Loc);
11232 DiagnoseBadDivideOrRemainderValues(S&: *this, LHS, RHS, Loc, IsDiv);
11233 DiagnoseDivisionSizeofPointerOrArray(S&: *this, LHS: LHS.get(), RHS: RHS.get(), Loc);
11234 }
11235 return compType;
11236}
11237
11238QualType Sema::CheckRemainderOperands(
11239 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, bool IsCompAssign) {
11240 checkArithmeticNull(S&: *this, LHS, RHS, Loc, /*IsCompare=*/false);
11241
11242 // Note: This check is here to simplify the double exclusions of
11243 // scalar and vector HLSL checks. No getLangOpts().HLSL
11244 // is needed since all languages exlcude doubles.
11245 if (LHS.get()->getType()->isDoubleType() ||
11246 RHS.get()->getType()->isDoubleType() ||
11247 (LHS.get()->getType()->isVectorType() && LHS.get()
11248 ->getType()
11249 ->getAs<VectorType>()
11250 ->getElementType()
11251 ->isDoubleType()) ||
11252 (RHS.get()->getType()->isVectorType() && RHS.get()
11253 ->getType()
11254 ->getAs<VectorType>()
11255 ->getElementType()
11256 ->isDoubleType()))
11257 return InvalidOperands(Loc, LHS, RHS);
11258
11259 if (LHS.get()->getType()->isVectorType() ||
11260 RHS.get()->getType()->isVectorType()) {
11261 if ((LHS.get()->getType()->hasIntegerRepresentation() &&
11262 RHS.get()->getType()->hasIntegerRepresentation()) ||
11263 (getLangOpts().HLSL &&
11264 (LHS.get()->getType()->hasFloatingRepresentation() ||
11265 RHS.get()->getType()->hasFloatingRepresentation())))
11266 return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign,
11267 /*AllowBothBool*/ getLangOpts().AltiVec,
11268 /*AllowBoolConversions*/ false,
11269 /*AllowBooleanOperation*/ AllowBoolOperation: false,
11270 /*ReportInvalid*/ true);
11271 return InvalidOperands(Loc, LHS, RHS);
11272 }
11273
11274 if (LHS.get()->getType()->isSveVLSBuiltinType() ||
11275 RHS.get()->getType()->isSveVLSBuiltinType()) {
11276 if (LHS.get()->getType()->hasIntegerRepresentation() &&
11277 RHS.get()->getType()->hasIntegerRepresentation())
11278 return CheckSizelessVectorOperands(LHS, RHS, Loc, IsCompAssign,
11279 OperationKind: ArithConvKind::Arithmetic);
11280
11281 return InvalidOperands(Loc, LHS, RHS);
11282 }
11283
11284 QualType compType = UsualArithmeticConversions(
11285 LHS, RHS, Loc,
11286 ACK: IsCompAssign ? ArithConvKind::CompAssign : ArithConvKind::Arithmetic);
11287 if (LHS.isInvalid() || RHS.isInvalid())
11288 return QualType();
11289
11290 if (compType.isNull() ||
11291 (!compType->isIntegerType() &&
11292 !(getLangOpts().HLSL && compType->isFloatingType()))) {
11293 QualType ResultTy = InvalidOperands(Loc, LHS, RHS);
11294 diagnoseScopedEnums(S&: *this, Loc, LHS, RHS,
11295 Opc: IsCompAssign ? BO_RemAssign : BO_Rem);
11296 return ResultTy;
11297 }
11298 DiagnoseBadDivideOrRemainderValues(S&: *this, LHS, RHS, Loc, IsDiv: false /* IsDiv */);
11299 return compType;
11300}
11301
11302/// Diagnose invalid arithmetic on two void pointers.
11303static void diagnoseArithmeticOnTwoVoidPointers(Sema &S, SourceLocation Loc,
11304 Expr *LHSExpr, Expr *RHSExpr) {
11305 S.Diag(Loc, DiagID: S.getLangOpts().CPlusPlus
11306 ? diag::err_typecheck_pointer_arith_void_type
11307 : diag::ext_gnu_void_ptr)
11308 << 1 /* two pointers */ << LHSExpr->getSourceRange()
11309 << RHSExpr->getSourceRange();
11310}
11311
11312/// Diagnose invalid arithmetic on a void pointer.
11313static void diagnoseArithmeticOnVoidPointer(Sema &S, SourceLocation Loc,
11314 Expr *Pointer) {
11315 S.Diag(Loc, DiagID: S.getLangOpts().CPlusPlus
11316 ? diag::err_typecheck_pointer_arith_void_type
11317 : diag::ext_gnu_void_ptr)
11318 << 0 /* one pointer */ << Pointer->getSourceRange();
11319}
11320
11321/// Diagnose invalid arithmetic on a null pointer.
11322///
11323/// If \p IsGNUIdiom is true, the operation is using the 'p = (i8*)nullptr + n'
11324/// idiom, which we recognize as a GNU extension.
11325///
11326static void diagnoseArithmeticOnNullPointer(Sema &S, SourceLocation Loc,
11327 Expr *Pointer, bool IsGNUIdiom) {
11328 if (IsGNUIdiom)
11329 S.Diag(Loc, DiagID: diag::warn_gnu_null_ptr_arith)
11330 << Pointer->getSourceRange();
11331 else
11332 S.Diag(Loc, DiagID: diag::warn_pointer_arith_null_ptr)
11333 << S.getLangOpts().CPlusPlus << Pointer->getSourceRange();
11334}
11335
11336/// Diagnose invalid subraction on a null pointer.
11337///
11338static void diagnoseSubtractionOnNullPointer(Sema &S, SourceLocation Loc,
11339 Expr *Pointer, bool BothNull) {
11340 // Null - null is valid in C++ [expr.add]p7
11341 if (BothNull && S.getLangOpts().CPlusPlus)
11342 return;
11343
11344 // Is this s a macro from a system header?
11345 if (S.Diags.getSuppressSystemWarnings() && S.SourceMgr.isInSystemMacro(loc: Loc))
11346 return;
11347
11348 S.DiagRuntimeBehavior(Loc, Statement: Pointer,
11349 PD: S.PDiag(DiagID: diag::warn_pointer_sub_null_ptr)
11350 << S.getLangOpts().CPlusPlus
11351 << Pointer->getSourceRange());
11352}
11353
11354/// Diagnose invalid arithmetic on two function pointers.
11355static void diagnoseArithmeticOnTwoFunctionPointers(Sema &S, SourceLocation Loc,
11356 Expr *LHS, Expr *RHS) {
11357 assert(LHS->getType()->isAnyPointerType());
11358 assert(RHS->getType()->isAnyPointerType());
11359 S.Diag(Loc, DiagID: S.getLangOpts().CPlusPlus
11360 ? diag::err_typecheck_pointer_arith_function_type
11361 : diag::ext_gnu_ptr_func_arith)
11362 << 1 /* two pointers */ << LHS->getType()->getPointeeType()
11363 // We only show the second type if it differs from the first.
11364 << (unsigned)!S.Context.hasSameUnqualifiedType(T1: LHS->getType(),
11365 T2: RHS->getType())
11366 << RHS->getType()->getPointeeType()
11367 << LHS->getSourceRange() << RHS->getSourceRange();
11368}
11369
11370/// Diagnose invalid arithmetic on a function pointer.
11371static void diagnoseArithmeticOnFunctionPointer(Sema &S, SourceLocation Loc,
11372 Expr *Pointer) {
11373 assert(Pointer->getType()->isAnyPointerType());
11374 S.Diag(Loc, DiagID: S.getLangOpts().CPlusPlus
11375 ? diag::err_typecheck_pointer_arith_function_type
11376 : diag::ext_gnu_ptr_func_arith)
11377 << 0 /* one pointer */ << Pointer->getType()->getPointeeType()
11378 << 0 /* one pointer, so only one type */
11379 << Pointer->getSourceRange();
11380}
11381
11382/// Emit error if Operand is incomplete pointer type
11383///
11384/// \returns True if pointer has incomplete type
11385static bool checkArithmeticIncompletePointerType(Sema &S, SourceLocation Loc,
11386 Expr *Operand) {
11387 QualType ResType = Operand->getType();
11388 if (const AtomicType *ResAtomicType = ResType->getAs<AtomicType>())
11389 ResType = ResAtomicType->getValueType();
11390
11391 assert(ResType->isAnyPointerType());
11392 QualType PointeeTy = ResType->getPointeeType();
11393 return S.RequireCompleteSizedType(
11394 Loc, T: PointeeTy,
11395 DiagID: diag::err_typecheck_arithmetic_incomplete_or_sizeless_type,
11396 Args: Operand->getSourceRange());
11397}
11398
11399/// Check the validity of an arithmetic pointer operand.
11400///
11401/// If the operand has pointer type, this code will check for pointer types
11402/// which are invalid in arithmetic operations. These will be diagnosed
11403/// appropriately, including whether or not the use is supported as an
11404/// extension.
11405///
11406/// \returns True when the operand is valid to use (even if as an extension).
11407static bool checkArithmeticOpPointerOperand(Sema &S, SourceLocation Loc,
11408 Expr *Operand) {
11409 QualType ResType = Operand->getType();
11410 if (const AtomicType *ResAtomicType = ResType->getAs<AtomicType>())
11411 ResType = ResAtomicType->getValueType();
11412
11413 if (!ResType->isAnyPointerType()) return true;
11414
11415 QualType PointeeTy = ResType->getPointeeType();
11416 if (PointeeTy->isVoidType()) {
11417 diagnoseArithmeticOnVoidPointer(S, Loc, Pointer: Operand);
11418 return !S.getLangOpts().CPlusPlus;
11419 }
11420 if (PointeeTy->isFunctionType()) {
11421 diagnoseArithmeticOnFunctionPointer(S, Loc, Pointer: Operand);
11422 return !S.getLangOpts().CPlusPlus;
11423 }
11424
11425 if (checkArithmeticIncompletePointerType(S, Loc, Operand)) return false;
11426
11427 return true;
11428}
11429
11430/// Check the validity of a binary arithmetic operation w.r.t. pointer
11431/// operands.
11432///
11433/// This routine will diagnose any invalid arithmetic on pointer operands much
11434/// like \see checkArithmeticOpPointerOperand. However, it has special logic
11435/// for emitting a single diagnostic even for operations where both LHS and RHS
11436/// are (potentially problematic) pointers.
11437///
11438/// \returns True when the operand is valid to use (even if as an extension).
11439static bool checkArithmeticBinOpPointerOperands(Sema &S, SourceLocation Loc,
11440 Expr *LHSExpr, Expr *RHSExpr) {
11441 bool isLHSPointer = LHSExpr->getType()->isAnyPointerType();
11442 bool isRHSPointer = RHSExpr->getType()->isAnyPointerType();
11443 if (!isLHSPointer && !isRHSPointer) return true;
11444
11445 QualType LHSPointeeTy, RHSPointeeTy;
11446 if (isLHSPointer) LHSPointeeTy = LHSExpr->getType()->getPointeeType();
11447 if (isRHSPointer) RHSPointeeTy = RHSExpr->getType()->getPointeeType();
11448
11449 // if both are pointers check if operation is valid wrt address spaces
11450 if (isLHSPointer && isRHSPointer) {
11451 if (!LHSPointeeTy.isAddressSpaceOverlapping(T: RHSPointeeTy,
11452 Ctx: S.getASTContext())) {
11453 S.Diag(Loc,
11454 DiagID: diag::err_typecheck_op_on_nonoverlapping_address_space_pointers)
11455 << LHSExpr->getType() << RHSExpr->getType() << 1 /*arithmetic op*/
11456 << LHSExpr->getSourceRange() << RHSExpr->getSourceRange();
11457 return false;
11458 }
11459 }
11460
11461 // Check for arithmetic on pointers to incomplete types.
11462 bool isLHSVoidPtr = isLHSPointer && LHSPointeeTy->isVoidType();
11463 bool isRHSVoidPtr = isRHSPointer && RHSPointeeTy->isVoidType();
11464 if (isLHSVoidPtr || isRHSVoidPtr) {
11465 if (!isRHSVoidPtr) diagnoseArithmeticOnVoidPointer(S, Loc, Pointer: LHSExpr);
11466 else if (!isLHSVoidPtr) diagnoseArithmeticOnVoidPointer(S, Loc, Pointer: RHSExpr);
11467 else diagnoseArithmeticOnTwoVoidPointers(S, Loc, LHSExpr, RHSExpr);
11468
11469 return !S.getLangOpts().CPlusPlus;
11470 }
11471
11472 bool isLHSFuncPtr = isLHSPointer && LHSPointeeTy->isFunctionType();
11473 bool isRHSFuncPtr = isRHSPointer && RHSPointeeTy->isFunctionType();
11474 if (isLHSFuncPtr || isRHSFuncPtr) {
11475 if (!isRHSFuncPtr) diagnoseArithmeticOnFunctionPointer(S, Loc, Pointer: LHSExpr);
11476 else if (!isLHSFuncPtr) diagnoseArithmeticOnFunctionPointer(S, Loc,
11477 Pointer: RHSExpr);
11478 else diagnoseArithmeticOnTwoFunctionPointers(S, Loc, LHS: LHSExpr, RHS: RHSExpr);
11479
11480 return !S.getLangOpts().CPlusPlus;
11481 }
11482
11483 if (isLHSPointer && checkArithmeticIncompletePointerType(S, Loc, Operand: LHSExpr))
11484 return false;
11485 if (isRHSPointer && checkArithmeticIncompletePointerType(S, Loc, Operand: RHSExpr))
11486 return false;
11487
11488 return true;
11489}
11490
11491/// diagnoseStringPlusInt - Emit a warning when adding an integer to a string
11492/// literal.
11493static void diagnoseStringPlusInt(Sema &Self, SourceLocation OpLoc,
11494 Expr *LHSExpr, Expr *RHSExpr) {
11495 StringLiteral* StrExpr = dyn_cast<StringLiteral>(Val: LHSExpr->IgnoreImpCasts());
11496 Expr* IndexExpr = RHSExpr;
11497 if (!StrExpr) {
11498 StrExpr = dyn_cast<StringLiteral>(Val: RHSExpr->IgnoreImpCasts());
11499 IndexExpr = LHSExpr;
11500 }
11501
11502 bool IsStringPlusInt = StrExpr &&
11503 IndexExpr->getType()->isIntegralOrUnscopedEnumerationType();
11504 if (!IsStringPlusInt || IndexExpr->isValueDependent())
11505 return;
11506
11507 SourceRange DiagRange(LHSExpr->getBeginLoc(), RHSExpr->getEndLoc());
11508 Self.Diag(Loc: OpLoc, DiagID: diag::warn_string_plus_int)
11509 << DiagRange << IndexExpr->IgnoreImpCasts()->getType();
11510
11511 // Only print a fixit for "str" + int, not for int + "str".
11512 if (IndexExpr == RHSExpr) {
11513 SourceLocation EndLoc = Self.getLocForEndOfToken(Loc: RHSExpr->getEndLoc());
11514 Self.Diag(Loc: OpLoc, DiagID: diag::note_string_plus_scalar_silence)
11515 << FixItHint::CreateInsertion(InsertionLoc: LHSExpr->getBeginLoc(), Code: "&")
11516 << FixItHint::CreateReplacement(RemoveRange: SourceRange(OpLoc), Code: "[")
11517 << FixItHint::CreateInsertion(InsertionLoc: EndLoc, Code: "]");
11518 } else
11519 Self.Diag(Loc: OpLoc, DiagID: diag::note_string_plus_scalar_silence);
11520}
11521
11522/// Emit a warning when adding a char literal to a string.
11523static void diagnoseStringPlusChar(Sema &Self, SourceLocation OpLoc,
11524 Expr *LHSExpr, Expr *RHSExpr) {
11525 const Expr *StringRefExpr = LHSExpr;
11526 const CharacterLiteral *CharExpr =
11527 dyn_cast<CharacterLiteral>(Val: RHSExpr->IgnoreImpCasts());
11528
11529 if (!CharExpr) {
11530 CharExpr = dyn_cast<CharacterLiteral>(Val: LHSExpr->IgnoreImpCasts());
11531 StringRefExpr = RHSExpr;
11532 }
11533
11534 if (!CharExpr || !StringRefExpr)
11535 return;
11536
11537 const QualType StringType = StringRefExpr->getType();
11538
11539 // Return if not a PointerType.
11540 if (!StringType->isAnyPointerType())
11541 return;
11542
11543 // Return if not a CharacterType.
11544 if (!StringType->getPointeeType()->isAnyCharacterType())
11545 return;
11546
11547 ASTContext &Ctx = Self.getASTContext();
11548 SourceRange DiagRange(LHSExpr->getBeginLoc(), RHSExpr->getEndLoc());
11549
11550 const QualType CharType = CharExpr->getType();
11551 if (!CharType->isAnyCharacterType() &&
11552 CharType->isIntegerType() &&
11553 llvm::isUIntN(N: Ctx.getCharWidth(), x: CharExpr->getValue())) {
11554 Self.Diag(Loc: OpLoc, DiagID: diag::warn_string_plus_char)
11555 << DiagRange << Ctx.CharTy;
11556 } else {
11557 Self.Diag(Loc: OpLoc, DiagID: diag::warn_string_plus_char)
11558 << DiagRange << CharExpr->getType();
11559 }
11560
11561 // Only print a fixit for str + char, not for char + str.
11562 if (isa<CharacterLiteral>(Val: RHSExpr->IgnoreImpCasts())) {
11563 SourceLocation EndLoc = Self.getLocForEndOfToken(Loc: RHSExpr->getEndLoc());
11564 Self.Diag(Loc: OpLoc, DiagID: diag::note_string_plus_scalar_silence)
11565 << FixItHint::CreateInsertion(InsertionLoc: LHSExpr->getBeginLoc(), Code: "&")
11566 << FixItHint::CreateReplacement(RemoveRange: SourceRange(OpLoc), Code: "[")
11567 << FixItHint::CreateInsertion(InsertionLoc: EndLoc, Code: "]");
11568 } else {
11569 Self.Diag(Loc: OpLoc, DiagID: diag::note_string_plus_scalar_silence);
11570 }
11571}
11572
11573/// Emit error when two pointers are incompatible.
11574static void diagnosePointerIncompatibility(Sema &S, SourceLocation Loc,
11575 Expr *LHSExpr, Expr *RHSExpr) {
11576 assert(LHSExpr->getType()->isAnyPointerType());
11577 assert(RHSExpr->getType()->isAnyPointerType());
11578 S.Diag(Loc, DiagID: diag::err_typecheck_sub_ptr_compatible)
11579 << LHSExpr->getType() << RHSExpr->getType() << LHSExpr->getSourceRange()
11580 << RHSExpr->getSourceRange();
11581}
11582
11583// C99 6.5.6
11584QualType Sema::CheckAdditionOperands(ExprResult &LHS, ExprResult &RHS,
11585 SourceLocation Loc, BinaryOperatorKind Opc,
11586 QualType* CompLHSTy) {
11587 checkArithmeticNull(S&: *this, LHS, RHS, Loc, /*IsCompare=*/false);
11588
11589 if (LHS.get()->getType()->isVectorType() ||
11590 RHS.get()->getType()->isVectorType()) {
11591 QualType compType =
11592 CheckVectorOperands(LHS, RHS, Loc, IsCompAssign: CompLHSTy,
11593 /*AllowBothBool*/ getLangOpts().AltiVec,
11594 /*AllowBoolConversions*/ getLangOpts().ZVector,
11595 /*AllowBooleanOperation*/ AllowBoolOperation: false,
11596 /*ReportInvalid*/ true);
11597 if (CompLHSTy) *CompLHSTy = compType;
11598 return compType;
11599 }
11600
11601 if (LHS.get()->getType()->isSveVLSBuiltinType() ||
11602 RHS.get()->getType()->isSveVLSBuiltinType()) {
11603 QualType compType = CheckSizelessVectorOperands(LHS, RHS, Loc, IsCompAssign: CompLHSTy,
11604 OperationKind: ArithConvKind::Arithmetic);
11605 if (CompLHSTy)
11606 *CompLHSTy = compType;
11607 return compType;
11608 }
11609
11610 if (LHS.get()->getType()->isConstantMatrixType() ||
11611 RHS.get()->getType()->isConstantMatrixType()) {
11612 QualType compType =
11613 CheckMatrixElementwiseOperands(LHS, RHS, Loc, IsCompAssign: CompLHSTy);
11614 if (CompLHSTy)
11615 *CompLHSTy = compType;
11616 return compType;
11617 }
11618
11619 QualType compType = UsualArithmeticConversions(
11620 LHS, RHS, Loc,
11621 ACK: CompLHSTy ? ArithConvKind::CompAssign : ArithConvKind::Arithmetic);
11622 if (LHS.isInvalid() || RHS.isInvalid())
11623 return QualType();
11624
11625 // Diagnose "string literal" '+' int and string '+' "char literal".
11626 if (Opc == BO_Add) {
11627 diagnoseStringPlusInt(Self&: *this, OpLoc: Loc, LHSExpr: LHS.get(), RHSExpr: RHS.get());
11628 diagnoseStringPlusChar(Self&: *this, OpLoc: Loc, LHSExpr: LHS.get(), RHSExpr: RHS.get());
11629 }
11630
11631 // handle the common case first (both operands are arithmetic).
11632 if (!compType.isNull() && compType->isArithmeticType()) {
11633 if (CompLHSTy) *CompLHSTy = compType;
11634 return compType;
11635 }
11636
11637 // Type-checking. Ultimately the pointer's going to be in PExp;
11638 // note that we bias towards the LHS being the pointer.
11639 Expr *PExp = LHS.get(), *IExp = RHS.get();
11640
11641 bool isObjCPointer;
11642 if (PExp->getType()->isPointerType()) {
11643 isObjCPointer = false;
11644 } else if (PExp->getType()->isObjCObjectPointerType()) {
11645 isObjCPointer = true;
11646 } else {
11647 std::swap(a&: PExp, b&: IExp);
11648 if (PExp->getType()->isPointerType()) {
11649 isObjCPointer = false;
11650 } else if (PExp->getType()->isObjCObjectPointerType()) {
11651 isObjCPointer = true;
11652 } else {
11653 QualType ResultTy = InvalidOperands(Loc, LHS, RHS);
11654 diagnoseScopedEnums(S&: *this, Loc, LHS, RHS, Opc);
11655 return ResultTy;
11656 }
11657 }
11658 assert(PExp->getType()->isAnyPointerType());
11659
11660 if (!IExp->getType()->isIntegerType())
11661 return InvalidOperands(Loc, LHS, RHS);
11662
11663 // Adding to a null pointer results in undefined behavior.
11664 if (PExp->IgnoreParenCasts()->isNullPointerConstant(
11665 Ctx&: Context, NPC: Expr::NPC_ValueDependentIsNotNull)) {
11666 // In C++ adding zero to a null pointer is defined.
11667 Expr::EvalResult KnownVal;
11668 if (!getLangOpts().CPlusPlus ||
11669 (!IExp->isValueDependent() &&
11670 (!IExp->EvaluateAsInt(Result&: KnownVal, Ctx: Context) ||
11671 KnownVal.Val.getInt() != 0))) {
11672 // Check the conditions to see if this is the 'p = nullptr + n' idiom.
11673 bool IsGNUIdiom = BinaryOperator::isNullPointerArithmeticExtension(
11674 Ctx&: Context, Opc: BO_Add, LHS: PExp, RHS: IExp);
11675 diagnoseArithmeticOnNullPointer(S&: *this, Loc, Pointer: PExp, IsGNUIdiom);
11676 }
11677 }
11678
11679 if (!checkArithmeticOpPointerOperand(S&: *this, Loc, Operand: PExp))
11680 return QualType();
11681
11682 if (isObjCPointer && checkArithmeticOnObjCPointer(S&: *this, opLoc: Loc, op: PExp))
11683 return QualType();
11684
11685 // Arithmetic on label addresses is normally allowed, except when we add
11686 // a ptrauth signature to the addresses.
11687 if (isa<AddrLabelExpr>(Val: PExp) && getLangOpts().PointerAuthIndirectGotos) {
11688 Diag(Loc, DiagID: diag::err_ptrauth_indirect_goto_addrlabel_arithmetic)
11689 << /*addition*/ 1;
11690 return QualType();
11691 }
11692
11693 // Check array bounds for pointer arithemtic
11694 CheckArrayAccess(BaseExpr: PExp, IndexExpr: IExp);
11695
11696 if (CompLHSTy) {
11697 QualType LHSTy = Context.isPromotableBitField(E: LHS.get());
11698 if (LHSTy.isNull()) {
11699 LHSTy = LHS.get()->getType();
11700 if (Context.isPromotableIntegerType(T: LHSTy))
11701 LHSTy = Context.getPromotedIntegerType(PromotableType: LHSTy);
11702 }
11703 *CompLHSTy = LHSTy;
11704 }
11705
11706 return PExp->getType();
11707}
11708
11709// C99 6.5.6
11710QualType Sema::CheckSubtractionOperands(ExprResult &LHS, ExprResult &RHS,
11711 SourceLocation Loc,
11712 BinaryOperatorKind Opc,
11713 QualType *CompLHSTy) {
11714 checkArithmeticNull(S&: *this, LHS, RHS, Loc, /*IsCompare=*/false);
11715
11716 if (LHS.get()->getType()->isVectorType() ||
11717 RHS.get()->getType()->isVectorType()) {
11718 QualType compType =
11719 CheckVectorOperands(LHS, RHS, Loc, IsCompAssign: CompLHSTy,
11720 /*AllowBothBool*/ getLangOpts().AltiVec,
11721 /*AllowBoolConversions*/ getLangOpts().ZVector,
11722 /*AllowBooleanOperation*/ AllowBoolOperation: false,
11723 /*ReportInvalid*/ true);
11724 if (CompLHSTy) *CompLHSTy = compType;
11725 return compType;
11726 }
11727
11728 if (LHS.get()->getType()->isSveVLSBuiltinType() ||
11729 RHS.get()->getType()->isSveVLSBuiltinType()) {
11730 QualType compType = CheckSizelessVectorOperands(LHS, RHS, Loc, IsCompAssign: CompLHSTy,
11731 OperationKind: ArithConvKind::Arithmetic);
11732 if (CompLHSTy)
11733 *CompLHSTy = compType;
11734 return compType;
11735 }
11736
11737 if (LHS.get()->getType()->isConstantMatrixType() ||
11738 RHS.get()->getType()->isConstantMatrixType()) {
11739 QualType compType =
11740 CheckMatrixElementwiseOperands(LHS, RHS, Loc, IsCompAssign: CompLHSTy);
11741 if (CompLHSTy)
11742 *CompLHSTy = compType;
11743 return compType;
11744 }
11745
11746 QualType compType = UsualArithmeticConversions(
11747 LHS, RHS, Loc,
11748 ACK: CompLHSTy ? ArithConvKind::CompAssign : ArithConvKind::Arithmetic);
11749 if (LHS.isInvalid() || RHS.isInvalid())
11750 return QualType();
11751
11752 // Enforce type constraints: C99 6.5.6p3.
11753
11754 // Handle the common case first (both operands are arithmetic).
11755 if (!compType.isNull() && compType->isArithmeticType()) {
11756 if (CompLHSTy) *CompLHSTy = compType;
11757 return compType;
11758 }
11759
11760 // Either ptr - int or ptr - ptr.
11761 if (LHS.get()->getType()->isAnyPointerType()) {
11762 QualType lpointee = LHS.get()->getType()->getPointeeType();
11763
11764 // Diagnose bad cases where we step over interface counts.
11765 if (LHS.get()->getType()->isObjCObjectPointerType() &&
11766 checkArithmeticOnObjCPointer(S&: *this, opLoc: Loc, op: LHS.get()))
11767 return QualType();
11768
11769 // Arithmetic on label addresses is normally allowed, except when we add
11770 // a ptrauth signature to the addresses.
11771 if (isa<AddrLabelExpr>(Val: LHS.get()) &&
11772 getLangOpts().PointerAuthIndirectGotos) {
11773 Diag(Loc, DiagID: diag::err_ptrauth_indirect_goto_addrlabel_arithmetic)
11774 << /*subtraction*/ 0;
11775 return QualType();
11776 }
11777
11778 // The result type of a pointer-int computation is the pointer type.
11779 if (RHS.get()->getType()->isIntegerType()) {
11780 // Subtracting from a null pointer should produce a warning.
11781 // The last argument to the diagnose call says this doesn't match the
11782 // GNU int-to-pointer idiom.
11783 if (LHS.get()->IgnoreParenCasts()->isNullPointerConstant(Ctx&: Context,
11784 NPC: Expr::NPC_ValueDependentIsNotNull)) {
11785 // In C++ adding zero to a null pointer is defined.
11786 Expr::EvalResult KnownVal;
11787 if (!getLangOpts().CPlusPlus ||
11788 (!RHS.get()->isValueDependent() &&
11789 (!RHS.get()->EvaluateAsInt(Result&: KnownVal, Ctx: Context) ||
11790 KnownVal.Val.getInt() != 0))) {
11791 diagnoseArithmeticOnNullPointer(S&: *this, Loc, Pointer: LHS.get(), IsGNUIdiom: false);
11792 }
11793 }
11794
11795 if (!checkArithmeticOpPointerOperand(S&: *this, Loc, Operand: LHS.get()))
11796 return QualType();
11797
11798 // Check array bounds for pointer arithemtic
11799 CheckArrayAccess(BaseExpr: LHS.get(), IndexExpr: RHS.get(), /*ArraySubscriptExpr*/ASE: nullptr,
11800 /*AllowOnePastEnd*/true, /*IndexNegated*/true);
11801
11802 if (CompLHSTy) *CompLHSTy = LHS.get()->getType();
11803 return LHS.get()->getType();
11804 }
11805
11806 // Handle pointer-pointer subtractions.
11807 if (const PointerType *RHSPTy
11808 = RHS.get()->getType()->getAs<PointerType>()) {
11809 QualType rpointee = RHSPTy->getPointeeType();
11810
11811 if (getLangOpts().CPlusPlus) {
11812 // Pointee types must be the same: C++ [expr.add]
11813 if (!Context.hasSameUnqualifiedType(T1: lpointee, T2: rpointee)) {
11814 diagnosePointerIncompatibility(S&: *this, Loc, LHSExpr: LHS.get(), RHSExpr: RHS.get());
11815 }
11816 } else {
11817 // Pointee types must be compatible C99 6.5.6p3
11818 if (!Context.typesAreCompatible(
11819 T1: Context.getCanonicalType(T: lpointee).getUnqualifiedType(),
11820 T2: Context.getCanonicalType(T: rpointee).getUnqualifiedType())) {
11821 diagnosePointerIncompatibility(S&: *this, Loc, LHSExpr: LHS.get(), RHSExpr: RHS.get());
11822 return QualType();
11823 }
11824 }
11825
11826 if (!checkArithmeticBinOpPointerOperands(S&: *this, Loc,
11827 LHSExpr: LHS.get(), RHSExpr: RHS.get()))
11828 return QualType();
11829
11830 bool LHSIsNullPtr = LHS.get()->IgnoreParenCasts()->isNullPointerConstant(
11831 Ctx&: Context, NPC: Expr::NPC_ValueDependentIsNotNull);
11832 bool RHSIsNullPtr = RHS.get()->IgnoreParenCasts()->isNullPointerConstant(
11833 Ctx&: Context, NPC: Expr::NPC_ValueDependentIsNotNull);
11834
11835 // Subtracting nullptr or from nullptr is suspect
11836 if (LHSIsNullPtr)
11837 diagnoseSubtractionOnNullPointer(S&: *this, Loc, Pointer: LHS.get(), BothNull: RHSIsNullPtr);
11838 if (RHSIsNullPtr)
11839 diagnoseSubtractionOnNullPointer(S&: *this, Loc, Pointer: RHS.get(), BothNull: LHSIsNullPtr);
11840
11841 // The pointee type may have zero size. As an extension, a structure or
11842 // union may have zero size or an array may have zero length. In this
11843 // case subtraction does not make sense.
11844 if (!rpointee->isVoidType() && !rpointee->isFunctionType()) {
11845 CharUnits ElementSize = Context.getTypeSizeInChars(T: rpointee);
11846 if (ElementSize.isZero()) {
11847 Diag(Loc,DiagID: diag::warn_sub_ptr_zero_size_types)
11848 << rpointee.getUnqualifiedType()
11849 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
11850 }
11851 }
11852
11853 if (CompLHSTy) *CompLHSTy = LHS.get()->getType();
11854 return Context.getPointerDiffType();
11855 }
11856 }
11857
11858 QualType ResultTy = InvalidOperands(Loc, LHS, RHS);
11859 diagnoseScopedEnums(S&: *this, Loc, LHS, RHS, Opc);
11860 return ResultTy;
11861}
11862
11863static bool isScopedEnumerationType(QualType T) {
11864 if (const EnumType *ET = T->getAsCanonical<EnumType>())
11865 return ET->getDecl()->isScoped();
11866 return false;
11867}
11868
11869static void DiagnoseBadShiftValues(Sema& S, ExprResult &LHS, ExprResult &RHS,
11870 SourceLocation Loc, BinaryOperatorKind Opc,
11871 QualType LHSType) {
11872 // OpenCL 6.3j: shift values are effectively % word size of LHS (more defined),
11873 // so skip remaining warnings as we don't want to modify values within Sema.
11874 if (S.getLangOpts().OpenCL)
11875 return;
11876
11877 if (Opc == BO_Shr &&
11878 LHS.get()->IgnoreParenImpCasts()->getType()->isBooleanType())
11879 S.Diag(Loc, DiagID: diag::warn_shift_bool) << LHS.get()->getSourceRange();
11880
11881 // Check right/shifter operand
11882 Expr::EvalResult RHSResult;
11883 if (RHS.get()->isValueDependent() ||
11884 !RHS.get()->EvaluateAsInt(Result&: RHSResult, Ctx: S.Context))
11885 return;
11886 llvm::APSInt Right = RHSResult.Val.getInt();
11887
11888 if (Right.isNegative()) {
11889 S.DiagRuntimeBehavior(Loc, Statement: RHS.get(),
11890 PD: S.PDiag(DiagID: diag::warn_shift_negative)
11891 << RHS.get()->getSourceRange());
11892 return;
11893 }
11894
11895 QualType LHSExprType = LHS.get()->getType();
11896 uint64_t LeftSize = S.Context.getTypeSize(T: LHSExprType);
11897 if (LHSExprType->isBitIntType())
11898 LeftSize = S.Context.getIntWidth(T: LHSExprType);
11899 else if (LHSExprType->isFixedPointType()) {
11900 auto FXSema = S.Context.getFixedPointSemantics(Ty: LHSExprType);
11901 LeftSize = FXSema.getWidth() - (unsigned)FXSema.hasUnsignedPadding();
11902 }
11903 if (Right.uge(RHS: LeftSize)) {
11904 S.DiagRuntimeBehavior(Loc, Statement: RHS.get(),
11905 PD: S.PDiag(DiagID: diag::warn_shift_gt_typewidth)
11906 << RHS.get()->getSourceRange());
11907 return;
11908 }
11909
11910 // FIXME: We probably need to handle fixed point types specially here.
11911 if (Opc != BO_Shl || LHSExprType->isFixedPointType())
11912 return;
11913
11914 // When left shifting an ICE which is signed, we can check for overflow which
11915 // according to C++ standards prior to C++2a has undefined behavior
11916 // ([expr.shift] 5.8/2). Unsigned integers have defined behavior modulo one
11917 // more than the maximum value representable in the result type, so never
11918 // warn for those. (FIXME: Unsigned left-shift overflow in a constant
11919 // expression is still probably a bug.)
11920 Expr::EvalResult LHSResult;
11921 if (LHS.get()->isValueDependent() ||
11922 LHSType->hasUnsignedIntegerRepresentation() ||
11923 !LHS.get()->EvaluateAsInt(Result&: LHSResult, Ctx: S.Context))
11924 return;
11925 llvm::APSInt Left = LHSResult.Val.getInt();
11926
11927 // Don't warn if signed overflow is defined, then all the rest of the
11928 // diagnostics will not be triggered because the behavior is defined.
11929 // Also don't warn in C++20 mode (and newer), as signed left shifts
11930 // always wrap and never overflow.
11931 if (S.getLangOpts().isSignedOverflowDefined() || S.getLangOpts().CPlusPlus20)
11932 return;
11933
11934 // If LHS does not have a non-negative value then, the
11935 // behavior is undefined before C++2a. Warn about it.
11936 if (Left.isNegative()) {
11937 S.DiagRuntimeBehavior(Loc, Statement: LHS.get(),
11938 PD: S.PDiag(DiagID: diag::warn_shift_lhs_negative)
11939 << LHS.get()->getSourceRange());
11940 return;
11941 }
11942
11943 llvm::APInt ResultBits =
11944 static_cast<llvm::APInt &>(Right) + Left.getSignificantBits();
11945 if (ResultBits.ule(RHS: LeftSize))
11946 return;
11947 llvm::APSInt Result = Left.extend(width: ResultBits.getLimitedValue());
11948 Result = Result.shl(ShiftAmt: Right);
11949
11950 // Print the bit representation of the signed integer as an unsigned
11951 // hexadecimal number.
11952 SmallString<40> HexResult;
11953 Result.toString(Str&: HexResult, Radix: 16, /*Signed =*/false, /*Literal =*/formatAsCLiteral: true);
11954
11955 // If we are only missing a sign bit, this is less likely to result in actual
11956 // bugs -- if the result is cast back to an unsigned type, it will have the
11957 // expected value. Thus we place this behind a different warning that can be
11958 // turned off separately if needed.
11959 if (ResultBits - 1 == LeftSize) {
11960 S.Diag(Loc, DiagID: diag::warn_shift_result_sets_sign_bit)
11961 << HexResult << LHSType
11962 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
11963 return;
11964 }
11965
11966 S.Diag(Loc, DiagID: diag::warn_shift_result_gt_typewidth)
11967 << HexResult.str() << Result.getSignificantBits() << LHSType
11968 << Left.getBitWidth() << LHS.get()->getSourceRange()
11969 << RHS.get()->getSourceRange();
11970}
11971
11972/// Return the resulting type when a vector is shifted
11973/// by a scalar or vector shift amount.
11974static QualType checkVectorShift(Sema &S, ExprResult &LHS, ExprResult &RHS,
11975 SourceLocation Loc, bool IsCompAssign) {
11976 // OpenCL v1.1 s6.3.j says RHS can be a vector only if LHS is a vector.
11977 if ((S.LangOpts.OpenCL || S.LangOpts.ZVector) &&
11978 !LHS.get()->getType()->isVectorType()) {
11979 S.Diag(Loc, DiagID: diag::err_shift_rhs_only_vector)
11980 << RHS.get()->getType() << LHS.get()->getType()
11981 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
11982 return QualType();
11983 }
11984
11985 if (!IsCompAssign) {
11986 LHS = S.UsualUnaryConversions(E: LHS.get());
11987 if (LHS.isInvalid()) return QualType();
11988 }
11989
11990 RHS = S.UsualUnaryConversions(E: RHS.get());
11991 if (RHS.isInvalid()) return QualType();
11992
11993 QualType LHSType = LHS.get()->getType();
11994 // Note that LHS might be a scalar because the routine calls not only in
11995 // OpenCL case.
11996 const VectorType *LHSVecTy = LHSType->getAs<VectorType>();
11997 QualType LHSEleType = LHSVecTy ? LHSVecTy->getElementType() : LHSType;
11998
11999 // Note that RHS might not be a vector.
12000 QualType RHSType = RHS.get()->getType();
12001 const VectorType *RHSVecTy = RHSType->getAs<VectorType>();
12002 QualType RHSEleType = RHSVecTy ? RHSVecTy->getElementType() : RHSType;
12003
12004 // Do not allow shifts for boolean vectors.
12005 if ((LHSVecTy && LHSVecTy->isExtVectorBoolType()) ||
12006 (RHSVecTy && RHSVecTy->isExtVectorBoolType())) {
12007 S.Diag(Loc, DiagID: diag::err_typecheck_invalid_operands)
12008 << LHS.get()->getType() << RHS.get()->getType()
12009 << LHS.get()->getSourceRange();
12010 return QualType();
12011 }
12012
12013 // The operands need to be integers.
12014 if (!LHSEleType->isIntegerType()) {
12015 S.Diag(Loc, DiagID: diag::err_typecheck_expect_int)
12016 << LHS.get()->getType() << LHS.get()->getSourceRange();
12017 return QualType();
12018 }
12019
12020 if (!RHSEleType->isIntegerType()) {
12021 S.Diag(Loc, DiagID: diag::err_typecheck_expect_int)
12022 << RHS.get()->getType() << RHS.get()->getSourceRange();
12023 return QualType();
12024 }
12025
12026 if (!LHSVecTy) {
12027 assert(RHSVecTy);
12028 if (IsCompAssign)
12029 return RHSType;
12030 if (LHSEleType != RHSEleType) {
12031 LHS = S.ImpCastExprToType(E: LHS.get(),Type: RHSEleType, CK: CK_IntegralCast);
12032 LHSEleType = RHSEleType;
12033 }
12034 QualType VecTy =
12035 S.Context.getExtVectorType(VectorType: LHSEleType, NumElts: RHSVecTy->getNumElements());
12036 LHS = S.ImpCastExprToType(E: LHS.get(), Type: VecTy, CK: CK_VectorSplat);
12037 LHSType = VecTy;
12038 } else if (RHSVecTy) {
12039 // OpenCL v1.1 s6.3.j says that for vector types, the operators
12040 // are applied component-wise. So if RHS is a vector, then ensure
12041 // that the number of elements is the same as LHS...
12042 if (RHSVecTy->getNumElements() != LHSVecTy->getNumElements()) {
12043 S.Diag(Loc, DiagID: diag::err_typecheck_vector_lengths_not_equal)
12044 << LHS.get()->getType() << RHS.get()->getType()
12045 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
12046 return QualType();
12047 }
12048 if (!S.LangOpts.OpenCL && !S.LangOpts.ZVector) {
12049 const BuiltinType *LHSBT = LHSEleType->getAs<clang::BuiltinType>();
12050 const BuiltinType *RHSBT = RHSEleType->getAs<clang::BuiltinType>();
12051 if (LHSBT != RHSBT &&
12052 S.Context.getTypeSize(T: LHSBT) != S.Context.getTypeSize(T: RHSBT)) {
12053 S.Diag(Loc, DiagID: diag::warn_typecheck_vector_element_sizes_not_equal)
12054 << LHS.get()->getType() << RHS.get()->getType()
12055 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
12056 }
12057 }
12058 } else {
12059 // ...else expand RHS to match the number of elements in LHS.
12060 QualType VecTy =
12061 S.Context.getExtVectorType(VectorType: RHSEleType, NumElts: LHSVecTy->getNumElements());
12062 RHS = S.ImpCastExprToType(E: RHS.get(), Type: VecTy, CK: CK_VectorSplat);
12063 }
12064
12065 return LHSType;
12066}
12067
12068static QualType checkSizelessVectorShift(Sema &S, ExprResult &LHS,
12069 ExprResult &RHS, SourceLocation Loc,
12070 bool IsCompAssign) {
12071 if (!IsCompAssign) {
12072 LHS = S.UsualUnaryConversions(E: LHS.get());
12073 if (LHS.isInvalid())
12074 return QualType();
12075 }
12076
12077 RHS = S.UsualUnaryConversions(E: RHS.get());
12078 if (RHS.isInvalid())
12079 return QualType();
12080
12081 QualType LHSType = LHS.get()->getType();
12082 const BuiltinType *LHSBuiltinTy = LHSType->castAs<BuiltinType>();
12083 QualType LHSEleType = LHSType->isSveVLSBuiltinType()
12084 ? LHSBuiltinTy->getSveEltType(Ctx: S.getASTContext())
12085 : LHSType;
12086
12087 // Note that RHS might not be a vector
12088 QualType RHSType = RHS.get()->getType();
12089 const BuiltinType *RHSBuiltinTy = RHSType->castAs<BuiltinType>();
12090 QualType RHSEleType = RHSType->isSveVLSBuiltinType()
12091 ? RHSBuiltinTy->getSveEltType(Ctx: S.getASTContext())
12092 : RHSType;
12093
12094 if ((LHSBuiltinTy && LHSBuiltinTy->isSVEBool()) ||
12095 (RHSBuiltinTy && RHSBuiltinTy->isSVEBool())) {
12096 S.Diag(Loc, DiagID: diag::err_typecheck_invalid_operands)
12097 << LHSType << RHSType << LHS.get()->getSourceRange();
12098 return QualType();
12099 }
12100
12101 if (!LHSEleType->isIntegerType()) {
12102 S.Diag(Loc, DiagID: diag::err_typecheck_expect_int)
12103 << LHS.get()->getType() << LHS.get()->getSourceRange();
12104 return QualType();
12105 }
12106
12107 if (!RHSEleType->isIntegerType()) {
12108 S.Diag(Loc, DiagID: diag::err_typecheck_expect_int)
12109 << RHS.get()->getType() << RHS.get()->getSourceRange();
12110 return QualType();
12111 }
12112
12113 if (LHSType->isSveVLSBuiltinType() && RHSType->isSveVLSBuiltinType() &&
12114 (S.Context.getBuiltinVectorTypeInfo(VecTy: LHSBuiltinTy).EC !=
12115 S.Context.getBuiltinVectorTypeInfo(VecTy: RHSBuiltinTy).EC)) {
12116 S.Diag(Loc, DiagID: diag::err_typecheck_invalid_operands)
12117 << LHSType << RHSType << LHS.get()->getSourceRange()
12118 << RHS.get()->getSourceRange();
12119 return QualType();
12120 }
12121
12122 if (!LHSType->isSveVLSBuiltinType()) {
12123 assert(RHSType->isSveVLSBuiltinType());
12124 if (IsCompAssign)
12125 return RHSType;
12126 if (LHSEleType != RHSEleType) {
12127 LHS = S.ImpCastExprToType(E: LHS.get(), Type: RHSEleType, CK: clang::CK_IntegralCast);
12128 LHSEleType = RHSEleType;
12129 }
12130 const llvm::ElementCount VecSize =
12131 S.Context.getBuiltinVectorTypeInfo(VecTy: RHSBuiltinTy).EC;
12132 QualType VecTy =
12133 S.Context.getScalableVectorType(EltTy: LHSEleType, NumElts: VecSize.getKnownMinValue());
12134 LHS = S.ImpCastExprToType(E: LHS.get(), Type: VecTy, CK: clang::CK_VectorSplat);
12135 LHSType = VecTy;
12136 } else if (RHSBuiltinTy && RHSBuiltinTy->isSveVLSBuiltinType()) {
12137 if (S.Context.getTypeSize(T: RHSBuiltinTy) !=
12138 S.Context.getTypeSize(T: LHSBuiltinTy)) {
12139 S.Diag(Loc, DiagID: diag::err_typecheck_vector_lengths_not_equal)
12140 << LHSType << RHSType << LHS.get()->getSourceRange()
12141 << RHS.get()->getSourceRange();
12142 return QualType();
12143 }
12144 } else {
12145 const llvm::ElementCount VecSize =
12146 S.Context.getBuiltinVectorTypeInfo(VecTy: LHSBuiltinTy).EC;
12147 if (LHSEleType != RHSEleType) {
12148 RHS = S.ImpCastExprToType(E: RHS.get(), Type: LHSEleType, CK: clang::CK_IntegralCast);
12149 RHSEleType = LHSEleType;
12150 }
12151 QualType VecTy =
12152 S.Context.getScalableVectorType(EltTy: RHSEleType, NumElts: VecSize.getKnownMinValue());
12153 RHS = S.ImpCastExprToType(E: RHS.get(), Type: VecTy, CK: CK_VectorSplat);
12154 }
12155
12156 return LHSType;
12157}
12158
12159// C99 6.5.7
12160QualType Sema::CheckShiftOperands(ExprResult &LHS, ExprResult &RHS,
12161 SourceLocation Loc, BinaryOperatorKind Opc,
12162 bool IsCompAssign) {
12163 checkArithmeticNull(S&: *this, LHS, RHS, Loc, /*IsCompare=*/false);
12164
12165 // Vector shifts promote their scalar inputs to vector type.
12166 if (LHS.get()->getType()->isVectorType() ||
12167 RHS.get()->getType()->isVectorType()) {
12168 if (LangOpts.ZVector) {
12169 // The shift operators for the z vector extensions work basically
12170 // like general shifts, except that neither the LHS nor the RHS is
12171 // allowed to be a "vector bool".
12172 if (auto LHSVecType = LHS.get()->getType()->getAs<VectorType>())
12173 if (LHSVecType->getVectorKind() == VectorKind::AltiVecBool)
12174 return InvalidOperands(Loc, LHS, RHS);
12175 if (auto RHSVecType = RHS.get()->getType()->getAs<VectorType>())
12176 if (RHSVecType->getVectorKind() == VectorKind::AltiVecBool)
12177 return InvalidOperands(Loc, LHS, RHS);
12178 }
12179 return checkVectorShift(S&: *this, LHS, RHS, Loc, IsCompAssign);
12180 }
12181
12182 if (LHS.get()->getType()->isSveVLSBuiltinType() ||
12183 RHS.get()->getType()->isSveVLSBuiltinType())
12184 return checkSizelessVectorShift(S&: *this, LHS, RHS, Loc, IsCompAssign);
12185
12186 // Shifts don't perform usual arithmetic conversions, they just do integer
12187 // promotions on each operand. C99 6.5.7p3
12188
12189 // For the LHS, do usual unary conversions, but then reset them away
12190 // if this is a compound assignment.
12191 ExprResult OldLHS = LHS;
12192 LHS = UsualUnaryConversions(E: LHS.get());
12193 if (LHS.isInvalid())
12194 return QualType();
12195 QualType LHSType = LHS.get()->getType();
12196 if (IsCompAssign) LHS = OldLHS;
12197
12198 // The RHS is simpler.
12199 RHS = UsualUnaryConversions(E: RHS.get());
12200 if (RHS.isInvalid())
12201 return QualType();
12202 QualType RHSType = RHS.get()->getType();
12203
12204 // C99 6.5.7p2: Each of the operands shall have integer type.
12205 // Embedded-C 4.1.6.2.2: The LHS may also be fixed-point.
12206 if ((!LHSType->isFixedPointOrIntegerType() &&
12207 !LHSType->hasIntegerRepresentation()) ||
12208 !RHSType->hasIntegerRepresentation()) {
12209 QualType ResultTy = InvalidOperands(Loc, LHS, RHS);
12210 diagnoseScopedEnums(S&: *this, Loc, LHS, RHS, Opc);
12211 return ResultTy;
12212 }
12213
12214 DiagnoseBadShiftValues(S&: *this, LHS, RHS, Loc, Opc, LHSType);
12215
12216 // "The type of the result is that of the promoted left operand."
12217 return LHSType;
12218}
12219
12220/// Diagnose bad pointer comparisons.
12221static void diagnoseDistinctPointerComparison(Sema &S, SourceLocation Loc,
12222 ExprResult &LHS, ExprResult &RHS,
12223 bool IsError) {
12224 S.Diag(Loc, DiagID: IsError ? diag::err_typecheck_comparison_of_distinct_pointers
12225 : diag::ext_typecheck_comparison_of_distinct_pointers)
12226 << LHS.get()->getType() << RHS.get()->getType()
12227 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
12228}
12229
12230/// Returns false if the pointers are converted to a composite type,
12231/// true otherwise.
12232static bool convertPointersToCompositeType(Sema &S, SourceLocation Loc,
12233 ExprResult &LHS, ExprResult &RHS) {
12234 // C++ [expr.rel]p2:
12235 // [...] Pointer conversions (4.10) and qualification
12236 // conversions (4.4) are performed on pointer operands (or on
12237 // a pointer operand and a null pointer constant) to bring
12238 // them to their composite pointer type. [...]
12239 //
12240 // C++ [expr.eq]p1 uses the same notion for (in)equality
12241 // comparisons of pointers.
12242
12243 QualType LHSType = LHS.get()->getType();
12244 QualType RHSType = RHS.get()->getType();
12245 assert(LHSType->isPointerType() || RHSType->isPointerType() ||
12246 LHSType->isMemberPointerType() || RHSType->isMemberPointerType());
12247
12248 QualType T = S.FindCompositePointerType(Loc, E1&: LHS, E2&: RHS);
12249 if (T.isNull()) {
12250 if ((LHSType->isAnyPointerType() || LHSType->isMemberPointerType()) &&
12251 (RHSType->isAnyPointerType() || RHSType->isMemberPointerType()))
12252 diagnoseDistinctPointerComparison(S, Loc, LHS, RHS, /*isError*/IsError: true);
12253 else
12254 S.InvalidOperands(Loc, LHS, RHS);
12255 return true;
12256 }
12257
12258 return false;
12259}
12260
12261static void diagnoseFunctionPointerToVoidComparison(Sema &S, SourceLocation Loc,
12262 ExprResult &LHS,
12263 ExprResult &RHS,
12264 bool IsError) {
12265 S.Diag(Loc, DiagID: IsError ? diag::err_typecheck_comparison_of_fptr_to_void
12266 : diag::ext_typecheck_comparison_of_fptr_to_void)
12267 << LHS.get()->getType() << RHS.get()->getType()
12268 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
12269}
12270
12271static bool isObjCObjectLiteral(ExprResult &E) {
12272 switch (E.get()->IgnoreParenImpCasts()->getStmtClass()) {
12273 case Stmt::ObjCArrayLiteralClass:
12274 case Stmt::ObjCDictionaryLiteralClass:
12275 case Stmt::ObjCStringLiteralClass:
12276 case Stmt::ObjCBoxedExprClass:
12277 return true;
12278 default:
12279 // Note that ObjCBoolLiteral is NOT an object literal!
12280 return false;
12281 }
12282}
12283
12284static bool hasIsEqualMethod(Sema &S, const Expr *LHS, const Expr *RHS) {
12285 const ObjCObjectPointerType *Type =
12286 LHS->getType()->getAs<ObjCObjectPointerType>();
12287
12288 // If this is not actually an Objective-C object, bail out.
12289 if (!Type)
12290 return false;
12291
12292 // Get the LHS object's interface type.
12293 QualType InterfaceType = Type->getPointeeType();
12294
12295 // If the RHS isn't an Objective-C object, bail out.
12296 if (!RHS->getType()->isObjCObjectPointerType())
12297 return false;
12298
12299 // Try to find the -isEqual: method.
12300 Selector IsEqualSel = S.ObjC().NSAPIObj->getIsEqualSelector();
12301 ObjCMethodDecl *Method =
12302 S.ObjC().LookupMethodInObjectType(Sel: IsEqualSel, Ty: InterfaceType,
12303 /*IsInstance=*/true);
12304 if (!Method) {
12305 if (Type->isObjCIdType()) {
12306 // For 'id', just check the global pool.
12307 Method =
12308 S.ObjC().LookupInstanceMethodInGlobalPool(Sel: IsEqualSel, R: SourceRange(),
12309 /*receiverId=*/receiverIdOrClass: true);
12310 } else {
12311 // Check protocols.
12312 Method = S.ObjC().LookupMethodInQualifiedType(Sel: IsEqualSel, OPT: Type,
12313 /*IsInstance=*/true);
12314 }
12315 }
12316
12317 if (!Method)
12318 return false;
12319
12320 QualType T = Method->parameters()[0]->getType();
12321 if (!T->isObjCObjectPointerType())
12322 return false;
12323
12324 QualType R = Method->getReturnType();
12325 if (!R->isScalarType())
12326 return false;
12327
12328 return true;
12329}
12330
12331static void diagnoseObjCLiteralComparison(Sema &S, SourceLocation Loc,
12332 ExprResult &LHS, ExprResult &RHS,
12333 BinaryOperator::Opcode Opc){
12334 Expr *Literal;
12335 Expr *Other;
12336 if (isObjCObjectLiteral(E&: LHS)) {
12337 Literal = LHS.get();
12338 Other = RHS.get();
12339 } else {
12340 Literal = RHS.get();
12341 Other = LHS.get();
12342 }
12343
12344 // Don't warn on comparisons against nil.
12345 Other = Other->IgnoreParenCasts();
12346 if (Other->isNullPointerConstant(Ctx&: S.getASTContext(),
12347 NPC: Expr::NPC_ValueDependentIsNotNull))
12348 return;
12349
12350 // This should be kept in sync with warn_objc_literal_comparison.
12351 // LK_String should always be after the other literals, since it has its own
12352 // warning flag.
12353 SemaObjC::ObjCLiteralKind LiteralKind = S.ObjC().CheckLiteralKind(FromE: Literal);
12354 assert(LiteralKind != SemaObjC::LK_Block);
12355 if (LiteralKind == SemaObjC::LK_None) {
12356 llvm_unreachable("Unknown Objective-C object literal kind");
12357 }
12358
12359 if (LiteralKind == SemaObjC::LK_String)
12360 S.Diag(Loc, DiagID: diag::warn_objc_string_literal_comparison)
12361 << Literal->getSourceRange();
12362 else
12363 S.Diag(Loc, DiagID: diag::warn_objc_literal_comparison)
12364 << LiteralKind << Literal->getSourceRange();
12365
12366 if (BinaryOperator::isEqualityOp(Opc) &&
12367 hasIsEqualMethod(S, LHS: LHS.get(), RHS: RHS.get())) {
12368 SourceLocation Start = LHS.get()->getBeginLoc();
12369 SourceLocation End = S.getLocForEndOfToken(Loc: RHS.get()->getEndLoc());
12370 CharSourceRange OpRange =
12371 CharSourceRange::getCharRange(B: Loc, E: S.getLocForEndOfToken(Loc));
12372
12373 S.Diag(Loc, DiagID: diag::note_objc_literal_comparison_isequal)
12374 << FixItHint::CreateInsertion(InsertionLoc: Start, Code: Opc == BO_EQ ? "[" : "![")
12375 << FixItHint::CreateReplacement(RemoveRange: OpRange, Code: " isEqual:")
12376 << FixItHint::CreateInsertion(InsertionLoc: End, Code: "]");
12377 }
12378}
12379
12380/// Warns on !x < y, !x & y where !(x < y), !(x & y) was probably intended.
12381static void diagnoseLogicalNotOnLHSofCheck(Sema &S, ExprResult &LHS,
12382 ExprResult &RHS, SourceLocation Loc,
12383 BinaryOperatorKind Opc) {
12384 // Check that left hand side is !something.
12385 UnaryOperator *UO = dyn_cast<UnaryOperator>(Val: LHS.get()->IgnoreImpCasts());
12386 if (!UO || UO->getOpcode() != UO_LNot) return;
12387
12388 // Only check if the right hand side is non-bool arithmetic type.
12389 if (RHS.get()->isKnownToHaveBooleanValue()) return;
12390
12391 // Make sure that the something in !something is not bool.
12392 Expr *SubExpr = UO->getSubExpr()->IgnoreImpCasts();
12393 if (SubExpr->isKnownToHaveBooleanValue()) return;
12394
12395 // Emit warning.
12396 bool IsBitwiseOp = Opc == BO_And || Opc == BO_Or || Opc == BO_Xor;
12397 S.Diag(Loc: UO->getOperatorLoc(), DiagID: diag::warn_logical_not_on_lhs_of_check)
12398 << Loc << IsBitwiseOp;
12399
12400 // First note suggest !(x < y)
12401 SourceLocation FirstOpen = SubExpr->getBeginLoc();
12402 SourceLocation FirstClose = RHS.get()->getEndLoc();
12403 FirstClose = S.getLocForEndOfToken(Loc: FirstClose);
12404 if (FirstClose.isInvalid())
12405 FirstOpen = SourceLocation();
12406 S.Diag(Loc: UO->getOperatorLoc(), DiagID: diag::note_logical_not_fix)
12407 << IsBitwiseOp
12408 << FixItHint::CreateInsertion(InsertionLoc: FirstOpen, Code: "(")
12409 << FixItHint::CreateInsertion(InsertionLoc: FirstClose, Code: ")");
12410
12411 // Second note suggests (!x) < y
12412 SourceLocation SecondOpen = LHS.get()->getBeginLoc();
12413 SourceLocation SecondClose = LHS.get()->getEndLoc();
12414 SecondClose = S.getLocForEndOfToken(Loc: SecondClose);
12415 if (SecondClose.isInvalid())
12416 SecondOpen = SourceLocation();
12417 S.Diag(Loc: UO->getOperatorLoc(), DiagID: diag::note_logical_not_silence_with_parens)
12418 << FixItHint::CreateInsertion(InsertionLoc: SecondOpen, Code: "(")
12419 << FixItHint::CreateInsertion(InsertionLoc: SecondClose, Code: ")");
12420}
12421
12422// Returns true if E refers to a non-weak array.
12423static bool checkForArray(const Expr *E) {
12424 const ValueDecl *D = nullptr;
12425 if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Val: E)) {
12426 D = DR->getDecl();
12427 } else if (const MemberExpr *Mem = dyn_cast<MemberExpr>(Val: E)) {
12428 if (Mem->isImplicitAccess())
12429 D = Mem->getMemberDecl();
12430 }
12431 if (!D)
12432 return false;
12433 return D->getType()->isArrayType() && !D->isWeak();
12434}
12435
12436/// Detect patterns ptr + size >= ptr and ptr + size < ptr, where ptr is a
12437/// pointer and size is an unsigned integer. Return whether the result is
12438/// always true/false.
12439static std::optional<bool> isTautologicalBoundsCheck(Sema &S, const Expr *LHS,
12440 const Expr *RHS,
12441 BinaryOperatorKind Opc) {
12442 if (!LHS->getType()->isPointerType() ||
12443 S.getLangOpts().PointerOverflowDefined)
12444 return std::nullopt;
12445
12446 // Canonicalize to >= or < predicate.
12447 switch (Opc) {
12448 case BO_GE:
12449 case BO_LT:
12450 break;
12451 case BO_GT:
12452 std::swap(a&: LHS, b&: RHS);
12453 Opc = BO_LT;
12454 break;
12455 case BO_LE:
12456 std::swap(a&: LHS, b&: RHS);
12457 Opc = BO_GE;
12458 break;
12459 default:
12460 return std::nullopt;
12461 }
12462
12463 auto *BO = dyn_cast<BinaryOperator>(Val: LHS);
12464 if (!BO || BO->getOpcode() != BO_Add)
12465 return std::nullopt;
12466
12467 Expr *Other;
12468 if (Expr::isSameComparisonOperand(E1: BO->getLHS(), E2: RHS))
12469 Other = BO->getRHS();
12470 else if (Expr::isSameComparisonOperand(E1: BO->getRHS(), E2: RHS))
12471 Other = BO->getLHS();
12472 else
12473 return std::nullopt;
12474
12475 if (!Other->getType()->isUnsignedIntegerType())
12476 return std::nullopt;
12477
12478 return Opc == BO_GE;
12479}
12480
12481/// Diagnose some forms of syntactically-obvious tautological comparison.
12482static void diagnoseTautologicalComparison(Sema &S, SourceLocation Loc,
12483 Expr *LHS, Expr *RHS,
12484 BinaryOperatorKind Opc) {
12485 Expr *LHSStripped = LHS->IgnoreParenImpCasts();
12486 Expr *RHSStripped = RHS->IgnoreParenImpCasts();
12487
12488 QualType LHSType = LHS->getType();
12489 QualType RHSType = RHS->getType();
12490 if (LHSType->hasFloatingRepresentation() ||
12491 (LHSType->isBlockPointerType() && !BinaryOperator::isEqualityOp(Opc)) ||
12492 S.inTemplateInstantiation())
12493 return;
12494
12495 // WebAssembly Tables cannot be compared, therefore shouldn't emit
12496 // Tautological diagnostics.
12497 if (LHSType->isWebAssemblyTableType() || RHSType->isWebAssemblyTableType())
12498 return;
12499
12500 // Comparisons between two array types are ill-formed for operator<=>, so
12501 // we shouldn't emit any additional warnings about it.
12502 if (Opc == BO_Cmp && LHSType->isArrayType() && RHSType->isArrayType())
12503 return;
12504
12505 // For non-floating point types, check for self-comparisons of the form
12506 // x == x, x != x, x < x, etc. These always evaluate to a constant, and
12507 // often indicate logic errors in the program.
12508 //
12509 // NOTE: Don't warn about comparison expressions resulting from macro
12510 // expansion. Also don't warn about comparisons which are only self
12511 // comparisons within a template instantiation. The warnings should catch
12512 // obvious cases in the definition of the template anyways. The idea is to
12513 // warn when the typed comparison operator will always evaluate to the same
12514 // result.
12515
12516 // Used for indexing into %select in warn_comparison_always
12517 enum {
12518 AlwaysConstant,
12519 AlwaysTrue,
12520 AlwaysFalse,
12521 AlwaysEqual, // std::strong_ordering::equal from operator<=>
12522 };
12523
12524 // C++1a [array.comp]:
12525 // Equality and relational comparisons ([expr.eq], [expr.rel]) between two
12526 // operands of array type.
12527 // C++2a [depr.array.comp]:
12528 // Equality and relational comparisons ([expr.eq], [expr.rel]) between two
12529 // operands of array type are deprecated.
12530 if (S.getLangOpts().CPlusPlus && LHSStripped->getType()->isArrayType() &&
12531 RHSStripped->getType()->isArrayType()) {
12532 auto IsDeprArrayComparionIgnored =
12533 S.getDiagnostics().isIgnored(DiagID: diag::warn_depr_array_comparison, Loc);
12534 auto DiagID = S.getLangOpts().CPlusPlus26
12535 ? diag::warn_array_comparison_cxx26
12536 : !S.getLangOpts().CPlusPlus20 || IsDeprArrayComparionIgnored
12537 ? diag::warn_array_comparison
12538 : diag::warn_depr_array_comparison;
12539 S.Diag(Loc, DiagID) << LHS->getSourceRange() << RHS->getSourceRange()
12540 << LHSStripped->getType() << RHSStripped->getType();
12541 // Carry on to produce the tautological comparison warning, if this
12542 // expression is potentially-evaluated, we can resolve the array to a
12543 // non-weak declaration, and so on.
12544 }
12545
12546 if (!LHS->getBeginLoc().isMacroID() && !RHS->getBeginLoc().isMacroID()) {
12547 if (Expr::isSameComparisonOperand(E1: LHS, E2: RHS)) {
12548 unsigned Result;
12549 switch (Opc) {
12550 case BO_EQ:
12551 case BO_LE:
12552 case BO_GE:
12553 Result = AlwaysTrue;
12554 break;
12555 case BO_NE:
12556 case BO_LT:
12557 case BO_GT:
12558 Result = AlwaysFalse;
12559 break;
12560 case BO_Cmp:
12561 Result = AlwaysEqual;
12562 break;
12563 default:
12564 Result = AlwaysConstant;
12565 break;
12566 }
12567 S.DiagRuntimeBehavior(Loc, Statement: nullptr,
12568 PD: S.PDiag(DiagID: diag::warn_comparison_always)
12569 << 0 /*self-comparison*/
12570 << Result);
12571 } else if (checkForArray(E: LHSStripped) && checkForArray(E: RHSStripped)) {
12572 // What is it always going to evaluate to?
12573 unsigned Result;
12574 switch (Opc) {
12575 case BO_EQ: // e.g. array1 == array2
12576 Result = AlwaysFalse;
12577 break;
12578 case BO_NE: // e.g. array1 != array2
12579 Result = AlwaysTrue;
12580 break;
12581 default: // e.g. array1 <= array2
12582 // The best we can say is 'a constant'
12583 Result = AlwaysConstant;
12584 break;
12585 }
12586 S.DiagRuntimeBehavior(Loc, Statement: nullptr,
12587 PD: S.PDiag(DiagID: diag::warn_comparison_always)
12588 << 1 /*array comparison*/
12589 << Result);
12590 } else if (std::optional<bool> Res =
12591 isTautologicalBoundsCheck(S, LHS, RHS, Opc)) {
12592 S.DiagRuntimeBehavior(Loc, Statement: nullptr,
12593 PD: S.PDiag(DiagID: diag::warn_comparison_always)
12594 << 2 /*pointer comparison*/
12595 << (*Res ? AlwaysTrue : AlwaysFalse));
12596 }
12597 }
12598
12599 if (isa<CastExpr>(Val: LHSStripped))
12600 LHSStripped = LHSStripped->IgnoreParenCasts();
12601 if (isa<CastExpr>(Val: RHSStripped))
12602 RHSStripped = RHSStripped->IgnoreParenCasts();
12603
12604 // Warn about comparisons against a string constant (unless the other
12605 // operand is null); the user probably wants string comparison function.
12606 Expr *LiteralString = nullptr;
12607 Expr *LiteralStringStripped = nullptr;
12608 if ((isa<StringLiteral>(Val: LHSStripped) || isa<ObjCEncodeExpr>(Val: LHSStripped)) &&
12609 !RHSStripped->isNullPointerConstant(Ctx&: S.Context,
12610 NPC: Expr::NPC_ValueDependentIsNull)) {
12611 LiteralString = LHS;
12612 LiteralStringStripped = LHSStripped;
12613 } else if ((isa<StringLiteral>(Val: RHSStripped) ||
12614 isa<ObjCEncodeExpr>(Val: RHSStripped)) &&
12615 !LHSStripped->isNullPointerConstant(Ctx&: S.Context,
12616 NPC: Expr::NPC_ValueDependentIsNull)) {
12617 LiteralString = RHS;
12618 LiteralStringStripped = RHSStripped;
12619 }
12620
12621 if (LiteralString) {
12622 S.DiagRuntimeBehavior(Loc, Statement: nullptr,
12623 PD: S.PDiag(DiagID: diag::warn_stringcompare)
12624 << isa<ObjCEncodeExpr>(Val: LiteralStringStripped)
12625 << LiteralString->getSourceRange());
12626 }
12627}
12628
12629static ImplicitConversionKind castKindToImplicitConversionKind(CastKind CK) {
12630 switch (CK) {
12631 default: {
12632#ifndef NDEBUG
12633 llvm::errs() << "unhandled cast kind: " << CastExpr::getCastKindName(CK)
12634 << "\n";
12635#endif
12636 llvm_unreachable("unhandled cast kind");
12637 }
12638 case CK_UserDefinedConversion:
12639 return ICK_Identity;
12640 case CK_LValueToRValue:
12641 return ICK_Lvalue_To_Rvalue;
12642 case CK_ArrayToPointerDecay:
12643 return ICK_Array_To_Pointer;
12644 case CK_FunctionToPointerDecay:
12645 return ICK_Function_To_Pointer;
12646 case CK_IntegralCast:
12647 return ICK_Integral_Conversion;
12648 case CK_FloatingCast:
12649 return ICK_Floating_Conversion;
12650 case CK_IntegralToFloating:
12651 case CK_FloatingToIntegral:
12652 return ICK_Floating_Integral;
12653 case CK_IntegralComplexCast:
12654 case CK_FloatingComplexCast:
12655 case CK_FloatingComplexToIntegralComplex:
12656 case CK_IntegralComplexToFloatingComplex:
12657 return ICK_Complex_Conversion;
12658 case CK_FloatingComplexToReal:
12659 case CK_FloatingRealToComplex:
12660 case CK_IntegralComplexToReal:
12661 case CK_IntegralRealToComplex:
12662 return ICK_Complex_Real;
12663 case CK_HLSLArrayRValue:
12664 return ICK_HLSL_Array_RValue;
12665 }
12666}
12667
12668static bool checkThreeWayNarrowingConversion(Sema &S, QualType ToType, Expr *E,
12669 QualType FromType,
12670 SourceLocation Loc) {
12671 // Check for a narrowing implicit conversion.
12672 StandardConversionSequence SCS;
12673 SCS.setAsIdentityConversion();
12674 SCS.setToType(Idx: 0, T: FromType);
12675 SCS.setToType(Idx: 1, T: ToType);
12676 if (const auto *ICE = dyn_cast<ImplicitCastExpr>(Val: E))
12677 SCS.Second = castKindToImplicitConversionKind(CK: ICE->getCastKind());
12678
12679 APValue PreNarrowingValue;
12680 QualType PreNarrowingType;
12681 switch (SCS.getNarrowingKind(Context&: S.Context, Converted: E, ConstantValue&: PreNarrowingValue,
12682 ConstantType&: PreNarrowingType,
12683 /*IgnoreFloatToIntegralConversion*/ true)) {
12684 case NK_Dependent_Narrowing:
12685 // Implicit conversion to a narrower type, but the expression is
12686 // value-dependent so we can't tell whether it's actually narrowing.
12687 case NK_Not_Narrowing:
12688 return false;
12689
12690 case NK_Constant_Narrowing:
12691 // Implicit conversion to a narrower type, and the value is not a constant
12692 // expression.
12693 S.Diag(Loc: E->getBeginLoc(), DiagID: diag::err_spaceship_argument_narrowing)
12694 << /*Constant*/ 1
12695 << PreNarrowingValue.getAsString(Ctx: S.Context, Ty: PreNarrowingType) << ToType;
12696 return true;
12697
12698 case NK_Variable_Narrowing:
12699 // Implicit conversion to a narrower type, and the value is not a constant
12700 // expression.
12701 case NK_Type_Narrowing:
12702 S.Diag(Loc: E->getBeginLoc(), DiagID: diag::err_spaceship_argument_narrowing)
12703 << /*Constant*/ 0 << FromType << ToType;
12704 // TODO: It's not a constant expression, but what if the user intended it
12705 // to be? Can we produce notes to help them figure out why it isn't?
12706 return true;
12707 }
12708 llvm_unreachable("unhandled case in switch");
12709}
12710
12711static QualType checkArithmeticOrEnumeralThreeWayCompare(Sema &S,
12712 ExprResult &LHS,
12713 ExprResult &RHS,
12714 SourceLocation Loc) {
12715 QualType LHSType = LHS.get()->getType();
12716 QualType RHSType = RHS.get()->getType();
12717 // Dig out the original argument type and expression before implicit casts
12718 // were applied. These are the types/expressions we need to check the
12719 // [expr.spaceship] requirements against.
12720 ExprResult LHSStripped = LHS.get()->IgnoreParenImpCasts();
12721 ExprResult RHSStripped = RHS.get()->IgnoreParenImpCasts();
12722 QualType LHSStrippedType = LHSStripped.get()->getType();
12723 QualType RHSStrippedType = RHSStripped.get()->getType();
12724
12725 // C++2a [expr.spaceship]p3: If one of the operands is of type bool and the
12726 // other is not, the program is ill-formed.
12727 if (LHSStrippedType->isBooleanType() != RHSStrippedType->isBooleanType()) {
12728 S.InvalidOperands(Loc, LHS&: LHSStripped, RHS&: RHSStripped);
12729 return QualType();
12730 }
12731
12732 // FIXME: Consider combining this with checkEnumArithmeticConversions.
12733 int NumEnumArgs = (int)LHSStrippedType->isEnumeralType() +
12734 RHSStrippedType->isEnumeralType();
12735 if (NumEnumArgs == 1) {
12736 bool LHSIsEnum = LHSStrippedType->isEnumeralType();
12737 QualType OtherTy = LHSIsEnum ? RHSStrippedType : LHSStrippedType;
12738 if (OtherTy->hasFloatingRepresentation()) {
12739 S.InvalidOperands(Loc, LHS&: LHSStripped, RHS&: RHSStripped);
12740 return QualType();
12741 }
12742 }
12743 if (NumEnumArgs == 2) {
12744 // C++2a [expr.spaceship]p5: If both operands have the same enumeration
12745 // type E, the operator yields the result of converting the operands
12746 // to the underlying type of E and applying <=> to the converted operands.
12747 if (!S.Context.hasSameUnqualifiedType(T1: LHSStrippedType, T2: RHSStrippedType)) {
12748 S.InvalidOperands(Loc, LHS, RHS);
12749 return QualType();
12750 }
12751 QualType IntType = LHSStrippedType->castAsEnumDecl()->getIntegerType();
12752 assert(IntType->isArithmeticType());
12753
12754 // We can't use `CK_IntegralCast` when the underlying type is 'bool', so we
12755 // promote the boolean type, and all other promotable integer types, to
12756 // avoid this.
12757 if (S.Context.isPromotableIntegerType(T: IntType))
12758 IntType = S.Context.getPromotedIntegerType(PromotableType: IntType);
12759
12760 LHS = S.ImpCastExprToType(E: LHS.get(), Type: IntType, CK: CK_IntegralCast);
12761 RHS = S.ImpCastExprToType(E: RHS.get(), Type: IntType, CK: CK_IntegralCast);
12762 LHSType = RHSType = IntType;
12763 }
12764
12765 // C++2a [expr.spaceship]p4: If both operands have arithmetic types, the
12766 // usual arithmetic conversions are applied to the operands.
12767 QualType Type =
12768 S.UsualArithmeticConversions(LHS, RHS, Loc, ACK: ArithConvKind::Comparison);
12769 if (LHS.isInvalid() || RHS.isInvalid())
12770 return QualType();
12771 if (Type.isNull()) {
12772 QualType ResultTy = S.InvalidOperands(Loc, LHS, RHS);
12773 diagnoseScopedEnums(S, Loc, LHS, RHS, Opc: BO_Cmp);
12774 return ResultTy;
12775 }
12776
12777 std::optional<ComparisonCategoryType> CCT =
12778 getComparisonCategoryForBuiltinCmp(T: Type);
12779 if (!CCT)
12780 return S.InvalidOperands(Loc, LHS, RHS);
12781
12782 bool HasNarrowing = checkThreeWayNarrowingConversion(
12783 S, ToType: Type, E: LHS.get(), FromType: LHSType, Loc: LHS.get()->getBeginLoc());
12784 HasNarrowing |= checkThreeWayNarrowingConversion(S, ToType: Type, E: RHS.get(), FromType: RHSType,
12785 Loc: RHS.get()->getBeginLoc());
12786 if (HasNarrowing)
12787 return QualType();
12788
12789 assert(!Type.isNull() && "composite type for <=> has not been set");
12790
12791 return S.CheckComparisonCategoryType(
12792 Kind: *CCT, Loc, Usage: Sema::ComparisonCategoryUsage::OperatorInExpression);
12793}
12794
12795static QualType checkArithmeticOrEnumeralCompare(Sema &S, ExprResult &LHS,
12796 ExprResult &RHS,
12797 SourceLocation Loc,
12798 BinaryOperatorKind Opc) {
12799 if (Opc == BO_Cmp)
12800 return checkArithmeticOrEnumeralThreeWayCompare(S, LHS, RHS, Loc);
12801
12802 // C99 6.5.8p3 / C99 6.5.9p4
12803 QualType Type =
12804 S.UsualArithmeticConversions(LHS, RHS, Loc, ACK: ArithConvKind::Comparison);
12805 if (LHS.isInvalid() || RHS.isInvalid())
12806 return QualType();
12807 if (Type.isNull()) {
12808 QualType ResultTy = S.InvalidOperands(Loc, LHS, RHS);
12809 diagnoseScopedEnums(S, Loc, LHS, RHS, Opc);
12810 return ResultTy;
12811 }
12812 assert(Type->isArithmeticType() || Type->isEnumeralType());
12813
12814 if (Type->isAnyComplexType() && BinaryOperator::isRelationalOp(Opc))
12815 return S.InvalidOperands(Loc, LHS, RHS);
12816
12817 // Check for comparisons of floating point operands using != and ==.
12818 if (Type->hasFloatingRepresentation())
12819 S.CheckFloatComparison(Loc, LHS: LHS.get(), RHS: RHS.get(), Opcode: Opc);
12820
12821 // The result of comparisons is 'bool' in C++, 'int' in C.
12822 return S.Context.getLogicalOperationType();
12823}
12824
12825void Sema::CheckPtrComparisonWithNullChar(ExprResult &E, ExprResult &NullE) {
12826 if (!NullE.get()->getType()->isAnyPointerType())
12827 return;
12828 int NullValue = PP.isMacroDefined(Id: "NULL") ? 0 : 1;
12829 if (!E.get()->getType()->isAnyPointerType() &&
12830 E.get()->isNullPointerConstant(Ctx&: Context,
12831 NPC: Expr::NPC_ValueDependentIsNotNull) ==
12832 Expr::NPCK_ZeroExpression) {
12833 if (const auto *CL = dyn_cast<CharacterLiteral>(Val: E.get())) {
12834 if (CL->getValue() == 0)
12835 Diag(Loc: E.get()->getExprLoc(), DiagID: diag::warn_pointer_compare)
12836 << NullValue
12837 << FixItHint::CreateReplacement(RemoveRange: E.get()->getExprLoc(),
12838 Code: NullValue ? "NULL" : "(void *)0");
12839 } else if (const auto *CE = dyn_cast<CStyleCastExpr>(Val: E.get())) {
12840 TypeSourceInfo *TI = CE->getTypeInfoAsWritten();
12841 QualType T = Context.getCanonicalType(T: TI->getType()).getUnqualifiedType();
12842 if (T == Context.CharTy)
12843 Diag(Loc: E.get()->getExprLoc(), DiagID: diag::warn_pointer_compare)
12844 << NullValue
12845 << FixItHint::CreateReplacement(RemoveRange: E.get()->getExprLoc(),
12846 Code: NullValue ? "NULL" : "(void *)0");
12847 }
12848 }
12849}
12850
12851// C99 6.5.8, C++ [expr.rel]
12852QualType Sema::CheckCompareOperands(ExprResult &LHS, ExprResult &RHS,
12853 SourceLocation Loc,
12854 BinaryOperatorKind Opc) {
12855 bool IsRelational = BinaryOperator::isRelationalOp(Opc);
12856 bool IsThreeWay = Opc == BO_Cmp;
12857 bool IsOrdered = IsRelational || IsThreeWay;
12858 auto IsAnyPointerType = [](ExprResult E) {
12859 QualType Ty = E.get()->getType();
12860 return Ty->isPointerType() || Ty->isMemberPointerType();
12861 };
12862
12863 // C++2a [expr.spaceship]p6: If at least one of the operands is of pointer
12864 // type, array-to-pointer, ..., conversions are performed on both operands to
12865 // bring them to their composite type.
12866 // Otherwise, all comparisons expect an rvalue, so convert to rvalue before
12867 // any type-related checks.
12868 if (!IsThreeWay || IsAnyPointerType(LHS) || IsAnyPointerType(RHS)) {
12869 LHS = DefaultFunctionArrayLvalueConversion(E: LHS.get());
12870 if (LHS.isInvalid())
12871 return QualType();
12872 RHS = DefaultFunctionArrayLvalueConversion(E: RHS.get());
12873 if (RHS.isInvalid())
12874 return QualType();
12875 } else {
12876 LHS = DefaultLvalueConversion(E: LHS.get());
12877 if (LHS.isInvalid())
12878 return QualType();
12879 RHS = DefaultLvalueConversion(E: RHS.get());
12880 if (RHS.isInvalid())
12881 return QualType();
12882 }
12883
12884 checkArithmeticNull(S&: *this, LHS, RHS, Loc, /*IsCompare=*/true);
12885 if (!getLangOpts().CPlusPlus && BinaryOperator::isEqualityOp(Opc)) {
12886 CheckPtrComparisonWithNullChar(E&: LHS, NullE&: RHS);
12887 CheckPtrComparisonWithNullChar(E&: RHS, NullE&: LHS);
12888 }
12889
12890 // Handle vector comparisons separately.
12891 if (LHS.get()->getType()->isVectorType() ||
12892 RHS.get()->getType()->isVectorType())
12893 return CheckVectorCompareOperands(LHS, RHS, Loc, Opc);
12894
12895 if (LHS.get()->getType()->isSveVLSBuiltinType() ||
12896 RHS.get()->getType()->isSveVLSBuiltinType())
12897 return CheckSizelessVectorCompareOperands(LHS, RHS, Loc, Opc);
12898
12899 diagnoseLogicalNotOnLHSofCheck(S&: *this, LHS, RHS, Loc, Opc);
12900 diagnoseTautologicalComparison(S&: *this, Loc, LHS: LHS.get(), RHS: RHS.get(), Opc);
12901
12902 QualType LHSType = LHS.get()->getType();
12903 QualType RHSType = RHS.get()->getType();
12904 if ((LHSType->isArithmeticType() || LHSType->isEnumeralType()) &&
12905 (RHSType->isArithmeticType() || RHSType->isEnumeralType()))
12906 return checkArithmeticOrEnumeralCompare(S&: *this, LHS, RHS, Loc, Opc);
12907
12908 if ((LHSType->isPointerType() &&
12909 LHSType->getPointeeType().isWebAssemblyReferenceType()) ||
12910 (RHSType->isPointerType() &&
12911 RHSType->getPointeeType().isWebAssemblyReferenceType()))
12912 return InvalidOperands(Loc, LHS, RHS);
12913
12914 const Expr::NullPointerConstantKind LHSNullKind =
12915 LHS.get()->isNullPointerConstant(Ctx&: Context, NPC: Expr::NPC_ValueDependentIsNull);
12916 const Expr::NullPointerConstantKind RHSNullKind =
12917 RHS.get()->isNullPointerConstant(Ctx&: Context, NPC: Expr::NPC_ValueDependentIsNull);
12918 bool LHSIsNull = LHSNullKind != Expr::NPCK_NotNull;
12919 bool RHSIsNull = RHSNullKind != Expr::NPCK_NotNull;
12920
12921 auto computeResultTy = [&]() {
12922 if (Opc != BO_Cmp)
12923 return QualType(Context.getLogicalOperationType());
12924 assert(getLangOpts().CPlusPlus);
12925 assert(Context.hasSameType(LHS.get()->getType(), RHS.get()->getType()));
12926
12927 QualType CompositeTy = LHS.get()->getType();
12928 assert(!CompositeTy->isReferenceType());
12929
12930 std::optional<ComparisonCategoryType> CCT =
12931 getComparisonCategoryForBuiltinCmp(T: CompositeTy);
12932 if (!CCT)
12933 return InvalidOperands(Loc, LHS, RHS);
12934
12935 if (CompositeTy->isPointerType() && LHSIsNull != RHSIsNull) {
12936 // P0946R0: Comparisons between a null pointer constant and an object
12937 // pointer result in std::strong_equality, which is ill-formed under
12938 // P1959R0.
12939 Diag(Loc, DiagID: diag::err_typecheck_three_way_comparison_of_pointer_and_zero)
12940 << (LHSIsNull ? LHS.get()->getSourceRange()
12941 : RHS.get()->getSourceRange());
12942 return QualType();
12943 }
12944
12945 return CheckComparisonCategoryType(
12946 Kind: *CCT, Loc, Usage: ComparisonCategoryUsage::OperatorInExpression);
12947 };
12948
12949 if (!IsOrdered && LHSIsNull != RHSIsNull) {
12950 bool IsEquality = Opc == BO_EQ;
12951 if (RHSIsNull)
12952 DiagnoseAlwaysNonNullPointer(E: LHS.get(), NullType: RHSNullKind, IsEqual: IsEquality,
12953 Range: RHS.get()->getSourceRange());
12954 else
12955 DiagnoseAlwaysNonNullPointer(E: RHS.get(), NullType: LHSNullKind, IsEqual: IsEquality,
12956 Range: LHS.get()->getSourceRange());
12957 }
12958
12959 if (IsOrdered && LHSType->isFunctionPointerType() &&
12960 RHSType->isFunctionPointerType()) {
12961 // Valid unless a relational comparison of function pointers
12962 bool IsError = Opc == BO_Cmp;
12963 auto DiagID =
12964 IsError ? diag::err_typecheck_ordered_comparison_of_function_pointers
12965 : getLangOpts().CPlusPlus
12966 ? diag::warn_typecheck_ordered_comparison_of_function_pointers
12967 : diag::ext_typecheck_ordered_comparison_of_function_pointers;
12968 Diag(Loc, DiagID) << LHSType << RHSType << LHS.get()->getSourceRange()
12969 << RHS.get()->getSourceRange();
12970 if (IsError)
12971 return QualType();
12972 }
12973
12974 if ((LHSType->isIntegerType() && !LHSIsNull) ||
12975 (RHSType->isIntegerType() && !RHSIsNull)) {
12976 // Skip normal pointer conversion checks in this case; we have better
12977 // diagnostics for this below.
12978 } else if (getLangOpts().CPlusPlus) {
12979 // Equality comparison of a function pointer to a void pointer is invalid,
12980 // but we allow it as an extension.
12981 // FIXME: If we really want to allow this, should it be part of composite
12982 // pointer type computation so it works in conditionals too?
12983 if (!IsOrdered &&
12984 ((LHSType->isFunctionPointerType() && RHSType->isVoidPointerType()) ||
12985 (RHSType->isFunctionPointerType() && LHSType->isVoidPointerType()))) {
12986 // This is a gcc extension compatibility comparison.
12987 // In a SFINAE context, we treat this as a hard error to maintain
12988 // conformance with the C++ standard.
12989 bool IsError = isSFINAEContext();
12990 diagnoseFunctionPointerToVoidComparison(S&: *this, Loc, LHS, RHS, IsError);
12991
12992 if (IsError)
12993 return QualType();
12994
12995 RHS = ImpCastExprToType(E: RHS.get(), Type: LHSType, CK: CK_BitCast);
12996 return computeResultTy();
12997 }
12998
12999 // C++ [expr.eq]p2:
13000 // If at least one operand is a pointer [...] bring them to their
13001 // composite pointer type.
13002 // C++ [expr.spaceship]p6
13003 // If at least one of the operands is of pointer type, [...] bring them
13004 // to their composite pointer type.
13005 // C++ [expr.rel]p2:
13006 // If both operands are pointers, [...] bring them to their composite
13007 // pointer type.
13008 // For <=>, the only valid non-pointer types are arrays and functions, and
13009 // we already decayed those, so this is really the same as the relational
13010 // comparison rule.
13011 if ((int)LHSType->isPointerType() + (int)RHSType->isPointerType() >=
13012 (IsOrdered ? 2 : 1) &&
13013 (!LangOpts.ObjCAutoRefCount || !(LHSType->isObjCObjectPointerType() ||
13014 RHSType->isObjCObjectPointerType()))) {
13015 if (convertPointersToCompositeType(S&: *this, Loc, LHS, RHS))
13016 return QualType();
13017 return computeResultTy();
13018 }
13019 } else if (LHSType->isPointerType() &&
13020 RHSType->isPointerType()) { // C99 6.5.8p2
13021 // All of the following pointer-related warnings are GCC extensions, except
13022 // when handling null pointer constants.
13023 QualType LCanPointeeTy =
13024 LHSType->castAs<PointerType>()->getPointeeType().getCanonicalType();
13025 QualType RCanPointeeTy =
13026 RHSType->castAs<PointerType>()->getPointeeType().getCanonicalType();
13027
13028 // C99 6.5.9p2 and C99 6.5.8p2
13029 if (Context.typesAreCompatible(T1: LCanPointeeTy.getUnqualifiedType(),
13030 T2: RCanPointeeTy.getUnqualifiedType())) {
13031 if (IsRelational) {
13032 // Pointers both need to point to complete or incomplete types
13033 if ((LCanPointeeTy->isIncompleteType() !=
13034 RCanPointeeTy->isIncompleteType()) &&
13035 !getLangOpts().C11) {
13036 Diag(Loc, DiagID: diag::ext_typecheck_compare_complete_incomplete_pointers)
13037 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange()
13038 << LHSType << RHSType << LCanPointeeTy->isIncompleteType()
13039 << RCanPointeeTy->isIncompleteType();
13040 }
13041 }
13042 } else if (!IsRelational &&
13043 (LCanPointeeTy->isVoidType() || RCanPointeeTy->isVoidType())) {
13044 // Valid unless comparison between non-null pointer and function pointer
13045 if ((LCanPointeeTy->isFunctionType() || RCanPointeeTy->isFunctionType())
13046 && !LHSIsNull && !RHSIsNull)
13047 diagnoseFunctionPointerToVoidComparison(S&: *this, Loc, LHS, RHS,
13048 /*isError*/IsError: false);
13049 } else {
13050 // Invalid
13051 diagnoseDistinctPointerComparison(S&: *this, Loc, LHS, RHS, /*isError*/IsError: false);
13052 }
13053 if (LCanPointeeTy != RCanPointeeTy) {
13054 // Treat NULL constant as a special case in OpenCL.
13055 if (getLangOpts().OpenCL && !LHSIsNull && !RHSIsNull) {
13056 if (!LCanPointeeTy.isAddressSpaceOverlapping(T: RCanPointeeTy,
13057 Ctx: getASTContext())) {
13058 Diag(Loc,
13059 DiagID: diag::err_typecheck_op_on_nonoverlapping_address_space_pointers)
13060 << LHSType << RHSType << 0 /* comparison */
13061 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
13062 }
13063 }
13064 LangAS AddrSpaceL = LCanPointeeTy.getAddressSpace();
13065 LangAS AddrSpaceR = RCanPointeeTy.getAddressSpace();
13066 CastKind Kind = AddrSpaceL != AddrSpaceR ? CK_AddressSpaceConversion
13067 : CK_BitCast;
13068
13069 const FunctionType *LFn = LCanPointeeTy->getAs<FunctionType>();
13070 const FunctionType *RFn = RCanPointeeTy->getAs<FunctionType>();
13071 bool LHSHasCFIUncheckedCallee = LFn && LFn->getCFIUncheckedCalleeAttr();
13072 bool RHSHasCFIUncheckedCallee = RFn && RFn->getCFIUncheckedCalleeAttr();
13073 bool ChangingCFIUncheckedCallee =
13074 LHSHasCFIUncheckedCallee != RHSHasCFIUncheckedCallee;
13075
13076 if (LHSIsNull && !RHSIsNull)
13077 LHS = ImpCastExprToType(E: LHS.get(), Type: RHSType, CK: Kind);
13078 else if (!ChangingCFIUncheckedCallee)
13079 RHS = ImpCastExprToType(E: RHS.get(), Type: LHSType, CK: Kind);
13080 }
13081 return computeResultTy();
13082 }
13083
13084
13085 // C++ [expr.eq]p4:
13086 // Two operands of type std::nullptr_t or one operand of type
13087 // std::nullptr_t and the other a null pointer constant compare
13088 // equal.
13089 // C23 6.5.9p5:
13090 // If both operands have type nullptr_t or one operand has type nullptr_t
13091 // and the other is a null pointer constant, they compare equal if the
13092 // former is a null pointer.
13093 if (!IsOrdered && LHSIsNull && RHSIsNull) {
13094 if (LHSType->isNullPtrType()) {
13095 RHS = ImpCastExprToType(E: RHS.get(), Type: LHSType, CK: CK_NullToPointer);
13096 return computeResultTy();
13097 }
13098 if (RHSType->isNullPtrType()) {
13099 LHS = ImpCastExprToType(E: LHS.get(), Type: RHSType, CK: CK_NullToPointer);
13100 return computeResultTy();
13101 }
13102 }
13103
13104 if (!getLangOpts().CPlusPlus && !IsOrdered && (LHSIsNull || RHSIsNull)) {
13105 // C23 6.5.9p6:
13106 // Otherwise, at least one operand is a pointer. If one is a pointer and
13107 // the other is a null pointer constant or has type nullptr_t, they
13108 // compare equal
13109 if (LHSIsNull && RHSType->isPointerType()) {
13110 LHS = ImpCastExprToType(E: LHS.get(), Type: RHSType, CK: CK_NullToPointer);
13111 return computeResultTy();
13112 }
13113 if (RHSIsNull && LHSType->isPointerType()) {
13114 RHS = ImpCastExprToType(E: RHS.get(), Type: LHSType, CK: CK_NullToPointer);
13115 return computeResultTy();
13116 }
13117 }
13118
13119 // Comparison of Objective-C pointers and block pointers against nullptr_t.
13120 // These aren't covered by the composite pointer type rules.
13121 if (!IsOrdered && RHSType->isNullPtrType() &&
13122 (LHSType->isObjCObjectPointerType() || LHSType->isBlockPointerType())) {
13123 RHS = ImpCastExprToType(E: RHS.get(), Type: LHSType, CK: CK_NullToPointer);
13124 return computeResultTy();
13125 }
13126 if (!IsOrdered && LHSType->isNullPtrType() &&
13127 (RHSType->isObjCObjectPointerType() || RHSType->isBlockPointerType())) {
13128 LHS = ImpCastExprToType(E: LHS.get(), Type: RHSType, CK: CK_NullToPointer);
13129 return computeResultTy();
13130 }
13131
13132 if (getLangOpts().CPlusPlus) {
13133 if (IsRelational &&
13134 ((LHSType->isNullPtrType() && RHSType->isPointerType()) ||
13135 (RHSType->isNullPtrType() && LHSType->isPointerType()))) {
13136 // HACK: Relational comparison of nullptr_t against a pointer type is
13137 // invalid per DR583, but we allow it within std::less<> and friends,
13138 // since otherwise common uses of it break.
13139 // FIXME: Consider removing this hack once LWG fixes std::less<> and
13140 // friends to have std::nullptr_t overload candidates.
13141 DeclContext *DC = CurContext;
13142 if (isa<FunctionDecl>(Val: DC))
13143 DC = DC->getParent();
13144 if (auto *CTSD = dyn_cast<ClassTemplateSpecializationDecl>(Val: DC)) {
13145 if (CTSD->isInStdNamespace() &&
13146 llvm::StringSwitch<bool>(CTSD->getName())
13147 .Cases(CaseStrings: {"less", "less_equal", "greater", "greater_equal"}, Value: true)
13148 .Default(Value: false)) {
13149 if (RHSType->isNullPtrType())
13150 RHS = ImpCastExprToType(E: RHS.get(), Type: LHSType, CK: CK_NullToPointer);
13151 else
13152 LHS = ImpCastExprToType(E: LHS.get(), Type: RHSType, CK: CK_NullToPointer);
13153 return computeResultTy();
13154 }
13155 }
13156 }
13157
13158 // C++ [expr.eq]p2:
13159 // If at least one operand is a pointer to member, [...] bring them to
13160 // their composite pointer type.
13161 if (!IsOrdered &&
13162 (LHSType->isMemberPointerType() || RHSType->isMemberPointerType())) {
13163 if (convertPointersToCompositeType(S&: *this, Loc, LHS, RHS))
13164 return QualType();
13165 else
13166 return computeResultTy();
13167 }
13168 }
13169
13170 // Handle block pointer types.
13171 if (!IsOrdered && LHSType->isBlockPointerType() &&
13172 RHSType->isBlockPointerType()) {
13173 QualType lpointee = LHSType->castAs<BlockPointerType>()->getPointeeType();
13174 QualType rpointee = RHSType->castAs<BlockPointerType>()->getPointeeType();
13175
13176 if (!LHSIsNull && !RHSIsNull &&
13177 !Context.typesAreCompatible(T1: lpointee, T2: rpointee)) {
13178 Diag(Loc, DiagID: diag::err_typecheck_comparison_of_distinct_blocks)
13179 << LHSType << RHSType << LHS.get()->getSourceRange()
13180 << RHS.get()->getSourceRange();
13181 }
13182 RHS = ImpCastExprToType(E: RHS.get(), Type: LHSType, CK: CK_BitCast);
13183 return computeResultTy();
13184 }
13185
13186 // Allow block pointers to be compared with null pointer constants.
13187 if (!IsOrdered
13188 && ((LHSType->isBlockPointerType() && RHSType->isPointerType())
13189 || (LHSType->isPointerType() && RHSType->isBlockPointerType()))) {
13190 if (!LHSIsNull && !RHSIsNull) {
13191 if (!((RHSType->isPointerType() && RHSType->castAs<PointerType>()
13192 ->getPointeeType()->isVoidType())
13193 || (LHSType->isPointerType() && LHSType->castAs<PointerType>()
13194 ->getPointeeType()->isVoidType())))
13195 Diag(Loc, DiagID: diag::err_typecheck_comparison_of_distinct_blocks)
13196 << LHSType << RHSType << LHS.get()->getSourceRange()
13197 << RHS.get()->getSourceRange();
13198 }
13199 if (LHSIsNull && !RHSIsNull)
13200 LHS = ImpCastExprToType(E: LHS.get(), Type: RHSType,
13201 CK: RHSType->isPointerType() ? CK_BitCast
13202 : CK_AnyPointerToBlockPointerCast);
13203 else
13204 RHS = ImpCastExprToType(E: RHS.get(), Type: LHSType,
13205 CK: LHSType->isPointerType() ? CK_BitCast
13206 : CK_AnyPointerToBlockPointerCast);
13207 return computeResultTy();
13208 }
13209
13210 if (LHSType->isObjCObjectPointerType() ||
13211 RHSType->isObjCObjectPointerType()) {
13212 const PointerType *LPT = LHSType->getAs<PointerType>();
13213 const PointerType *RPT = RHSType->getAs<PointerType>();
13214 if (LPT || RPT) {
13215 bool LPtrToVoid = LPT ? LPT->getPointeeType()->isVoidType() : false;
13216 bool RPtrToVoid = RPT ? RPT->getPointeeType()->isVoidType() : false;
13217
13218 if (!LPtrToVoid && !RPtrToVoid &&
13219 !Context.typesAreCompatible(T1: LHSType, T2: RHSType)) {
13220 diagnoseDistinctPointerComparison(S&: *this, Loc, LHS, RHS,
13221 /*isError*/IsError: false);
13222 }
13223 // FIXME: If LPtrToVoid, we should presumably convert the LHS rather than
13224 // the RHS, but we have test coverage for this behavior.
13225 // FIXME: Consider using convertPointersToCompositeType in C++.
13226 if (LHSIsNull && !RHSIsNull) {
13227 Expr *E = LHS.get();
13228 if (getLangOpts().ObjCAutoRefCount)
13229 ObjC().CheckObjCConversion(castRange: SourceRange(), castType: RHSType, op&: E,
13230 CCK: CheckedConversionKind::Implicit);
13231 LHS = ImpCastExprToType(E, Type: RHSType,
13232 CK: RPT ? CK_BitCast :CK_CPointerToObjCPointerCast);
13233 }
13234 else {
13235 Expr *E = RHS.get();
13236 if (getLangOpts().ObjCAutoRefCount)
13237 ObjC().CheckObjCConversion(castRange: SourceRange(), castType: LHSType, op&: E,
13238 CCK: CheckedConversionKind::Implicit,
13239 /*Diagnose=*/true,
13240 /*DiagnoseCFAudited=*/false, Opc);
13241 RHS = ImpCastExprToType(E, Type: LHSType,
13242 CK: LPT ? CK_BitCast :CK_CPointerToObjCPointerCast);
13243 }
13244 return computeResultTy();
13245 }
13246 if (LHSType->isObjCObjectPointerType() &&
13247 RHSType->isObjCObjectPointerType()) {
13248 if (!Context.areComparableObjCPointerTypes(LHS: LHSType, RHS: RHSType))
13249 diagnoseDistinctPointerComparison(S&: *this, Loc, LHS, RHS,
13250 /*isError*/IsError: false);
13251 if (isObjCObjectLiteral(E&: LHS) || isObjCObjectLiteral(E&: RHS))
13252 diagnoseObjCLiteralComparison(S&: *this, Loc, LHS, RHS, Opc);
13253
13254 if (LHSIsNull && !RHSIsNull)
13255 LHS = ImpCastExprToType(E: LHS.get(), Type: RHSType, CK: CK_BitCast);
13256 else
13257 RHS = ImpCastExprToType(E: RHS.get(), Type: LHSType, CK: CK_BitCast);
13258 return computeResultTy();
13259 }
13260
13261 if (!IsOrdered && LHSType->isBlockPointerType() &&
13262 RHSType->isBlockCompatibleObjCPointerType(ctx&: Context)) {
13263 LHS = ImpCastExprToType(E: LHS.get(), Type: RHSType,
13264 CK: CK_BlockPointerToObjCPointerCast);
13265 return computeResultTy();
13266 } else if (!IsOrdered &&
13267 LHSType->isBlockCompatibleObjCPointerType(ctx&: Context) &&
13268 RHSType->isBlockPointerType()) {
13269 RHS = ImpCastExprToType(E: RHS.get(), Type: LHSType,
13270 CK: CK_BlockPointerToObjCPointerCast);
13271 return computeResultTy();
13272 }
13273 }
13274 if ((LHSType->isAnyPointerType() && RHSType->isIntegerType()) ||
13275 (LHSType->isIntegerType() && RHSType->isAnyPointerType())) {
13276 unsigned DiagID = 0;
13277 bool isError = false;
13278 if (LangOpts.DebuggerSupport) {
13279 // Under a debugger, allow the comparison of pointers to integers,
13280 // since users tend to want to compare addresses.
13281 } else if ((LHSIsNull && LHSType->isIntegerType()) ||
13282 (RHSIsNull && RHSType->isIntegerType())) {
13283 if (IsOrdered) {
13284 isError = getLangOpts().CPlusPlus;
13285 DiagID =
13286 isError ? diag::err_typecheck_ordered_comparison_of_pointer_and_zero
13287 : diag::ext_typecheck_ordered_comparison_of_pointer_and_zero;
13288 }
13289 } else if (getLangOpts().CPlusPlus) {
13290 DiagID = diag::err_typecheck_comparison_of_pointer_integer;
13291 isError = true;
13292 } else if (IsOrdered)
13293 DiagID = diag::ext_typecheck_ordered_comparison_of_pointer_integer;
13294 else
13295 DiagID = diag::ext_typecheck_comparison_of_pointer_integer;
13296
13297 if (DiagID) {
13298 Diag(Loc, DiagID)
13299 << LHSType << RHSType << LHS.get()->getSourceRange()
13300 << RHS.get()->getSourceRange();
13301 if (isError)
13302 return QualType();
13303 }
13304
13305 if (LHSType->isIntegerType())
13306 LHS = ImpCastExprToType(E: LHS.get(), Type: RHSType,
13307 CK: LHSIsNull ? CK_NullToPointer : CK_IntegralToPointer);
13308 else
13309 RHS = ImpCastExprToType(E: RHS.get(), Type: LHSType,
13310 CK: RHSIsNull ? CK_NullToPointer : CK_IntegralToPointer);
13311 return computeResultTy();
13312 }
13313
13314 // Handle block pointers.
13315 if (!IsOrdered && RHSIsNull
13316 && LHSType->isBlockPointerType() && RHSType->isIntegerType()) {
13317 RHS = ImpCastExprToType(E: RHS.get(), Type: LHSType, CK: CK_NullToPointer);
13318 return computeResultTy();
13319 }
13320 if (!IsOrdered && LHSIsNull
13321 && LHSType->isIntegerType() && RHSType->isBlockPointerType()) {
13322 LHS = ImpCastExprToType(E: LHS.get(), Type: RHSType, CK: CK_NullToPointer);
13323 return computeResultTy();
13324 }
13325
13326 if (getLangOpts().getOpenCLCompatibleVersion() >= 200) {
13327 if (LHSType->isClkEventT() && RHSType->isClkEventT()) {
13328 return computeResultTy();
13329 }
13330
13331 if (LHSType->isQueueT() && RHSType->isQueueT()) {
13332 return computeResultTy();
13333 }
13334
13335 if (LHSIsNull && RHSType->isQueueT()) {
13336 LHS = ImpCastExprToType(E: LHS.get(), Type: RHSType, CK: CK_NullToPointer);
13337 return computeResultTy();
13338 }
13339
13340 if (LHSType->isQueueT() && RHSIsNull) {
13341 RHS = ImpCastExprToType(E: RHS.get(), Type: LHSType, CK: CK_NullToPointer);
13342 return computeResultTy();
13343 }
13344 }
13345
13346 return InvalidOperands(Loc, LHS, RHS);
13347}
13348
13349QualType Sema::GetSignedVectorType(QualType V) {
13350 const VectorType *VTy = V->castAs<VectorType>();
13351 unsigned TypeSize = Context.getTypeSize(T: VTy->getElementType());
13352
13353 if (isa<ExtVectorType>(Val: VTy)) {
13354 if (VTy->isExtVectorBoolType())
13355 return Context.getExtVectorType(VectorType: Context.BoolTy, NumElts: VTy->getNumElements());
13356 if (TypeSize == Context.getTypeSize(T: Context.CharTy))
13357 return Context.getExtVectorType(VectorType: Context.CharTy, NumElts: VTy->getNumElements());
13358 if (TypeSize == Context.getTypeSize(T: Context.ShortTy))
13359 return Context.getExtVectorType(VectorType: Context.ShortTy, NumElts: VTy->getNumElements());
13360 if (TypeSize == Context.getTypeSize(T: Context.IntTy))
13361 return Context.getExtVectorType(VectorType: Context.IntTy, NumElts: VTy->getNumElements());
13362 if (TypeSize == Context.getTypeSize(T: Context.Int128Ty))
13363 return Context.getExtVectorType(VectorType: Context.Int128Ty, NumElts: VTy->getNumElements());
13364 if (TypeSize == Context.getTypeSize(T: Context.LongTy))
13365 return Context.getExtVectorType(VectorType: Context.LongTy, NumElts: VTy->getNumElements());
13366 assert(TypeSize == Context.getTypeSize(Context.LongLongTy) &&
13367 "Unhandled vector element size in vector compare");
13368 return Context.getExtVectorType(VectorType: Context.LongLongTy, NumElts: VTy->getNumElements());
13369 }
13370
13371 if (TypeSize == Context.getTypeSize(T: Context.Int128Ty))
13372 return Context.getVectorType(VectorType: Context.Int128Ty, NumElts: VTy->getNumElements(),
13373 VecKind: VectorKind::Generic);
13374 if (TypeSize == Context.getTypeSize(T: Context.LongLongTy))
13375 return Context.getVectorType(VectorType: Context.LongLongTy, NumElts: VTy->getNumElements(),
13376 VecKind: VectorKind::Generic);
13377 if (TypeSize == Context.getTypeSize(T: Context.LongTy))
13378 return Context.getVectorType(VectorType: Context.LongTy, NumElts: VTy->getNumElements(),
13379 VecKind: VectorKind::Generic);
13380 if (TypeSize == Context.getTypeSize(T: Context.IntTy))
13381 return Context.getVectorType(VectorType: Context.IntTy, NumElts: VTy->getNumElements(),
13382 VecKind: VectorKind::Generic);
13383 if (TypeSize == Context.getTypeSize(T: Context.ShortTy))
13384 return Context.getVectorType(VectorType: Context.ShortTy, NumElts: VTy->getNumElements(),
13385 VecKind: VectorKind::Generic);
13386 assert(TypeSize == Context.getTypeSize(Context.CharTy) &&
13387 "Unhandled vector element size in vector compare");
13388 return Context.getVectorType(VectorType: Context.CharTy, NumElts: VTy->getNumElements(),
13389 VecKind: VectorKind::Generic);
13390}
13391
13392QualType Sema::GetSignedSizelessVectorType(QualType V) {
13393 const BuiltinType *VTy = V->castAs<BuiltinType>();
13394 assert(VTy->isSizelessBuiltinType() && "expected sizeless type");
13395
13396 const QualType ETy = V->getSveEltType(Ctx: Context);
13397 const auto TypeSize = Context.getTypeSize(T: ETy);
13398
13399 const QualType IntTy = Context.getIntTypeForBitwidth(DestWidth: TypeSize, Signed: true);
13400 const llvm::ElementCount VecSize = Context.getBuiltinVectorTypeInfo(VecTy: VTy).EC;
13401 return Context.getScalableVectorType(EltTy: IntTy, NumElts: VecSize.getKnownMinValue());
13402}
13403
13404QualType Sema::CheckVectorCompareOperands(ExprResult &LHS, ExprResult &RHS,
13405 SourceLocation Loc,
13406 BinaryOperatorKind Opc) {
13407 if (Opc == BO_Cmp) {
13408 Diag(Loc, DiagID: diag::err_three_way_vector_comparison);
13409 return QualType();
13410 }
13411
13412 // Check to make sure we're operating on vectors of the same type and width,
13413 // Allowing one side to be a scalar of element type.
13414 QualType vType =
13415 CheckVectorOperands(LHS, RHS, Loc, /*isCompAssign*/ IsCompAssign: false,
13416 /*AllowBothBool*/ true,
13417 /*AllowBoolConversions*/ getLangOpts().ZVector,
13418 /*AllowBooleanOperation*/ AllowBoolOperation: true,
13419 /*ReportInvalid*/ true);
13420 if (vType.isNull())
13421 return vType;
13422
13423 QualType LHSType = LHS.get()->getType();
13424
13425 // Determine the return type of a vector compare. By default clang will return
13426 // a scalar for all vector compares except vector bool and vector pixel.
13427 // With the gcc compiler we will always return a vector type and with the xl
13428 // compiler we will always return a scalar type. This switch allows choosing
13429 // which behavior is prefered.
13430 if (getLangOpts().AltiVec) {
13431 switch (getLangOpts().getAltivecSrcCompat()) {
13432 case LangOptions::AltivecSrcCompatKind::Mixed:
13433 // If AltiVec, the comparison results in a numeric type, i.e.
13434 // bool for C++, int for C
13435 if (vType->castAs<VectorType>()->getVectorKind() ==
13436 VectorKind::AltiVecVector)
13437 return Context.getLogicalOperationType();
13438 else
13439 Diag(Loc, DiagID: diag::warn_deprecated_altivec_src_compat);
13440 break;
13441 case LangOptions::AltivecSrcCompatKind::GCC:
13442 // For GCC we always return the vector type.
13443 break;
13444 case LangOptions::AltivecSrcCompatKind::XL:
13445 return Context.getLogicalOperationType();
13446 break;
13447 }
13448 }
13449
13450 // For non-floating point types, check for self-comparisons of the form
13451 // x == x, x != x, x < x, etc. These always evaluate to a constant, and
13452 // often indicate logic errors in the program.
13453 diagnoseTautologicalComparison(S&: *this, Loc, LHS: LHS.get(), RHS: RHS.get(), Opc);
13454
13455 // Check for comparisons of floating point operands using != and ==.
13456 if (LHSType->hasFloatingRepresentation()) {
13457 assert(RHS.get()->getType()->hasFloatingRepresentation());
13458 CheckFloatComparison(Loc, LHS: LHS.get(), RHS: RHS.get(), Opcode: Opc);
13459 }
13460
13461 // Return a signed type for the vector.
13462 return GetSignedVectorType(V: vType);
13463}
13464
13465QualType Sema::CheckSizelessVectorCompareOperands(ExprResult &LHS,
13466 ExprResult &RHS,
13467 SourceLocation Loc,
13468 BinaryOperatorKind Opc) {
13469 if (Opc == BO_Cmp) {
13470 Diag(Loc, DiagID: diag::err_three_way_vector_comparison);
13471 return QualType();
13472 }
13473
13474 // Check to make sure we're operating on vectors of the same type and width,
13475 // Allowing one side to be a scalar of element type.
13476 QualType vType = CheckSizelessVectorOperands(
13477 LHS, RHS, Loc, /*isCompAssign*/ IsCompAssign: false, OperationKind: ArithConvKind::Comparison);
13478
13479 if (vType.isNull())
13480 return vType;
13481
13482 QualType LHSType = LHS.get()->getType();
13483
13484 // For non-floating point types, check for self-comparisons of the form
13485 // x == x, x != x, x < x, etc. These always evaluate to a constant, and
13486 // often indicate logic errors in the program.
13487 diagnoseTautologicalComparison(S&: *this, Loc, LHS: LHS.get(), RHS: RHS.get(), Opc);
13488
13489 // Check for comparisons of floating point operands using != and ==.
13490 if (LHSType->hasFloatingRepresentation()) {
13491 assert(RHS.get()->getType()->hasFloatingRepresentation());
13492 CheckFloatComparison(Loc, LHS: LHS.get(), RHS: RHS.get(), Opcode: Opc);
13493 }
13494
13495 const BuiltinType *LHSBuiltinTy = LHSType->getAs<BuiltinType>();
13496 const BuiltinType *RHSBuiltinTy = RHS.get()->getType()->getAs<BuiltinType>();
13497
13498 if (LHSBuiltinTy && RHSBuiltinTy && LHSBuiltinTy->isSVEBool() &&
13499 RHSBuiltinTy->isSVEBool())
13500 return LHSType;
13501
13502 // Return a signed type for the vector.
13503 return GetSignedSizelessVectorType(V: vType);
13504}
13505
13506static void diagnoseXorMisusedAsPow(Sema &S, const ExprResult &XorLHS,
13507 const ExprResult &XorRHS,
13508 const SourceLocation Loc) {
13509 // Do not diagnose macros.
13510 if (Loc.isMacroID())
13511 return;
13512
13513 // Do not diagnose if both LHS and RHS are macros.
13514 if (XorLHS.get()->getExprLoc().isMacroID() &&
13515 XorRHS.get()->getExprLoc().isMacroID())
13516 return;
13517
13518 bool Negative = false;
13519 bool ExplicitPlus = false;
13520 const auto *LHSInt = dyn_cast<IntegerLiteral>(Val: XorLHS.get());
13521 const auto *RHSInt = dyn_cast<IntegerLiteral>(Val: XorRHS.get());
13522
13523 if (!LHSInt)
13524 return;
13525 if (!RHSInt) {
13526 // Check negative literals.
13527 if (const auto *UO = dyn_cast<UnaryOperator>(Val: XorRHS.get())) {
13528 UnaryOperatorKind Opc = UO->getOpcode();
13529 if (Opc != UO_Minus && Opc != UO_Plus)
13530 return;
13531 RHSInt = dyn_cast<IntegerLiteral>(Val: UO->getSubExpr());
13532 if (!RHSInt)
13533 return;
13534 Negative = (Opc == UO_Minus);
13535 ExplicitPlus = !Negative;
13536 } else {
13537 return;
13538 }
13539 }
13540
13541 const llvm::APInt &LeftSideValue = LHSInt->getValue();
13542 llvm::APInt RightSideValue = RHSInt->getValue();
13543 if (LeftSideValue != 2 && LeftSideValue != 10)
13544 return;
13545
13546 if (LeftSideValue.getBitWidth() != RightSideValue.getBitWidth())
13547 return;
13548
13549 CharSourceRange ExprRange = CharSourceRange::getCharRange(
13550 B: LHSInt->getBeginLoc(), E: S.getLocForEndOfToken(Loc: RHSInt->getLocation()));
13551 llvm::StringRef ExprStr =
13552 Lexer::getSourceText(Range: ExprRange, SM: S.getSourceManager(), LangOpts: S.getLangOpts());
13553
13554 CharSourceRange XorRange =
13555 CharSourceRange::getCharRange(B: Loc, E: S.getLocForEndOfToken(Loc));
13556 llvm::StringRef XorStr =
13557 Lexer::getSourceText(Range: XorRange, SM: S.getSourceManager(), LangOpts: S.getLangOpts());
13558 // Do not diagnose if xor keyword/macro is used.
13559 if (XorStr == "xor")
13560 return;
13561
13562 std::string LHSStr = std::string(Lexer::getSourceText(
13563 Range: CharSourceRange::getTokenRange(R: LHSInt->getSourceRange()),
13564 SM: S.getSourceManager(), LangOpts: S.getLangOpts()));
13565 std::string RHSStr = std::string(Lexer::getSourceText(
13566 Range: CharSourceRange::getTokenRange(R: RHSInt->getSourceRange()),
13567 SM: S.getSourceManager(), LangOpts: S.getLangOpts()));
13568
13569 if (Negative) {
13570 RightSideValue = -RightSideValue;
13571 RHSStr = "-" + RHSStr;
13572 } else if (ExplicitPlus) {
13573 RHSStr = "+" + RHSStr;
13574 }
13575
13576 StringRef LHSStrRef = LHSStr;
13577 StringRef RHSStrRef = RHSStr;
13578 // Do not diagnose literals with digit separators, binary, hexadecimal, octal
13579 // literals.
13580 if (LHSStrRef.starts_with(Prefix: "0b") || LHSStrRef.starts_with(Prefix: "0B") ||
13581 RHSStrRef.starts_with(Prefix: "0b") || RHSStrRef.starts_with(Prefix: "0B") ||
13582 LHSStrRef.starts_with(Prefix: "0x") || LHSStrRef.starts_with(Prefix: "0X") ||
13583 RHSStrRef.starts_with(Prefix: "0x") || RHSStrRef.starts_with(Prefix: "0X") ||
13584 (LHSStrRef.size() > 1 && LHSStrRef.starts_with(Prefix: "0")) ||
13585 (RHSStrRef.size() > 1 && RHSStrRef.starts_with(Prefix: "0")) ||
13586 LHSStrRef.contains(C: '\'') || RHSStrRef.contains(C: '\''))
13587 return;
13588
13589 bool SuggestXor =
13590 S.getLangOpts().CPlusPlus || S.getPreprocessor().isMacroDefined(Id: "xor");
13591 const llvm::APInt XorValue = LeftSideValue ^ RightSideValue;
13592 int64_t RightSideIntValue = RightSideValue.getSExtValue();
13593 if (LeftSideValue == 2 && RightSideIntValue >= 0) {
13594 std::string SuggestedExpr = "1 << " + RHSStr;
13595 bool Overflow = false;
13596 llvm::APInt One = (LeftSideValue - 1);
13597 llvm::APInt PowValue = One.sshl_ov(Amt: RightSideValue, Overflow);
13598 if (Overflow) {
13599 if (RightSideIntValue < 64)
13600 S.Diag(Loc, DiagID: diag::warn_xor_used_as_pow_base)
13601 << ExprStr << toString(I: XorValue, Radix: 10, Signed: true) << ("1LL << " + RHSStr)
13602 << FixItHint::CreateReplacement(RemoveRange: ExprRange, Code: "1LL << " + RHSStr);
13603 else if (RightSideIntValue == 64)
13604 S.Diag(Loc, DiagID: diag::warn_xor_used_as_pow)
13605 << ExprStr << toString(I: XorValue, Radix: 10, Signed: true);
13606 else
13607 return;
13608 } else {
13609 S.Diag(Loc, DiagID: diag::warn_xor_used_as_pow_base_extra)
13610 << ExprStr << toString(I: XorValue, Radix: 10, Signed: true) << SuggestedExpr
13611 << toString(I: PowValue, Radix: 10, Signed: true)
13612 << FixItHint::CreateReplacement(
13613 RemoveRange: ExprRange, Code: (RightSideIntValue == 0) ? "1" : SuggestedExpr);
13614 }
13615
13616 S.Diag(Loc, DiagID: diag::note_xor_used_as_pow_silence)
13617 << ("0x2 ^ " + RHSStr) << SuggestXor;
13618 } else if (LeftSideValue == 10) {
13619 std::string SuggestedValue = "1e" + std::to_string(val: RightSideIntValue);
13620 S.Diag(Loc, DiagID: diag::warn_xor_used_as_pow_base)
13621 << ExprStr << toString(I: XorValue, Radix: 10, Signed: true) << SuggestedValue
13622 << FixItHint::CreateReplacement(RemoveRange: ExprRange, Code: SuggestedValue);
13623 S.Diag(Loc, DiagID: diag::note_xor_used_as_pow_silence)
13624 << ("0xA ^ " + RHSStr) << SuggestXor;
13625 }
13626}
13627
13628QualType Sema::CheckVectorLogicalOperands(ExprResult &LHS, ExprResult &RHS,
13629 SourceLocation Loc,
13630 BinaryOperatorKind Opc) {
13631 // Ensure that either both operands are of the same vector type, or
13632 // one operand is of a vector type and the other is of its element type.
13633 QualType vType = CheckVectorOperands(LHS, RHS, Loc, IsCompAssign: false,
13634 /*AllowBothBool*/ true,
13635 /*AllowBoolConversions*/ false,
13636 /*AllowBooleanOperation*/ AllowBoolOperation: false,
13637 /*ReportInvalid*/ false);
13638 if (vType.isNull())
13639 return InvalidOperands(Loc, LHS, RHS);
13640 if (getLangOpts().OpenCL &&
13641 getLangOpts().getOpenCLCompatibleVersion() < 120 &&
13642 vType->hasFloatingRepresentation())
13643 return InvalidOperands(Loc, LHS, RHS);
13644 // FIXME: The check for C++ here is for GCC compatibility. GCC rejects the
13645 // usage of the logical operators && and || with vectors in C. This
13646 // check could be notionally dropped.
13647 if (!getLangOpts().CPlusPlus &&
13648 !(isa<ExtVectorType>(Val: vType->getAs<VectorType>())))
13649 return InvalidLogicalVectorOperands(Loc, LHS, RHS);
13650 // Beginning with HLSL 2021, HLSL disallows logical operators on vector
13651 // operands and instead requires the use of the `and`, `or`, `any`, `all`, and
13652 // `select` functions.
13653 if (getLangOpts().HLSL &&
13654 getLangOpts().getHLSLVersion() >= LangOptionsBase::HLSL_2021) {
13655 (void)InvalidOperands(Loc, LHS, RHS);
13656 HLSL().emitLogicalOperatorFixIt(LHS: LHS.get(), RHS: RHS.get(), Opc);
13657 return QualType();
13658 }
13659
13660 return GetSignedVectorType(V: LHS.get()->getType());
13661}
13662
13663QualType Sema::CheckMatrixLogicalOperands(ExprResult &LHS, ExprResult &RHS,
13664 SourceLocation Loc,
13665 BinaryOperatorKind Opc) {
13666
13667 if (!getLangOpts().HLSL) {
13668 assert(false && "Logical operands are not supported in C\\C++");
13669 return QualType();
13670 }
13671
13672 if (getLangOpts().getHLSLVersion() >= LangOptionsBase::HLSL_2021) {
13673 (void)InvalidOperands(Loc, LHS, RHS);
13674 HLSL().emitLogicalOperatorFixIt(LHS: LHS.get(), RHS: RHS.get(), Opc);
13675 return QualType();
13676 }
13677 SemaRef.Diag(Loc: LHS.get()->getBeginLoc(), DiagID: diag::err_hlsl_langstd_unimplemented)
13678 << getLangOpts().getHLSLVersion();
13679 return QualType();
13680}
13681
13682QualType Sema::CheckMatrixElementwiseOperands(ExprResult &LHS, ExprResult &RHS,
13683 SourceLocation Loc,
13684 bool IsCompAssign) {
13685 if (!IsCompAssign) {
13686 LHS = DefaultFunctionArrayLvalueConversion(E: LHS.get());
13687 if (LHS.isInvalid())
13688 return QualType();
13689 }
13690 RHS = DefaultFunctionArrayLvalueConversion(E: RHS.get());
13691 if (RHS.isInvalid())
13692 return QualType();
13693
13694 // For conversion purposes, we ignore any qualifiers.
13695 // For example, "const float" and "float" are equivalent.
13696 QualType LHSType = LHS.get()->getType().getUnqualifiedType();
13697 QualType RHSType = RHS.get()->getType().getUnqualifiedType();
13698
13699 const MatrixType *LHSMatType = LHSType->getAs<MatrixType>();
13700 const MatrixType *RHSMatType = RHSType->getAs<MatrixType>();
13701 assert((LHSMatType || RHSMatType) && "At least one operand must be a matrix");
13702
13703 if (Context.hasSameType(T1: LHSType, T2: RHSType))
13704 return Context.getCommonSugaredType(X: LHSType, Y: RHSType);
13705
13706 // Type conversion may change LHS/RHS. Keep copies to the original results, in
13707 // case we have to return InvalidOperands.
13708 ExprResult OriginalLHS = LHS;
13709 ExprResult OriginalRHS = RHS;
13710 if (LHSMatType && !RHSMatType) {
13711 RHS = tryConvertExprToType(E: RHS.get(), Ty: LHSMatType->getElementType());
13712 if (!RHS.isInvalid())
13713 return LHSType;
13714
13715 return InvalidOperands(Loc, LHS&: OriginalLHS, RHS&: OriginalRHS);
13716 }
13717
13718 if (!LHSMatType && RHSMatType) {
13719 LHS = tryConvertExprToType(E: LHS.get(), Ty: RHSMatType->getElementType());
13720 if (!LHS.isInvalid())
13721 return RHSType;
13722 return InvalidOperands(Loc, LHS&: OriginalLHS, RHS&: OriginalRHS);
13723 }
13724
13725 return InvalidOperands(Loc, LHS, RHS);
13726}
13727
13728QualType Sema::CheckMatrixMultiplyOperands(ExprResult &LHS, ExprResult &RHS,
13729 SourceLocation Loc,
13730 bool IsCompAssign) {
13731 if (!IsCompAssign) {
13732 LHS = DefaultFunctionArrayLvalueConversion(E: LHS.get());
13733 if (LHS.isInvalid())
13734 return QualType();
13735 }
13736 RHS = DefaultFunctionArrayLvalueConversion(E: RHS.get());
13737 if (RHS.isInvalid())
13738 return QualType();
13739
13740 auto *LHSMatType = LHS.get()->getType()->getAs<ConstantMatrixType>();
13741 auto *RHSMatType = RHS.get()->getType()->getAs<ConstantMatrixType>();
13742 assert((LHSMatType || RHSMatType) && "At least one operand must be a matrix");
13743
13744 if (LHSMatType && RHSMatType) {
13745 if (LHSMatType->getNumColumns() != RHSMatType->getNumRows())
13746 return InvalidOperands(Loc, LHS, RHS);
13747
13748 if (Context.hasSameType(T1: LHSMatType, T2: RHSMatType))
13749 return Context.getCommonSugaredType(
13750 X: LHS.get()->getType().getUnqualifiedType(),
13751 Y: RHS.get()->getType().getUnqualifiedType());
13752
13753 QualType LHSELTy = LHSMatType->getElementType(),
13754 RHSELTy = RHSMatType->getElementType();
13755 if (!Context.hasSameType(T1: LHSELTy, T2: RHSELTy))
13756 return InvalidOperands(Loc, LHS, RHS);
13757
13758 return Context.getConstantMatrixType(
13759 ElementType: Context.getCommonSugaredType(X: LHSELTy, Y: RHSELTy),
13760 NumRows: LHSMatType->getNumRows(), NumColumns: RHSMatType->getNumColumns());
13761 }
13762 return CheckMatrixElementwiseOperands(LHS, RHS, Loc, IsCompAssign);
13763}
13764
13765static bool isLegalBoolVectorBinaryOp(BinaryOperatorKind Opc) {
13766 switch (Opc) {
13767 default:
13768 return false;
13769 case BO_And:
13770 case BO_AndAssign:
13771 case BO_Or:
13772 case BO_OrAssign:
13773 case BO_Xor:
13774 case BO_XorAssign:
13775 return true;
13776 }
13777}
13778
13779inline QualType Sema::CheckBitwiseOperands(ExprResult &LHS, ExprResult &RHS,
13780 SourceLocation Loc,
13781 BinaryOperatorKind Opc) {
13782 checkArithmeticNull(S&: *this, LHS, RHS, Loc, /*IsCompare=*/false);
13783
13784 bool IsCompAssign =
13785 Opc == BO_AndAssign || Opc == BO_OrAssign || Opc == BO_XorAssign;
13786
13787 bool LegalBoolVecOperator = isLegalBoolVectorBinaryOp(Opc);
13788
13789 if (LHS.get()->getType()->isVectorType() ||
13790 RHS.get()->getType()->isVectorType()) {
13791 if (LHS.get()->getType()->hasIntegerRepresentation() &&
13792 RHS.get()->getType()->hasIntegerRepresentation())
13793 return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign,
13794 /*AllowBothBool*/ true,
13795 /*AllowBoolConversions*/ getLangOpts().ZVector,
13796 /*AllowBooleanOperation*/ AllowBoolOperation: LegalBoolVecOperator,
13797 /*ReportInvalid*/ true);
13798 return InvalidOperands(Loc, LHS, RHS);
13799 }
13800
13801 if (LHS.get()->getType()->isSveVLSBuiltinType() ||
13802 RHS.get()->getType()->isSveVLSBuiltinType()) {
13803 if (LHS.get()->getType()->hasIntegerRepresentation() &&
13804 RHS.get()->getType()->hasIntegerRepresentation())
13805 return CheckSizelessVectorOperands(LHS, RHS, Loc, IsCompAssign,
13806 OperationKind: ArithConvKind::BitwiseOp);
13807 return InvalidOperands(Loc, LHS, RHS);
13808 }
13809
13810 if (LHS.get()->getType()->isSveVLSBuiltinType() ||
13811 RHS.get()->getType()->isSveVLSBuiltinType()) {
13812 if (LHS.get()->getType()->hasIntegerRepresentation() &&
13813 RHS.get()->getType()->hasIntegerRepresentation())
13814 return CheckSizelessVectorOperands(LHS, RHS, Loc, IsCompAssign,
13815 OperationKind: ArithConvKind::BitwiseOp);
13816 return InvalidOperands(Loc, LHS, RHS);
13817 }
13818
13819 if (Opc == BO_And)
13820 diagnoseLogicalNotOnLHSofCheck(S&: *this, LHS, RHS, Loc, Opc);
13821
13822 if (LHS.get()->getType()->hasFloatingRepresentation() ||
13823 RHS.get()->getType()->hasFloatingRepresentation())
13824 return InvalidOperands(Loc, LHS, RHS);
13825
13826 ExprResult LHSResult = LHS, RHSResult = RHS;
13827 QualType compType = UsualArithmeticConversions(
13828 LHS&: LHSResult, RHS&: RHSResult, Loc,
13829 ACK: IsCompAssign ? ArithConvKind::CompAssign : ArithConvKind::BitwiseOp);
13830 if (LHSResult.isInvalid() || RHSResult.isInvalid())
13831 return QualType();
13832 LHS = LHSResult.get();
13833 RHS = RHSResult.get();
13834
13835 if (Opc == BO_Xor)
13836 diagnoseXorMisusedAsPow(S&: *this, XorLHS: LHS, XorRHS: RHS, Loc);
13837
13838 if (!compType.isNull() && compType->isIntegralOrUnscopedEnumerationType())
13839 return compType;
13840 QualType ResultTy = InvalidOperands(Loc, LHS, RHS);
13841 diagnoseScopedEnums(S&: *this, Loc, LHS, RHS, Opc);
13842 return ResultTy;
13843}
13844
13845// C99 6.5.[13,14]
13846inline QualType Sema::CheckLogicalOperands(ExprResult &LHS, ExprResult &RHS,
13847 SourceLocation Loc,
13848 BinaryOperatorKind Opc) {
13849 // Check vector operands differently.
13850 if (LHS.get()->getType()->isVectorType() ||
13851 RHS.get()->getType()->isVectorType())
13852 return CheckVectorLogicalOperands(LHS, RHS, Loc, Opc);
13853
13854 if (LHS.get()->getType()->isConstantMatrixType() ||
13855 RHS.get()->getType()->isConstantMatrixType())
13856 return CheckMatrixLogicalOperands(LHS, RHS, Loc, Opc);
13857
13858 bool EnumConstantInBoolContext = false;
13859 for (const ExprResult &HS : {LHS, RHS}) {
13860 if (const auto *DREHS = dyn_cast<DeclRefExpr>(Val: HS.get())) {
13861 const auto *ECDHS = dyn_cast<EnumConstantDecl>(Val: DREHS->getDecl());
13862 if (ECDHS && ECDHS->getInitVal() != 0 && ECDHS->getInitVal() != 1)
13863 EnumConstantInBoolContext = true;
13864 }
13865 }
13866
13867 if (EnumConstantInBoolContext)
13868 Diag(Loc, DiagID: diag::warn_enum_constant_in_bool_context);
13869
13870 // WebAssembly tables can't be used with logical operators.
13871 QualType LHSTy = LHS.get()->getType();
13872 QualType RHSTy = RHS.get()->getType();
13873 const auto *LHSATy = dyn_cast<ArrayType>(Val&: LHSTy);
13874 const auto *RHSATy = dyn_cast<ArrayType>(Val&: RHSTy);
13875 if ((LHSATy && LHSATy->getElementType().isWebAssemblyReferenceType()) ||
13876 (RHSATy && RHSATy->getElementType().isWebAssemblyReferenceType())) {
13877 return InvalidOperands(Loc, LHS, RHS);
13878 }
13879
13880 // Diagnose cases where the user write a logical and/or but probably meant a
13881 // bitwise one. We do this when the LHS is a non-bool integer and the RHS
13882 // is a constant.
13883 if (!EnumConstantInBoolContext && LHS.get()->getType()->isIntegerType() &&
13884 !LHS.get()->getType()->isBooleanType() &&
13885 RHS.get()->getType()->isIntegerType() && !RHS.get()->isValueDependent() &&
13886 // Don't warn in macros or template instantiations.
13887 !Loc.isMacroID() && !inTemplateInstantiation()) {
13888 // If the RHS can be constant folded, and if it constant folds to something
13889 // that isn't 0 or 1 (which indicate a potential logical operation that
13890 // happened to fold to true/false) then warn.
13891 // Parens on the RHS are ignored.
13892 Expr::EvalResult EVResult;
13893 if (RHS.get()->EvaluateAsInt(Result&: EVResult, Ctx: Context)) {
13894 llvm::APSInt Result = EVResult.Val.getInt();
13895 if ((getLangOpts().CPlusPlus && !RHS.get()->getType()->isBooleanType() &&
13896 !RHS.get()->getExprLoc().isMacroID()) ||
13897 (Result != 0 && Result != 1)) {
13898 Diag(Loc, DiagID: diag::warn_logical_instead_of_bitwise)
13899 << RHS.get()->getSourceRange() << (Opc == BO_LAnd ? "&&" : "||");
13900 // Suggest replacing the logical operator with the bitwise version
13901 Diag(Loc, DiagID: diag::note_logical_instead_of_bitwise_change_operator)
13902 << (Opc == BO_LAnd ? "&" : "|")
13903 << FixItHint::CreateReplacement(
13904 RemoveRange: SourceRange(Loc, getLocForEndOfToken(Loc)),
13905 Code: Opc == BO_LAnd ? "&" : "|");
13906 if (Opc == BO_LAnd)
13907 // Suggest replacing "Foo() && kNonZero" with "Foo()"
13908 Diag(Loc, DiagID: diag::note_logical_instead_of_bitwise_remove_constant)
13909 << FixItHint::CreateRemoval(
13910 RemoveRange: SourceRange(getLocForEndOfToken(Loc: LHS.get()->getEndLoc()),
13911 RHS.get()->getEndLoc()));
13912 }
13913 }
13914 }
13915
13916 if (!Context.getLangOpts().CPlusPlus) {
13917 // OpenCL v1.1 s6.3.g: The logical operators and (&&), or (||) do
13918 // not operate on the built-in scalar and vector float types.
13919 if (Context.getLangOpts().OpenCL &&
13920 Context.getLangOpts().OpenCLVersion < 120) {
13921 if (LHS.get()->getType()->isFloatingType() ||
13922 RHS.get()->getType()->isFloatingType())
13923 return InvalidOperands(Loc, LHS, RHS);
13924 }
13925
13926 LHS = UsualUnaryConversions(E: LHS.get());
13927 if (LHS.isInvalid())
13928 return QualType();
13929
13930 RHS = UsualUnaryConversions(E: RHS.get());
13931 if (RHS.isInvalid())
13932 return QualType();
13933
13934 if (LHS.get()->getType() == Context.AMDGPUFeaturePredicateTy)
13935 LHS = AMDGPU().ExpandAMDGPUPredicateBuiltIn(CE: LHS.get());
13936 if (RHS.get()->getType() == Context.AMDGPUFeaturePredicateTy)
13937 RHS = AMDGPU().ExpandAMDGPUPredicateBuiltIn(CE: RHS.get());
13938
13939 if (!LHS.get()->getType()->isScalarType() ||
13940 !RHS.get()->getType()->isScalarType())
13941 return InvalidOperands(Loc, LHS, RHS);
13942
13943 return Context.IntTy;
13944 }
13945
13946 // The following is safe because we only use this method for
13947 // non-overloadable operands.
13948
13949 // C++ [expr.log.and]p1
13950 // C++ [expr.log.or]p1
13951 // The operands are both contextually converted to type bool.
13952 ExprResult LHSRes = PerformContextuallyConvertToBool(From: LHS.get());
13953 if (LHSRes.isInvalid()) {
13954 QualType ResultTy = InvalidOperands(Loc, LHS, RHS);
13955 diagnoseScopedEnums(S&: *this, Loc, LHS, RHS, Opc);
13956 return ResultTy;
13957 }
13958 LHS = LHSRes;
13959
13960 ExprResult RHSRes = PerformContextuallyConvertToBool(From: RHS.get());
13961 if (RHSRes.isInvalid()) {
13962 QualType ResultTy = InvalidOperands(Loc, LHS, RHS);
13963 diagnoseScopedEnums(S&: *this, Loc, LHS, RHS, Opc);
13964 return ResultTy;
13965 }
13966 RHS = RHSRes;
13967
13968 // C++ [expr.log.and]p2
13969 // C++ [expr.log.or]p2
13970 // The result is a bool.
13971 return Context.BoolTy;
13972}
13973
13974static bool IsReadonlyMessage(Expr *E, Sema &S) {
13975 const MemberExpr *ME = dyn_cast<MemberExpr>(Val: E);
13976 if (!ME) return false;
13977 if (!isa<FieldDecl>(Val: ME->getMemberDecl())) return false;
13978 ObjCMessageExpr *Base = dyn_cast<ObjCMessageExpr>(
13979 Val: ME->getBase()->IgnoreImplicit()->IgnoreParenImpCasts());
13980 if (!Base) return false;
13981 return Base->getMethodDecl() != nullptr;
13982}
13983
13984/// Is the given expression (which must be 'const') a reference to a
13985/// variable which was originally non-const, but which has become
13986/// 'const' due to being captured within a block?
13987enum NonConstCaptureKind { NCCK_None, NCCK_Block, NCCK_Lambda };
13988static NonConstCaptureKind isReferenceToNonConstCapture(Sema &S, Expr *E) {
13989 assert(E->isLValue() && E->getType().isConstQualified());
13990 E = E->IgnoreParens();
13991
13992 // Must be a reference to a declaration from an enclosing scope.
13993 DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Val: E);
13994 if (!DRE) return NCCK_None;
13995 if (!DRE->refersToEnclosingVariableOrCapture()) return NCCK_None;
13996
13997 ValueDecl *Value = DRE->getDecl();
13998
13999 // The declaration must be a value which is not declared 'const'.
14000 if (Value->getType().isConstQualified())
14001 return NCCK_None;
14002
14003 BindingDecl *Binding = dyn_cast<BindingDecl>(Val: Value);
14004 if (Binding) {
14005 assert(S.getLangOpts().CPlusPlus && "BindingDecl outside of C++?");
14006 assert(!isa<BlockDecl>(Binding->getDeclContext()));
14007 return NCCK_Lambda;
14008 }
14009
14010 VarDecl *Var = dyn_cast<VarDecl>(Val: Value);
14011 if (!Var)
14012 return NCCK_None;
14013 if (Var->getType()->isReferenceType())
14014 return NCCK_None;
14015
14016 assert(Var->hasLocalStorage() && "capture added 'const' to non-local?");
14017
14018 // Decide whether the first capture was for a block or a lambda.
14019 DeclContext *DC = S.CurContext, *Prev = nullptr;
14020 // Decide whether the first capture was for a block or a lambda.
14021 while (DC) {
14022 // For init-capture, it is possible that the variable belongs to the
14023 // template pattern of the current context.
14024 if (auto *FD = dyn_cast<FunctionDecl>(Val: DC))
14025 if (Var->isInitCapture() &&
14026 FD->getTemplateInstantiationPattern() == Var->getDeclContext())
14027 break;
14028 if (DC == Var->getDeclContext())
14029 break;
14030 Prev = DC;
14031 DC = DC->getParent();
14032 }
14033 // Unless we have an init-capture, we've gone one step too far.
14034 if (!Var->isInitCapture())
14035 DC = Prev;
14036 return (isa<BlockDecl>(Val: DC) ? NCCK_Block : NCCK_Lambda);
14037}
14038
14039static bool IsTypeModifiable(QualType Ty, bool IsDereference) {
14040 Ty = Ty.getNonReferenceType();
14041 if (IsDereference && Ty->isPointerType())
14042 Ty = Ty->getPointeeType();
14043 return !Ty.isConstQualified();
14044}
14045
14046// Update err_typecheck_assign_const and note_typecheck_assign_const
14047// when this enum is changed.
14048enum {
14049 ConstFunction,
14050 ConstVariable,
14051 ConstMember,
14052 NestedConstMember,
14053 ConstUnknown, // Keep as last element
14054};
14055
14056/// Emit the "read-only variable not assignable" error and print notes to give
14057/// more information about why the variable is not assignable, such as pointing
14058/// to the declaration of a const variable, showing that a method is const, or
14059/// that the function is returning a const reference.
14060static void DiagnoseConstAssignment(Sema &S, const Expr *E,
14061 SourceLocation Loc) {
14062 SourceRange ExprRange = E->getSourceRange();
14063
14064 // Only emit one error on the first const found. All other consts will emit
14065 // a note to the error.
14066 bool DiagnosticEmitted = false;
14067
14068 // Track if the current expression is the result of a dereference, and if the
14069 // next checked expression is the result of a dereference.
14070 bool IsDereference = false;
14071 bool NextIsDereference = false;
14072
14073 // Loop to process MemberExpr chains.
14074 while (true) {
14075 IsDereference = NextIsDereference;
14076
14077 E = E->IgnoreImplicit()->IgnoreParenImpCasts();
14078 if (const MemberExpr *ME = dyn_cast<MemberExpr>(Val: E)) {
14079 NextIsDereference = ME->isArrow();
14080 const ValueDecl *VD = ME->getMemberDecl();
14081 if (const FieldDecl *Field = dyn_cast<FieldDecl>(Val: VD)) {
14082 // Mutable fields can be modified even if the class is const.
14083 if (Field->isMutable()) {
14084 assert(DiagnosticEmitted && "Expected diagnostic not emitted.");
14085 break;
14086 }
14087
14088 if (!IsTypeModifiable(Ty: Field->getType(), IsDereference)) {
14089 if (!DiagnosticEmitted) {
14090 S.Diag(Loc, DiagID: diag::err_typecheck_assign_const)
14091 << ExprRange << ConstMember << false /*static*/ << Field
14092 << Field->getType();
14093 DiagnosticEmitted = true;
14094 }
14095 S.Diag(Loc: VD->getLocation(), DiagID: diag::note_typecheck_assign_const)
14096 << ConstMember << false /*static*/ << Field << Field->getType()
14097 << Field->getSourceRange();
14098 }
14099 E = ME->getBase();
14100 continue;
14101 } else if (const VarDecl *VDecl = dyn_cast<VarDecl>(Val: VD)) {
14102 if (VDecl->getType().isConstQualified()) {
14103 if (!DiagnosticEmitted) {
14104 S.Diag(Loc, DiagID: diag::err_typecheck_assign_const)
14105 << ExprRange << ConstMember << true /*static*/ << VDecl
14106 << VDecl->getType();
14107 DiagnosticEmitted = true;
14108 }
14109 S.Diag(Loc: VD->getLocation(), DiagID: diag::note_typecheck_assign_const)
14110 << ConstMember << true /*static*/ << VDecl << VDecl->getType()
14111 << VDecl->getSourceRange();
14112 }
14113 // Static fields do not inherit constness from parents.
14114 break;
14115 }
14116 break; // End MemberExpr
14117 } else if (const ArraySubscriptExpr *ASE =
14118 dyn_cast<ArraySubscriptExpr>(Val: E)) {
14119 E = ASE->getBase()->IgnoreParenImpCasts();
14120 continue;
14121 } else if (const ExtVectorElementExpr *EVE =
14122 dyn_cast<ExtVectorElementExpr>(Val: E)) {
14123 E = EVE->getBase()->IgnoreParenImpCasts();
14124 continue;
14125 }
14126 break;
14127 }
14128
14129 if (const CallExpr *CE = dyn_cast<CallExpr>(Val: E)) {
14130 // Function calls
14131 const FunctionDecl *FD = CE->getDirectCallee();
14132 if (FD && !IsTypeModifiable(Ty: FD->getReturnType(), IsDereference)) {
14133 if (!DiagnosticEmitted) {
14134 S.Diag(Loc, DiagID: diag::err_typecheck_assign_const) << ExprRange
14135 << ConstFunction << FD;
14136 DiagnosticEmitted = true;
14137 }
14138 S.Diag(Loc: FD->getReturnTypeSourceRange().getBegin(),
14139 DiagID: diag::note_typecheck_assign_const)
14140 << ConstFunction << FD << FD->getReturnType()
14141 << FD->getReturnTypeSourceRange();
14142 }
14143 } else if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Val: E)) {
14144 // Point to variable declaration.
14145 if (const ValueDecl *VD = DRE->getDecl()) {
14146 if (!IsTypeModifiable(Ty: VD->getType(), IsDereference)) {
14147 if (!DiagnosticEmitted) {
14148 S.Diag(Loc, DiagID: diag::err_typecheck_assign_const)
14149 << ExprRange << ConstVariable << VD << VD->getType();
14150 DiagnosticEmitted = true;
14151 }
14152 S.Diag(Loc: VD->getLocation(), DiagID: diag::note_typecheck_assign_const)
14153 << ConstVariable << VD << VD->getType() << VD->getSourceRange();
14154 }
14155 }
14156 } else if (isa<CXXThisExpr>(Val: E)) {
14157 if (const DeclContext *DC = S.getFunctionLevelDeclContext()) {
14158 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Val: DC)) {
14159 if (MD->isConst()) {
14160 if (!DiagnosticEmitted) {
14161 S.Diag(Loc, DiagID: diag::err_typecheck_assign_const_method)
14162 << ExprRange << MD;
14163 DiagnosticEmitted = true;
14164 }
14165 S.Diag(Loc: MD->getLocation(), DiagID: diag::note_typecheck_assign_const_method)
14166 << MD << MD->getSourceRange();
14167 }
14168 }
14169 }
14170 }
14171
14172 if (DiagnosticEmitted)
14173 return;
14174
14175 // Can't determine a more specific message, so display the generic error.
14176 S.Diag(Loc, DiagID: diag::err_typecheck_assign_const) << ExprRange << ConstUnknown;
14177}
14178
14179enum OriginalExprKind {
14180 OEK_Variable,
14181 OEK_Member,
14182 OEK_LValue
14183};
14184
14185static void DiagnoseRecursiveConstFields(Sema &S, const ValueDecl *VD,
14186 const RecordType *Ty,
14187 SourceLocation Loc, SourceRange Range,
14188 OriginalExprKind OEK,
14189 bool &DiagnosticEmitted) {
14190 std::vector<const RecordType *> RecordTypeList;
14191 RecordTypeList.push_back(x: Ty);
14192 unsigned NextToCheckIndex = 0;
14193 // We walk the record hierarchy breadth-first to ensure that we print
14194 // diagnostics in field nesting order.
14195 while (RecordTypeList.size() > NextToCheckIndex) {
14196 bool IsNested = NextToCheckIndex > 0;
14197 for (const FieldDecl *Field : RecordTypeList[NextToCheckIndex]
14198 ->getDecl()
14199 ->getDefinitionOrSelf()
14200 ->fields()) {
14201 // First, check every field for constness.
14202 QualType FieldTy = Field->getType();
14203 if (FieldTy.isConstQualified()) {
14204 if (!DiagnosticEmitted) {
14205 S.Diag(Loc, DiagID: diag::err_typecheck_assign_const)
14206 << Range << NestedConstMember << OEK << VD
14207 << IsNested << Field;
14208 DiagnosticEmitted = true;
14209 }
14210 S.Diag(Loc: Field->getLocation(), DiagID: diag::note_typecheck_assign_const)
14211 << NestedConstMember << IsNested << Field
14212 << FieldTy << Field->getSourceRange();
14213 }
14214
14215 // Then we append it to the list to check next in order.
14216 FieldTy = FieldTy.getCanonicalType();
14217 if (const auto *FieldRecTy = FieldTy->getAsCanonical<RecordType>()) {
14218 if (!llvm::is_contained(Range&: RecordTypeList, Element: FieldRecTy))
14219 RecordTypeList.push_back(x: FieldRecTy);
14220 }
14221 }
14222 ++NextToCheckIndex;
14223 }
14224}
14225
14226/// Emit an error for the case where a record we are trying to assign to has a
14227/// const-qualified field somewhere in its hierarchy.
14228static void DiagnoseRecursiveConstFields(Sema &S, const Expr *E,
14229 SourceLocation Loc) {
14230 QualType Ty = E->getType();
14231 assert(Ty->isRecordType() && "lvalue was not record?");
14232 SourceRange Range = E->getSourceRange();
14233 const auto *RTy = Ty->getAsCanonical<RecordType>();
14234 bool DiagEmitted = false;
14235
14236 if (const MemberExpr *ME = dyn_cast<MemberExpr>(Val: E))
14237 DiagnoseRecursiveConstFields(S, VD: ME->getMemberDecl(), Ty: RTy, Loc,
14238 Range, OEK: OEK_Member, DiagnosticEmitted&: DiagEmitted);
14239 else if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Val: E))
14240 DiagnoseRecursiveConstFields(S, VD: DRE->getDecl(), Ty: RTy, Loc,
14241 Range, OEK: OEK_Variable, DiagnosticEmitted&: DiagEmitted);
14242 else
14243 DiagnoseRecursiveConstFields(S, VD: nullptr, Ty: RTy, Loc,
14244 Range, OEK: OEK_LValue, DiagnosticEmitted&: DiagEmitted);
14245 if (!DiagEmitted)
14246 DiagnoseConstAssignment(S, E, Loc);
14247}
14248
14249/// CheckForModifiableLvalue - Verify that E is a modifiable lvalue. If not,
14250/// emit an error and return true. If so, return false.
14251static bool CheckForModifiableLvalue(Expr *E, SourceLocation Loc, Sema &S) {
14252 assert(!E->hasPlaceholderType(BuiltinType::PseudoObject));
14253
14254 S.CheckShadowingDeclModification(E, Loc);
14255
14256 SourceLocation OrigLoc = Loc;
14257 Expr::isModifiableLvalueResult IsLV = E->isModifiableLvalue(Ctx&: S.Context,
14258 Loc: &Loc);
14259 if (IsLV == Expr::MLV_ClassTemporary && IsReadonlyMessage(E, S))
14260 IsLV = Expr::MLV_InvalidMessageExpression;
14261 if (IsLV == Expr::MLV_Valid)
14262 return false;
14263
14264 unsigned DiagID = 0;
14265 bool NeedType = false;
14266 switch (IsLV) { // C99 6.5.16p2
14267 case Expr::MLV_ConstQualified:
14268 // Use a specialized diagnostic when we're assigning to an object
14269 // from an enclosing function or block.
14270 if (NonConstCaptureKind NCCK = isReferenceToNonConstCapture(S, E)) {
14271 if (NCCK == NCCK_Block)
14272 DiagID = diag::err_block_decl_ref_not_modifiable_lvalue;
14273 else
14274 DiagID = diag::err_lambda_decl_ref_not_modifiable_lvalue;
14275 break;
14276 }
14277
14278 // In ARC, use some specialized diagnostics for occasions where we
14279 // infer 'const'. These are always pseudo-strong variables.
14280 if (S.getLangOpts().ObjCAutoRefCount) {
14281 DeclRefExpr *declRef = dyn_cast<DeclRefExpr>(Val: E->IgnoreParenCasts());
14282 if (declRef && isa<VarDecl>(Val: declRef->getDecl())) {
14283 VarDecl *var = cast<VarDecl>(Val: declRef->getDecl());
14284
14285 // Use the normal diagnostic if it's pseudo-__strong but the
14286 // user actually wrote 'const'.
14287 if (var->isARCPseudoStrong() &&
14288 (!var->getTypeSourceInfo() ||
14289 !var->getTypeSourceInfo()->getType().isConstQualified())) {
14290 // There are three pseudo-strong cases:
14291 // - self
14292 ObjCMethodDecl *method = S.getCurMethodDecl();
14293 if (method && var == method->getSelfDecl()) {
14294 DiagID = method->isClassMethod()
14295 ? diag::err_typecheck_arc_assign_self_class_method
14296 : diag::err_typecheck_arc_assign_self;
14297
14298 // - Objective-C externally_retained attribute.
14299 } else if (var->hasAttr<ObjCExternallyRetainedAttr>() ||
14300 isa<ParmVarDecl>(Val: var)) {
14301 DiagID = diag::err_typecheck_arc_assign_externally_retained;
14302
14303 // - fast enumeration variables
14304 } else {
14305 DiagID = diag::err_typecheck_arr_assign_enumeration;
14306 }
14307
14308 SourceRange Assign;
14309 if (Loc != OrigLoc)
14310 Assign = SourceRange(OrigLoc, OrigLoc);
14311 S.Diag(Loc, DiagID) << E->getSourceRange() << Assign;
14312 // We need to preserve the AST regardless, so migration tool
14313 // can do its job.
14314 return false;
14315 }
14316 }
14317 }
14318
14319 // If none of the special cases above are triggered, then this is a
14320 // simple const assignment.
14321 if (DiagID == 0) {
14322 DiagnoseConstAssignment(S, E, Loc);
14323 return true;
14324 }
14325
14326 break;
14327 case Expr::MLV_ConstAddrSpace:
14328 DiagnoseConstAssignment(S, E, Loc);
14329 return true;
14330 case Expr::MLV_ConstQualifiedField:
14331 DiagnoseRecursiveConstFields(S, E, Loc);
14332 return true;
14333 case Expr::MLV_ArrayType:
14334 case Expr::MLV_ArrayTemporary:
14335 DiagID = diag::err_typecheck_array_not_modifiable_lvalue;
14336 NeedType = true;
14337 break;
14338 case Expr::MLV_NotObjectType:
14339 DiagID = diag::err_typecheck_non_object_not_modifiable_lvalue;
14340 NeedType = true;
14341 break;
14342 case Expr::MLV_LValueCast:
14343 DiagID = diag::err_typecheck_lvalue_casts_not_supported;
14344 break;
14345 case Expr::MLV_Valid:
14346 llvm_unreachable("did not take early return for MLV_Valid");
14347 case Expr::MLV_InvalidExpression:
14348 case Expr::MLV_MemberFunction:
14349 case Expr::MLV_ClassTemporary:
14350 DiagID = diag::err_typecheck_expression_not_modifiable_lvalue;
14351 break;
14352 case Expr::MLV_IncompleteType:
14353 case Expr::MLV_IncompleteVoidType:
14354 return S.RequireCompleteType(Loc, T: E->getType(),
14355 DiagID: diag::err_typecheck_incomplete_type_not_modifiable_lvalue, Args: E);
14356 case Expr::MLV_DuplicateVectorComponents:
14357 DiagID = diag::err_typecheck_duplicate_vector_components_not_mlvalue;
14358 break;
14359 case Expr::MLV_DuplicateMatrixComponents:
14360 DiagID = diag::err_typecheck_duplicate_matrix_components_not_mlvalue;
14361 break;
14362 case Expr::MLV_NoSetterProperty:
14363 llvm_unreachable("readonly properties should be processed differently");
14364 case Expr::MLV_InvalidMessageExpression:
14365 DiagID = diag::err_readonly_message_assignment;
14366 break;
14367 case Expr::MLV_SubObjCPropertySetting:
14368 DiagID = diag::err_no_subobject_property_setting;
14369 break;
14370 }
14371
14372 SourceRange Assign;
14373 if (Loc != OrigLoc)
14374 Assign = SourceRange(OrigLoc, OrigLoc);
14375 if (NeedType)
14376 S.Diag(Loc, DiagID) << E->getType() << E->getSourceRange() << Assign;
14377 else
14378 S.Diag(Loc, DiagID) << E->getSourceRange() << Assign;
14379 return true;
14380}
14381
14382static void CheckIdentityFieldAssignment(Expr *LHSExpr, Expr *RHSExpr,
14383 SourceLocation Loc,
14384 Sema &Sema) {
14385 if (Sema.inTemplateInstantiation())
14386 return;
14387 if (Sema.isUnevaluatedContext())
14388 return;
14389 if (Loc.isInvalid() || Loc.isMacroID())
14390 return;
14391 if (LHSExpr->getExprLoc().isMacroID() || RHSExpr->getExprLoc().isMacroID())
14392 return;
14393
14394 // C / C++ fields
14395 MemberExpr *ML = dyn_cast<MemberExpr>(Val: LHSExpr);
14396 MemberExpr *MR = dyn_cast<MemberExpr>(Val: RHSExpr);
14397 if (ML && MR) {
14398 if (!(isa<CXXThisExpr>(Val: ML->getBase()) && isa<CXXThisExpr>(Val: MR->getBase())))
14399 return;
14400 const ValueDecl *LHSDecl =
14401 cast<ValueDecl>(Val: ML->getMemberDecl()->getCanonicalDecl());
14402 const ValueDecl *RHSDecl =
14403 cast<ValueDecl>(Val: MR->getMemberDecl()->getCanonicalDecl());
14404 if (LHSDecl != RHSDecl)
14405 return;
14406 if (LHSDecl->getType().isVolatileQualified())
14407 return;
14408 if (const ReferenceType *RefTy = LHSDecl->getType()->getAs<ReferenceType>())
14409 if (RefTy->getPointeeType().isVolatileQualified())
14410 return;
14411
14412 Sema.Diag(Loc, DiagID: diag::warn_identity_field_assign) << 0;
14413 }
14414
14415 // Objective-C instance variables
14416 ObjCIvarRefExpr *OL = dyn_cast<ObjCIvarRefExpr>(Val: LHSExpr);
14417 ObjCIvarRefExpr *OR = dyn_cast<ObjCIvarRefExpr>(Val: RHSExpr);
14418 if (OL && OR && OL->getDecl() == OR->getDecl()) {
14419 DeclRefExpr *RL = dyn_cast<DeclRefExpr>(Val: OL->getBase()->IgnoreImpCasts());
14420 DeclRefExpr *RR = dyn_cast<DeclRefExpr>(Val: OR->getBase()->IgnoreImpCasts());
14421 if (RL && RR && RL->getDecl() == RR->getDecl())
14422 Sema.Diag(Loc, DiagID: diag::warn_identity_field_assign) << 1;
14423 }
14424}
14425
14426// C99 6.5.16.1
14427QualType Sema::CheckAssignmentOperands(Expr *LHSExpr, ExprResult &RHS,
14428 SourceLocation Loc,
14429 QualType CompoundType,
14430 BinaryOperatorKind Opc) {
14431 assert(!LHSExpr->hasPlaceholderType(BuiltinType::PseudoObject));
14432
14433 // Verify that LHS is a modifiable lvalue, and emit error if not.
14434 if (CheckForModifiableLvalue(E: LHSExpr, Loc, S&: *this))
14435 return QualType();
14436
14437 QualType LHSType = LHSExpr->getType();
14438 QualType RHSType = CompoundType.isNull() ? RHS.get()->getType() :
14439 CompoundType;
14440
14441 if (RHS.isUsable()) {
14442 // Even if this check fails don't return early to allow the best
14443 // possible error recovery and to allow any subsequent diagnostics to
14444 // work.
14445 const ValueDecl *Assignee = nullptr;
14446 bool ShowFullyQualifiedAssigneeName = false;
14447 // In simple cases describe what is being assigned to
14448 if (auto *DR = dyn_cast<DeclRefExpr>(Val: LHSExpr->IgnoreParenCasts())) {
14449 Assignee = DR->getDecl();
14450 } else if (auto *ME = dyn_cast<MemberExpr>(Val: LHSExpr->IgnoreParenCasts())) {
14451 Assignee = ME->getMemberDecl();
14452 ShowFullyQualifiedAssigneeName = true;
14453 }
14454
14455 BoundsSafetyCheckAssignmentToCountAttrPtr(
14456 LHSTy: LHSType, RHSExpr: RHS.get(), Action: AssignmentAction::Assigning, Loc, Assignee,
14457 ShowFullyQualifiedAssigneeName);
14458 }
14459
14460 // OpenCL v1.2 s6.1.1.1 p2:
14461 // The half data type can only be used to declare a pointer to a buffer that
14462 // contains half values
14463 if (getLangOpts().OpenCL &&
14464 !getOpenCLOptions().isAvailableOption(Ext: "cl_khr_fp16", LO: getLangOpts()) &&
14465 LHSType->isHalfType()) {
14466 Diag(Loc, DiagID: diag::err_opencl_half_load_store) << 1
14467 << LHSType.getUnqualifiedType();
14468 return QualType();
14469 }
14470
14471 // WebAssembly tables can't be used on RHS of an assignment expression.
14472 if (RHSType->isWebAssemblyTableType()) {
14473 Diag(Loc, DiagID: diag::err_wasm_table_art) << 0;
14474 return QualType();
14475 }
14476
14477 AssignConvertType ConvTy;
14478 if (CompoundType.isNull()) {
14479 Expr *RHSCheck = RHS.get();
14480
14481 CheckIdentityFieldAssignment(LHSExpr, RHSExpr: RHSCheck, Loc, Sema&: *this);
14482
14483 QualType LHSTy(LHSType);
14484 ConvTy = CheckSingleAssignmentConstraints(LHSType: LHSTy, CallerRHS&: RHS);
14485 if (RHS.isInvalid())
14486 return QualType();
14487 // Special case of NSObject attributes on c-style pointer types.
14488 if (ConvTy == AssignConvertType::IncompatiblePointer &&
14489 ((Context.isObjCNSObjectType(Ty: LHSType) &&
14490 RHSType->isObjCObjectPointerType()) ||
14491 (Context.isObjCNSObjectType(Ty: RHSType) &&
14492 LHSType->isObjCObjectPointerType())))
14493 ConvTy = AssignConvertType::Compatible;
14494
14495 if (IsAssignConvertCompatible(ConvTy) && LHSType->isObjCObjectType())
14496 Diag(Loc, DiagID: diag::err_objc_object_assignment) << LHSType;
14497
14498 // If the RHS is a unary plus or minus, check to see if they = and + are
14499 // right next to each other. If so, the user may have typo'd "x =+ 4"
14500 // instead of "x += 4".
14501 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Val: RHSCheck))
14502 RHSCheck = ICE->getSubExpr();
14503 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(Val: RHSCheck)) {
14504 if ((UO->getOpcode() == UO_Plus || UO->getOpcode() == UO_Minus) &&
14505 Loc.isFileID() && UO->getOperatorLoc().isFileID() &&
14506 // Only if the two operators are exactly adjacent.
14507 Loc.getLocWithOffset(Offset: 1) == UO->getOperatorLoc() &&
14508 // And there is a space or other character before the subexpr of the
14509 // unary +/-. We don't want to warn on "x=-1".
14510 Loc.getLocWithOffset(Offset: 2) != UO->getSubExpr()->getBeginLoc() &&
14511 UO->getSubExpr()->getBeginLoc().isFileID()) {
14512 Diag(Loc, DiagID: diag::warn_not_compound_assign)
14513 << (UO->getOpcode() == UO_Plus ? "+" : "-")
14514 << SourceRange(UO->getOperatorLoc(), UO->getOperatorLoc());
14515 }
14516 }
14517
14518 if (IsAssignConvertCompatible(ConvTy)) {
14519 if (LHSType.getObjCLifetime() == Qualifiers::OCL_Strong) {
14520 // Warn about retain cycles where a block captures the LHS, but
14521 // not if the LHS is a simple variable into which the block is
14522 // being stored...unless that variable can be captured by reference!
14523 const Expr *InnerLHS = LHSExpr->IgnoreParenCasts();
14524 const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Val: InnerLHS);
14525 if (!DRE || DRE->getDecl()->hasAttr<BlocksAttr>())
14526 ObjC().checkRetainCycles(receiver: LHSExpr, argument: RHS.get());
14527 }
14528
14529 if (LHSType.getObjCLifetime() == Qualifiers::OCL_Strong ||
14530 LHSType.isNonWeakInMRRWithObjCWeak(Context)) {
14531 // It is safe to assign a weak reference into a strong variable.
14532 // Although this code can still have problems:
14533 // id x = self.weakProp;
14534 // id y = self.weakProp;
14535 // we do not warn to warn spuriously when 'x' and 'y' are on separate
14536 // paths through the function. This should be revisited if
14537 // -Wrepeated-use-of-weak is made flow-sensitive.
14538 // For ObjCWeak only, we do not warn if the assign is to a non-weak
14539 // variable, which will be valid for the current autorelease scope.
14540 if (!Diags.isIgnored(DiagID: diag::warn_arc_repeated_use_of_weak,
14541 Loc: RHS.get()->getBeginLoc()))
14542 getCurFunction()->markSafeWeakUse(E: RHS.get());
14543
14544 } else if (getLangOpts().ObjCAutoRefCount || getLangOpts().ObjCWeak) {
14545 checkUnsafeExprAssigns(Loc, LHS: LHSExpr, RHS: RHS.get());
14546 }
14547 }
14548 } else {
14549 // Compound assignment "x += y"
14550 ConvTy = CheckAssignmentConstraints(Loc, LHSType, RHSType);
14551 }
14552
14553 if (DiagnoseAssignmentResult(ConvTy, Loc, DstType: LHSType, SrcType: RHSType, SrcExpr: RHS.get(),
14554 Action: AssignmentAction::Assigning))
14555 return QualType();
14556
14557 CheckForNullPointerDereference(S&: *this, E: LHSExpr);
14558
14559 AssignedEntity AE{.LHS: LHSExpr};
14560 checkAssignmentLifetime(SemaRef&: *this, Entity: AE, Init: RHS.get());
14561
14562 if (getLangOpts().CPlusPlus20 && LHSType.isVolatileQualified()) {
14563 if (CompoundType.isNull()) {
14564 // C++2a [expr.ass]p5:
14565 // A simple-assignment whose left operand is of a volatile-qualified
14566 // type is deprecated unless the assignment is either a discarded-value
14567 // expression or an unevaluated operand
14568 ExprEvalContexts.back().VolatileAssignmentLHSs.push_back(Elt: LHSExpr);
14569 }
14570 }
14571
14572 // C11 6.5.16p3: The type of an assignment expression is the type of the
14573 // left operand would have after lvalue conversion.
14574 // C11 6.3.2.1p2: ...this is called lvalue conversion. If the lvalue has
14575 // qualified type, the value has the unqualified version of the type of the
14576 // lvalue; additionally, if the lvalue has atomic type, the value has the
14577 // non-atomic version of the type of the lvalue.
14578 // C++ 5.17p1: the type of the assignment expression is that of its left
14579 // operand.
14580 return getLangOpts().CPlusPlus ? LHSType : LHSType.getAtomicUnqualifiedType();
14581}
14582
14583// Scenarios to ignore if expression E is:
14584// 1. an explicit cast expression into void
14585// 2. a function call expression that returns void
14586static bool IgnoreCommaOperand(const Expr *E, const ASTContext &Context) {
14587 E = E->IgnoreParens();
14588
14589 if (const CastExpr *CE = dyn_cast<CastExpr>(Val: E)) {
14590 if (CE->getCastKind() == CK_ToVoid) {
14591 return true;
14592 }
14593
14594 // static_cast<void> on a dependent type will not show up as CK_ToVoid.
14595 if (CE->getCastKind() == CK_Dependent && E->getType()->isVoidType() &&
14596 CE->getSubExpr()->getType()->isDependentType()) {
14597 return true;
14598 }
14599 }
14600
14601 if (const auto *CE = dyn_cast<CallExpr>(Val: E))
14602 return CE->getCallReturnType(Ctx: Context)->isVoidType();
14603 return false;
14604}
14605
14606void Sema::DiagnoseCommaOperator(const Expr *LHS, SourceLocation Loc) {
14607 // No warnings in macros
14608 if (Loc.isMacroID())
14609 return;
14610
14611 // Don't warn in template instantiations.
14612 if (inTemplateInstantiation())
14613 return;
14614
14615 // Scope isn't fine-grained enough to explicitly list the specific cases, so
14616 // instead, skip more than needed, then call back into here with the
14617 // CommaVisitor in SemaStmt.cpp.
14618 // The listed locations are the initialization and increment portions
14619 // of a for loop. The additional checks are on the condition of
14620 // if statements, do/while loops, and for loops.
14621 // Differences in scope flags for C89 mode requires the extra logic.
14622 const unsigned ForIncrementFlags =
14623 getLangOpts().C99 || getLangOpts().CPlusPlus
14624 ? Scope::ControlScope | Scope::ContinueScope | Scope::BreakScope
14625 : Scope::ContinueScope | Scope::BreakScope;
14626 const unsigned ForInitFlags = Scope::ControlScope | Scope::DeclScope;
14627 const unsigned ScopeFlags = getCurScope()->getFlags();
14628 if ((ScopeFlags & ForIncrementFlags) == ForIncrementFlags ||
14629 (ScopeFlags & ForInitFlags) == ForInitFlags)
14630 return;
14631
14632 // If there are multiple comma operators used together, get the RHS of the
14633 // of the comma operator as the LHS.
14634 while (const BinaryOperator *BO = dyn_cast<BinaryOperator>(Val: LHS)) {
14635 if (BO->getOpcode() != BO_Comma)
14636 break;
14637 LHS = BO->getRHS();
14638 }
14639
14640 // Only allow some expressions on LHS to not warn.
14641 if (IgnoreCommaOperand(E: LHS, Context))
14642 return;
14643
14644 Diag(Loc, DiagID: diag::warn_comma_operator);
14645 Diag(Loc: LHS->getBeginLoc(), DiagID: diag::note_cast_to_void)
14646 << LHS->getSourceRange()
14647 << FixItHint::CreateInsertion(InsertionLoc: LHS->getBeginLoc(),
14648 Code: LangOpts.CPlusPlus ? "static_cast<void>("
14649 : "(void)(")
14650 << FixItHint::CreateInsertion(InsertionLoc: PP.getLocForEndOfToken(Loc: LHS->getEndLoc()),
14651 Code: ")");
14652}
14653
14654// C99 6.5.17
14655static QualType CheckCommaOperands(Sema &S, ExprResult &LHS, ExprResult &RHS,
14656 SourceLocation Loc) {
14657 LHS = S.CheckPlaceholderExpr(E: LHS.get());
14658 RHS = S.CheckPlaceholderExpr(E: RHS.get());
14659 if (LHS.isInvalid() || RHS.isInvalid())
14660 return QualType();
14661
14662 // C's comma performs lvalue conversion (C99 6.3.2.1) on both its
14663 // operands, but not unary promotions.
14664 // C++'s comma does not do any conversions at all (C++ [expr.comma]p1).
14665
14666 // So we treat the LHS as a ignored value, and in C++ we allow the
14667 // containing site to determine what should be done with the RHS.
14668 LHS = S.IgnoredValueConversions(E: LHS.get());
14669 if (LHS.isInvalid())
14670 return QualType();
14671
14672 S.DiagnoseUnusedExprResult(S: LHS.get(), DiagID: diag::warn_unused_comma_left_operand);
14673
14674 if (!S.getLangOpts().CPlusPlus) {
14675 RHS = S.DefaultFunctionArrayLvalueConversion(E: RHS.get());
14676 if (RHS.isInvalid())
14677 return QualType();
14678 if (!RHS.get()->getType()->isVoidType())
14679 S.RequireCompleteType(Loc, T: RHS.get()->getType(),
14680 DiagID: diag::err_incomplete_type);
14681 }
14682
14683 if (!S.getDiagnostics().isIgnored(DiagID: diag::warn_comma_operator, Loc))
14684 S.DiagnoseCommaOperator(LHS: LHS.get(), Loc);
14685
14686 return RHS.get()->getType();
14687}
14688
14689/// CheckIncrementDecrementOperand - unlike most "Check" methods, this routine
14690/// doesn't need to call UsualUnaryConversions or UsualArithmeticConversions.
14691static QualType CheckIncrementDecrementOperand(Sema &S, Expr *Op,
14692 ExprValueKind &VK,
14693 ExprObjectKind &OK,
14694 SourceLocation OpLoc, bool IsInc,
14695 bool IsPrefix) {
14696 QualType ResType = Op->getType();
14697 // Atomic types can be used for increment / decrement where the non-atomic
14698 // versions can, so ignore the _Atomic() specifier for the purpose of
14699 // checking.
14700 if (const AtomicType *ResAtomicType = ResType->getAs<AtomicType>())
14701 ResType = ResAtomicType->getValueType();
14702
14703 assert(!ResType.isNull() && "no type for increment/decrement expression");
14704
14705 if (S.getLangOpts().CPlusPlus && ResType->isBooleanType()) {
14706 // Decrement of bool is not allowed.
14707 if (!IsInc) {
14708 S.Diag(Loc: OpLoc, DiagID: diag::err_decrement_bool) << Op->getSourceRange();
14709 return QualType();
14710 }
14711 // Increment of bool sets it to true, but is deprecated.
14712 S.Diag(Loc: OpLoc, DiagID: S.getLangOpts().CPlusPlus17 ? diag::ext_increment_bool
14713 : diag::warn_increment_bool)
14714 << Op->getSourceRange();
14715 } else if (S.getLangOpts().CPlusPlus && ResType->isEnumeralType()) {
14716 // Error on enum increments and decrements in C++ mode
14717 S.Diag(Loc: OpLoc, DiagID: diag::err_increment_decrement_enum) << IsInc << ResType;
14718 return QualType();
14719 } else if (ResType->isRealType()) {
14720 // OK!
14721 } else if (ResType->isPointerType()) {
14722 // C99 6.5.2.4p2, 6.5.6p2
14723 if (!checkArithmeticOpPointerOperand(S, Loc: OpLoc, Operand: Op))
14724 return QualType();
14725 } else if (ResType->isOverflowBehaviorType()) {
14726 // OK!
14727 } else if (ResType->isObjCObjectPointerType()) {
14728 // On modern runtimes, ObjC pointer arithmetic is forbidden.
14729 // Otherwise, we just need a complete type.
14730 if (checkArithmeticIncompletePointerType(S, Loc: OpLoc, Operand: Op) ||
14731 checkArithmeticOnObjCPointer(S, opLoc: OpLoc, op: Op))
14732 return QualType();
14733 } else if (ResType->isAnyComplexType()) {
14734 // C99 does not support ++/-- on complex types, we allow as an extension.
14735 S.Diag(Loc: OpLoc, DiagID: S.getLangOpts().C2y ? diag::warn_c2y_compat_increment_complex
14736 : diag::ext_c2y_increment_complex)
14737 << IsInc << Op->getSourceRange();
14738 } else if (ResType->isPlaceholderType()) {
14739 ExprResult PR = S.CheckPlaceholderExpr(E: Op);
14740 if (PR.isInvalid()) return QualType();
14741 return CheckIncrementDecrementOperand(S, Op: PR.get(), VK, OK, OpLoc,
14742 IsInc, IsPrefix);
14743 } else if (S.getLangOpts().AltiVec && ResType->isVectorType()) {
14744 // OK! ( C/C++ Language Extensions for CBEA(Version 2.6) 10.3 )
14745 } else if (S.getLangOpts().ZVector && ResType->isVectorType() &&
14746 (ResType->castAs<VectorType>()->getVectorKind() !=
14747 VectorKind::AltiVecBool)) {
14748 // The z vector extensions allow ++ and -- for non-bool vectors.
14749 } else if (S.getLangOpts().OpenCL && ResType->isVectorType() &&
14750 ResType->castAs<VectorType>()->getElementType()->isIntegerType()) {
14751 // OpenCL V1.2 6.3 says dec/inc ops operate on integer vector types.
14752 } else {
14753 S.Diag(Loc: OpLoc, DiagID: diag::err_typecheck_illegal_increment_decrement)
14754 << ResType << int(IsInc) << Op->getSourceRange();
14755 return QualType();
14756 }
14757 // At this point, we know we have a real, complex or pointer type.
14758 // Now make sure the operand is a modifiable lvalue.
14759 if (CheckForModifiableLvalue(E: Op, Loc: OpLoc, S))
14760 return QualType();
14761 if (S.getLangOpts().CPlusPlus20 && ResType.isVolatileQualified()) {
14762 // C++2a [expr.pre.inc]p1, [expr.post.inc]p1:
14763 // An operand with volatile-qualified type is deprecated
14764 S.Diag(Loc: OpLoc, DiagID: diag::warn_deprecated_increment_decrement_volatile)
14765 << IsInc << ResType;
14766 }
14767 // In C++, a prefix increment is the same type as the operand. Otherwise
14768 // (in C or with postfix), the increment is the unqualified type of the
14769 // operand.
14770 if (IsPrefix && S.getLangOpts().CPlusPlus) {
14771 VK = VK_LValue;
14772 OK = Op->getObjectKind();
14773 return ResType;
14774 } else {
14775 VK = VK_PRValue;
14776 return ResType.getUnqualifiedType();
14777 }
14778}
14779
14780/// getPrimaryDecl - Helper function for CheckAddressOfOperand().
14781/// This routine allows us to typecheck complex/recursive expressions
14782/// where the declaration is needed for type checking. We only need to
14783/// handle cases when the expression references a function designator
14784/// or is an lvalue. Here are some examples:
14785/// - &(x) => x
14786/// - &*****f => f for f a function designator.
14787/// - &s.xx => s
14788/// - &s.zz[1].yy -> s, if zz is an array
14789/// - *(x + 1) -> x, if x is an array
14790/// - &"123"[2] -> 0
14791/// - & __real__ x -> x
14792///
14793/// FIXME: We don't recurse to the RHS of a comma, nor handle pointers to
14794/// members.
14795static ValueDecl *getPrimaryDecl(Expr *E) {
14796 switch (E->getStmtClass()) {
14797 case Stmt::DeclRefExprClass:
14798 return cast<DeclRefExpr>(Val: E)->getDecl();
14799 case Stmt::MemberExprClass:
14800 // If this is an arrow operator, the address is an offset from
14801 // the base's value, so the object the base refers to is
14802 // irrelevant.
14803 if (cast<MemberExpr>(Val: E)->isArrow())
14804 return nullptr;
14805 // Otherwise, the expression refers to a part of the base
14806 return getPrimaryDecl(E: cast<MemberExpr>(Val: E)->getBase());
14807 case Stmt::ArraySubscriptExprClass: {
14808 // FIXME: This code shouldn't be necessary! We should catch the implicit
14809 // promotion of register arrays earlier.
14810 Expr* Base = cast<ArraySubscriptExpr>(Val: E)->getBase();
14811 if (ImplicitCastExpr* ICE = dyn_cast<ImplicitCastExpr>(Val: Base)) {
14812 if (ICE->getSubExpr()->getType()->isArrayType())
14813 return getPrimaryDecl(E: ICE->getSubExpr());
14814 }
14815 return nullptr;
14816 }
14817 case Stmt::UnaryOperatorClass: {
14818 UnaryOperator *UO = cast<UnaryOperator>(Val: E);
14819
14820 switch(UO->getOpcode()) {
14821 case UO_Real:
14822 case UO_Imag:
14823 case UO_Extension:
14824 return getPrimaryDecl(E: UO->getSubExpr());
14825 default:
14826 return nullptr;
14827 }
14828 }
14829 case Stmt::ParenExprClass:
14830 return getPrimaryDecl(E: cast<ParenExpr>(Val: E)->getSubExpr());
14831 case Stmt::ImplicitCastExprClass:
14832 // If the result of an implicit cast is an l-value, we care about
14833 // the sub-expression; otherwise, the result here doesn't matter.
14834 return getPrimaryDecl(E: cast<ImplicitCastExpr>(Val: E)->getSubExpr());
14835 case Stmt::CXXUuidofExprClass:
14836 return cast<CXXUuidofExpr>(Val: E)->getGuidDecl();
14837 default:
14838 return nullptr;
14839 }
14840}
14841
14842namespace {
14843enum {
14844 AO_Bit_Field = 0,
14845 AO_Vector_Element = 1,
14846 AO_Property_Expansion = 2,
14847 AO_Register_Variable = 3,
14848 AO_Matrix_Element = 4,
14849 AO_No_Error = 5
14850};
14851}
14852/// Diagnose invalid operand for address of operations.
14853///
14854/// \param Type The type of operand which cannot have its address taken.
14855static void diagnoseAddressOfInvalidType(Sema &S, SourceLocation Loc,
14856 Expr *E, unsigned Type) {
14857 S.Diag(Loc, DiagID: diag::err_typecheck_address_of) << Type << E->getSourceRange();
14858}
14859
14860bool Sema::CheckUseOfCXXMethodAsAddressOfOperand(SourceLocation OpLoc,
14861 const Expr *Op,
14862 const CXXMethodDecl *MD) {
14863 const auto *DRE = cast<DeclRefExpr>(Val: Op->IgnoreParens());
14864
14865 if (Op != DRE)
14866 return Diag(Loc: OpLoc, DiagID: diag::err_parens_pointer_member_function)
14867 << Op->getSourceRange();
14868
14869 // Taking the address of a dtor is illegal per C++ [class.dtor]p2.
14870 if (isa<CXXDestructorDecl>(Val: MD))
14871 return Diag(Loc: OpLoc, DiagID: diag::err_typecheck_addrof_dtor)
14872 << DRE->getSourceRange();
14873
14874 if (DRE->getQualifier())
14875 return false;
14876
14877 if (MD->getParent()->getName().empty())
14878 return Diag(Loc: OpLoc, DiagID: diag::err_unqualified_pointer_member_function)
14879 << DRE->getSourceRange();
14880
14881 SmallString<32> Str;
14882 StringRef Qual = (MD->getParent()->getName() + "::").toStringRef(Out&: Str);
14883 return Diag(Loc: OpLoc, DiagID: diag::err_unqualified_pointer_member_function)
14884 << DRE->getSourceRange()
14885 << FixItHint::CreateInsertion(InsertionLoc: DRE->getSourceRange().getBegin(), Code: Qual);
14886}
14887
14888QualType Sema::CheckAddressOfOperand(ExprResult &OrigOp, SourceLocation OpLoc) {
14889 if (const BuiltinType *PTy = OrigOp.get()->getType()->getAsPlaceholderType()){
14890 if (PTy->getKind() == BuiltinType::Overload) {
14891 Expr *E = OrigOp.get()->IgnoreParens();
14892 if (!isa<OverloadExpr>(Val: E)) {
14893 assert(cast<UnaryOperator>(E)->getOpcode() == UO_AddrOf);
14894 Diag(Loc: OpLoc, DiagID: diag::err_typecheck_invalid_lvalue_addrof_addrof_function)
14895 << OrigOp.get()->getSourceRange();
14896 return QualType();
14897 }
14898
14899 OverloadExpr *Ovl = cast<OverloadExpr>(Val: E);
14900 if (isa<UnresolvedMemberExpr>(Val: Ovl))
14901 if (!ResolveSingleFunctionTemplateSpecialization(ovl: Ovl)) {
14902 Diag(Loc: OpLoc, DiagID: diag::err_invalid_form_pointer_member_function)
14903 << OrigOp.get()->getSourceRange();
14904 return QualType();
14905 }
14906
14907 return Context.OverloadTy;
14908 }
14909
14910 if (PTy->getKind() == BuiltinType::UnknownAny)
14911 return Context.UnknownAnyTy;
14912
14913 if (PTy->getKind() == BuiltinType::BoundMember) {
14914 Diag(Loc: OpLoc, DiagID: diag::err_invalid_form_pointer_member_function)
14915 << OrigOp.get()->getSourceRange();
14916 return QualType();
14917 }
14918
14919 OrigOp = CheckPlaceholderExpr(E: OrigOp.get());
14920 if (OrigOp.isInvalid()) return QualType();
14921 }
14922
14923 if (OrigOp.get()->isTypeDependent())
14924 return Context.DependentTy;
14925
14926 assert(!OrigOp.get()->hasPlaceholderType());
14927
14928 // Make sure to ignore parentheses in subsequent checks
14929 Expr *op = OrigOp.get()->IgnoreParens();
14930
14931 // In OpenCL captures for blocks called as lambda functions
14932 // are located in the private address space. Blocks used in
14933 // enqueue_kernel can be located in a different address space
14934 // depending on a vendor implementation. Thus preventing
14935 // taking an address of the capture to avoid invalid AS casts.
14936 if (LangOpts.OpenCL) {
14937 auto* VarRef = dyn_cast<DeclRefExpr>(Val: op);
14938 if (VarRef && VarRef->refersToEnclosingVariableOrCapture()) {
14939 Diag(Loc: op->getExprLoc(), DiagID: diag::err_opencl_taking_address_capture);
14940 return QualType();
14941 }
14942 }
14943
14944 if (getLangOpts().C99) {
14945 // Implement C99-only parts of addressof rules.
14946 if (UnaryOperator* uOp = dyn_cast<UnaryOperator>(Val: op)) {
14947 if (uOp->getOpcode() == UO_Deref)
14948 // Per C99 6.5.3.2, the address of a deref always returns a valid result
14949 // (assuming the deref expression is valid).
14950 return uOp->getSubExpr()->getType();
14951 }
14952 // Technically, there should be a check for array subscript
14953 // expressions here, but the result of one is always an lvalue anyway.
14954 }
14955 ValueDecl *dcl = getPrimaryDecl(E: op);
14956
14957 if (auto *FD = dyn_cast_or_null<FunctionDecl>(Val: dcl))
14958 if (!checkAddressOfFunctionIsAvailable(Function: FD, /*Complain=*/true,
14959 Loc: op->getBeginLoc()))
14960 return QualType();
14961
14962 Expr::LValueClassification lval = op->ClassifyLValue(Ctx&: Context);
14963 unsigned AddressOfError = AO_No_Error;
14964
14965 if (lval == Expr::LV_ClassTemporary || lval == Expr::LV_ArrayTemporary) {
14966 bool IsError = isSFINAEContext();
14967 Diag(Loc: OpLoc, DiagID: IsError ? diag::err_typecheck_addrof_temporary
14968 : diag::ext_typecheck_addrof_temporary)
14969 << op->getType() << op->getSourceRange();
14970 if (IsError)
14971 return QualType();
14972 // Materialize the temporary as an lvalue so that we can take its address.
14973 OrigOp = op =
14974 CreateMaterializeTemporaryExpr(T: op->getType(), Temporary: OrigOp.get(), BoundToLvalueReference: true);
14975 } else if (isa<ObjCSelectorExpr>(Val: op)) {
14976 return Context.getPointerType(T: op->getType());
14977 } else if (lval == Expr::LV_MemberFunction) {
14978 // If it's an instance method, make a member pointer.
14979 // The expression must have exactly the form &A::foo.
14980
14981 // If the underlying expression isn't a decl ref, give up.
14982 if (!isa<DeclRefExpr>(Val: op)) {
14983 Diag(Loc: OpLoc, DiagID: diag::err_invalid_form_pointer_member_function)
14984 << OrigOp.get()->getSourceRange();
14985 return QualType();
14986 }
14987 DeclRefExpr *DRE = cast<DeclRefExpr>(Val: op);
14988 CXXMethodDecl *MD = cast<CXXMethodDecl>(Val: DRE->getDecl());
14989
14990 CheckUseOfCXXMethodAsAddressOfOperand(OpLoc, Op: OrigOp.get(), MD);
14991 QualType MPTy = Context.getMemberPointerType(
14992 T: op->getType(), Qualifier: DRE->getQualifier(), Cls: MD->getParent());
14993
14994 if (getLangOpts().PointerAuthCalls && MD->isVirtual() &&
14995 !isUnevaluatedContext() && !MPTy->isDependentType()) {
14996 // When pointer authentication is enabled, argument and return types of
14997 // vitual member functions must be complete. This is because vitrual
14998 // member function pointers are implemented using virtual dispatch
14999 // thunks and the thunks cannot be emitted if the argument or return
15000 // types are incomplete.
15001 auto ReturnOrParamTypeIsIncomplete = [&](QualType T,
15002 SourceLocation DeclRefLoc,
15003 SourceLocation RetArgTypeLoc) {
15004 if (RequireCompleteType(Loc: DeclRefLoc, T, DiagID: diag::err_incomplete_type)) {
15005 Diag(Loc: DeclRefLoc,
15006 DiagID: diag::note_ptrauth_virtual_function_pointer_incomplete_arg_ret);
15007 Diag(Loc: RetArgTypeLoc,
15008 DiagID: diag::note_ptrauth_virtual_function_incomplete_arg_ret_type)
15009 << T;
15010 return true;
15011 }
15012 return false;
15013 };
15014 QualType RetTy = MD->getReturnType();
15015 bool IsIncomplete =
15016 !RetTy->isVoidType() &&
15017 ReturnOrParamTypeIsIncomplete(
15018 RetTy, OpLoc, MD->getReturnTypeSourceRange().getBegin());
15019 for (auto *PVD : MD->parameters())
15020 IsIncomplete |= ReturnOrParamTypeIsIncomplete(PVD->getType(), OpLoc,
15021 PVD->getBeginLoc());
15022 if (IsIncomplete)
15023 return QualType();
15024 }
15025
15026 // Under the MS ABI, lock down the inheritance model now.
15027 if (Context.getTargetInfo().getCXXABI().isMicrosoft())
15028 (void)isCompleteType(Loc: OpLoc, T: MPTy);
15029 return MPTy;
15030 } else if (lval != Expr::LV_Valid && lval != Expr::LV_IncompleteVoidType) {
15031 // C99 6.5.3.2p1
15032 // The operand must be either an l-value or a function designator
15033 if (!op->getType()->isFunctionType()) {
15034 // Use a special diagnostic for loads from property references.
15035 if (isa<PseudoObjectExpr>(Val: op)) {
15036 AddressOfError = AO_Property_Expansion;
15037 } else {
15038 Diag(Loc: OpLoc, DiagID: diag::err_typecheck_invalid_lvalue_addrof)
15039 << op->getType() << op->getSourceRange();
15040 return QualType();
15041 }
15042 } else if (const auto *DRE = dyn_cast<DeclRefExpr>(Val: op)) {
15043 if (const auto *MD = dyn_cast_or_null<CXXMethodDecl>(Val: DRE->getDecl()))
15044 CheckUseOfCXXMethodAsAddressOfOperand(OpLoc, Op: OrigOp.get(), MD);
15045 }
15046
15047 } else if (op->getObjectKind() == OK_BitField) { // C99 6.5.3.2p1
15048 // The operand cannot be a bit-field
15049 AddressOfError = AO_Bit_Field;
15050 } else if (op->getObjectKind() == OK_VectorComponent) {
15051 // The operand cannot be an element of a vector
15052 AddressOfError = AO_Vector_Element;
15053 } else if (op->getObjectKind() == OK_MatrixComponent) {
15054 // The operand cannot be an element of a matrix.
15055 AddressOfError = AO_Matrix_Element;
15056 } else if (dcl) { // C99 6.5.3.2p1
15057 // We have an lvalue with a decl. Make sure the decl is not declared
15058 // with the register storage-class specifier.
15059 if (const VarDecl *vd = dyn_cast<VarDecl>(Val: dcl)) {
15060 // in C++ it is not error to take address of a register
15061 // variable (c++03 7.1.1P3)
15062 if (vd->getStorageClass() == SC_Register &&
15063 !getLangOpts().CPlusPlus) {
15064 AddressOfError = AO_Register_Variable;
15065 }
15066 } else if (isa<MSPropertyDecl>(Val: dcl)) {
15067 AddressOfError = AO_Property_Expansion;
15068 } else if (isa<FunctionTemplateDecl>(Val: dcl)) {
15069 return Context.OverloadTy;
15070 } else if (isa<FieldDecl>(Val: dcl) || isa<IndirectFieldDecl>(Val: dcl)) {
15071 // Okay: we can take the address of a field.
15072 // Could be a pointer to member, though, if there is an explicit
15073 // scope qualifier for the class.
15074
15075 // [C++26] [expr.prim.id.general]
15076 // If an id-expression E denotes a non-static non-type member
15077 // of some class C [...] and if E is a qualified-id, E is
15078 // not the un-parenthesized operand of the unary & operator [...]
15079 // the id-expression is transformed into a class member access expression.
15080 if (auto *DRE = dyn_cast<DeclRefExpr>(Val: op);
15081 DRE && DRE->getQualifier() && !isa<ParenExpr>(Val: OrigOp.get())) {
15082 DeclContext *Ctx = dcl->getDeclContext();
15083 if (Ctx && Ctx->isRecord()) {
15084 if (dcl->getType()->isReferenceType()) {
15085 Diag(Loc: OpLoc,
15086 DiagID: diag::err_cannot_form_pointer_to_member_of_reference_type)
15087 << dcl->getDeclName() << dcl->getType();
15088 return QualType();
15089 }
15090
15091 while (cast<RecordDecl>(Val: Ctx)->isAnonymousStructOrUnion())
15092 Ctx = Ctx->getParent();
15093
15094 QualType MPTy = Context.getMemberPointerType(
15095 T: op->getType(), Qualifier: DRE->getQualifier(), Cls: cast<CXXRecordDecl>(Val: Ctx));
15096 // Under the MS ABI, lock down the inheritance model now.
15097 if (Context.getTargetInfo().getCXXABI().isMicrosoft())
15098 (void)isCompleteType(Loc: OpLoc, T: MPTy);
15099 return MPTy;
15100 }
15101 }
15102 } else if (!isa<FunctionDecl, TemplateParamObjectDecl,
15103 NonTypeTemplateParmDecl, BindingDecl, MSGuidDecl,
15104 UnnamedGlobalConstantDecl>(Val: dcl))
15105 llvm_unreachable("Unknown/unexpected decl type");
15106 }
15107
15108 if (AddressOfError != AO_No_Error) {
15109 diagnoseAddressOfInvalidType(S&: *this, Loc: OpLoc, E: op, Type: AddressOfError);
15110 return QualType();
15111 }
15112
15113 if (lval == Expr::LV_IncompleteVoidType) {
15114 // Taking the address of a void variable is technically illegal, but we
15115 // allow it in cases which are otherwise valid.
15116 // Example: "extern void x; void* y = &x;".
15117 Diag(Loc: OpLoc, DiagID: diag::ext_typecheck_addrof_void) << op->getSourceRange();
15118 }
15119
15120 // If the operand has type "type", the result has type "pointer to type".
15121 if (op->getType()->isObjCObjectType())
15122 return Context.getObjCObjectPointerType(OIT: op->getType());
15123
15124 // Cannot take the address of WebAssembly references or tables.
15125 if (Context.getTargetInfo().getTriple().isWasm()) {
15126 QualType OpTy = op->getType();
15127 if (OpTy.isWebAssemblyReferenceType()) {
15128 Diag(Loc: OpLoc, DiagID: diag::err_wasm_ca_reference)
15129 << 1 << OrigOp.get()->getSourceRange();
15130 return QualType();
15131 }
15132 if (OpTy->isWebAssemblyTableType()) {
15133 Diag(Loc: OpLoc, DiagID: diag::err_wasm_table_pr)
15134 << 1 << OrigOp.get()->getSourceRange();
15135 return QualType();
15136 }
15137 }
15138
15139 CheckAddressOfPackedMember(rhs: op);
15140
15141 return Context.getPointerType(T: op->getType());
15142}
15143
15144static void RecordModifiableNonNullParam(Sema &S, const Expr *Exp) {
15145 const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Val: Exp);
15146 if (!DRE)
15147 return;
15148 const Decl *D = DRE->getDecl();
15149 if (!D)
15150 return;
15151 const ParmVarDecl *Param = dyn_cast<ParmVarDecl>(Val: D);
15152 if (!Param)
15153 return;
15154 if (const FunctionDecl* FD = dyn_cast<FunctionDecl>(Val: Param->getDeclContext()))
15155 if (!FD->hasAttr<NonNullAttr>() && !Param->hasAttr<NonNullAttr>())
15156 return;
15157 if (FunctionScopeInfo *FD = S.getCurFunction())
15158 FD->ModifiedNonNullParams.insert(Ptr: Param);
15159}
15160
15161/// CheckIndirectionOperand - Type check unary indirection (prefix '*').
15162static QualType CheckIndirectionOperand(Sema &S, Expr *Op, ExprValueKind &VK,
15163 SourceLocation OpLoc,
15164 bool IsAfterAmp = false) {
15165 ExprResult ConvResult = S.UsualUnaryConversions(E: Op);
15166 if (ConvResult.isInvalid())
15167 return QualType();
15168 Op = ConvResult.get();
15169 QualType OpTy = Op->getType();
15170 QualType Result;
15171
15172 if (isa<CXXReinterpretCastExpr>(Val: Op->IgnoreParens())) {
15173 QualType OpOrigType = Op->IgnoreParenCasts()->getType();
15174 S.CheckCompatibleReinterpretCast(SrcType: OpOrigType, DestType: OpTy, /*IsDereference*/true,
15175 Range: Op->getSourceRange());
15176 }
15177
15178 if (const PointerType *PT = OpTy->getAs<PointerType>())
15179 {
15180 Result = PT->getPointeeType();
15181 }
15182 else if (const ObjCObjectPointerType *OPT =
15183 OpTy->getAs<ObjCObjectPointerType>())
15184 Result = OPT->getPointeeType();
15185 else {
15186 ExprResult PR = S.CheckPlaceholderExpr(E: Op);
15187 if (PR.isInvalid()) return QualType();
15188 if (PR.get() != Op)
15189 return CheckIndirectionOperand(S, Op: PR.get(), VK, OpLoc);
15190 }
15191
15192 if (Result.isNull()) {
15193 S.Diag(Loc: OpLoc, DiagID: diag::err_typecheck_indirection_requires_pointer)
15194 << OpTy << Op->getSourceRange();
15195 return QualType();
15196 }
15197
15198 if (Result->isVoidType()) {
15199 // C++ [expr.unary.op]p1:
15200 // [...] the expression to which [the unary * operator] is applied shall
15201 // be a pointer to an object type, or a pointer to a function type
15202 LangOptions LO = S.getLangOpts();
15203 if (LO.CPlusPlus)
15204 S.Diag(Loc: OpLoc, DiagID: diag::err_typecheck_indirection_through_void_pointer_cpp)
15205 << OpTy << Op->getSourceRange();
15206 else if (!(LO.C99 && IsAfterAmp) && !S.isUnevaluatedContext())
15207 S.Diag(Loc: OpLoc, DiagID: diag::ext_typecheck_indirection_through_void_pointer)
15208 << OpTy << Op->getSourceRange();
15209 }
15210
15211 // Dereferences are usually l-values...
15212 VK = VK_LValue;
15213
15214 // ...except that certain expressions are never l-values in C.
15215 if (!S.getLangOpts().CPlusPlus && Result.isCForbiddenLValueType())
15216 VK = VK_PRValue;
15217
15218 return Result;
15219}
15220
15221BinaryOperatorKind Sema::ConvertTokenKindToBinaryOpcode(tok::TokenKind Kind) {
15222 BinaryOperatorKind Opc;
15223 switch (Kind) {
15224 default: llvm_unreachable("Unknown binop!");
15225 case tok::periodstar: Opc = BO_PtrMemD; break;
15226 case tok::arrowstar: Opc = BO_PtrMemI; break;
15227 case tok::star: Opc = BO_Mul; break;
15228 case tok::slash: Opc = BO_Div; break;
15229 case tok::percent: Opc = BO_Rem; break;
15230 case tok::plus: Opc = BO_Add; break;
15231 case tok::minus: Opc = BO_Sub; break;
15232 case tok::lessless: Opc = BO_Shl; break;
15233 case tok::greatergreater: Opc = BO_Shr; break;
15234 case tok::lessequal: Opc = BO_LE; break;
15235 case tok::less: Opc = BO_LT; break;
15236 case tok::greaterequal: Opc = BO_GE; break;
15237 case tok::greater: Opc = BO_GT; break;
15238 case tok::exclaimequal: Opc = BO_NE; break;
15239 case tok::equalequal: Opc = BO_EQ; break;
15240 case tok::spaceship: Opc = BO_Cmp; break;
15241 case tok::amp: Opc = BO_And; break;
15242 case tok::caret: Opc = BO_Xor; break;
15243 case tok::pipe: Opc = BO_Or; break;
15244 case tok::ampamp: Opc = BO_LAnd; break;
15245 case tok::pipepipe: Opc = BO_LOr; break;
15246 case tok::equal: Opc = BO_Assign; break;
15247 case tok::starequal: Opc = BO_MulAssign; break;
15248 case tok::slashequal: Opc = BO_DivAssign; break;
15249 case tok::percentequal: Opc = BO_RemAssign; break;
15250 case tok::plusequal: Opc = BO_AddAssign; break;
15251 case tok::minusequal: Opc = BO_SubAssign; break;
15252 case tok::lesslessequal: Opc = BO_ShlAssign; break;
15253 case tok::greatergreaterequal: Opc = BO_ShrAssign; break;
15254 case tok::ampequal: Opc = BO_AndAssign; break;
15255 case tok::caretequal: Opc = BO_XorAssign; break;
15256 case tok::pipeequal: Opc = BO_OrAssign; break;
15257 case tok::comma: Opc = BO_Comma; break;
15258 }
15259 return Opc;
15260}
15261
15262static inline UnaryOperatorKind ConvertTokenKindToUnaryOpcode(
15263 tok::TokenKind Kind) {
15264 UnaryOperatorKind Opc;
15265 switch (Kind) {
15266 default: llvm_unreachable("Unknown unary op!");
15267 case tok::plusplus: Opc = UO_PreInc; break;
15268 case tok::minusminus: Opc = UO_PreDec; break;
15269 case tok::amp: Opc = UO_AddrOf; break;
15270 case tok::star: Opc = UO_Deref; break;
15271 case tok::plus: Opc = UO_Plus; break;
15272 case tok::minus: Opc = UO_Minus; break;
15273 case tok::tilde: Opc = UO_Not; break;
15274 case tok::exclaim: Opc = UO_LNot; break;
15275 case tok::kw___real: Opc = UO_Real; break;
15276 case tok::kw___imag: Opc = UO_Imag; break;
15277 case tok::kw___extension__: Opc = UO_Extension; break;
15278 }
15279 return Opc;
15280}
15281
15282const FieldDecl *
15283Sema::getSelfAssignmentClassMemberCandidate(const ValueDecl *SelfAssigned) {
15284 // Explore the case for adding 'this->' to the LHS of a self assignment, very
15285 // common for setters.
15286 // struct A {
15287 // int X;
15288 // -void setX(int X) { X = X; }
15289 // +void setX(int X) { this->X = X; }
15290 // };
15291
15292 // Only consider parameters for self assignment fixes.
15293 if (!isa<ParmVarDecl>(Val: SelfAssigned))
15294 return nullptr;
15295 const auto *Method =
15296 dyn_cast_or_null<CXXMethodDecl>(Val: getCurFunctionDecl(AllowLambda: true));
15297 if (!Method)
15298 return nullptr;
15299
15300 const CXXRecordDecl *Parent = Method->getParent();
15301 // In theory this is fixable if the lambda explicitly captures this, but
15302 // that's added complexity that's rarely going to be used.
15303 if (Parent->isLambda())
15304 return nullptr;
15305
15306 // FIXME: Use an actual Lookup operation instead of just traversing fields
15307 // in order to get base class fields.
15308 auto Field =
15309 llvm::find_if(Range: Parent->fields(),
15310 P: [Name(SelfAssigned->getDeclName())](const FieldDecl *F) {
15311 return F->getDeclName() == Name;
15312 });
15313 return (Field != Parent->field_end()) ? *Field : nullptr;
15314}
15315
15316/// DiagnoseSelfAssignment - Emits a warning if a value is assigned to itself.
15317/// This warning suppressed in the event of macro expansions.
15318static void DiagnoseSelfAssignment(Sema &S, Expr *LHSExpr, Expr *RHSExpr,
15319 SourceLocation OpLoc, bool IsBuiltin) {
15320 if (S.inTemplateInstantiation())
15321 return;
15322 if (S.isUnevaluatedContext())
15323 return;
15324 if (OpLoc.isInvalid() || OpLoc.isMacroID())
15325 return;
15326 LHSExpr = LHSExpr->IgnoreParenImpCasts();
15327 RHSExpr = RHSExpr->IgnoreParenImpCasts();
15328 const DeclRefExpr *LHSDeclRef = dyn_cast<DeclRefExpr>(Val: LHSExpr);
15329 const DeclRefExpr *RHSDeclRef = dyn_cast<DeclRefExpr>(Val: RHSExpr);
15330 if (!LHSDeclRef || !RHSDeclRef ||
15331 LHSDeclRef->getLocation().isMacroID() ||
15332 RHSDeclRef->getLocation().isMacroID())
15333 return;
15334 const ValueDecl *LHSDecl =
15335 cast<ValueDecl>(Val: LHSDeclRef->getDecl()->getCanonicalDecl());
15336 const ValueDecl *RHSDecl =
15337 cast<ValueDecl>(Val: RHSDeclRef->getDecl()->getCanonicalDecl());
15338 if (LHSDecl != RHSDecl)
15339 return;
15340 if (LHSDecl->getType().isVolatileQualified())
15341 return;
15342 if (const ReferenceType *RefTy = LHSDecl->getType()->getAs<ReferenceType>())
15343 if (RefTy->getPointeeType().isVolatileQualified())
15344 return;
15345
15346 auto Diag = S.Diag(Loc: OpLoc, DiagID: IsBuiltin ? diag::warn_self_assignment_builtin
15347 : diag::warn_self_assignment_overloaded)
15348 << LHSDeclRef->getType() << LHSExpr->getSourceRange()
15349 << RHSExpr->getSourceRange();
15350 if (const FieldDecl *SelfAssignField =
15351 S.getSelfAssignmentClassMemberCandidate(SelfAssigned: RHSDecl))
15352 Diag << 1 << SelfAssignField
15353 << FixItHint::CreateInsertion(InsertionLoc: LHSDeclRef->getBeginLoc(), Code: "this->");
15354 else
15355 Diag << 0;
15356}
15357
15358/// Check if a bitwise-& is performed on an Objective-C pointer. This
15359/// is usually indicative of introspection within the Objective-C pointer.
15360static void checkObjCPointerIntrospection(Sema &S, ExprResult &L, ExprResult &R,
15361 SourceLocation OpLoc) {
15362 if (!S.getLangOpts().ObjC)
15363 return;
15364
15365 const Expr *ObjCPointerExpr = nullptr, *OtherExpr = nullptr;
15366 const Expr *LHS = L.get();
15367 const Expr *RHS = R.get();
15368
15369 if (LHS->IgnoreParenCasts()->getType()->isObjCObjectPointerType()) {
15370 ObjCPointerExpr = LHS;
15371 OtherExpr = RHS;
15372 }
15373 else if (RHS->IgnoreParenCasts()->getType()->isObjCObjectPointerType()) {
15374 ObjCPointerExpr = RHS;
15375 OtherExpr = LHS;
15376 }
15377
15378 // This warning is deliberately made very specific to reduce false
15379 // positives with logic that uses '&' for hashing. This logic mainly
15380 // looks for code trying to introspect into tagged pointers, which
15381 // code should generally never do.
15382 if (ObjCPointerExpr && isa<IntegerLiteral>(Val: OtherExpr->IgnoreParenCasts())) {
15383 unsigned Diag = diag::warn_objc_pointer_masking;
15384 // Determine if we are introspecting the result of performSelectorXXX.
15385 const Expr *Ex = ObjCPointerExpr->IgnoreParenCasts();
15386 // Special case messages to -performSelector and friends, which
15387 // can return non-pointer values boxed in a pointer value.
15388 // Some clients may wish to silence warnings in this subcase.
15389 if (const ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(Val: Ex)) {
15390 Selector S = ME->getSelector();
15391 StringRef SelArg0 = S.getNameForSlot(argIndex: 0);
15392 if (SelArg0.starts_with(Prefix: "performSelector"))
15393 Diag = diag::warn_objc_pointer_masking_performSelector;
15394 }
15395
15396 S.Diag(Loc: OpLoc, DiagID: Diag)
15397 << ObjCPointerExpr->getSourceRange();
15398 }
15399}
15400
15401// This helper function promotes a binary operator's operands (which are of a
15402// half vector type) to a vector of floats and then truncates the result to
15403// a vector of either half or short.
15404static ExprResult convertHalfVecBinOp(Sema &S, ExprResult LHS, ExprResult RHS,
15405 BinaryOperatorKind Opc, QualType ResultTy,
15406 ExprValueKind VK, ExprObjectKind OK,
15407 bool IsCompAssign, SourceLocation OpLoc,
15408 FPOptionsOverride FPFeatures) {
15409 auto &Context = S.getASTContext();
15410 assert((isVector(ResultTy, Context.HalfTy) ||
15411 isVector(ResultTy, Context.ShortTy)) &&
15412 "Result must be a vector of half or short");
15413 assert(isVector(LHS.get()->getType(), Context.HalfTy) &&
15414 isVector(RHS.get()->getType(), Context.HalfTy) &&
15415 "both operands expected to be a half vector");
15416
15417 RHS = convertVector(E: RHS.get(), ElementType: Context.FloatTy, S);
15418 QualType BinOpResTy = RHS.get()->getType();
15419
15420 // If Opc is a comparison, ResultType is a vector of shorts. In that case,
15421 // change BinOpResTy to a vector of ints.
15422 if (isVector(QT: ResultTy, ElementType: Context.ShortTy))
15423 BinOpResTy = S.GetSignedVectorType(V: BinOpResTy);
15424
15425 if (IsCompAssign)
15426 return CompoundAssignOperator::Create(C: Context, lhs: LHS.get(), rhs: RHS.get(), opc: Opc,
15427 ResTy: ResultTy, VK, OK, opLoc: OpLoc, FPFeatures,
15428 CompLHSType: BinOpResTy, CompResultType: BinOpResTy);
15429
15430 LHS = convertVector(E: LHS.get(), ElementType: Context.FloatTy, S);
15431 auto *BO = BinaryOperator::Create(C: Context, lhs: LHS.get(), rhs: RHS.get(), opc: Opc,
15432 ResTy: BinOpResTy, VK, OK, opLoc: OpLoc, FPFeatures);
15433 return convertVector(E: BO, ElementType: ResultTy->castAs<VectorType>()->getElementType(), S);
15434}
15435
15436/// Returns true if conversion between vectors of halfs and vectors of floats
15437/// is needed.
15438static bool needsConversionOfHalfVec(bool OpRequiresConversion, ASTContext &Ctx,
15439 Expr *E0, Expr *E1 = nullptr) {
15440 if (!OpRequiresConversion || Ctx.getLangOpts().NativeHalfType ||
15441 Ctx.getTargetInfo().useFP16ConversionIntrinsics())
15442 return false;
15443
15444 auto HasVectorOfHalfType = [&Ctx](Expr *E) {
15445 QualType Ty = E->IgnoreImplicit()->getType();
15446
15447 // Don't promote half precision neon vectors like float16x4_t in arm_neon.h
15448 // to vectors of floats. Although the element type of the vectors is __fp16,
15449 // the vectors shouldn't be treated as storage-only types. See the
15450 // discussion here: https://reviews.llvm.org/rG825235c140e7
15451 if (const VectorType *VT = Ty->getAs<VectorType>()) {
15452 if (VT->getVectorKind() == VectorKind::Neon)
15453 return false;
15454 return VT->getElementType().getCanonicalType() == Ctx.HalfTy;
15455 }
15456 return false;
15457 };
15458
15459 return HasVectorOfHalfType(E0) && (!E1 || HasVectorOfHalfType(E1));
15460}
15461
15462ExprResult Sema::CreateBuiltinBinOp(SourceLocation OpLoc,
15463 BinaryOperatorKind Opc, Expr *LHSExpr,
15464 Expr *RHSExpr, bool ForFoldExpression) {
15465 if (getLangOpts().CPlusPlus11 && isa<InitListExpr>(Val: RHSExpr)) {
15466 // The syntax only allows initializer lists on the RHS of assignment,
15467 // so we don't need to worry about accepting invalid code for
15468 // non-assignment operators.
15469 // C++11 5.17p9:
15470 // The meaning of x = {v} [...] is that of x = T(v) [...]. The meaning
15471 // of x = {} is x = T().
15472 InitializationKind Kind = InitializationKind::CreateDirectList(
15473 InitLoc: RHSExpr->getBeginLoc(), LBraceLoc: RHSExpr->getBeginLoc(), RBraceLoc: RHSExpr->getEndLoc());
15474 InitializedEntity Entity =
15475 InitializedEntity::InitializeTemporary(Type: LHSExpr->getType());
15476 InitializationSequence InitSeq(*this, Entity, Kind, RHSExpr);
15477 ExprResult Init = InitSeq.Perform(S&: *this, Entity, Kind, Args: RHSExpr);
15478 if (Init.isInvalid())
15479 return Init;
15480 RHSExpr = Init.get();
15481 }
15482
15483 ExprResult LHS = LHSExpr, RHS = RHSExpr;
15484 QualType ResultTy; // Result type of the binary operator.
15485 // The following two variables are used for compound assignment operators
15486 QualType CompLHSTy; // Type of LHS after promotions for computation
15487 QualType CompResultTy; // Type of computation result
15488 ExprValueKind VK = VK_PRValue;
15489 ExprObjectKind OK = OK_Ordinary;
15490 bool ConvertHalfVec = false;
15491
15492 if (!LHS.isUsable() || !RHS.isUsable())
15493 return ExprError();
15494
15495 if (getLangOpts().OpenCL) {
15496 QualType LHSTy = LHSExpr->getType();
15497 QualType RHSTy = RHSExpr->getType();
15498 // OpenCLC v2.0 s6.13.11.1 allows atomic variables to be initialized by
15499 // the ATOMIC_VAR_INIT macro.
15500 if (LHSTy->isAtomicType() || RHSTy->isAtomicType()) {
15501 SourceRange SR(LHSExpr->getBeginLoc(), RHSExpr->getEndLoc());
15502 if (BO_Assign == Opc)
15503 Diag(Loc: OpLoc, DiagID: diag::err_opencl_atomic_init) << 0 << SR;
15504 else
15505 ResultTy = InvalidOperands(Loc: OpLoc, LHS, RHS);
15506 return ExprError();
15507 }
15508
15509 // OpenCL special types - image, sampler, pipe, and blocks are to be used
15510 // only with a builtin functions and therefore should be disallowed here.
15511 if (LHSTy->isImageType() || RHSTy->isImageType() ||
15512 LHSTy->isSamplerT() || RHSTy->isSamplerT() ||
15513 LHSTy->isPipeType() || RHSTy->isPipeType() ||
15514 LHSTy->isBlockPointerType() || RHSTy->isBlockPointerType()) {
15515 ResultTy = InvalidOperands(Loc: OpLoc, LHS, RHS);
15516 return ExprError();
15517 }
15518 }
15519
15520 checkTypeSupport(Ty: LHSExpr->getType(), Loc: OpLoc, /*ValueDecl*/ D: nullptr);
15521 checkTypeSupport(Ty: RHSExpr->getType(), Loc: OpLoc, /*ValueDecl*/ D: nullptr);
15522
15523 switch (Opc) {
15524 case BO_Assign:
15525 ResultTy = CheckAssignmentOperands(LHSExpr: LHS.get(), RHS, Loc: OpLoc, CompoundType: QualType(), Opc);
15526 if (getLangOpts().CPlusPlus &&
15527 LHS.get()->getObjectKind() != OK_ObjCProperty) {
15528 VK = LHS.get()->getValueKind();
15529 OK = LHS.get()->getObjectKind();
15530 }
15531 if (!ResultTy.isNull()) {
15532 DiagnoseSelfAssignment(S&: *this, LHSExpr: LHS.get(), RHSExpr: RHS.get(), OpLoc, IsBuiltin: true);
15533 DiagnoseSelfMove(LHSExpr: LHS.get(), RHSExpr: RHS.get(), OpLoc);
15534
15535 // Avoid copying a block to the heap if the block is assigned to a local
15536 // auto variable that is declared in the same scope as the block. This
15537 // optimization is unsafe if the local variable is declared in an outer
15538 // scope. For example:
15539 //
15540 // BlockTy b;
15541 // {
15542 // b = ^{...};
15543 // }
15544 // // It is unsafe to invoke the block here if it wasn't copied to the
15545 // // heap.
15546 // b();
15547
15548 if (auto *BE = dyn_cast<BlockExpr>(Val: RHS.get()->IgnoreParens()))
15549 if (auto *DRE = dyn_cast<DeclRefExpr>(Val: LHS.get()->IgnoreParens()))
15550 if (auto *VD = dyn_cast<VarDecl>(Val: DRE->getDecl()))
15551 if (VD->hasLocalStorage() && getCurScope()->isDeclScope(D: VD))
15552 BE->getBlockDecl()->setCanAvoidCopyToHeap();
15553
15554 if (LHS.get()->getType().hasNonTrivialToPrimitiveCopyCUnion())
15555 checkNonTrivialCUnion(QT: LHS.get()->getType(), Loc: LHS.get()->getExprLoc(),
15556 UseContext: NonTrivialCUnionContext::Assignment, NonTrivialKind: NTCUK_Copy);
15557 }
15558 RecordModifiableNonNullParam(S&: *this, Exp: LHS.get());
15559 break;
15560 case BO_PtrMemD:
15561 case BO_PtrMemI:
15562 ResultTy = CheckPointerToMemberOperands(LHS, RHS, VK, OpLoc,
15563 isIndirect: Opc == BO_PtrMemI);
15564 break;
15565 case BO_Mul:
15566 case BO_Div:
15567 ConvertHalfVec = true;
15568 ResultTy = CheckMultiplyDivideOperands(LHS, RHS, Loc: OpLoc, Opc);
15569 break;
15570 case BO_Rem:
15571 ResultTy = CheckRemainderOperands(LHS, RHS, Loc: OpLoc);
15572 break;
15573 case BO_Add:
15574 ConvertHalfVec = true;
15575 ResultTy = CheckAdditionOperands(LHS, RHS, Loc: OpLoc, Opc);
15576 break;
15577 case BO_Sub:
15578 ConvertHalfVec = true;
15579 ResultTy = CheckSubtractionOperands(LHS, RHS, Loc: OpLoc, Opc);
15580 break;
15581 case BO_Shl:
15582 case BO_Shr:
15583 ResultTy = CheckShiftOperands(LHS, RHS, Loc: OpLoc, Opc);
15584 break;
15585 case BO_LE:
15586 case BO_LT:
15587 case BO_GE:
15588 case BO_GT:
15589 ConvertHalfVec = true;
15590 ResultTy = CheckCompareOperands(LHS, RHS, Loc: OpLoc, Opc);
15591
15592 if (const auto *BI = dyn_cast<BinaryOperator>(Val: LHSExpr);
15593 !ForFoldExpression && BI && BI->isComparisonOp())
15594 Diag(Loc: OpLoc, DiagID: diag::warn_consecutive_comparison)
15595 << BI->getOpcodeStr() << BinaryOperator::getOpcodeStr(Op: Opc);
15596
15597 break;
15598 case BO_EQ:
15599 case BO_NE:
15600 ConvertHalfVec = true;
15601 ResultTy = CheckCompareOperands(LHS, RHS, Loc: OpLoc, Opc);
15602 break;
15603 case BO_Cmp:
15604 ConvertHalfVec = true;
15605 ResultTy = CheckCompareOperands(LHS, RHS, Loc: OpLoc, Opc);
15606 assert(ResultTy.isNull() || ResultTy->getAsCXXRecordDecl());
15607 break;
15608 case BO_And:
15609 checkObjCPointerIntrospection(S&: *this, L&: LHS, R&: RHS, OpLoc);
15610 [[fallthrough]];
15611 case BO_Xor:
15612 case BO_Or:
15613 ResultTy = CheckBitwiseOperands(LHS, RHS, Loc: OpLoc, Opc);
15614 break;
15615 case BO_LAnd:
15616 case BO_LOr:
15617 ConvertHalfVec = true;
15618 ResultTy = CheckLogicalOperands(LHS, RHS, Loc: OpLoc, Opc);
15619 break;
15620 case BO_MulAssign:
15621 case BO_DivAssign:
15622 ConvertHalfVec = true;
15623 CompResultTy = CheckMultiplyDivideOperands(LHS, RHS, Loc: OpLoc, Opc);
15624 CompLHSTy = CompResultTy;
15625 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
15626 ResultTy =
15627 CheckAssignmentOperands(LHSExpr: LHS.get(), RHS, Loc: OpLoc, CompoundType: CompResultTy, Opc);
15628 break;
15629 case BO_RemAssign:
15630 CompResultTy = CheckRemainderOperands(LHS, RHS, Loc: OpLoc, IsCompAssign: true);
15631 CompLHSTy = CompResultTy;
15632 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
15633 ResultTy =
15634 CheckAssignmentOperands(LHSExpr: LHS.get(), RHS, Loc: OpLoc, CompoundType: CompResultTy, Opc);
15635 break;
15636 case BO_AddAssign:
15637 ConvertHalfVec = true;
15638 CompResultTy = CheckAdditionOperands(LHS, RHS, Loc: OpLoc, Opc, CompLHSTy: &CompLHSTy);
15639 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
15640 ResultTy =
15641 CheckAssignmentOperands(LHSExpr: LHS.get(), RHS, Loc: OpLoc, CompoundType: CompResultTy, Opc);
15642 break;
15643 case BO_SubAssign:
15644 ConvertHalfVec = true;
15645 CompResultTy = CheckSubtractionOperands(LHS, RHS, Loc: OpLoc, Opc, CompLHSTy: &CompLHSTy);
15646 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
15647 ResultTy =
15648 CheckAssignmentOperands(LHSExpr: LHS.get(), RHS, Loc: OpLoc, CompoundType: CompResultTy, Opc);
15649 break;
15650 case BO_ShlAssign:
15651 case BO_ShrAssign:
15652 CompResultTy = CheckShiftOperands(LHS, RHS, Loc: OpLoc, Opc, IsCompAssign: true);
15653 CompLHSTy = CompResultTy;
15654 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
15655 ResultTy =
15656 CheckAssignmentOperands(LHSExpr: LHS.get(), RHS, Loc: OpLoc, CompoundType: CompResultTy, Opc);
15657 break;
15658 case BO_AndAssign:
15659 case BO_OrAssign: // fallthrough
15660 DiagnoseSelfAssignment(S&: *this, LHSExpr: LHS.get(), RHSExpr: RHS.get(), OpLoc, IsBuiltin: true);
15661 [[fallthrough]];
15662 case BO_XorAssign:
15663 CompResultTy = CheckBitwiseOperands(LHS, RHS, Loc: OpLoc, Opc);
15664 CompLHSTy = CompResultTy;
15665 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
15666 ResultTy =
15667 CheckAssignmentOperands(LHSExpr: LHS.get(), RHS, Loc: OpLoc, CompoundType: CompResultTy, Opc);
15668 break;
15669 case BO_Comma:
15670 ResultTy = CheckCommaOperands(S&: *this, LHS, RHS, Loc: OpLoc);
15671 if (getLangOpts().CPlusPlus && !RHS.isInvalid()) {
15672 VK = RHS.get()->getValueKind();
15673 OK = RHS.get()->getObjectKind();
15674 }
15675 break;
15676 }
15677 if (ResultTy.isNull() || LHS.isInvalid() || RHS.isInvalid())
15678 return ExprError();
15679
15680 // Some of the binary operations require promoting operands of half vector to
15681 // float vectors and truncating the result back to half vector. For now, we do
15682 // this only when HalfArgsAndReturn is set (that is, when the target is arm or
15683 // arm64).
15684 assert(
15685 (Opc == BO_Comma || isVector(RHS.get()->getType(), Context.HalfTy) ==
15686 isVector(LHS.get()->getType(), Context.HalfTy)) &&
15687 "both sides are half vectors or neither sides are");
15688 ConvertHalfVec =
15689 needsConversionOfHalfVec(OpRequiresConversion: ConvertHalfVec, Ctx&: Context, E0: LHS.get(), E1: RHS.get());
15690
15691 // Check for array bounds violations for both sides of the BinaryOperator
15692 CheckArrayAccess(E: LHS.get());
15693 CheckArrayAccess(E: RHS.get());
15694
15695 if (const ObjCIsaExpr *OISA = dyn_cast<ObjCIsaExpr>(Val: LHS.get()->IgnoreParenCasts())) {
15696 NamedDecl *ObjectSetClass = LookupSingleName(S: TUScope,
15697 Name: &Context.Idents.get(Name: "object_setClass"),
15698 Loc: SourceLocation(), NameKind: LookupOrdinaryName);
15699 if (ObjectSetClass && isa<ObjCIsaExpr>(Val: LHS.get())) {
15700 SourceLocation RHSLocEnd = getLocForEndOfToken(Loc: RHS.get()->getEndLoc());
15701 Diag(Loc: LHS.get()->getExprLoc(), DiagID: diag::warn_objc_isa_assign)
15702 << FixItHint::CreateInsertion(InsertionLoc: LHS.get()->getBeginLoc(),
15703 Code: "object_setClass(")
15704 << FixItHint::CreateReplacement(RemoveRange: SourceRange(OISA->getOpLoc(), OpLoc),
15705 Code: ",")
15706 << FixItHint::CreateInsertion(InsertionLoc: RHSLocEnd, Code: ")");
15707 }
15708 else
15709 Diag(Loc: LHS.get()->getExprLoc(), DiagID: diag::warn_objc_isa_assign);
15710 }
15711 else if (const ObjCIvarRefExpr *OIRE =
15712 dyn_cast<ObjCIvarRefExpr>(Val: LHS.get()->IgnoreParenCasts()))
15713 DiagnoseDirectIsaAccess(S&: *this, OIRE, AssignLoc: OpLoc, RHS: RHS.get());
15714
15715 // Opc is not a compound assignment if CompResultTy is null.
15716 if (CompResultTy.isNull()) {
15717 if (ConvertHalfVec)
15718 return convertHalfVecBinOp(S&: *this, LHS, RHS, Opc, ResultTy, VK, OK, IsCompAssign: false,
15719 OpLoc, FPFeatures: CurFPFeatureOverrides());
15720 return BinaryOperator::Create(C: Context, lhs: LHS.get(), rhs: RHS.get(), opc: Opc, ResTy: ResultTy,
15721 VK, OK, opLoc: OpLoc, FPFeatures: CurFPFeatureOverrides());
15722 }
15723
15724 // Handle compound assignments.
15725 if (getLangOpts().CPlusPlus && LHS.get()->getObjectKind() !=
15726 OK_ObjCProperty) {
15727 VK = VK_LValue;
15728 OK = LHS.get()->getObjectKind();
15729 }
15730
15731 // The LHS is not converted to the result type for fixed-point compound
15732 // assignment as the common type is computed on demand. Reset the CompLHSTy
15733 // to the LHS type we would have gotten after unary conversions.
15734 if (CompResultTy->isFixedPointType())
15735 CompLHSTy = UsualUnaryConversions(E: LHS.get()).get()->getType();
15736
15737 if (ConvertHalfVec)
15738 return convertHalfVecBinOp(S&: *this, LHS, RHS, Opc, ResultTy, VK, OK, IsCompAssign: true,
15739 OpLoc, FPFeatures: CurFPFeatureOverrides());
15740
15741 return CompoundAssignOperator::Create(
15742 C: Context, lhs: LHS.get(), rhs: RHS.get(), opc: Opc, ResTy: ResultTy, VK, OK, opLoc: OpLoc,
15743 FPFeatures: CurFPFeatureOverrides(), CompLHSType: CompLHSTy, CompResultType: CompResultTy);
15744}
15745
15746/// DiagnoseBitwisePrecedence - Emit a warning when bitwise and comparison
15747/// operators are mixed in a way that suggests that the programmer forgot that
15748/// comparison operators have higher precedence. The most typical example of
15749/// such code is "flags & 0x0020 != 0", which is equivalent to "flags & 1".
15750static void DiagnoseBitwisePrecedence(Sema &Self, BinaryOperatorKind Opc,
15751 SourceLocation OpLoc, Expr *LHSExpr,
15752 Expr *RHSExpr) {
15753 BinaryOperator *LHSBO = dyn_cast<BinaryOperator>(Val: LHSExpr);
15754 BinaryOperator *RHSBO = dyn_cast<BinaryOperator>(Val: RHSExpr);
15755
15756 // Check that one of the sides is a comparison operator and the other isn't.
15757 bool isLeftComp = LHSBO && LHSBO->isComparisonOp();
15758 bool isRightComp = RHSBO && RHSBO->isComparisonOp();
15759 if (isLeftComp == isRightComp)
15760 return;
15761
15762 // Bitwise operations are sometimes used as eager logical ops.
15763 // Don't diagnose this.
15764 bool isLeftBitwise = LHSBO && LHSBO->isBitwiseOp();
15765 bool isRightBitwise = RHSBO && RHSBO->isBitwiseOp();
15766 if (isLeftBitwise || isRightBitwise)
15767 return;
15768
15769 SourceRange DiagRange = isLeftComp
15770 ? SourceRange(LHSExpr->getBeginLoc(), OpLoc)
15771 : SourceRange(OpLoc, RHSExpr->getEndLoc());
15772 StringRef OpStr = isLeftComp ? LHSBO->getOpcodeStr() : RHSBO->getOpcodeStr();
15773 SourceRange ParensRange =
15774 isLeftComp
15775 ? SourceRange(LHSBO->getRHS()->getBeginLoc(), RHSExpr->getEndLoc())
15776 : SourceRange(LHSExpr->getBeginLoc(), RHSBO->getLHS()->getEndLoc());
15777
15778 Self.Diag(Loc: OpLoc, DiagID: diag::warn_precedence_bitwise_rel)
15779 << DiagRange << BinaryOperator::getOpcodeStr(Op: Opc) << OpStr;
15780 SuggestParentheses(Self, Loc: OpLoc,
15781 Note: Self.PDiag(DiagID: diag::note_precedence_silence) << OpStr,
15782 ParenRange: (isLeftComp ? LHSExpr : RHSExpr)->getSourceRange());
15783 SuggestParentheses(Self, Loc: OpLoc,
15784 Note: Self.PDiag(DiagID: diag::note_precedence_bitwise_first)
15785 << BinaryOperator::getOpcodeStr(Op: Opc),
15786 ParenRange: ParensRange);
15787}
15788
15789/// It accepts a '&&' expr that is inside a '||' one.
15790/// Emit a diagnostic together with a fixit hint that wraps the '&&' expression
15791/// in parentheses.
15792static void
15793EmitDiagnosticForLogicalAndInLogicalOr(Sema &Self, SourceLocation OpLoc,
15794 BinaryOperator *Bop) {
15795 assert(Bop->getOpcode() == BO_LAnd);
15796 Self.Diag(Loc: Bop->getOperatorLoc(), DiagID: diag::warn_logical_and_in_logical_or)
15797 << Bop->getSourceRange() << OpLoc;
15798 SuggestParentheses(Self, Loc: Bop->getOperatorLoc(),
15799 Note: Self.PDiag(DiagID: diag::note_precedence_silence)
15800 << Bop->getOpcodeStr(),
15801 ParenRange: Bop->getSourceRange());
15802}
15803
15804/// Look for '&&' in the left hand of a '||' expr.
15805static void DiagnoseLogicalAndInLogicalOrLHS(Sema &S, SourceLocation OpLoc,
15806 Expr *LHSExpr, Expr *RHSExpr) {
15807 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(Val: LHSExpr)) {
15808 if (Bop->getOpcode() == BO_LAnd) {
15809 // If it's "string_literal && a || b" don't warn since the precedence
15810 // doesn't matter.
15811 if (!isa<StringLiteral>(Val: Bop->getLHS()->IgnoreParenImpCasts()))
15812 return EmitDiagnosticForLogicalAndInLogicalOr(Self&: S, OpLoc, Bop);
15813 } else if (Bop->getOpcode() == BO_LOr) {
15814 if (BinaryOperator *RBop = dyn_cast<BinaryOperator>(Val: Bop->getRHS())) {
15815 // If it's "a || b && string_literal || c" we didn't warn earlier for
15816 // "a || b && string_literal", but warn now.
15817 if (RBop->getOpcode() == BO_LAnd &&
15818 isa<StringLiteral>(Val: RBop->getRHS()->IgnoreParenImpCasts()))
15819 return EmitDiagnosticForLogicalAndInLogicalOr(Self&: S, OpLoc, Bop: RBop);
15820 }
15821 }
15822 }
15823}
15824
15825/// Look for '&&' in the right hand of a '||' expr.
15826static void DiagnoseLogicalAndInLogicalOrRHS(Sema &S, SourceLocation OpLoc,
15827 Expr *LHSExpr, Expr *RHSExpr) {
15828 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(Val: RHSExpr)) {
15829 if (Bop->getOpcode() == BO_LAnd) {
15830 // If it's "a || b && string_literal" don't warn since the precedence
15831 // doesn't matter.
15832 if (!isa<StringLiteral>(Val: Bop->getRHS()->IgnoreParenImpCasts()))
15833 return EmitDiagnosticForLogicalAndInLogicalOr(Self&: S, OpLoc, Bop);
15834 }
15835 }
15836}
15837
15838/// Look for bitwise op in the left or right hand of a bitwise op with
15839/// lower precedence and emit a diagnostic together with a fixit hint that wraps
15840/// the '&' expression in parentheses.
15841static void DiagnoseBitwiseOpInBitwiseOp(Sema &S, BinaryOperatorKind Opc,
15842 SourceLocation OpLoc, Expr *SubExpr) {
15843 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(Val: SubExpr)) {
15844 if (Bop->isBitwiseOp() && Bop->getOpcode() < Opc) {
15845 S.Diag(Loc: Bop->getOperatorLoc(), DiagID: diag::warn_bitwise_op_in_bitwise_op)
15846 << Bop->getOpcodeStr() << BinaryOperator::getOpcodeStr(Op: Opc)
15847 << Bop->getSourceRange() << OpLoc;
15848 SuggestParentheses(Self&: S, Loc: Bop->getOperatorLoc(),
15849 Note: S.PDiag(DiagID: diag::note_precedence_silence)
15850 << Bop->getOpcodeStr(),
15851 ParenRange: Bop->getSourceRange());
15852 }
15853 }
15854}
15855
15856static void DiagnoseAdditionInShift(Sema &S, SourceLocation OpLoc,
15857 Expr *SubExpr, StringRef Shift) {
15858 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(Val: SubExpr)) {
15859 if (Bop->getOpcode() == BO_Add || Bop->getOpcode() == BO_Sub) {
15860 StringRef Op = Bop->getOpcodeStr();
15861 S.Diag(Loc: Bop->getOperatorLoc(), DiagID: diag::warn_addition_in_bitshift)
15862 << Bop->getSourceRange() << OpLoc << Shift << Op;
15863 SuggestParentheses(Self&: S, Loc: Bop->getOperatorLoc(),
15864 Note: S.PDiag(DiagID: diag::note_precedence_silence) << Op,
15865 ParenRange: Bop->getSourceRange());
15866 }
15867 }
15868}
15869
15870static void DiagnoseShiftCompare(Sema &S, SourceLocation OpLoc,
15871 Expr *LHSExpr, Expr *RHSExpr) {
15872 CXXOperatorCallExpr *OCE = dyn_cast<CXXOperatorCallExpr>(Val: LHSExpr);
15873 if (!OCE)
15874 return;
15875
15876 FunctionDecl *FD = OCE->getDirectCallee();
15877 if (!FD || !FD->isOverloadedOperator())
15878 return;
15879
15880 OverloadedOperatorKind Kind = FD->getOverloadedOperator();
15881 if (Kind != OO_LessLess && Kind != OO_GreaterGreater)
15882 return;
15883
15884 S.Diag(Loc: OpLoc, DiagID: diag::warn_overloaded_shift_in_comparison)
15885 << LHSExpr->getSourceRange() << RHSExpr->getSourceRange()
15886 << (Kind == OO_LessLess);
15887 SuggestParentheses(Self&: S, Loc: OCE->getOperatorLoc(),
15888 Note: S.PDiag(DiagID: diag::note_precedence_silence)
15889 << (Kind == OO_LessLess ? "<<" : ">>"),
15890 ParenRange: OCE->getSourceRange());
15891 SuggestParentheses(
15892 Self&: S, Loc: OpLoc, Note: S.PDiag(DiagID: diag::note_evaluate_comparison_first),
15893 ParenRange: SourceRange(OCE->getArg(Arg: 1)->getBeginLoc(), RHSExpr->getEndLoc()));
15894}
15895
15896/// DiagnoseBinOpPrecedence - Emit warnings for expressions with tricky
15897/// precedence.
15898static void DiagnoseBinOpPrecedence(Sema &Self, BinaryOperatorKind Opc,
15899 SourceLocation OpLoc, Expr *LHSExpr,
15900 Expr *RHSExpr){
15901 // Diagnose "arg1 'bitwise' arg2 'eq' arg3".
15902 if (BinaryOperator::isBitwiseOp(Opc))
15903 DiagnoseBitwisePrecedence(Self, Opc, OpLoc, LHSExpr, RHSExpr);
15904
15905 // Diagnose "arg1 & arg2 | arg3"
15906 if ((Opc == BO_Or || Opc == BO_Xor) &&
15907 !OpLoc.isMacroID()/* Don't warn in macros. */) {
15908 DiagnoseBitwiseOpInBitwiseOp(S&: Self, Opc, OpLoc, SubExpr: LHSExpr);
15909 DiagnoseBitwiseOpInBitwiseOp(S&: Self, Opc, OpLoc, SubExpr: RHSExpr);
15910 }
15911
15912 // Warn about arg1 || arg2 && arg3, as GCC 4.3+ does.
15913 // We don't warn for 'assert(a || b && "bad")' since this is safe.
15914 if (Opc == BO_LOr && !OpLoc.isMacroID()/* Don't warn in macros. */) {
15915 DiagnoseLogicalAndInLogicalOrLHS(S&: Self, OpLoc, LHSExpr, RHSExpr);
15916 DiagnoseLogicalAndInLogicalOrRHS(S&: Self, OpLoc, LHSExpr, RHSExpr);
15917 }
15918
15919 if ((Opc == BO_Shl && LHSExpr->getType()->isIntegralType(Ctx: Self.getASTContext()))
15920 || Opc == BO_Shr) {
15921 StringRef Shift = BinaryOperator::getOpcodeStr(Op: Opc);
15922 DiagnoseAdditionInShift(S&: Self, OpLoc, SubExpr: LHSExpr, Shift);
15923 DiagnoseAdditionInShift(S&: Self, OpLoc, SubExpr: RHSExpr, Shift);
15924 }
15925
15926 // Warn on overloaded shift operators and comparisons, such as:
15927 // cout << 5 == 4;
15928 if (BinaryOperator::isComparisonOp(Opc))
15929 DiagnoseShiftCompare(S&: Self, OpLoc, LHSExpr, RHSExpr);
15930}
15931
15932ExprResult Sema::ActOnBinOp(Scope *S, SourceLocation TokLoc,
15933 tok::TokenKind Kind,
15934 Expr *LHSExpr, Expr *RHSExpr) {
15935 BinaryOperatorKind Opc = ConvertTokenKindToBinaryOpcode(Kind);
15936 assert(LHSExpr && "ActOnBinOp(): missing left expression");
15937 assert(RHSExpr && "ActOnBinOp(): missing right expression");
15938
15939 // Emit warnings for tricky precedence issues, e.g. "bitfield & 0x4 == 0"
15940 DiagnoseBinOpPrecedence(Self&: *this, Opc, OpLoc: TokLoc, LHSExpr, RHSExpr);
15941
15942 BuiltinCountedByRefKind K = BinaryOperator::isAssignmentOp(Opc)
15943 ? BuiltinCountedByRefKind::Assignment
15944 : BuiltinCountedByRefKind::BinaryExpr;
15945
15946 CheckInvalidBuiltinCountedByRef(E: LHSExpr, K);
15947 CheckInvalidBuiltinCountedByRef(E: RHSExpr, K);
15948
15949 return BuildBinOp(S, OpLoc: TokLoc, Opc, LHSExpr, RHSExpr);
15950}
15951
15952void Sema::LookupBinOp(Scope *S, SourceLocation OpLoc, BinaryOperatorKind Opc,
15953 UnresolvedSetImpl &Functions) {
15954 OverloadedOperatorKind OverOp = BinaryOperator::getOverloadedOperator(Opc);
15955 if (OverOp != OO_None && OverOp != OO_Equal)
15956 LookupOverloadedOperatorName(Op: OverOp, S, Functions);
15957
15958 // In C++20 onwards, we may have a second operator to look up.
15959 if (getLangOpts().CPlusPlus20) {
15960 if (OverloadedOperatorKind ExtraOp = getRewrittenOverloadedOperator(Kind: OverOp))
15961 LookupOverloadedOperatorName(Op: ExtraOp, S, Functions);
15962 }
15963}
15964
15965/// Build an overloaded binary operator expression in the given scope.
15966static ExprResult BuildOverloadedBinOp(Sema &S, Scope *Sc, SourceLocation OpLoc,
15967 BinaryOperatorKind Opc,
15968 Expr *LHS, Expr *RHS) {
15969 switch (Opc) {
15970 case BO_Assign:
15971 // In the non-overloaded case, we warn about self-assignment (x = x) for
15972 // both simple assignment and certain compound assignments where algebra
15973 // tells us the operation yields a constant result. When the operator is
15974 // overloaded, we can't do the latter because we don't want to assume that
15975 // those algebraic identities still apply; for example, a path-building
15976 // library might use operator/= to append paths. But it's still reasonable
15977 // to assume that simple assignment is just moving/copying values around
15978 // and so self-assignment is likely a bug.
15979 DiagnoseSelfAssignment(S, LHSExpr: LHS, RHSExpr: RHS, OpLoc, IsBuiltin: false);
15980 [[fallthrough]];
15981 case BO_DivAssign:
15982 case BO_RemAssign:
15983 case BO_SubAssign:
15984 case BO_AndAssign:
15985 case BO_OrAssign:
15986 case BO_XorAssign:
15987 CheckIdentityFieldAssignment(LHSExpr: LHS, RHSExpr: RHS, Loc: OpLoc, Sema&: S);
15988 break;
15989 default:
15990 break;
15991 }
15992
15993 // Find all of the overloaded operators visible from this point.
15994 UnresolvedSet<16> Functions;
15995 S.LookupBinOp(S: Sc, OpLoc, Opc, Functions);
15996
15997 // Build the (potentially-overloaded, potentially-dependent)
15998 // binary operation.
15999 return S.CreateOverloadedBinOp(OpLoc, Opc, Fns: Functions, LHS, RHS);
16000}
16001
16002ExprResult Sema::BuildBinOp(Scope *S, SourceLocation OpLoc,
16003 BinaryOperatorKind Opc, Expr *LHSExpr,
16004 Expr *RHSExpr, bool ForFoldExpression) {
16005 if (!LHSExpr || !RHSExpr)
16006 return ExprError();
16007
16008 // We want to end up calling one of SemaPseudoObject::checkAssignment
16009 // (if the LHS is a pseudo-object), BuildOverloadedBinOp (if
16010 // both expressions are overloadable or either is type-dependent),
16011 // or CreateBuiltinBinOp (in any other case). We also want to get
16012 // any placeholder types out of the way.
16013
16014 // Handle pseudo-objects in the LHS.
16015 if (const BuiltinType *pty = LHSExpr->getType()->getAsPlaceholderType()) {
16016 // Assignments with a pseudo-object l-value need special analysis.
16017 if (pty->getKind() == BuiltinType::PseudoObject &&
16018 BinaryOperator::isAssignmentOp(Opc))
16019 return PseudoObject().checkAssignment(S, OpLoc, Opcode: Opc, LHS: LHSExpr, RHS: RHSExpr);
16020
16021 // Don't resolve overloads if the other type is overloadable.
16022 if (getLangOpts().CPlusPlus && pty->getKind() == BuiltinType::Overload) {
16023 // We can't actually test that if we still have a placeholder,
16024 // though. Fortunately, none of the exceptions we see in that
16025 // code below are valid when the LHS is an overload set. Note
16026 // that an overload set can be dependently-typed, but it never
16027 // instantiates to having an overloadable type.
16028 ExprResult resolvedRHS = CheckPlaceholderExpr(E: RHSExpr);
16029 if (resolvedRHS.isInvalid()) return ExprError();
16030 RHSExpr = resolvedRHS.get();
16031
16032 if (RHSExpr->isTypeDependent() ||
16033 RHSExpr->getType()->isOverloadableType())
16034 return BuildOverloadedBinOp(S&: *this, Sc: S, OpLoc, Opc, LHS: LHSExpr, RHS: RHSExpr);
16035 }
16036
16037 // If we're instantiating "a.x < b" or "A::x < b" and 'x' names a function
16038 // template, diagnose the missing 'template' keyword instead of diagnosing
16039 // an invalid use of a bound member function.
16040 //
16041 // Note that "A::x < b" might be valid if 'b' has an overloadable type due
16042 // to C++1z [over.over]/1.4, but we already checked for that case above.
16043 if (Opc == BO_LT && inTemplateInstantiation() &&
16044 (pty->getKind() == BuiltinType::BoundMember ||
16045 pty->getKind() == BuiltinType::Overload)) {
16046 auto *OE = dyn_cast<OverloadExpr>(Val: LHSExpr);
16047 if (OE && !OE->hasTemplateKeyword() && !OE->hasExplicitTemplateArgs() &&
16048 llvm::any_of(Range: OE->decls(), P: [](NamedDecl *ND) {
16049 return isa<FunctionTemplateDecl>(Val: ND);
16050 })) {
16051 Diag(Loc: OE->getQualifier() ? OE->getQualifierLoc().getBeginLoc()
16052 : OE->getNameLoc(),
16053 DiagID: diag::err_template_kw_missing)
16054 << OE->getName().getAsIdentifierInfo();
16055 return ExprError();
16056 }
16057 }
16058
16059 ExprResult LHS = CheckPlaceholderExpr(E: LHSExpr);
16060 if (LHS.isInvalid()) return ExprError();
16061 LHSExpr = LHS.get();
16062 }
16063
16064 // Handle pseudo-objects in the RHS.
16065 if (const BuiltinType *pty = RHSExpr->getType()->getAsPlaceholderType()) {
16066 // An overload in the RHS can potentially be resolved by the type
16067 // being assigned to.
16068 if (Opc == BO_Assign && pty->getKind() == BuiltinType::Overload) {
16069 if (getLangOpts().CPlusPlus &&
16070 (LHSExpr->isTypeDependent() || RHSExpr->isTypeDependent() ||
16071 LHSExpr->getType()->isOverloadableType()))
16072 return BuildOverloadedBinOp(S&: *this, Sc: S, OpLoc, Opc, LHS: LHSExpr, RHS: RHSExpr);
16073
16074 return CreateBuiltinBinOp(OpLoc, Opc, LHSExpr, RHSExpr,
16075 ForFoldExpression);
16076 }
16077
16078 // Don't resolve overloads if the other type is overloadable.
16079 if (getLangOpts().CPlusPlus && pty->getKind() == BuiltinType::Overload &&
16080 LHSExpr->getType()->isOverloadableType())
16081 return BuildOverloadedBinOp(S&: *this, Sc: S, OpLoc, Opc, LHS: LHSExpr, RHS: RHSExpr);
16082
16083 ExprResult resolvedRHS = CheckPlaceholderExpr(E: RHSExpr);
16084 if (!resolvedRHS.isUsable()) return ExprError();
16085 RHSExpr = resolvedRHS.get();
16086 }
16087
16088 if (getLangOpts().HLSL && (LHSExpr->getType()->isHLSLResourceRecord() ||
16089 LHSExpr->getType()->isHLSLResourceRecordArray())) {
16090 if (!HLSL().CheckResourceBinOp(Opc, LHSExpr, RHSExpr, Loc: OpLoc))
16091 return ExprError();
16092 }
16093
16094 if (getLangOpts().CPlusPlus) {
16095 // Otherwise, build an overloaded op if either expression is type-dependent
16096 // or has an overloadable type.
16097 if (LHSExpr->isTypeDependent() || RHSExpr->isTypeDependent() ||
16098 LHSExpr->getType()->isOverloadableType() ||
16099 RHSExpr->getType()->isOverloadableType())
16100 return BuildOverloadedBinOp(S&: *this, Sc: S, OpLoc, Opc, LHS: LHSExpr, RHS: RHSExpr);
16101 }
16102
16103 if (getLangOpts().RecoveryAST &&
16104 (LHSExpr->isTypeDependent() || RHSExpr->isTypeDependent())) {
16105 assert(!getLangOpts().CPlusPlus);
16106 assert((LHSExpr->containsErrors() || RHSExpr->containsErrors()) &&
16107 "Should only occur in error-recovery path.");
16108 if (BinaryOperator::isCompoundAssignmentOp(Opc))
16109 // C [6.15.16] p3:
16110 // An assignment expression has the value of the left operand after the
16111 // assignment, but is not an lvalue.
16112 return CompoundAssignOperator::Create(
16113 C: Context, lhs: LHSExpr, rhs: RHSExpr, opc: Opc,
16114 ResTy: LHSExpr->getType().getUnqualifiedType(), VK: VK_PRValue, OK: OK_Ordinary,
16115 opLoc: OpLoc, FPFeatures: CurFPFeatureOverrides());
16116 QualType ResultType;
16117 switch (Opc) {
16118 case BO_Assign:
16119 ResultType = LHSExpr->getType().getUnqualifiedType();
16120 break;
16121 case BO_LT:
16122 case BO_GT:
16123 case BO_LE:
16124 case BO_GE:
16125 case BO_EQ:
16126 case BO_NE:
16127 case BO_LAnd:
16128 case BO_LOr:
16129 // These operators have a fixed result type regardless of operands.
16130 ResultType = Context.IntTy;
16131 break;
16132 case BO_Comma:
16133 ResultType = RHSExpr->getType();
16134 break;
16135 default:
16136 ResultType = Context.DependentTy;
16137 break;
16138 }
16139 return BinaryOperator::Create(C: Context, lhs: LHSExpr, rhs: RHSExpr, opc: Opc, ResTy: ResultType,
16140 VK: VK_PRValue, OK: OK_Ordinary, opLoc: OpLoc,
16141 FPFeatures: CurFPFeatureOverrides());
16142 }
16143
16144 // Build a built-in binary operation.
16145 return CreateBuiltinBinOp(OpLoc, Opc, LHSExpr, RHSExpr, ForFoldExpression);
16146}
16147
16148static bool isOverflowingIntegerType(ASTContext &Ctx, QualType T) {
16149 if (T.isNull() || T->isDependentType())
16150 return false;
16151
16152 if (!Ctx.isPromotableIntegerType(T))
16153 return true;
16154
16155 return Ctx.getIntWidth(T) >= Ctx.getIntWidth(T: Ctx.IntTy);
16156}
16157
16158ExprResult Sema::CreateBuiltinUnaryOp(SourceLocation OpLoc,
16159 UnaryOperatorKind Opc, Expr *InputExpr,
16160 bool IsAfterAmp) {
16161 ExprResult Input = InputExpr;
16162 ExprValueKind VK = VK_PRValue;
16163 ExprObjectKind OK = OK_Ordinary;
16164 QualType resultType;
16165 bool CanOverflow = false;
16166
16167 bool ConvertHalfVec = false;
16168 if (getLangOpts().OpenCL) {
16169 QualType Ty = InputExpr->getType();
16170 // The only legal unary operation for atomics is '&'.
16171 if ((Opc != UO_AddrOf && Ty->isAtomicType()) ||
16172 // OpenCL special types - image, sampler, pipe, and blocks are to be used
16173 // only with a builtin functions and therefore should be disallowed here.
16174 (Ty->isImageType() || Ty->isSamplerT() || Ty->isPipeType()
16175 || Ty->isBlockPointerType())) {
16176 return ExprError(Diag(Loc: OpLoc, DiagID: diag::err_typecheck_unary_expr)
16177 << InputExpr->getType()
16178 << Input.get()->getSourceRange());
16179 }
16180 }
16181
16182 if (getLangOpts().HLSL && OpLoc.isValid()) {
16183 if (Opc == UO_AddrOf)
16184 return ExprError(Diag(Loc: OpLoc, DiagID: diag::err_hlsl_operator_unsupported) << 0);
16185 if (Opc == UO_Deref)
16186 return ExprError(Diag(Loc: OpLoc, DiagID: diag::err_hlsl_operator_unsupported) << 1);
16187 }
16188
16189 if (InputExpr->isTypeDependent() &&
16190 InputExpr->getType()->isSpecificBuiltinType(K: BuiltinType::Dependent)) {
16191 resultType = Context.DependentTy;
16192 } else {
16193 switch (Opc) {
16194 case UO_PreInc:
16195 case UO_PreDec:
16196 case UO_PostInc:
16197 case UO_PostDec:
16198 resultType =
16199 CheckIncrementDecrementOperand(S&: *this, Op: Input.get(), VK, OK, OpLoc,
16200 IsInc: Opc == UO_PreInc || Opc == UO_PostInc,
16201 IsPrefix: Opc == UO_PreInc || Opc == UO_PreDec);
16202 CanOverflow = isOverflowingIntegerType(Ctx&: Context, T: resultType);
16203 break;
16204 case UO_AddrOf:
16205 resultType = CheckAddressOfOperand(OrigOp&: Input, OpLoc);
16206 CheckAddressOfNoDeref(E: InputExpr);
16207 RecordModifiableNonNullParam(S&: *this, Exp: InputExpr);
16208 break;
16209 case UO_Deref: {
16210 Input = DefaultFunctionArrayLvalueConversion(E: Input.get());
16211 if (Input.isInvalid())
16212 return ExprError();
16213 resultType =
16214 CheckIndirectionOperand(S&: *this, Op: Input.get(), VK, OpLoc, IsAfterAmp);
16215 break;
16216 }
16217 case UO_Plus:
16218 case UO_Minus:
16219 CanOverflow = Opc == UO_Minus &&
16220 isOverflowingIntegerType(Ctx&: Context, T: Input.get()->getType());
16221 Input = UsualUnaryConversions(E: Input.get());
16222 if (Input.isInvalid())
16223 return ExprError();
16224 // Unary plus and minus require promoting an operand of half vector to a
16225 // float vector and truncating the result back to a half vector. For now,
16226 // we do this only when HalfArgsAndReturns is set (that is, when the
16227 // target is arm or arm64).
16228 ConvertHalfVec = needsConversionOfHalfVec(OpRequiresConversion: true, Ctx&: Context, E0: Input.get());
16229
16230 // If the operand is a half vector, promote it to a float vector.
16231 if (ConvertHalfVec)
16232 Input = convertVector(E: Input.get(), ElementType: Context.FloatTy, S&: *this);
16233 resultType = Input.get()->getType();
16234 if (resultType->isArithmeticType()) // C99 6.5.3.3p1
16235 break;
16236 else if (resultType->isVectorType() &&
16237 // The z vector extensions don't allow + or - with bool vectors.
16238 (!Context.getLangOpts().ZVector ||
16239 resultType->castAs<VectorType>()->getVectorKind() !=
16240 VectorKind::AltiVecBool))
16241 break;
16242 else if (resultType->isSveVLSBuiltinType()) // SVE vectors allow + and -
16243 break;
16244 else if (getLangOpts().CPlusPlus && // C++ [expr.unary.op]p6
16245 Opc == UO_Plus && resultType->isPointerType())
16246 break;
16247
16248 return ExprError(Diag(Loc: OpLoc, DiagID: diag::err_typecheck_unary_expr)
16249 << resultType << Input.get()->getSourceRange());
16250
16251 case UO_Not: // bitwise complement
16252 Input = UsualUnaryConversions(E: Input.get());
16253 if (Input.isInvalid())
16254 return ExprError();
16255 resultType = Input.get()->getType();
16256 // C99 6.5.3.3p1. We allow complex int and float as a GCC extension.
16257 if (resultType->isComplexType() || resultType->isComplexIntegerType())
16258 // C99 does not support '~' for complex conjugation.
16259 Diag(Loc: OpLoc, DiagID: diag::ext_integer_complement_complex)
16260 << resultType << Input.get()->getSourceRange();
16261 else if (resultType->hasIntegerRepresentation())
16262 break;
16263 else if (resultType->isExtVectorType() && Context.getLangOpts().OpenCL) {
16264 // OpenCL v1.1 s6.3.f: The bitwise operator not (~) does not operate
16265 // on vector float types.
16266 QualType T = resultType->castAs<ExtVectorType>()->getElementType();
16267 if (!T->isIntegerType())
16268 return ExprError(Diag(Loc: OpLoc, DiagID: diag::err_typecheck_unary_expr)
16269 << resultType << Input.get()->getSourceRange());
16270 } else {
16271 return ExprError(Diag(Loc: OpLoc, DiagID: diag::err_typecheck_unary_expr)
16272 << resultType << Input.get()->getSourceRange());
16273 }
16274 break;
16275
16276 case UO_LNot: // logical negation
16277 // Unlike +/-/~, integer promotions aren't done here (C99 6.5.3.3p5).
16278 Input = DefaultFunctionArrayLvalueConversion(E: Input.get());
16279 if (Input.isInvalid())
16280 return ExprError();
16281 resultType = Input.get()->getType();
16282
16283 // Though we still have to promote half FP to float...
16284 if (resultType->isHalfType() && !Context.getLangOpts().NativeHalfType) {
16285 Input = ImpCastExprToType(E: Input.get(), Type: Context.FloatTy, CK: CK_FloatingCast)
16286 .get();
16287 resultType = Context.FloatTy;
16288 }
16289
16290 // WebAsembly tables can't be used in unary expressions.
16291 if (resultType->isPointerType() &&
16292 resultType->getPointeeType().isWebAssemblyReferenceType()) {
16293 return ExprError(Diag(Loc: OpLoc, DiagID: diag::err_typecheck_unary_expr)
16294 << resultType << Input.get()->getSourceRange());
16295 }
16296
16297 if (resultType->isScalarType() && !isScopedEnumerationType(T: resultType)) {
16298 // C99 6.5.3.3p1: ok, fallthrough;
16299 if (Context.getLangOpts().CPlusPlus) {
16300 // C++03 [expr.unary.op]p8, C++0x [expr.unary.op]p9:
16301 // operand contextually converted to bool.
16302 Input = ImpCastExprToType(E: Input.get(), Type: Context.BoolTy,
16303 CK: ScalarTypeToBooleanCastKind(ScalarTy: resultType));
16304 } else if (Context.getLangOpts().OpenCL &&
16305 Context.getLangOpts().OpenCLVersion < 120) {
16306 // OpenCL v1.1 6.3.h: The logical operator not (!) does not
16307 // operate on scalar float types.
16308 if (!resultType->isIntegerType() && !resultType->isPointerType())
16309 return ExprError(Diag(Loc: OpLoc, DiagID: diag::err_typecheck_unary_expr)
16310 << resultType << Input.get()->getSourceRange());
16311 }
16312 } else if (Context.getLangOpts().HLSL && resultType->isVectorType() &&
16313 !resultType->hasBooleanRepresentation()) {
16314 // HLSL unary logical 'not' behaves like C++, which states that the
16315 // operand is converted to bool and the result is bool, however HLSL
16316 // extends this property to vectors.
16317 const VectorType *VTy = resultType->castAs<VectorType>();
16318 resultType =
16319 Context.getExtVectorType(VectorType: Context.BoolTy, NumElts: VTy->getNumElements());
16320
16321 Input = ImpCastExprToType(
16322 E: Input.get(), Type: resultType,
16323 CK: ScalarTypeToBooleanCastKind(ScalarTy: VTy->getElementType()))
16324 .get();
16325 break;
16326 } else if (resultType->isExtVectorType()) {
16327 if (Context.getLangOpts().OpenCL &&
16328 Context.getLangOpts().getOpenCLCompatibleVersion() < 120) {
16329 // OpenCL v1.1 6.3.h: The logical operator not (!) does not
16330 // operate on vector float types.
16331 QualType T = resultType->castAs<ExtVectorType>()->getElementType();
16332 if (!T->isIntegerType())
16333 return ExprError(Diag(Loc: OpLoc, DiagID: diag::err_typecheck_unary_expr)
16334 << resultType << Input.get()->getSourceRange());
16335 }
16336 // Vector logical not returns the signed variant of the operand type.
16337 resultType = GetSignedVectorType(V: resultType);
16338 break;
16339 } else if (Context.getLangOpts().CPlusPlus &&
16340 resultType->isVectorType()) {
16341 const VectorType *VTy = resultType->castAs<VectorType>();
16342 if (VTy->getVectorKind() != VectorKind::Generic)
16343 return ExprError(Diag(Loc: OpLoc, DiagID: diag::err_typecheck_unary_expr)
16344 << resultType << Input.get()->getSourceRange());
16345
16346 // Vector logical not returns the signed variant of the operand type.
16347 resultType = GetSignedVectorType(V: resultType);
16348 break;
16349 } else if (resultType == Context.AMDGPUFeaturePredicateTy) {
16350 resultType = Context.getLogicalOperationType();
16351 Input = AMDGPU().ExpandAMDGPUPredicateBuiltIn(CE: InputExpr);
16352 break;
16353 } else {
16354 return ExprError(Diag(Loc: OpLoc, DiagID: diag::err_typecheck_unary_expr)
16355 << resultType << Input.get()->getSourceRange());
16356 }
16357
16358 // LNot always has type int. C99 6.5.3.3p5.
16359 // In C++, it's bool. C++ 5.3.1p8
16360 resultType = Context.getLogicalOperationType();
16361 break;
16362 case UO_Real:
16363 case UO_Imag:
16364 resultType = CheckRealImagOperand(S&: *this, V&: Input, Loc: OpLoc, IsReal: Opc == UO_Real);
16365 // _Real maps ordinary l-values into ordinary l-values. _Imag maps
16366 // ordinary complex l-values to ordinary l-values and all other values to
16367 // r-values.
16368 if (Input.isInvalid())
16369 return ExprError();
16370 if (Opc == UO_Real || Input.get()->getType()->isAnyComplexType()) {
16371 if (Input.get()->isGLValue() &&
16372 Input.get()->getObjectKind() == OK_Ordinary)
16373 VK = Input.get()->getValueKind();
16374 } else if (!getLangOpts().CPlusPlus) {
16375 // In C, a volatile scalar is read by __imag. In C++, it is not.
16376 Input = DefaultLvalueConversion(E: Input.get());
16377 }
16378 break;
16379 case UO_Extension:
16380 resultType = Input.get()->getType();
16381 VK = Input.get()->getValueKind();
16382 OK = Input.get()->getObjectKind();
16383 break;
16384 case UO_Coawait:
16385 // It's unnecessary to represent the pass-through operator co_await in the
16386 // AST; just return the input expression instead.
16387 assert(!Input.get()->getType()->isDependentType() &&
16388 "the co_await expression must be non-dependant before "
16389 "building operator co_await");
16390 return Input;
16391 }
16392 }
16393 if (resultType.isNull() || Input.isInvalid())
16394 return ExprError();
16395
16396 // Check for array bounds violations in the operand of the UnaryOperator,
16397 // except for the '*' and '&' operators that have to be handled specially
16398 // by CheckArrayAccess (as there are special cases like &array[arraysize]
16399 // that are explicitly defined as valid by the standard).
16400 if (Opc != UO_AddrOf && Opc != UO_Deref)
16401 CheckArrayAccess(E: Input.get());
16402
16403 auto *UO =
16404 UnaryOperator::Create(C: Context, input: Input.get(), opc: Opc, type: resultType, VK, OK,
16405 l: OpLoc, CanOverflow, FPFeatures: CurFPFeatureOverrides());
16406
16407 if (Opc == UO_Deref && UO->getType()->hasAttr(AK: attr::NoDeref) &&
16408 !isa<ArrayType>(Val: UO->getType().getDesugaredType(Context)) &&
16409 !isUnevaluatedContext())
16410 ExprEvalContexts.back().PossibleDerefs.insert(Ptr: UO);
16411
16412 // Convert the result back to a half vector.
16413 if (ConvertHalfVec)
16414 return convertVector(E: UO, ElementType: Context.HalfTy, S&: *this);
16415 return UO;
16416}
16417
16418bool Sema::isQualifiedMemberAccess(Expr *E) {
16419 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Val: E)) {
16420 if (!DRE->getQualifier())
16421 return false;
16422
16423 ValueDecl *VD = DRE->getDecl();
16424 if (!VD->isCXXClassMember())
16425 return false;
16426
16427 if (isa<FieldDecl>(Val: VD) || isa<IndirectFieldDecl>(Val: VD))
16428 return true;
16429 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Val: VD))
16430 return Method->isImplicitObjectMemberFunction();
16431
16432 return false;
16433 }
16434
16435 if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(Val: E)) {
16436 if (!ULE->getQualifier())
16437 return false;
16438
16439 for (NamedDecl *D : ULE->decls()) {
16440 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Val: D)) {
16441 if (Method->isImplicitObjectMemberFunction())
16442 return true;
16443 } else {
16444 // Overload set does not contain methods.
16445 break;
16446 }
16447 }
16448
16449 return false;
16450 }
16451
16452 return false;
16453}
16454
16455ExprResult Sema::BuildUnaryOp(Scope *S, SourceLocation OpLoc,
16456 UnaryOperatorKind Opc, Expr *Input,
16457 bool IsAfterAmp) {
16458 // First things first: handle placeholders so that the
16459 // overloaded-operator check considers the right type.
16460 if (const BuiltinType *pty = Input->getType()->getAsPlaceholderType()) {
16461 // Increment and decrement of pseudo-object references.
16462 if (pty->getKind() == BuiltinType::PseudoObject &&
16463 UnaryOperator::isIncrementDecrementOp(Op: Opc))
16464 return PseudoObject().checkIncDec(S, OpLoc, Opcode: Opc, Op: Input);
16465
16466 // extension is always a builtin operator.
16467 if (Opc == UO_Extension)
16468 return CreateBuiltinUnaryOp(OpLoc, Opc, InputExpr: Input);
16469
16470 // & gets special logic for several kinds of placeholder.
16471 // The builtin code knows what to do.
16472 if (Opc == UO_AddrOf &&
16473 (pty->getKind() == BuiltinType::Overload ||
16474 pty->getKind() == BuiltinType::UnknownAny ||
16475 pty->getKind() == BuiltinType::BoundMember))
16476 return CreateBuiltinUnaryOp(OpLoc, Opc, InputExpr: Input);
16477
16478 // Anything else needs to be handled now.
16479 ExprResult Result = CheckPlaceholderExpr(E: Input);
16480 if (Result.isInvalid()) return ExprError();
16481 Input = Result.get();
16482 }
16483
16484 if (getLangOpts().CPlusPlus && Input->getType()->isOverloadableType() &&
16485 UnaryOperator::getOverloadedOperator(Opc) != OO_None &&
16486 !(Opc == UO_AddrOf && isQualifiedMemberAccess(E: Input))) {
16487 // Find all of the overloaded operators visible from this point.
16488 UnresolvedSet<16> Functions;
16489 OverloadedOperatorKind OverOp = UnaryOperator::getOverloadedOperator(Opc);
16490 if (S && OverOp != OO_None)
16491 LookupOverloadedOperatorName(Op: OverOp, S, Functions);
16492
16493 return CreateOverloadedUnaryOp(OpLoc, Opc, Fns: Functions, input: Input);
16494 }
16495
16496 return CreateBuiltinUnaryOp(OpLoc, Opc, InputExpr: Input, IsAfterAmp);
16497}
16498
16499ExprResult Sema::ActOnUnaryOp(Scope *S, SourceLocation OpLoc, tok::TokenKind Op,
16500 Expr *Input, bool IsAfterAmp) {
16501 return BuildUnaryOp(S, OpLoc, Opc: ConvertTokenKindToUnaryOpcode(Kind: Op), Input,
16502 IsAfterAmp);
16503}
16504
16505ExprResult Sema::ActOnAddrLabel(SourceLocation OpLoc, SourceLocation LabLoc,
16506 LabelDecl *TheDecl) {
16507 TheDecl->markUsed(C&: Context);
16508 // Create the AST node. The address of a label always has type 'void*'.
16509 auto *Res = new (Context) AddrLabelExpr(
16510 OpLoc, LabLoc, TheDecl, Context.getPointerType(T: Context.VoidTy));
16511
16512 if (getCurFunction())
16513 getCurFunction()->AddrLabels.push_back(Elt: Res);
16514
16515 return Res;
16516}
16517
16518void Sema::ActOnStartStmtExpr() {
16519 PushExpressionEvaluationContext(NewContext: ExprEvalContexts.back().Context);
16520 // Make sure we diagnose jumping into a statement expression.
16521 setFunctionHasBranchProtectedScope();
16522}
16523
16524void Sema::ActOnStmtExprError() {
16525 // Note that function is also called by TreeTransform when leaving a
16526 // StmtExpr scope without rebuilding anything.
16527
16528 DiscardCleanupsInEvaluationContext();
16529 PopExpressionEvaluationContext();
16530}
16531
16532ExprResult Sema::ActOnStmtExpr(Scope *S, SourceLocation LPLoc, Stmt *SubStmt,
16533 SourceLocation RPLoc) {
16534 return BuildStmtExpr(LPLoc, SubStmt, RPLoc, TemplateDepth: getTemplateDepth(S));
16535}
16536
16537ExprResult Sema::BuildStmtExpr(SourceLocation LPLoc, Stmt *SubStmt,
16538 SourceLocation RPLoc, unsigned TemplateDepth) {
16539 assert(SubStmt && isa<CompoundStmt>(SubStmt) && "Invalid action invocation!");
16540 CompoundStmt *Compound = cast<CompoundStmt>(Val: SubStmt);
16541
16542 if (hasAnyUnrecoverableErrorsInThisFunction())
16543 DiscardCleanupsInEvaluationContext();
16544 assert(!Cleanup.exprNeedsCleanups() &&
16545 "cleanups within StmtExpr not correctly bound!");
16546 PopExpressionEvaluationContext();
16547
16548 // FIXME: there are a variety of strange constraints to enforce here, for
16549 // example, it is not possible to goto into a stmt expression apparently.
16550 // More semantic analysis is needed.
16551
16552 // If there are sub-stmts in the compound stmt, take the type of the last one
16553 // as the type of the stmtexpr.
16554 QualType Ty = Context.VoidTy;
16555 bool StmtExprMayBindToTemp = false;
16556 if (!Compound->body_empty()) {
16557 if (const auto *LastStmt = dyn_cast<ValueStmt>(Val: Compound->body_back())) {
16558 if (const Expr *Value = LastStmt->getExprStmt()) {
16559 StmtExprMayBindToTemp = true;
16560 Ty = Value->getType();
16561 }
16562 }
16563 }
16564
16565 // FIXME: Check that expression type is complete/non-abstract; statement
16566 // expressions are not lvalues.
16567 Expr *ResStmtExpr =
16568 new (Context) StmtExpr(Compound, Ty, LPLoc, RPLoc, TemplateDepth);
16569 if (StmtExprMayBindToTemp)
16570 return MaybeBindToTemporary(E: ResStmtExpr);
16571 return ResStmtExpr;
16572}
16573
16574ExprResult Sema::ActOnStmtExprResult(ExprResult ER) {
16575 if (ER.isInvalid())
16576 return ExprError();
16577
16578 // Do function/array conversion on the last expression, but not
16579 // lvalue-to-rvalue. However, initialize an unqualified type.
16580 ER = DefaultFunctionArrayConversion(E: ER.get());
16581 if (ER.isInvalid())
16582 return ExprError();
16583 Expr *E = ER.get();
16584
16585 if (E->isTypeDependent())
16586 return E;
16587
16588 // In ARC, if the final expression ends in a consume, splice
16589 // the consume out and bind it later. In the alternate case
16590 // (when dealing with a retainable type), the result
16591 // initialization will create a produce. In both cases the
16592 // result will be +1, and we'll need to balance that out with
16593 // a bind.
16594 auto *Cast = dyn_cast<ImplicitCastExpr>(Val: E);
16595 if (Cast && Cast->getCastKind() == CK_ARCConsumeObject)
16596 return Cast->getSubExpr();
16597
16598 // FIXME: Provide a better location for the initialization.
16599 return PerformCopyInitialization(
16600 Entity: InitializedEntity::InitializeStmtExprResult(
16601 ReturnLoc: E->getBeginLoc(), Type: E->getType().getAtomicUnqualifiedType()),
16602 EqualLoc: SourceLocation(), Init: E);
16603}
16604
16605ExprResult Sema::BuildBuiltinOffsetOf(SourceLocation BuiltinLoc,
16606 TypeSourceInfo *TInfo,
16607 ArrayRef<OffsetOfComponent> Components,
16608 SourceLocation RParenLoc) {
16609 QualType ArgTy = TInfo->getType();
16610 bool Dependent = ArgTy->isDependentType();
16611 SourceRange TypeRange = TInfo->getTypeLoc().getLocalSourceRange();
16612
16613 // We must have at least one component that refers to the type, and the first
16614 // one is known to be a field designator. Verify that the ArgTy represents
16615 // a struct/union/class.
16616 if (!Dependent && !ArgTy->isRecordType())
16617 return ExprError(Diag(Loc: BuiltinLoc, DiagID: diag::err_offsetof_record_type)
16618 << ArgTy << TypeRange);
16619
16620 // Type must be complete per C99 7.17p3 because a declaring a variable
16621 // with an incomplete type would be ill-formed.
16622 if (!Dependent
16623 && RequireCompleteType(Loc: BuiltinLoc, T: ArgTy,
16624 DiagID: diag::err_offsetof_incomplete_type, Args: TypeRange))
16625 return ExprError();
16626
16627 bool DidWarnAboutNonPOD = false;
16628 QualType CurrentType = ArgTy;
16629 SmallVector<OffsetOfNode, 4> Comps;
16630 SmallVector<Expr*, 4> Exprs;
16631 for (const OffsetOfComponent &OC : Components) {
16632 if (OC.isBrackets) {
16633 // Offset of an array sub-field. TODO: Should we allow vector elements?
16634 if (!CurrentType->isDependentType()) {
16635 const ArrayType *AT = Context.getAsArrayType(T: CurrentType);
16636 if(!AT)
16637 return ExprError(Diag(Loc: OC.LocEnd, DiagID: diag::err_offsetof_array_type)
16638 << CurrentType);
16639 CurrentType = AT->getElementType();
16640 } else
16641 CurrentType = Context.DependentTy;
16642
16643 ExprResult IdxRval = DefaultLvalueConversion(E: static_cast<Expr*>(OC.U.E));
16644 if (IdxRval.isInvalid())
16645 return ExprError();
16646 Expr *Idx = IdxRval.get();
16647
16648 // The expression must be an integral expression.
16649 // FIXME: An integral constant expression?
16650 if (!Idx->isTypeDependent() && !Idx->isValueDependent() &&
16651 !Idx->getType()->isIntegerType())
16652 return ExprError(
16653 Diag(Loc: Idx->getBeginLoc(), DiagID: diag::err_typecheck_subscript_not_integer)
16654 << Idx->getSourceRange());
16655
16656 // Record this array index.
16657 Comps.push_back(Elt: OffsetOfNode(OC.LocStart, Exprs.size(), OC.LocEnd));
16658 Exprs.push_back(Elt: Idx);
16659 continue;
16660 }
16661
16662 // Offset of a field.
16663 if (CurrentType->isDependentType()) {
16664 // We have the offset of a field, but we can't look into the dependent
16665 // type. Just record the identifier of the field.
16666 Comps.push_back(Elt: OffsetOfNode(OC.LocStart, OC.U.IdentInfo, OC.LocEnd));
16667 CurrentType = Context.DependentTy;
16668 continue;
16669 }
16670
16671 // We need to have a complete type to look into.
16672 if (RequireCompleteType(Loc: OC.LocStart, T: CurrentType,
16673 DiagID: diag::err_offsetof_incomplete_type))
16674 return ExprError();
16675
16676 // Look for the designated field.
16677 auto *RD = CurrentType->getAsRecordDecl();
16678 if (!RD)
16679 return ExprError(Diag(Loc: OC.LocEnd, DiagID: diag::err_offsetof_record_type)
16680 << CurrentType);
16681
16682 // C++ [lib.support.types]p5:
16683 // The macro offsetof accepts a restricted set of type arguments in this
16684 // International Standard. type shall be a POD structure or a POD union
16685 // (clause 9).
16686 // C++11 [support.types]p4:
16687 // If type is not a standard-layout class (Clause 9), the results are
16688 // undefined.
16689 if (CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(Val: RD)) {
16690 bool IsSafe = LangOpts.CPlusPlus11? CRD->isStandardLayout() : CRD->isPOD();
16691 unsigned DiagID =
16692 LangOpts.CPlusPlus11? diag::ext_offsetof_non_standardlayout_type
16693 : diag::ext_offsetof_non_pod_type;
16694
16695 if (!IsSafe && !DidWarnAboutNonPOD && !isUnevaluatedContext()) {
16696 Diag(Loc: BuiltinLoc, DiagID)
16697 << SourceRange(Components[0].LocStart, OC.LocEnd) << CurrentType;
16698 DidWarnAboutNonPOD = true;
16699 }
16700 }
16701
16702 // Look for the field.
16703 LookupResult R(*this, OC.U.IdentInfo, OC.LocStart, LookupMemberName);
16704 LookupQualifiedName(R, LookupCtx: RD);
16705 FieldDecl *MemberDecl = R.getAsSingle<FieldDecl>();
16706 IndirectFieldDecl *IndirectMemberDecl = nullptr;
16707 if (!MemberDecl) {
16708 if ((IndirectMemberDecl = R.getAsSingle<IndirectFieldDecl>()))
16709 MemberDecl = IndirectMemberDecl->getAnonField();
16710 }
16711
16712 if (!MemberDecl) {
16713 // Lookup could be ambiguous when looking up a placeholder variable
16714 // __builtin_offsetof(S, _).
16715 // In that case we would already have emitted a diagnostic
16716 if (!R.isAmbiguous())
16717 Diag(Loc: BuiltinLoc, DiagID: diag::err_no_member)
16718 << OC.U.IdentInfo << RD << SourceRange(OC.LocStart, OC.LocEnd);
16719 return ExprError();
16720 }
16721
16722 // C99 7.17p3:
16723 // (If the specified member is a bit-field, the behavior is undefined.)
16724 //
16725 // We diagnose this as an error.
16726 if (MemberDecl->isBitField()) {
16727 Diag(Loc: OC.LocEnd, DiagID: diag::err_offsetof_bitfield)
16728 << MemberDecl->getDeclName()
16729 << SourceRange(BuiltinLoc, RParenLoc);
16730 Diag(Loc: MemberDecl->getLocation(), DiagID: diag::note_bitfield_decl);
16731 return ExprError();
16732 }
16733
16734 RecordDecl *Parent = MemberDecl->getParent();
16735 if (IndirectMemberDecl)
16736 Parent = cast<RecordDecl>(Val: IndirectMemberDecl->getDeclContext());
16737
16738 // If the member was found in a base class, introduce OffsetOfNodes for
16739 // the base class indirections.
16740 CXXBasePaths Paths;
16741 if (IsDerivedFrom(Loc: OC.LocStart, Derived: CurrentType,
16742 Base: Context.getCanonicalTagType(TD: Parent), Paths)) {
16743 if (Paths.getDetectedVirtual()) {
16744 Diag(Loc: OC.LocEnd, DiagID: diag::err_offsetof_field_of_virtual_base)
16745 << MemberDecl->getDeclName()
16746 << SourceRange(BuiltinLoc, RParenLoc);
16747 return ExprError();
16748 }
16749
16750 CXXBasePath &Path = Paths.front();
16751 for (const CXXBasePathElement &B : Path)
16752 Comps.push_back(Elt: OffsetOfNode(B.Base));
16753 }
16754
16755 if (IndirectMemberDecl) {
16756 for (auto *FI : IndirectMemberDecl->chain()) {
16757 assert(isa<FieldDecl>(FI));
16758 Comps.push_back(Elt: OffsetOfNode(OC.LocStart,
16759 cast<FieldDecl>(Val: FI), OC.LocEnd));
16760 }
16761 } else
16762 Comps.push_back(Elt: OffsetOfNode(OC.LocStart, MemberDecl, OC.LocEnd));
16763
16764 CurrentType = MemberDecl->getType().getNonReferenceType();
16765 }
16766
16767 return OffsetOfExpr::Create(C: Context, type: Context.getSizeType(), OperatorLoc: BuiltinLoc, tsi: TInfo,
16768 comps: Comps, exprs: Exprs, RParenLoc);
16769}
16770
16771ExprResult Sema::ActOnBuiltinOffsetOf(Scope *S,
16772 SourceLocation BuiltinLoc,
16773 SourceLocation TypeLoc,
16774 ParsedType ParsedArgTy,
16775 ArrayRef<OffsetOfComponent> Components,
16776 SourceLocation RParenLoc) {
16777
16778 TypeSourceInfo *ArgTInfo;
16779 QualType ArgTy = GetTypeFromParser(Ty: ParsedArgTy, TInfo: &ArgTInfo);
16780 if (ArgTy.isNull())
16781 return ExprError();
16782
16783 if (!ArgTInfo)
16784 ArgTInfo = Context.getTrivialTypeSourceInfo(T: ArgTy, Loc: TypeLoc);
16785
16786 return BuildBuiltinOffsetOf(BuiltinLoc, TInfo: ArgTInfo, Components, RParenLoc);
16787}
16788
16789
16790ExprResult Sema::ActOnChooseExpr(SourceLocation BuiltinLoc,
16791 Expr *CondExpr,
16792 Expr *LHSExpr, Expr *RHSExpr,
16793 SourceLocation RPLoc) {
16794 assert((CondExpr && LHSExpr && RHSExpr) && "Missing type argument(s)");
16795
16796 ExprValueKind VK = VK_PRValue;
16797 ExprObjectKind OK = OK_Ordinary;
16798 QualType resType;
16799 bool CondIsTrue = false;
16800 if (CondExpr->isTypeDependent() || CondExpr->isValueDependent()) {
16801 resType = Context.DependentTy;
16802 } else {
16803 // The conditional expression is required to be a constant expression.
16804 llvm::APSInt condEval(32);
16805 ExprResult CondICE = VerifyIntegerConstantExpression(
16806 E: CondExpr, Result: &condEval, DiagID: diag::err_typecheck_choose_expr_requires_constant);
16807 if (CondICE.isInvalid())
16808 return ExprError();
16809 CondExpr = CondICE.get();
16810 CondIsTrue = condEval.getZExtValue();
16811
16812 // If the condition is > zero, then the AST type is the same as the LHSExpr.
16813 Expr *ActiveExpr = CondIsTrue ? LHSExpr : RHSExpr;
16814
16815 resType = ActiveExpr->getType();
16816 VK = ActiveExpr->getValueKind();
16817 OK = ActiveExpr->getObjectKind();
16818 }
16819
16820 return new (Context) ChooseExpr(BuiltinLoc, CondExpr, LHSExpr, RHSExpr,
16821 resType, VK, OK, RPLoc, CondIsTrue);
16822}
16823
16824//===----------------------------------------------------------------------===//
16825// Clang Extensions.
16826//===----------------------------------------------------------------------===//
16827
16828void Sema::ActOnBlockStart(SourceLocation CaretLoc, Scope *CurScope) {
16829 BlockDecl *Block = BlockDecl::Create(C&: Context, DC: CurContext, L: CaretLoc);
16830
16831 if (LangOpts.CPlusPlus) {
16832 MangleNumberingContext *MCtx;
16833 Decl *ManglingContextDecl;
16834 std::tie(args&: MCtx, args&: ManglingContextDecl) =
16835 getCurrentMangleNumberContext(DC: Block->getDeclContext());
16836 if (MCtx) {
16837 unsigned ManglingNumber = MCtx->getManglingNumber(BD: Block);
16838 Block->setBlockMangling(Number: ManglingNumber, Ctx: ManglingContextDecl);
16839 }
16840 }
16841
16842 PushBlockScope(BlockScope: CurScope, Block);
16843 CurContext->addDecl(D: Block);
16844 if (CurScope)
16845 PushDeclContext(S: CurScope, DC: Block);
16846 else
16847 CurContext = Block;
16848
16849 getCurBlock()->HasImplicitReturnType = true;
16850
16851 // Enter a new evaluation context to insulate the block from any
16852 // cleanups from the enclosing full-expression.
16853 PushExpressionEvaluationContext(
16854 NewContext: ExpressionEvaluationContext::PotentiallyEvaluated);
16855}
16856
16857void Sema::ActOnBlockArguments(SourceLocation CaretLoc, Declarator &ParamInfo,
16858 Scope *CurScope) {
16859 assert(ParamInfo.getIdentifier() == nullptr &&
16860 "block-id should have no identifier!");
16861 assert(ParamInfo.getContext() == DeclaratorContext::BlockLiteral);
16862 BlockScopeInfo *CurBlock = getCurBlock();
16863
16864 TypeSourceInfo *Sig = GetTypeForDeclarator(D&: ParamInfo);
16865 QualType T = Sig->getType();
16866 DiagnoseUnexpandedParameterPack(Loc: CaretLoc, T: Sig, UPPC: UPPC_Block);
16867
16868 // GetTypeForDeclarator always produces a function type for a block
16869 // literal signature. Furthermore, it is always a FunctionProtoType
16870 // unless the function was written with a typedef.
16871 assert(T->isFunctionType() &&
16872 "GetTypeForDeclarator made a non-function block signature");
16873
16874 // Look for an explicit signature in that function type.
16875 FunctionProtoTypeLoc ExplicitSignature;
16876
16877 if ((ExplicitSignature = Sig->getTypeLoc()
16878 .getAsAdjusted<FunctionProtoTypeLoc>())) {
16879
16880 // Check whether that explicit signature was synthesized by
16881 // GetTypeForDeclarator. If so, don't save that as part of the
16882 // written signature.
16883 if (ExplicitSignature.getLocalRangeBegin() ==
16884 ExplicitSignature.getLocalRangeEnd()) {
16885 // This would be much cheaper if we stored TypeLocs instead of
16886 // TypeSourceInfos.
16887 TypeLoc Result = ExplicitSignature.getReturnLoc();
16888 unsigned Size = Result.getFullDataSize();
16889 Sig = Context.CreateTypeSourceInfo(T: Result.getType(), Size);
16890 Sig->getTypeLoc().initializeFullCopy(Other: Result, Size);
16891
16892 ExplicitSignature = FunctionProtoTypeLoc();
16893 }
16894 }
16895
16896 CurBlock->TheDecl->setSignatureAsWritten(Sig);
16897 CurBlock->FunctionType = T;
16898
16899 const auto *Fn = T->castAs<FunctionType>();
16900 QualType RetTy = Fn->getReturnType();
16901 bool isVariadic =
16902 (isa<FunctionProtoType>(Val: Fn) && cast<FunctionProtoType>(Val: Fn)->isVariadic());
16903
16904 CurBlock->TheDecl->setIsVariadic(isVariadic);
16905
16906 // Context.DependentTy is used as a placeholder for a missing block
16907 // return type. TODO: what should we do with declarators like:
16908 // ^ * { ... }
16909 // If the answer is "apply template argument deduction"....
16910 if (RetTy != Context.DependentTy) {
16911 CurBlock->ReturnType = RetTy;
16912 CurBlock->TheDecl->setBlockMissingReturnType(false);
16913 CurBlock->HasImplicitReturnType = false;
16914 }
16915
16916 // Push block parameters from the declarator if we had them.
16917 SmallVector<ParmVarDecl*, 8> Params;
16918 if (ExplicitSignature) {
16919 for (unsigned I = 0, E = ExplicitSignature.getNumParams(); I != E; ++I) {
16920 ParmVarDecl *Param = ExplicitSignature.getParam(i: I);
16921 if (Param->getIdentifier() == nullptr && !Param->isImplicit() &&
16922 !Param->isInvalidDecl() && !getLangOpts().CPlusPlus) {
16923 // Diagnose this as an extension in C17 and earlier.
16924 if (!getLangOpts().C23)
16925 Diag(Loc: Param->getLocation(), DiagID: diag::ext_parameter_name_omitted_c23);
16926 }
16927 Params.push_back(Elt: Param);
16928 }
16929
16930 // Fake up parameter variables if we have a typedef, like
16931 // ^ fntype { ... }
16932 } else if (const FunctionProtoType *Fn = T->getAs<FunctionProtoType>()) {
16933 for (const auto &I : Fn->param_types()) {
16934 ParmVarDecl *Param = BuildParmVarDeclForTypedef(
16935 DC: CurBlock->TheDecl, Loc: ParamInfo.getBeginLoc(), T: I);
16936 Params.push_back(Elt: Param);
16937 }
16938 }
16939
16940 // Set the parameters on the block decl.
16941 if (!Params.empty()) {
16942 CurBlock->TheDecl->setParams(Params);
16943 CheckParmsForFunctionDef(Parameters: CurBlock->TheDecl->parameters(),
16944 /*CheckParameterNames=*/false);
16945 }
16946
16947 // Finally we can process decl attributes.
16948 ProcessDeclAttributes(S: CurScope, D: CurBlock->TheDecl, PD: ParamInfo);
16949
16950 // Put the parameter variables in scope.
16951 for (auto *AI : CurBlock->TheDecl->parameters()) {
16952 AI->setOwningFunction(CurBlock->TheDecl);
16953
16954 // If this has an identifier, add it to the scope stack.
16955 if (AI->getIdentifier()) {
16956 CheckShadow(S: CurBlock->TheScope, D: AI);
16957
16958 PushOnScopeChains(D: AI, S: CurBlock->TheScope);
16959 }
16960
16961 if (AI->isInvalidDecl())
16962 CurBlock->TheDecl->setInvalidDecl();
16963 }
16964}
16965
16966void Sema::ActOnBlockError(SourceLocation CaretLoc, Scope *CurScope) {
16967 // Leave the expression-evaluation context.
16968 DiscardCleanupsInEvaluationContext();
16969 PopExpressionEvaluationContext();
16970
16971 // Pop off CurBlock, handle nested blocks.
16972 PopDeclContext();
16973 PopFunctionScopeInfo();
16974}
16975
16976ExprResult Sema::ActOnBlockStmtExpr(SourceLocation CaretLoc,
16977 Stmt *Body, Scope *CurScope) {
16978 // If blocks are disabled, emit an error.
16979 if (!LangOpts.Blocks)
16980 Diag(Loc: CaretLoc, DiagID: diag::err_blocks_disable) << LangOpts.OpenCL;
16981
16982 // Leave the expression-evaluation context.
16983 if (hasAnyUnrecoverableErrorsInThisFunction())
16984 DiscardCleanupsInEvaluationContext();
16985 assert(!Cleanup.exprNeedsCleanups() &&
16986 "cleanups within block not correctly bound!");
16987 PopExpressionEvaluationContext();
16988
16989 BlockScopeInfo *BSI = cast<BlockScopeInfo>(Val: FunctionScopes.back());
16990 BlockDecl *BD = BSI->TheDecl;
16991
16992 maybeAddDeclWithEffects(D: BD);
16993
16994 if (BSI->HasImplicitReturnType)
16995 deduceClosureReturnType(CSI&: *BSI);
16996
16997 QualType RetTy = Context.VoidTy;
16998 if (!BSI->ReturnType.isNull())
16999 RetTy = BSI->ReturnType;
17000
17001 bool NoReturn = BD->hasAttr<NoReturnAttr>();
17002 QualType BlockTy;
17003
17004 // If the user wrote a function type in some form, try to use that.
17005 if (!BSI->FunctionType.isNull()) {
17006 const FunctionType *FTy = BSI->FunctionType->castAs<FunctionType>();
17007
17008 FunctionType::ExtInfo Ext = FTy->getExtInfo();
17009 if (NoReturn && !Ext.getNoReturn()) Ext = Ext.withNoReturn(noReturn: true);
17010
17011 // Turn protoless block types into nullary block types.
17012 if (isa<FunctionNoProtoType>(Val: FTy)) {
17013 FunctionProtoType::ExtProtoInfo EPI;
17014 EPI.ExtInfo = Ext;
17015 BlockTy = Context.getFunctionType(ResultTy: RetTy, Args: {}, EPI);
17016
17017 // Otherwise, if we don't need to change anything about the function type,
17018 // preserve its sugar structure.
17019 } else if (FTy->getReturnType() == RetTy &&
17020 (!NoReturn || FTy->getNoReturnAttr())) {
17021 BlockTy = BSI->FunctionType;
17022
17023 // Otherwise, make the minimal modifications to the function type.
17024 } else {
17025 const FunctionProtoType *FPT = cast<FunctionProtoType>(Val: FTy);
17026 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
17027 EPI.TypeQuals = Qualifiers();
17028 EPI.ExtInfo = Ext;
17029 BlockTy = Context.getFunctionType(ResultTy: RetTy, Args: FPT->getParamTypes(), EPI);
17030 }
17031
17032 // If we don't have a function type, just build one from nothing.
17033 } else {
17034 FunctionProtoType::ExtProtoInfo EPI;
17035 EPI.ExtInfo = FunctionType::ExtInfo().withNoReturn(noReturn: NoReturn);
17036 BlockTy = Context.getFunctionType(ResultTy: RetTy, Args: {}, EPI);
17037 }
17038
17039 DiagnoseUnusedParameters(Parameters: BD->parameters());
17040 BlockTy = Context.getBlockPointerType(T: BlockTy);
17041
17042 // If needed, diagnose invalid gotos and switches in the block.
17043 if (getCurFunction()->NeedsScopeChecking() &&
17044 !PP.isCodeCompletionEnabled())
17045 DiagnoseInvalidJumps(Body: cast<CompoundStmt>(Val: Body));
17046
17047 BD->setBody(cast<CompoundStmt>(Val: Body));
17048
17049 if (Body && getCurFunction()->HasPotentialAvailabilityViolations)
17050 DiagnoseUnguardedAvailabilityViolations(FD: BD);
17051
17052 // Try to apply the named return value optimization. We have to check again
17053 // if we can do this, though, because blocks keep return statements around
17054 // to deduce an implicit return type.
17055 if (getLangOpts().CPlusPlus && RetTy->isRecordType() &&
17056 !BD->isDependentContext())
17057 computeNRVO(Body, Scope: BSI);
17058
17059 if (RetTy.hasNonTrivialToPrimitiveDestructCUnion() ||
17060 RetTy.hasNonTrivialToPrimitiveCopyCUnion())
17061 checkNonTrivialCUnion(QT: RetTy, Loc: BD->getCaretLocation(),
17062 UseContext: NonTrivialCUnionContext::FunctionReturn,
17063 NonTrivialKind: NTCUK_Destruct | NTCUK_Copy);
17064
17065 PopDeclContext();
17066
17067 // Set the captured variables on the block.
17068 SmallVector<BlockDecl::Capture, 4> Captures;
17069 for (Capture &Cap : BSI->Captures) {
17070 if (Cap.isInvalid() || Cap.isThisCapture())
17071 continue;
17072 // Cap.getVariable() is always a VarDecl because
17073 // blocks cannot capture structured bindings or other ValueDecl kinds.
17074 auto *Var = cast<VarDecl>(Val: Cap.getVariable());
17075 Expr *CopyExpr = nullptr;
17076 if (getLangOpts().CPlusPlus && Cap.isCopyCapture()) {
17077 if (auto *Record = Cap.getCaptureType()->getAsCXXRecordDecl()) {
17078 // The capture logic needs the destructor, so make sure we mark it.
17079 // Usually this is unnecessary because most local variables have
17080 // their destructors marked at declaration time, but parameters are
17081 // an exception because it's technically only the call site that
17082 // actually requires the destructor.
17083 if (isa<ParmVarDecl>(Val: Var))
17084 FinalizeVarWithDestructor(VD: Var, DeclInit: Record);
17085
17086 // Enter a separate potentially-evaluated context while building block
17087 // initializers to isolate their cleanups from those of the block
17088 // itself.
17089 // FIXME: Is this appropriate even when the block itself occurs in an
17090 // unevaluated operand?
17091 EnterExpressionEvaluationContext EvalContext(
17092 *this, ExpressionEvaluationContext::PotentiallyEvaluated);
17093
17094 SourceLocation Loc = Cap.getLocation();
17095
17096 ExprResult Result = BuildDeclarationNameExpr(
17097 SS: CXXScopeSpec(), NameInfo: DeclarationNameInfo(Var->getDeclName(), Loc), D: Var);
17098
17099 // According to the blocks spec, the capture of a variable from
17100 // the stack requires a const copy constructor. This is not true
17101 // of the copy/move done to move a __block variable to the heap.
17102 if (!Result.isInvalid() &&
17103 !Result.get()->getType().isConstQualified()) {
17104 Result = ImpCastExprToType(E: Result.get(),
17105 Type: Result.get()->getType().withConst(),
17106 CK: CK_NoOp, VK: VK_LValue);
17107 }
17108
17109 if (!Result.isInvalid()) {
17110 Result = PerformCopyInitialization(
17111 Entity: InitializedEntity::InitializeBlock(BlockVarLoc: Var->getLocation(),
17112 Type: Cap.getCaptureType()),
17113 EqualLoc: Loc, Init: Result.get());
17114 }
17115
17116 // Build a full-expression copy expression if initialization
17117 // succeeded and used a non-trivial constructor. Recover from
17118 // errors by pretending that the copy isn't necessary.
17119 if (!Result.isInvalid() &&
17120 !cast<CXXConstructExpr>(Val: Result.get())->getConstructor()
17121 ->isTrivial()) {
17122 Result = MaybeCreateExprWithCleanups(SubExpr: Result);
17123 CopyExpr = Result.get();
17124 }
17125 }
17126 }
17127
17128 BlockDecl::Capture NewCap(Var, Cap.isBlockCapture(), Cap.isNested(),
17129 CopyExpr);
17130 Captures.push_back(Elt: NewCap);
17131 }
17132 BD->setCaptures(Context, Captures, CapturesCXXThis: BSI->CXXThisCaptureIndex != 0);
17133
17134 // Pop the block scope now but keep it alive to the end of this function.
17135 AnalysisBasedWarnings::Policy WP =
17136 AnalysisWarnings.getPolicyInEffectAt(Loc: Body->getEndLoc());
17137 PoppedFunctionScopePtr ScopeRAII = PopFunctionScopeInfo(WP: &WP, D: BD, BlockType: BlockTy);
17138
17139 BlockExpr *Result = new (Context)
17140 BlockExpr(BD, BlockTy, BSI->ContainsUnexpandedParameterPack);
17141
17142 // If the block isn't obviously global, i.e. it captures anything at
17143 // all, then we need to do a few things in the surrounding context:
17144 if (Result->getBlockDecl()->hasCaptures()) {
17145 // First, this expression has a new cleanup object.
17146 ExprCleanupObjects.push_back(Elt: Result->getBlockDecl());
17147 Cleanup.setExprNeedsCleanups(true);
17148
17149 // It also gets a branch-protected scope if any of the captured
17150 // variables needs destruction.
17151 for (const auto &CI : Result->getBlockDecl()->captures()) {
17152 const VarDecl *var = CI.getVariable();
17153 if (var->getType().isDestructedType() != QualType::DK_none) {
17154 setFunctionHasBranchProtectedScope();
17155 break;
17156 }
17157 }
17158 }
17159
17160 if (getCurFunction())
17161 getCurFunction()->addBlock(BD);
17162
17163 // This can happen if the block's return type is deduced, but
17164 // the return expression is invalid.
17165 if (BD->isInvalidDecl())
17166 return CreateRecoveryExpr(Begin: Result->getBeginLoc(), End: Result->getEndLoc(),
17167 SubExprs: {Result}, T: Result->getType());
17168 return Result;
17169}
17170
17171ExprResult Sema::ActOnVAArg(SourceLocation BuiltinLoc, Expr *E, ParsedType Ty,
17172 SourceLocation RPLoc) {
17173 TypeSourceInfo *TInfo;
17174 GetTypeFromParser(Ty, TInfo: &TInfo);
17175 return BuildVAArgExpr(BuiltinLoc, E, TInfo, RPLoc);
17176}
17177
17178ExprResult Sema::BuildVAArgExpr(SourceLocation BuiltinLoc,
17179 Expr *E, TypeSourceInfo *TInfo,
17180 SourceLocation RPLoc) {
17181 Expr *OrigExpr = E;
17182 bool IsMS = false;
17183
17184 // CUDA device global function does not support varargs.
17185 if (getLangOpts().CUDA && getLangOpts().CUDAIsDevice) {
17186 if (const FunctionDecl *F = dyn_cast<FunctionDecl>(Val: CurContext)) {
17187 CUDAFunctionTarget T = CUDA().IdentifyTarget(D: F);
17188 if (T == CUDAFunctionTarget::Global)
17189 return ExprError(Diag(Loc: E->getBeginLoc(), DiagID: diag::err_va_arg_in_device));
17190 }
17191 }
17192
17193 // NVPTX does not support va_arg expression.
17194 if (getLangOpts().OpenMP && getLangOpts().OpenMPIsTargetDevice &&
17195 Context.getTargetInfo().getTriple().isNVPTX())
17196 targetDiag(Loc: E->getBeginLoc(), DiagID: diag::err_va_arg_in_device);
17197
17198 // It might be a __builtin_ms_va_list. (But don't ever mark a va_arg()
17199 // as Microsoft ABI on an actual Microsoft platform, where
17200 // __builtin_ms_va_list and __builtin_va_list are the same.)
17201 if (!E->isTypeDependent() && Context.getTargetInfo().hasBuiltinMSVaList() &&
17202 Context.getTargetInfo().getBuiltinVaListKind() != TargetInfo::CharPtrBuiltinVaList) {
17203 QualType MSVaListType = Context.getBuiltinMSVaListType();
17204 if (Context.hasSameType(T1: MSVaListType, T2: E->getType())) {
17205 if (CheckForModifiableLvalue(E, Loc: BuiltinLoc, S&: *this))
17206 return ExprError();
17207 IsMS = true;
17208 }
17209 }
17210
17211 // Get the va_list type
17212 QualType VaListType = Context.getBuiltinVaListType();
17213 if (!IsMS) {
17214 if (VaListType->isArrayType()) {
17215 // Deal with implicit array decay; for example, on x86-64,
17216 // va_list is an array, but it's supposed to decay to
17217 // a pointer for va_arg.
17218 VaListType = Context.getArrayDecayedType(T: VaListType);
17219 // Make sure the input expression also decays appropriately.
17220 ExprResult Result = UsualUnaryConversions(E);
17221 if (Result.isInvalid())
17222 return ExprError();
17223 E = Result.get();
17224 } else if (VaListType->isRecordType() && getLangOpts().CPlusPlus) {
17225 // If va_list is a record type and we are compiling in C++ mode,
17226 // check the argument using reference binding.
17227 InitializedEntity Entity = InitializedEntity::InitializeParameter(
17228 Context, Type: Context.getLValueReferenceType(T: VaListType), Consumed: false);
17229 ExprResult Init = PerformCopyInitialization(Entity, EqualLoc: SourceLocation(), Init: E);
17230 if (Init.isInvalid())
17231 return ExprError();
17232 E = Init.getAs<Expr>();
17233 } else {
17234 // Otherwise, the va_list argument must be an l-value because
17235 // it is modified by va_arg.
17236 if (!E->isTypeDependent() &&
17237 CheckForModifiableLvalue(E, Loc: BuiltinLoc, S&: *this))
17238 return ExprError();
17239 }
17240 }
17241
17242 if (!IsMS && !E->isTypeDependent() &&
17243 !Context.hasSameType(T1: VaListType, T2: E->getType()))
17244 return ExprError(
17245 Diag(Loc: E->getBeginLoc(),
17246 DiagID: diag::err_first_argument_to_va_arg_not_of_type_va_list)
17247 << OrigExpr->getType() << E->getSourceRange());
17248
17249 if (!TInfo->getType()->isDependentType()) {
17250 if (RequireCompleteType(Loc: TInfo->getTypeLoc().getBeginLoc(), T: TInfo->getType(),
17251 DiagID: diag::err_second_parameter_to_va_arg_incomplete,
17252 Args: TInfo->getTypeLoc()))
17253 return ExprError();
17254
17255 if (RequireNonAbstractType(Loc: TInfo->getTypeLoc().getBeginLoc(),
17256 T: TInfo->getType(),
17257 DiagID: diag::err_second_parameter_to_va_arg_abstract,
17258 Args: TInfo->getTypeLoc()))
17259 return ExprError();
17260
17261 if (!TInfo->getType().isPODType(Context)) {
17262 Diag(Loc: TInfo->getTypeLoc().getBeginLoc(),
17263 DiagID: TInfo->getType()->isObjCLifetimeType()
17264 ? diag::warn_second_parameter_to_va_arg_ownership_qualified
17265 : diag::warn_second_parameter_to_va_arg_not_pod)
17266 << TInfo->getType()
17267 << TInfo->getTypeLoc().getSourceRange();
17268 }
17269
17270 if (TInfo->getType()->isArrayType()) {
17271 DiagRuntimeBehavior(Loc: TInfo->getTypeLoc().getBeginLoc(), Statement: E,
17272 PD: PDiag(DiagID: diag::warn_second_parameter_to_va_arg_array)
17273 << TInfo->getType()
17274 << TInfo->getTypeLoc().getSourceRange());
17275 }
17276
17277 // Check for va_arg where arguments of the given type will be promoted
17278 // (i.e. this va_arg is guaranteed to have undefined behavior).
17279 QualType PromoteType;
17280 if (Context.isPromotableIntegerType(T: TInfo->getType())) {
17281 PromoteType = Context.getPromotedIntegerType(PromotableType: TInfo->getType());
17282 // [cstdarg.syn]p1 defers the C++ behavior to what the C standard says,
17283 // and C23 7.16.1.1p2 says, in part:
17284 // If type is not compatible with the type of the actual next argument
17285 // (as promoted according to the default argument promotions), the
17286 // behavior is undefined, except for the following cases:
17287 // - both types are pointers to qualified or unqualified versions of
17288 // compatible types;
17289 // - one type is compatible with a signed integer type, the other
17290 // type is compatible with the corresponding unsigned integer type,
17291 // and the value is representable in both types;
17292 // - one type is pointer to qualified or unqualified void and the
17293 // other is a pointer to a qualified or unqualified character type;
17294 // - or, the type of the next argument is nullptr_t and type is a
17295 // pointer type that has the same representation and alignment
17296 // requirements as a pointer to a character type.
17297 // Given that type compatibility is the primary requirement (ignoring
17298 // qualifications), you would think we could call typesAreCompatible()
17299 // directly to test this. However, in C++, that checks for *same type*,
17300 // which causes false positives when passing an enumeration type to
17301 // va_arg. Instead, get the underlying type of the enumeration and pass
17302 // that.
17303 QualType UnderlyingType = TInfo->getType();
17304 if (const auto *ED = UnderlyingType->getAsEnumDecl())
17305 UnderlyingType = ED->getIntegerType();
17306 if (Context.typesAreCompatible(T1: PromoteType, T2: UnderlyingType,
17307 /*CompareUnqualified*/ true))
17308 PromoteType = QualType();
17309
17310 // If the types are still not compatible, we need to test whether the
17311 // promoted type and the underlying type are the same except for
17312 // signedness. Ask the AST for the correctly corresponding type and see
17313 // if that's compatible.
17314 if (!PromoteType.isNull() && !UnderlyingType->isBooleanType() &&
17315 PromoteType->isUnsignedIntegerType() !=
17316 UnderlyingType->isUnsignedIntegerType()) {
17317 UnderlyingType =
17318 UnderlyingType->isUnsignedIntegerType()
17319 ? Context.getCorrespondingSignedType(T: UnderlyingType)
17320 : Context.getCorrespondingUnsignedType(T: UnderlyingType);
17321 if (Context.typesAreCompatible(T1: PromoteType, T2: UnderlyingType,
17322 /*CompareUnqualified*/ true))
17323 PromoteType = QualType();
17324 }
17325 }
17326 if (TInfo->getType()->isSpecificBuiltinType(K: BuiltinType::Float))
17327 PromoteType = Context.DoubleTy;
17328 if (!PromoteType.isNull())
17329 DiagRuntimeBehavior(Loc: TInfo->getTypeLoc().getBeginLoc(), Statement: E,
17330 PD: PDiag(DiagID: diag::warn_second_parameter_to_va_arg_never_compatible)
17331 << TInfo->getType()
17332 << PromoteType
17333 << TInfo->getTypeLoc().getSourceRange());
17334 }
17335
17336 QualType T = TInfo->getType().getNonLValueExprType(Context);
17337 return new (Context) VAArgExpr(BuiltinLoc, E, TInfo, RPLoc, T, IsMS);
17338}
17339
17340ExprResult Sema::ActOnGNUNullExpr(SourceLocation TokenLoc) {
17341 // The type of __null will be int or long, depending on the size of
17342 // pointers on the target.
17343 QualType Ty;
17344 unsigned pw = Context.getTargetInfo().getPointerWidth(AddrSpace: LangAS::Default);
17345 if (pw == Context.getTargetInfo().getIntWidth())
17346 Ty = Context.IntTy;
17347 else if (pw == Context.getTargetInfo().getLongWidth())
17348 Ty = Context.LongTy;
17349 else if (pw == Context.getTargetInfo().getLongLongWidth())
17350 Ty = Context.LongLongTy;
17351 else {
17352 llvm_unreachable("I don't know size of pointer!");
17353 }
17354
17355 return new (Context) GNUNullExpr(Ty, TokenLoc);
17356}
17357
17358static CXXRecordDecl *LookupStdSourceLocationImpl(Sema &S, SourceLocation Loc) {
17359 CXXRecordDecl *ImplDecl = nullptr;
17360
17361 // Fetch the std::source_location::__impl decl.
17362 if (NamespaceDecl *Std = S.getStdNamespace()) {
17363 LookupResult ResultSL(S, &S.PP.getIdentifierTable().get(Name: "source_location"),
17364 Loc, Sema::LookupOrdinaryName);
17365 if (S.LookupQualifiedName(R&: ResultSL, LookupCtx: Std)) {
17366 if (auto *SLDecl = ResultSL.getAsSingle<RecordDecl>()) {
17367 LookupResult ResultImpl(S, &S.PP.getIdentifierTable().get(Name: "__impl"),
17368 Loc, Sema::LookupOrdinaryName);
17369 if ((SLDecl->isCompleteDefinition() || SLDecl->isBeingDefined()) &&
17370 S.LookupQualifiedName(R&: ResultImpl, LookupCtx: SLDecl)) {
17371 ImplDecl = ResultImpl.getAsSingle<CXXRecordDecl>();
17372 }
17373 }
17374 }
17375 }
17376
17377 if (!ImplDecl || !ImplDecl->isCompleteDefinition()) {
17378 S.Diag(Loc, DiagID: diag::err_std_source_location_impl_not_found);
17379 return nullptr;
17380 }
17381
17382 // Verify that __impl is a trivial struct type, with no base classes, and with
17383 // only the four expected fields.
17384 if (ImplDecl->isUnion() || !ImplDecl->isStandardLayout() ||
17385 ImplDecl->getNumBases() != 0) {
17386 S.Diag(Loc, DiagID: diag::err_std_source_location_impl_malformed);
17387 return nullptr;
17388 }
17389
17390 unsigned Count = 0;
17391 for (FieldDecl *F : ImplDecl->fields()) {
17392 StringRef Name = F->getName();
17393
17394 if (Name == "_M_file_name") {
17395 if (F->getType() !=
17396 S.Context.getPointerType(T: S.Context.CharTy.withConst()))
17397 break;
17398 Count++;
17399 } else if (Name == "_M_function_name") {
17400 if (F->getType() !=
17401 S.Context.getPointerType(T: S.Context.CharTy.withConst()))
17402 break;
17403 Count++;
17404 } else if (Name == "_M_line") {
17405 if (!F->getType()->isIntegerType())
17406 break;
17407 Count++;
17408 } else if (Name == "_M_column") {
17409 if (!F->getType()->isIntegerType())
17410 break;
17411 Count++;
17412 } else {
17413 Count = 100; // invalid
17414 break;
17415 }
17416 }
17417 if (Count != 4) {
17418 S.Diag(Loc, DiagID: diag::err_std_source_location_impl_malformed);
17419 return nullptr;
17420 }
17421
17422 return ImplDecl;
17423}
17424
17425ExprResult Sema::ActOnSourceLocExpr(SourceLocIdentKind Kind,
17426 SourceLocation BuiltinLoc,
17427 SourceLocation RPLoc) {
17428 QualType ResultTy;
17429 switch (Kind) {
17430 case SourceLocIdentKind::File:
17431 case SourceLocIdentKind::FileName:
17432 case SourceLocIdentKind::Function:
17433 case SourceLocIdentKind::FuncSig: {
17434 QualType ArrTy = Context.getStringLiteralArrayType(EltTy: Context.CharTy, Length: 0);
17435 ResultTy =
17436 Context.getPointerType(T: ArrTy->getAsArrayTypeUnsafe()->getElementType());
17437 break;
17438 }
17439 case SourceLocIdentKind::Line:
17440 case SourceLocIdentKind::Column:
17441 ResultTy = Context.UnsignedIntTy;
17442 break;
17443 case SourceLocIdentKind::SourceLocStruct:
17444 if (!StdSourceLocationImplDecl) {
17445 StdSourceLocationImplDecl =
17446 LookupStdSourceLocationImpl(S&: *this, Loc: BuiltinLoc);
17447 if (!StdSourceLocationImplDecl)
17448 return ExprError();
17449 }
17450 ResultTy = Context.getPointerType(
17451 T: Context.getCanonicalTagType(TD: StdSourceLocationImplDecl).withConst());
17452 break;
17453 }
17454
17455 return BuildSourceLocExpr(Kind, ResultTy, BuiltinLoc, RPLoc, ParentContext: CurContext);
17456}
17457
17458ExprResult Sema::BuildSourceLocExpr(SourceLocIdentKind Kind, QualType ResultTy,
17459 SourceLocation BuiltinLoc,
17460 SourceLocation RPLoc,
17461 DeclContext *ParentContext) {
17462 return new (Context)
17463 SourceLocExpr(Context, Kind, ResultTy, BuiltinLoc, RPLoc, ParentContext);
17464}
17465
17466ExprResult Sema::ActOnEmbedExpr(SourceLocation EmbedKeywordLoc,
17467 StringLiteral *BinaryData, StringRef FileName) {
17468 EmbedDataStorage *Data = new (Context) EmbedDataStorage;
17469 Data->BinaryData = BinaryData;
17470 Data->FileName = FileName;
17471 return new (Context)
17472 EmbedExpr(Context, EmbedKeywordLoc, Data, /*NumOfElements=*/0,
17473 Data->getDataElementCount());
17474}
17475
17476static bool maybeDiagnoseAssignmentToFunction(Sema &S, QualType DstType,
17477 const Expr *SrcExpr) {
17478 if (!DstType->isFunctionPointerType() ||
17479 !SrcExpr->getType()->isFunctionType())
17480 return false;
17481
17482 auto *DRE = dyn_cast<DeclRefExpr>(Val: SrcExpr->IgnoreParenImpCasts());
17483 if (!DRE)
17484 return false;
17485
17486 auto *FD = dyn_cast<FunctionDecl>(Val: DRE->getDecl());
17487 if (!FD)
17488 return false;
17489
17490 return !S.checkAddressOfFunctionIsAvailable(Function: FD,
17491 /*Complain=*/true,
17492 Loc: SrcExpr->getBeginLoc());
17493}
17494
17495bool Sema::DiagnoseAssignmentResult(AssignConvertType ConvTy,
17496 SourceLocation Loc,
17497 QualType DstType, QualType SrcType,
17498 Expr *SrcExpr, AssignmentAction Action,
17499 bool *Complained) {
17500 if (Complained)
17501 *Complained = false;
17502
17503 // Decode the result (notice that AST's are still created for extensions).
17504 bool CheckInferredResultType = false;
17505 bool isInvalid = false;
17506 unsigned DiagKind = 0;
17507 ConversionFixItGenerator ConvHints;
17508 bool MayHaveConvFixit = false;
17509 bool MayHaveFunctionDiff = false;
17510 const ObjCInterfaceDecl *IFace = nullptr;
17511 const ObjCProtocolDecl *PDecl = nullptr;
17512
17513 switch (ConvTy) {
17514 case AssignConvertType::Compatible:
17515 DiagnoseAssignmentEnum(DstType, SrcType, SrcExpr);
17516 return false;
17517 case AssignConvertType::CompatibleVoidPtrToNonVoidPtr:
17518 // Still a valid conversion, but we may want to diagnose for C++
17519 // compatibility reasons.
17520 DiagKind = diag::warn_compatible_implicit_pointer_conv;
17521 break;
17522 case AssignConvertType::PointerToInt:
17523 if (getLangOpts().CPlusPlus) {
17524 DiagKind = diag::err_typecheck_convert_pointer_int;
17525 isInvalid = true;
17526 } else {
17527 DiagKind = diag::ext_typecheck_convert_pointer_int;
17528 }
17529 ConvHints.tryToFixConversion(FromExpr: SrcExpr, FromQTy: SrcType, ToQTy: DstType, S&: *this);
17530 MayHaveConvFixit = true;
17531 break;
17532 case AssignConvertType::IntToPointer:
17533 if (getLangOpts().CPlusPlus) {
17534 DiagKind = diag::err_typecheck_convert_int_pointer;
17535 isInvalid = true;
17536 } else {
17537 DiagKind = diag::ext_typecheck_convert_int_pointer;
17538 }
17539 ConvHints.tryToFixConversion(FromExpr: SrcExpr, FromQTy: SrcType, ToQTy: DstType, S&: *this);
17540 MayHaveConvFixit = true;
17541 break;
17542 case AssignConvertType::IncompatibleFunctionPointerStrict:
17543 DiagKind =
17544 diag::warn_typecheck_convert_incompatible_function_pointer_strict;
17545 ConvHints.tryToFixConversion(FromExpr: SrcExpr, FromQTy: SrcType, ToQTy: DstType, S&: *this);
17546 MayHaveConvFixit = true;
17547 break;
17548 case AssignConvertType::IncompatibleFunctionPointer:
17549 if (getLangOpts().CPlusPlus) {
17550 DiagKind = diag::err_typecheck_convert_incompatible_function_pointer;
17551 isInvalid = true;
17552 } else {
17553 DiagKind = diag::ext_typecheck_convert_incompatible_function_pointer;
17554 }
17555 ConvHints.tryToFixConversion(FromExpr: SrcExpr, FromQTy: SrcType, ToQTy: DstType, S&: *this);
17556 MayHaveConvFixit = true;
17557 break;
17558 case AssignConvertType::IncompatiblePointer:
17559 if (Action == AssignmentAction::Passing_CFAudited) {
17560 DiagKind = diag::err_arc_typecheck_convert_incompatible_pointer;
17561 } else if (getLangOpts().CPlusPlus) {
17562 DiagKind = diag::err_typecheck_convert_incompatible_pointer;
17563 isInvalid = true;
17564 } else {
17565 DiagKind = diag::ext_typecheck_convert_incompatible_pointer;
17566 }
17567 CheckInferredResultType = DstType->isObjCObjectPointerType() &&
17568 SrcType->isObjCObjectPointerType();
17569 if (CheckInferredResultType) {
17570 SrcType = SrcType.getUnqualifiedType();
17571 DstType = DstType.getUnqualifiedType();
17572 } else {
17573 ConvHints.tryToFixConversion(FromExpr: SrcExpr, FromQTy: SrcType, ToQTy: DstType, S&: *this);
17574 }
17575 MayHaveConvFixit = true;
17576 break;
17577 case AssignConvertType::IncompatiblePointerSign:
17578 if (getLangOpts().CPlusPlus) {
17579 DiagKind = diag::err_typecheck_convert_incompatible_pointer_sign;
17580 isInvalid = true;
17581 } else {
17582 DiagKind = diag::ext_typecheck_convert_incompatible_pointer_sign;
17583 }
17584 break;
17585 case AssignConvertType::FunctionVoidPointer:
17586 if (getLangOpts().CPlusPlus) {
17587 DiagKind = diag::err_typecheck_convert_pointer_void_func;
17588 isInvalid = true;
17589 } else {
17590 DiagKind = diag::ext_typecheck_convert_pointer_void_func;
17591 }
17592 break;
17593 case AssignConvertType::IncompatiblePointerDiscardsQualifiers: {
17594 // Perform array-to-pointer decay if necessary.
17595 if (SrcType->isArrayType()) SrcType = Context.getArrayDecayedType(T: SrcType);
17596
17597 isInvalid = true;
17598
17599 Qualifiers lhq = SrcType->getPointeeType().getQualifiers();
17600 Qualifiers rhq = DstType->getPointeeType().getQualifiers();
17601 if (lhq.getAddressSpace() != rhq.getAddressSpace()) {
17602 DiagKind = diag::err_typecheck_incompatible_address_space;
17603 break;
17604 } else if (lhq.getObjCLifetime() != rhq.getObjCLifetime()) {
17605 DiagKind = diag::err_typecheck_incompatible_ownership;
17606 break;
17607 } else if (!lhq.getPointerAuth().isEquivalent(Other: rhq.getPointerAuth())) {
17608 DiagKind = diag::err_typecheck_incompatible_ptrauth;
17609 break;
17610 }
17611
17612 llvm_unreachable("unknown error case for discarding qualifiers!");
17613 // fallthrough
17614 }
17615 case AssignConvertType::IncompatiblePointerDiscardsOverflowBehavior:
17616 if (SrcType->isArrayType())
17617 SrcType = Context.getArrayDecayedType(T: SrcType);
17618
17619 DiagKind = diag::ext_typecheck_convert_discards_overflow_behavior;
17620 break;
17621 case AssignConvertType::CompatiblePointerDiscardsQualifiers:
17622 // If the qualifiers lost were because we were applying the
17623 // (deprecated) C++ conversion from a string literal to a char*
17624 // (or wchar_t*), then there was no error (C++ 4.2p2). FIXME:
17625 // Ideally, this check would be performed in
17626 // checkPointerTypesForAssignment. However, that would require a
17627 // bit of refactoring (so that the second argument is an
17628 // expression, rather than a type), which should be done as part
17629 // of a larger effort to fix checkPointerTypesForAssignment for
17630 // C++ semantics.
17631 if (getLangOpts().CPlusPlus &&
17632 IsStringLiteralToNonConstPointerConversion(From: SrcExpr, ToType: DstType))
17633 return false;
17634 if (getLangOpts().CPlusPlus) {
17635 DiagKind = diag::err_typecheck_convert_discards_qualifiers;
17636 isInvalid = true;
17637 } else {
17638 DiagKind = diag::ext_typecheck_convert_discards_qualifiers;
17639 }
17640
17641 break;
17642 case AssignConvertType::IncompatibleNestedPointerQualifiers:
17643 if (getLangOpts().CPlusPlus) {
17644 isInvalid = true;
17645 DiagKind = diag::err_nested_pointer_qualifier_mismatch;
17646 } else {
17647 DiagKind = diag::ext_nested_pointer_qualifier_mismatch;
17648 }
17649 break;
17650 case AssignConvertType::IncompatibleNestedPointerAddressSpaceMismatch:
17651 DiagKind = diag::err_typecheck_incompatible_nested_address_space;
17652 isInvalid = true;
17653 break;
17654 case AssignConvertType::IntToBlockPointer:
17655 DiagKind = diag::err_int_to_block_pointer;
17656 isInvalid = true;
17657 break;
17658 case AssignConvertType::IncompatibleBlockPointer:
17659 DiagKind = diag::err_typecheck_convert_incompatible_block_pointer;
17660 isInvalid = true;
17661 break;
17662 case AssignConvertType::IncompatibleObjCQualifiedId: {
17663 if (SrcType->isObjCQualifiedIdType()) {
17664 const ObjCObjectPointerType *srcOPT =
17665 SrcType->castAs<ObjCObjectPointerType>();
17666 for (auto *srcProto : srcOPT->quals()) {
17667 PDecl = srcProto;
17668 break;
17669 }
17670 if (const ObjCInterfaceType *IFaceT =
17671 DstType->castAs<ObjCObjectPointerType>()->getInterfaceType())
17672 IFace = IFaceT->getDecl();
17673 }
17674 else if (DstType->isObjCQualifiedIdType()) {
17675 const ObjCObjectPointerType *dstOPT =
17676 DstType->castAs<ObjCObjectPointerType>();
17677 for (auto *dstProto : dstOPT->quals()) {
17678 PDecl = dstProto;
17679 break;
17680 }
17681 if (const ObjCInterfaceType *IFaceT =
17682 SrcType->castAs<ObjCObjectPointerType>()->getInterfaceType())
17683 IFace = IFaceT->getDecl();
17684 }
17685 if (getLangOpts().CPlusPlus) {
17686 DiagKind = diag::err_incompatible_qualified_id;
17687 isInvalid = true;
17688 } else {
17689 DiagKind = diag::warn_incompatible_qualified_id;
17690 }
17691 break;
17692 }
17693 case AssignConvertType::IncompatibleVectors:
17694 if (getLangOpts().CPlusPlus) {
17695 DiagKind = diag::err_incompatible_vectors;
17696 isInvalid = true;
17697 } else {
17698 DiagKind = diag::warn_incompatible_vectors;
17699 }
17700 break;
17701 case AssignConvertType::IncompatibleObjCWeakRef:
17702 DiagKind = diag::err_arc_weak_unavailable_assign;
17703 isInvalid = true;
17704 break;
17705 case AssignConvertType::CompatibleOBTDiscards:
17706 return false;
17707 case AssignConvertType::IncompatibleOBTKinds: {
17708 auto getOBTKindName = [](QualType Ty) -> StringRef {
17709 if (Ty->isPointerType())
17710 Ty = Ty->getPointeeType();
17711 if (const auto *OBT = Ty->getAs<OverflowBehaviorType>()) {
17712 return OBT->getBehaviorKind() ==
17713 OverflowBehaviorType::OverflowBehaviorKind::Trap
17714 ? "__ob_trap"
17715 : "__ob_wrap";
17716 }
17717 llvm_unreachable("OBT kind unhandled");
17718 };
17719
17720 Diag(Loc, DiagID: diag::err_incompatible_obt_kinds_assignment)
17721 << DstType << SrcType << getOBTKindName(DstType)
17722 << getOBTKindName(SrcType);
17723 isInvalid = true;
17724 return true;
17725 }
17726 case AssignConvertType::Incompatible:
17727 if (maybeDiagnoseAssignmentToFunction(S&: *this, DstType, SrcExpr)) {
17728 if (Complained)
17729 *Complained = true;
17730 return true;
17731 }
17732
17733 DiagKind = diag::err_typecheck_convert_incompatible;
17734 ConvHints.tryToFixConversion(FromExpr: SrcExpr, FromQTy: SrcType, ToQTy: DstType, S&: *this);
17735 MayHaveConvFixit = true;
17736 isInvalid = true;
17737 MayHaveFunctionDiff = true;
17738 break;
17739 }
17740
17741 QualType FirstType, SecondType;
17742 switch (Action) {
17743 case AssignmentAction::Assigning:
17744 case AssignmentAction::Initializing:
17745 // The destination type comes first.
17746 FirstType = DstType;
17747 SecondType = SrcType;
17748 break;
17749
17750 case AssignmentAction::Returning:
17751 case AssignmentAction::Passing:
17752 case AssignmentAction::Passing_CFAudited:
17753 case AssignmentAction::Converting:
17754 case AssignmentAction::Sending:
17755 case AssignmentAction::Casting:
17756 // The source type comes first.
17757 FirstType = SrcType;
17758 SecondType = DstType;
17759 break;
17760 }
17761
17762 PartialDiagnostic FDiag = PDiag(DiagID: DiagKind);
17763 AssignmentAction ActionForDiag = Action;
17764 if (Action == AssignmentAction::Passing_CFAudited)
17765 ActionForDiag = AssignmentAction::Passing;
17766
17767 FDiag << FirstType << SecondType << ActionForDiag
17768 << SrcExpr->getSourceRange();
17769
17770 if (DiagKind == diag::ext_typecheck_convert_incompatible_pointer_sign ||
17771 DiagKind == diag::err_typecheck_convert_incompatible_pointer_sign) {
17772 auto isPlainChar = [](const clang::Type *Type) {
17773 return Type->isSpecificBuiltinType(K: BuiltinType::Char_S) ||
17774 Type->isSpecificBuiltinType(K: BuiltinType::Char_U);
17775 };
17776 FDiag << (isPlainChar(FirstType->getPointeeOrArrayElementType()) ||
17777 isPlainChar(SecondType->getPointeeOrArrayElementType()));
17778 }
17779
17780 // If we can fix the conversion, suggest the FixIts.
17781 if (!ConvHints.isNull()) {
17782 for (FixItHint &H : ConvHints.Hints)
17783 FDiag << H;
17784 }
17785
17786 if (MayHaveConvFixit) { FDiag << (unsigned) (ConvHints.Kind); }
17787
17788 if (MayHaveFunctionDiff)
17789 HandleFunctionTypeMismatch(PDiag&: FDiag, FromType: SecondType, ToType: FirstType);
17790
17791 Diag(Loc, PD: FDiag);
17792 if ((DiagKind == diag::warn_incompatible_qualified_id ||
17793 DiagKind == diag::err_incompatible_qualified_id) &&
17794 PDecl && IFace && !IFace->hasDefinition())
17795 Diag(Loc: IFace->getLocation(), DiagID: diag::note_incomplete_class_and_qualified_id)
17796 << IFace << PDecl;
17797
17798 if (SecondType == Context.OverloadTy)
17799 NoteAllOverloadCandidates(E: OverloadExpr::find(E: SrcExpr).Expression,
17800 DestType: FirstType, /*TakingAddress=*/true);
17801
17802 if (CheckInferredResultType)
17803 ObjC().EmitRelatedResultTypeNote(E: SrcExpr);
17804
17805 if (Action == AssignmentAction::Returning &&
17806 ConvTy == AssignConvertType::IncompatiblePointer)
17807 ObjC().EmitRelatedResultTypeNoteForReturn(destType: DstType);
17808
17809 if (Complained)
17810 *Complained = true;
17811 return isInvalid;
17812}
17813
17814ExprResult Sema::VerifyIntegerConstantExpression(Expr *E,
17815 llvm::APSInt *Result,
17816 AllowFoldKind CanFold) {
17817 class SimpleICEDiagnoser : public VerifyICEDiagnoser {
17818 public:
17819 SemaDiagnosticBuilder diagnoseNotICEType(Sema &S, SourceLocation Loc,
17820 QualType T) override {
17821 return S.Diag(Loc, DiagID: diag::err_ice_not_integral)
17822 << T << S.LangOpts.CPlusPlus;
17823 }
17824 SemaDiagnosticBuilder diagnoseNotICE(Sema &S, SourceLocation Loc) override {
17825 return S.Diag(Loc, DiagID: diag::err_expr_not_ice) << S.LangOpts.CPlusPlus;
17826 }
17827 } Diagnoser;
17828
17829 return VerifyIntegerConstantExpression(E, Result, Diagnoser, CanFold);
17830}
17831
17832ExprResult Sema::VerifyIntegerConstantExpression(Expr *E,
17833 llvm::APSInt *Result,
17834 unsigned DiagID,
17835 AllowFoldKind CanFold) {
17836 class IDDiagnoser : public VerifyICEDiagnoser {
17837 unsigned DiagID;
17838
17839 public:
17840 IDDiagnoser(unsigned DiagID)
17841 : VerifyICEDiagnoser(DiagID == 0), DiagID(DiagID) { }
17842
17843 SemaDiagnosticBuilder diagnoseNotICE(Sema &S, SourceLocation Loc) override {
17844 return S.Diag(Loc, DiagID);
17845 }
17846 } Diagnoser(DiagID);
17847
17848 return VerifyIntegerConstantExpression(E, Result, Diagnoser, CanFold);
17849}
17850
17851Sema::SemaDiagnosticBuilder
17852Sema::VerifyICEDiagnoser::diagnoseNotICEType(Sema &S, SourceLocation Loc,
17853 QualType T) {
17854 return diagnoseNotICE(S, Loc);
17855}
17856
17857Sema::SemaDiagnosticBuilder
17858Sema::VerifyICEDiagnoser::diagnoseFold(Sema &S, SourceLocation Loc) {
17859 return S.Diag(Loc, DiagID: diag::ext_expr_not_ice) << S.LangOpts.CPlusPlus;
17860}
17861
17862ExprResult
17863Sema::VerifyIntegerConstantExpression(Expr *E, llvm::APSInt *Result,
17864 VerifyICEDiagnoser &Diagnoser,
17865 AllowFoldKind CanFold) {
17866 SourceLocation DiagLoc = E->getBeginLoc();
17867
17868 if (getLangOpts().CPlusPlus11) {
17869 // C++11 [expr.const]p5:
17870 // If an expression of literal class type is used in a context where an
17871 // integral constant expression is required, then that class type shall
17872 // have a single non-explicit conversion function to an integral or
17873 // unscoped enumeration type
17874 ExprResult Converted;
17875 class CXX11ConvertDiagnoser : public ICEConvertDiagnoser {
17876 VerifyICEDiagnoser &BaseDiagnoser;
17877 public:
17878 CXX11ConvertDiagnoser(VerifyICEDiagnoser &BaseDiagnoser)
17879 : ICEConvertDiagnoser(/*AllowScopedEnumerations*/ false,
17880 BaseDiagnoser.Suppress, true),
17881 BaseDiagnoser(BaseDiagnoser) {}
17882
17883 SemaDiagnosticBuilder diagnoseNotInt(Sema &S, SourceLocation Loc,
17884 QualType T) override {
17885 return BaseDiagnoser.diagnoseNotICEType(S, Loc, T);
17886 }
17887
17888 SemaDiagnosticBuilder diagnoseIncomplete(
17889 Sema &S, SourceLocation Loc, QualType T) override {
17890 return S.Diag(Loc, DiagID: diag::err_ice_incomplete_type) << T;
17891 }
17892
17893 SemaDiagnosticBuilder diagnoseExplicitConv(
17894 Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) override {
17895 return S.Diag(Loc, DiagID: diag::err_ice_explicit_conversion) << T << ConvTy;
17896 }
17897
17898 SemaDiagnosticBuilder noteExplicitConv(
17899 Sema &S, CXXConversionDecl *Conv, QualType ConvTy) override {
17900 return S.Diag(Loc: Conv->getLocation(), DiagID: diag::note_ice_conversion_here)
17901 << ConvTy->isEnumeralType() << ConvTy;
17902 }
17903
17904 SemaDiagnosticBuilder diagnoseAmbiguous(
17905 Sema &S, SourceLocation Loc, QualType T) override {
17906 return S.Diag(Loc, DiagID: diag::err_ice_ambiguous_conversion) << T;
17907 }
17908
17909 SemaDiagnosticBuilder noteAmbiguous(
17910 Sema &S, CXXConversionDecl *Conv, QualType ConvTy) override {
17911 return S.Diag(Loc: Conv->getLocation(), DiagID: diag::note_ice_conversion_here)
17912 << ConvTy->isEnumeralType() << ConvTy;
17913 }
17914
17915 SemaDiagnosticBuilder diagnoseConversion(
17916 Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) override {
17917 llvm_unreachable("conversion functions are permitted");
17918 }
17919 } ConvertDiagnoser(Diagnoser);
17920
17921 Converted = PerformContextualImplicitConversion(Loc: DiagLoc, FromE: E,
17922 Converter&: ConvertDiagnoser);
17923 if (Converted.isInvalid())
17924 return Converted;
17925 E = Converted.get();
17926 // The 'explicit' case causes us to get a RecoveryExpr. Give up here so we
17927 // don't try to evaluate it later. We also don't want to return the
17928 // RecoveryExpr here, as it results in this call succeeding, thus callers of
17929 // this function will attempt to use 'Value'.
17930 if (isa<RecoveryExpr>(Val: E))
17931 return ExprError();
17932 if (!E->getType()->isIntegralOrUnscopedEnumerationType())
17933 return ExprError();
17934 } else if (!E->getType()->isIntegralOrUnscopedEnumerationType()) {
17935 // An ICE must be of integral or unscoped enumeration type.
17936 if (!Diagnoser.Suppress)
17937 Diagnoser.diagnoseNotICEType(S&: *this, Loc: DiagLoc, T: E->getType())
17938 << E->getSourceRange();
17939 return ExprError();
17940 }
17941
17942 ExprResult RValueExpr = DefaultLvalueConversion(E);
17943 if (RValueExpr.isInvalid())
17944 return ExprError();
17945
17946 E = RValueExpr.get();
17947
17948 // Circumvent ICE checking in C++11 to avoid evaluating the expression twice
17949 // in the non-ICE case.
17950 if (!getLangOpts().CPlusPlus11 && E->isIntegerConstantExpr(Ctx: Context)) {
17951 SmallVector<PartialDiagnosticAt, 8> Notes;
17952 if (Result)
17953 *Result = E->EvaluateKnownConstIntCheckOverflow(Ctx: Context, Diag: &Notes);
17954 if (!isa<ConstantExpr>(Val: E))
17955 E = Result ? ConstantExpr::Create(Context, E, Result: APValue(*Result))
17956 : ConstantExpr::Create(Context, E);
17957
17958 if (Notes.empty())
17959 return E;
17960
17961 // If our only note is the usual "invalid subexpression" note, just point
17962 // the caret at its location rather than producing an essentially
17963 // redundant note.
17964 if (Notes.size() == 1 && Notes[0].second.getDiagID() ==
17965 diag::note_invalid_subexpr_in_const_expr) {
17966 DiagLoc = Notes[0].first;
17967 Notes.clear();
17968 }
17969
17970 if (getLangOpts().CPlusPlus) {
17971 if (!Diagnoser.Suppress) {
17972 Diagnoser.diagnoseNotICE(S&: *this, Loc: DiagLoc) << E->getSourceRange();
17973 for (const PartialDiagnosticAt &Note : Notes)
17974 Diag(Loc: Note.first, PD: Note.second);
17975 }
17976 return ExprError();
17977 }
17978
17979 Diagnoser.diagnoseFold(S&: *this, Loc: DiagLoc) << E->getSourceRange();
17980 for (const PartialDiagnosticAt &Note : Notes)
17981 Diag(Loc: Note.first, PD: Note.second);
17982
17983 return E;
17984 }
17985
17986 Expr::EvalResult EvalResult;
17987 SmallVector<PartialDiagnosticAt, 8> Notes;
17988 EvalResult.Diag = &Notes;
17989
17990 // Try to evaluate the expression, and produce diagnostics explaining why it's
17991 // not a constant expression as a side-effect.
17992 bool Folded =
17993 E->EvaluateAsRValue(Result&: EvalResult, Ctx: Context, /*isConstantContext*/ InConstantContext: true) &&
17994 EvalResult.Val.isInt() && !EvalResult.HasSideEffects &&
17995 (!getLangOpts().CPlusPlus || !EvalResult.HasUndefinedBehavior);
17996
17997 if (!isa<ConstantExpr>(Val: E))
17998 E = ConstantExpr::Create(Context, E, Result: EvalResult.Val);
17999
18000 // In C++11, we can rely on diagnostics being produced for any expression
18001 // which is not a constant expression. If no diagnostics were produced, then
18002 // this is a constant expression.
18003 if (Folded && getLangOpts().CPlusPlus11 && Notes.empty()) {
18004 if (Result)
18005 *Result = EvalResult.Val.getInt();
18006 return E;
18007 }
18008
18009 // If our only note is the usual "invalid subexpression" note, just point
18010 // the caret at its location rather than producing an essentially
18011 // redundant note.
18012 if (Notes.size() == 1 && Notes[0].second.getDiagID() ==
18013 diag::note_invalid_subexpr_in_const_expr) {
18014 DiagLoc = Notes[0].first;
18015 Notes.clear();
18016 }
18017
18018 if (!Folded || CanFold == AllowFoldKind::No) {
18019 if (!Diagnoser.Suppress) {
18020 Diagnoser.diagnoseNotICE(S&: *this, Loc: DiagLoc) << E->getSourceRange();
18021 for (const PartialDiagnosticAt &Note : Notes)
18022 Diag(Loc: Note.first, PD: Note.second);
18023 }
18024
18025 return ExprError();
18026 }
18027
18028 Diagnoser.diagnoseFold(S&: *this, Loc: DiagLoc) << E->getSourceRange();
18029 for (const PartialDiagnosticAt &Note : Notes)
18030 Diag(Loc: Note.first, PD: Note.second);
18031
18032 if (Result)
18033 *Result = EvalResult.Val.getInt();
18034 return E;
18035}
18036
18037namespace {
18038 // Handle the case where we conclude a expression which we speculatively
18039 // considered to be unevaluated is actually evaluated.
18040 class TransformToPE : public TreeTransform<TransformToPE> {
18041 typedef TreeTransform<TransformToPE> BaseTransform;
18042
18043 public:
18044 TransformToPE(Sema &SemaRef) : BaseTransform(SemaRef) { }
18045
18046 // Make sure we redo semantic analysis
18047 bool AlwaysRebuild() { return true; }
18048 bool ReplacingOriginal() { return true; }
18049
18050 // We need to special-case DeclRefExprs referring to FieldDecls which
18051 // are not part of a member pointer formation; normal TreeTransforming
18052 // doesn't catch this case because of the way we represent them in the AST.
18053 // FIXME: This is a bit ugly; is it really the best way to handle this
18054 // case?
18055 //
18056 // Error on DeclRefExprs referring to FieldDecls.
18057 ExprResult TransformDeclRefExpr(DeclRefExpr *E) {
18058 if (isa<FieldDecl>(Val: E->getDecl()) &&
18059 !SemaRef.isUnevaluatedContext())
18060 return SemaRef.Diag(Loc: E->getLocation(),
18061 DiagID: diag::err_invalid_non_static_member_use)
18062 << E->getDecl() << E->getSourceRange();
18063
18064 return BaseTransform::TransformDeclRefExpr(E);
18065 }
18066
18067 // Exception: filter out member pointer formation
18068 ExprResult TransformUnaryOperator(UnaryOperator *E) {
18069 if (E->getOpcode() == UO_AddrOf && E->getType()->isMemberPointerType())
18070 return E;
18071
18072 return BaseTransform::TransformUnaryOperator(E);
18073 }
18074
18075 // The body of a lambda-expression is in a separate expression evaluation
18076 // context so never needs to be transformed.
18077 // FIXME: Ideally we wouldn't transform the closure type either, and would
18078 // just recreate the capture expressions and lambda expression.
18079 StmtResult TransformLambdaBody(LambdaExpr *E, Stmt *Body) {
18080 return SkipLambdaBody(E, S: Body);
18081 }
18082 };
18083}
18084
18085ExprResult Sema::TransformToPotentiallyEvaluated(Expr *E) {
18086 assert(isUnevaluatedContext() &&
18087 "Should only transform unevaluated expressions");
18088 ExprEvalContexts.back().Context =
18089 ExprEvalContexts[ExprEvalContexts.size()-2].Context;
18090 if (isUnevaluatedContext())
18091 return E;
18092 return TransformToPE(*this).TransformExpr(E);
18093}
18094
18095TypeSourceInfo *Sema::TransformToPotentiallyEvaluated(TypeSourceInfo *TInfo) {
18096 assert(isUnevaluatedContext() &&
18097 "Should only transform unevaluated expressions");
18098 ExprEvalContexts.back().Context = parentEvaluationContext().Context;
18099 if (isUnevaluatedContext())
18100 return TInfo;
18101 return TransformToPE(*this).TransformType(TSI: TInfo);
18102}
18103
18104void
18105Sema::PushExpressionEvaluationContext(
18106 ExpressionEvaluationContext NewContext, Decl *LambdaContextDecl,
18107 ExpressionEvaluationContextRecord::ExpressionKind ExprContext) {
18108 ExprEvalContexts.emplace_back(Args&: NewContext, Args: ExprCleanupObjects.size(), Args&: Cleanup,
18109 Args&: LambdaContextDecl, Args&: ExprContext);
18110
18111 // Discarded statements and immediate contexts nested in other
18112 // discarded statements or immediate context are themselves
18113 // a discarded statement or an immediate context, respectively.
18114 ExprEvalContexts.back().InDiscardedStatement =
18115 parentEvaluationContext().isDiscardedStatementContext();
18116
18117 // C++23 [expr.const]/p15
18118 // An expression or conversion is in an immediate function context if [...]
18119 // it is a subexpression of a manifestly constant-evaluated expression or
18120 // conversion.
18121 const auto &Prev = parentEvaluationContext();
18122 ExprEvalContexts.back().InImmediateFunctionContext =
18123 Prev.isImmediateFunctionContext() || Prev.isConstantEvaluated();
18124
18125 ExprEvalContexts.back().InImmediateEscalatingFunctionContext =
18126 Prev.InImmediateEscalatingFunctionContext;
18127
18128 Cleanup.reset();
18129 if (!MaybeODRUseExprs.empty())
18130 std::swap(LHS&: MaybeODRUseExprs, RHS&: ExprEvalContexts.back().SavedMaybeODRUseExprs);
18131}
18132
18133void
18134Sema::PushExpressionEvaluationContext(
18135 ExpressionEvaluationContext NewContext, ReuseLambdaContextDecl_t,
18136 ExpressionEvaluationContextRecord::ExpressionKind ExprContext) {
18137 Decl *ClosureContextDecl = ExprEvalContexts.back().ManglingContextDecl;
18138 PushExpressionEvaluationContext(NewContext, LambdaContextDecl: ClosureContextDecl, ExprContext);
18139}
18140
18141void Sema::PushExpressionEvaluationContextForFunction(
18142 ExpressionEvaluationContext NewContext, FunctionDecl *FD) {
18143 // [expr.const]/p14.1
18144 // An expression or conversion is in an immediate function context if it is
18145 // potentially evaluated and either: its innermost enclosing non-block scope
18146 // is a function parameter scope of an immediate function.
18147 PushExpressionEvaluationContext(
18148 NewContext: FD && FD->isConsteval()
18149 ? ExpressionEvaluationContext::ImmediateFunctionContext
18150 : NewContext);
18151 const Sema::ExpressionEvaluationContextRecord &Parent =
18152 parentEvaluationContext();
18153 Sema::ExpressionEvaluationContextRecord &Current = currentEvaluationContext();
18154
18155 Current.InDiscardedStatement = false;
18156
18157 if (FD) {
18158
18159 // Each ExpressionEvaluationContextRecord also keeps track of whether the
18160 // context is nested in an immediate function context, so smaller contexts
18161 // that appear inside immediate functions (like variable initializers) are
18162 // considered to be inside an immediate function context even though by
18163 // themselves they are not immediate function contexts. But when a new
18164 // function is entered, we need to reset this tracking, since the entered
18165 // function might be not an immediate function.
18166
18167 Current.InImmediateEscalatingFunctionContext =
18168 getLangOpts().CPlusPlus20 && FD->isImmediateEscalating();
18169
18170 if (isLambdaMethod(DC: FD))
18171 Current.InImmediateFunctionContext =
18172 FD->isConsteval() ||
18173 (isLambdaMethod(DC: FD) && (Parent.isConstantEvaluated() ||
18174 Parent.isImmediateFunctionContext()));
18175 else
18176 Current.InImmediateFunctionContext = FD->isConsteval();
18177 }
18178}
18179
18180ExprResult Sema::ActOnCXXReflectExpr(SourceLocation CaretCaretLoc,
18181 TypeSourceInfo *TSI) {
18182 return BuildCXXReflectExpr(OperatorLoc: CaretCaretLoc, TSI);
18183}
18184
18185ExprResult Sema::BuildCXXReflectExpr(SourceLocation CaretCaretLoc,
18186 TypeSourceInfo *TSI) {
18187 return CXXReflectExpr::Create(C&: Context, OperatorLoc: CaretCaretLoc, TL: TSI);
18188}
18189
18190namespace {
18191
18192const DeclRefExpr *CheckPossibleDeref(Sema &S, const Expr *PossibleDeref) {
18193 PossibleDeref = PossibleDeref->IgnoreParenImpCasts();
18194 if (const auto *E = dyn_cast<UnaryOperator>(Val: PossibleDeref)) {
18195 if (E->getOpcode() == UO_Deref)
18196 return CheckPossibleDeref(S, PossibleDeref: E->getSubExpr());
18197 } else if (const auto *E = dyn_cast<ArraySubscriptExpr>(Val: PossibleDeref)) {
18198 return CheckPossibleDeref(S, PossibleDeref: E->getBase());
18199 } else if (const auto *E = dyn_cast<MemberExpr>(Val: PossibleDeref)) {
18200 return CheckPossibleDeref(S, PossibleDeref: E->getBase());
18201 } else if (const auto E = dyn_cast<DeclRefExpr>(Val: PossibleDeref)) {
18202 QualType Inner;
18203 QualType Ty = E->getType();
18204 if (const auto *Ptr = Ty->getAs<PointerType>())
18205 Inner = Ptr->getPointeeType();
18206 else if (const auto *Arr = S.Context.getAsArrayType(T: Ty))
18207 Inner = Arr->getElementType();
18208 else
18209 return nullptr;
18210
18211 if (Inner->hasAttr(AK: attr::NoDeref))
18212 return E;
18213 }
18214 return nullptr;
18215}
18216
18217} // namespace
18218
18219void Sema::WarnOnPendingNoDerefs(ExpressionEvaluationContextRecord &Rec) {
18220 for (const Expr *E : Rec.PossibleDerefs) {
18221 const DeclRefExpr *DeclRef = CheckPossibleDeref(S&: *this, PossibleDeref: E);
18222 if (DeclRef) {
18223 const ValueDecl *Decl = DeclRef->getDecl();
18224 Diag(Loc: E->getExprLoc(), DiagID: diag::warn_dereference_of_noderef_type)
18225 << Decl->getName() << E->getSourceRange();
18226 Diag(Loc: Decl->getLocation(), DiagID: diag::note_previous_decl) << Decl->getName();
18227 } else {
18228 Diag(Loc: E->getExprLoc(), DiagID: diag::warn_dereference_of_noderef_type_no_decl)
18229 << E->getSourceRange();
18230 }
18231 }
18232 Rec.PossibleDerefs.clear();
18233}
18234
18235void Sema::CheckUnusedVolatileAssignment(Expr *E) {
18236 if (!E->getType().isVolatileQualified() || !getLangOpts().CPlusPlus20)
18237 return;
18238
18239 // Note: ignoring parens here is not justified by the standard rules, but
18240 // ignoring parentheses seems like a more reasonable approach, and this only
18241 // drives a deprecation warning so doesn't affect conformance.
18242 if (auto *BO = dyn_cast<BinaryOperator>(Val: E->IgnoreParenImpCasts())) {
18243 if (BO->getOpcode() == BO_Assign) {
18244 auto &LHSs = ExprEvalContexts.back().VolatileAssignmentLHSs;
18245 llvm::erase(C&: LHSs, V: BO->getLHS());
18246 }
18247 }
18248}
18249
18250void Sema::MarkExpressionAsImmediateEscalating(Expr *E) {
18251 assert(getLangOpts().CPlusPlus20 &&
18252 ExprEvalContexts.back().InImmediateEscalatingFunctionContext &&
18253 "Cannot mark an immediate escalating expression outside of an "
18254 "immediate escalating context");
18255 if (auto *Call = dyn_cast<CallExpr>(Val: E->IgnoreImplicit());
18256 Call && Call->getCallee()) {
18257 if (auto *DeclRef =
18258 dyn_cast<DeclRefExpr>(Val: Call->getCallee()->IgnoreImplicit()))
18259 DeclRef->setIsImmediateEscalating(true);
18260 } else if (auto *Ctr = dyn_cast<CXXConstructExpr>(Val: E->IgnoreImplicit())) {
18261 Ctr->setIsImmediateEscalating(true);
18262 } else if (auto *DeclRef = dyn_cast<DeclRefExpr>(Val: E->IgnoreImplicit())) {
18263 DeclRef->setIsImmediateEscalating(true);
18264 } else {
18265 assert(false && "expected an immediately escalating expression");
18266 }
18267 if (FunctionScopeInfo *FI = getCurFunction())
18268 FI->FoundImmediateEscalatingExpression = true;
18269}
18270
18271ExprResult Sema::CheckForImmediateInvocation(ExprResult E, FunctionDecl *Decl) {
18272 if (isUnevaluatedContext() || !E.isUsable() || !Decl ||
18273 !Decl->isImmediateFunction() || isAlwaysConstantEvaluatedContext() ||
18274 isCheckingDefaultArgumentOrInitializer() ||
18275 RebuildingImmediateInvocation || isImmediateFunctionContext())
18276 return E;
18277
18278 /// Opportunistically remove the callee from ReferencesToConsteval if we can.
18279 /// It's OK if this fails; we'll also remove this in
18280 /// HandleImmediateInvocations, but catching it here allows us to avoid
18281 /// walking the AST looking for it in simple cases.
18282 if (auto *Call = dyn_cast<CallExpr>(Val: E.get()->IgnoreImplicit()))
18283 if (auto *DeclRef =
18284 dyn_cast<DeclRefExpr>(Val: Call->getCallee()->IgnoreImplicit()))
18285 ExprEvalContexts.back().ReferenceToConsteval.erase(Ptr: DeclRef);
18286
18287 // C++23 [expr.const]/p16
18288 // An expression or conversion is immediate-escalating if it is not initially
18289 // in an immediate function context and it is [...] an immediate invocation
18290 // that is not a constant expression and is not a subexpression of an
18291 // immediate invocation.
18292 APValue Cached;
18293 auto CheckConstantExpressionAndKeepResult = [&]() {
18294 llvm::SmallVector<PartialDiagnosticAt, 8> Notes;
18295 Expr::EvalResult Eval;
18296 Eval.Diag = &Notes;
18297 bool Res = E.get()->EvaluateAsConstantExpr(
18298 Result&: Eval, Ctx: getASTContext(), Kind: ConstantExprKind::ImmediateInvocation);
18299 if (Res && Notes.empty()) {
18300 Cached = std::move(Eval.Val);
18301 return true;
18302 }
18303 return false;
18304 };
18305
18306 if (!E.get()->isValueDependent() &&
18307 ExprEvalContexts.back().InImmediateEscalatingFunctionContext &&
18308 !CheckConstantExpressionAndKeepResult()) {
18309 MarkExpressionAsImmediateEscalating(E: E.get());
18310 return E;
18311 }
18312
18313 if (Cleanup.exprNeedsCleanups()) {
18314 // Since an immediate invocation is a full expression itself - it requires
18315 // an additional ExprWithCleanups node, but it can participate to a bigger
18316 // full expression which actually requires cleanups to be run after so
18317 // create ExprWithCleanups without using MaybeCreateExprWithCleanups as it
18318 // may discard cleanups for outer expression too early.
18319
18320 // Note that ExprWithCleanups created here must always have empty cleanup
18321 // objects:
18322 // - compound literals do not create cleanup objects in C++ and immediate
18323 // invocations are C++-only.
18324 // - blocks are not allowed inside constant expressions and compiler will
18325 // issue an error if they appear there.
18326 //
18327 // Hence, in correct code any cleanup objects created inside current
18328 // evaluation context must be outside the immediate invocation.
18329 E = ExprWithCleanups::Create(C: getASTContext(), subexpr: E.get(),
18330 CleanupsHaveSideEffects: Cleanup.cleanupsHaveSideEffects(), objects: {});
18331 }
18332
18333 ConstantExpr *Res = ConstantExpr::Create(
18334 Context: getASTContext(), E: E.get(),
18335 Storage: ConstantExpr::getStorageKind(T: Decl->getReturnType().getTypePtr(),
18336 Context: getASTContext()),
18337 /*IsImmediateInvocation*/ true);
18338 if (Cached.hasValue())
18339 Res->MoveIntoResult(Value&: Cached, Context: getASTContext());
18340 /// Value-dependent constant expressions should not be immediately
18341 /// evaluated until they are instantiated.
18342 if (!Res->isValueDependent())
18343 ExprEvalContexts.back().ImmediateInvocationCandidates.emplace_back(Args&: Res, Args: 0);
18344 return Res;
18345}
18346
18347static void EvaluateAndDiagnoseImmediateInvocation(
18348 Sema &SemaRef, Sema::ImmediateInvocationCandidate Candidate) {
18349 llvm::SmallVector<PartialDiagnosticAt, 8> Notes;
18350 Expr::EvalResult Eval;
18351 Eval.Diag = &Notes;
18352 ConstantExpr *CE = Candidate.getPointer();
18353 bool Result = CE->EvaluateAsConstantExpr(
18354 Result&: Eval, Ctx: SemaRef.getASTContext(), Kind: ConstantExprKind::ImmediateInvocation);
18355 if (!Result || !Notes.empty()) {
18356 SemaRef.FailedImmediateInvocations.insert(Ptr: CE);
18357 Expr *InnerExpr = CE->getSubExpr()->IgnoreImplicit();
18358 if (auto *FunctionalCast = dyn_cast<CXXFunctionalCastExpr>(Val: InnerExpr))
18359 InnerExpr = FunctionalCast->getSubExpr()->IgnoreImplicit();
18360 FunctionDecl *FD = nullptr;
18361 if (auto *Call = dyn_cast<CallExpr>(Val: InnerExpr))
18362 FD = cast<FunctionDecl>(Val: Call->getCalleeDecl());
18363 else if (auto *Call = dyn_cast<CXXConstructExpr>(Val: InnerExpr))
18364 FD = Call->getConstructor();
18365 else if (auto *Cast = dyn_cast<CastExpr>(Val: InnerExpr))
18366 FD = dyn_cast_or_null<FunctionDecl>(Val: Cast->getConversionFunction());
18367
18368 assert(FD && FD->isImmediateFunction() &&
18369 "could not find an immediate function in this expression");
18370 if (FD->isInvalidDecl())
18371 return;
18372 SemaRef.Diag(Loc: CE->getBeginLoc(), DiagID: diag::err_invalid_consteval_call)
18373 << FD << FD->isConsteval();
18374 if (auto Context =
18375 SemaRef.InnermostDeclarationWithDelayedImmediateInvocations()) {
18376 SemaRef.Diag(Loc: Context->Loc, DiagID: diag::note_invalid_consteval_initializer)
18377 << Context->Decl;
18378 SemaRef.Diag(Loc: Context->Decl->getBeginLoc(), DiagID: diag::note_declared_at);
18379 }
18380 if (!FD->isConsteval())
18381 SemaRef.DiagnoseImmediateEscalatingReason(FD);
18382 for (auto &Note : Notes)
18383 SemaRef.Diag(Loc: Note.first, PD: Note.second);
18384 return;
18385 }
18386 CE->MoveIntoResult(Value&: Eval.Val, Context: SemaRef.getASTContext());
18387}
18388
18389static void RemoveNestedImmediateInvocation(
18390 Sema &SemaRef, Sema::ExpressionEvaluationContextRecord &Rec,
18391 SmallVector<Sema::ImmediateInvocationCandidate, 4>::reverse_iterator It) {
18392 struct ComplexRemove : TreeTransform<ComplexRemove> {
18393 using Base = TreeTransform<ComplexRemove>;
18394 llvm::SmallPtrSetImpl<DeclRefExpr *> &DRSet;
18395 SmallVector<Sema::ImmediateInvocationCandidate, 4> &IISet;
18396 SmallVector<Sema::ImmediateInvocationCandidate, 4>::reverse_iterator
18397 CurrentII;
18398 ComplexRemove(Sema &SemaRef, llvm::SmallPtrSetImpl<DeclRefExpr *> &DR,
18399 SmallVector<Sema::ImmediateInvocationCandidate, 4> &II,
18400 SmallVector<Sema::ImmediateInvocationCandidate,
18401 4>::reverse_iterator Current)
18402 : Base(SemaRef), DRSet(DR), IISet(II), CurrentII(Current) {}
18403 void RemoveImmediateInvocation(ConstantExpr* E) {
18404 auto It = std::find_if(first: CurrentII, last: IISet.rend(),
18405 pred: [E](Sema::ImmediateInvocationCandidate Elem) {
18406 return Elem.getPointer() == E;
18407 });
18408 // It is possible that some subexpression of the current immediate
18409 // invocation was handled from another expression evaluation context. Do
18410 // not handle the current immediate invocation if some of its
18411 // subexpressions failed before.
18412 if (It == IISet.rend()) {
18413 if (SemaRef.FailedImmediateInvocations.contains(Ptr: E))
18414 CurrentII->setInt(1);
18415 } else {
18416 It->setInt(1); // Mark as deleted
18417 }
18418 }
18419 ExprResult TransformConstantExpr(ConstantExpr *E) {
18420 if (!E->isImmediateInvocation())
18421 return Base::TransformConstantExpr(E);
18422 RemoveImmediateInvocation(E);
18423 return Base::TransformExpr(E: E->getSubExpr());
18424 }
18425 /// Base::TransfromCXXOperatorCallExpr doesn't traverse the callee so
18426 /// we need to remove its DeclRefExpr from the DRSet.
18427 ExprResult TransformCXXOperatorCallExpr(CXXOperatorCallExpr *E) {
18428 DRSet.erase(Ptr: cast<DeclRefExpr>(Val: E->getCallee()->IgnoreImplicit()));
18429 return Base::TransformCXXOperatorCallExpr(E);
18430 }
18431 /// Base::TransformUserDefinedLiteral doesn't preserve the
18432 /// UserDefinedLiteral node.
18433 ExprResult TransformUserDefinedLiteral(UserDefinedLiteral *E) { return E; }
18434 /// Base::TransformInitializer skips ConstantExpr so we need to visit them
18435 /// here.
18436 ExprResult TransformInitializer(Expr *Init, bool NotCopyInit) {
18437 if (!Init)
18438 return Init;
18439
18440 // We cannot use IgnoreImpCasts because we need to preserve
18441 // full expressions.
18442 while (true) {
18443 if (auto *ICE = dyn_cast<ImplicitCastExpr>(Val: Init))
18444 Init = ICE->getSubExpr();
18445 else if (auto *ICE = dyn_cast<MaterializeTemporaryExpr>(Val: Init))
18446 Init = ICE->getSubExpr();
18447 else
18448 break;
18449 }
18450 /// ConstantExprs are the first layer of implicit node to be removed so if
18451 /// Init isn't a ConstantExpr, no ConstantExpr will be skipped.
18452 if (auto *CE = dyn_cast<ConstantExpr>(Val: Init);
18453 CE && CE->isImmediateInvocation())
18454 RemoveImmediateInvocation(E: CE);
18455 return Base::TransformInitializer(Init, NotCopyInit);
18456 }
18457 ExprResult TransformDeclRefExpr(DeclRefExpr *E) {
18458 DRSet.erase(Ptr: E);
18459 return E;
18460 }
18461 ExprResult TransformLambdaExpr(LambdaExpr *E) {
18462 // Do not rebuild lambdas to avoid creating a new type.
18463 // Lambdas have already been processed inside their eval contexts.
18464 return E;
18465 }
18466 bool AlwaysRebuild() { return false; }
18467 bool ReplacingOriginal() { return true; }
18468 bool AllowSkippingCXXConstructExpr() {
18469 bool Res = AllowSkippingFirstCXXConstructExpr;
18470 AllowSkippingFirstCXXConstructExpr = true;
18471 return Res;
18472 }
18473 bool AllowSkippingFirstCXXConstructExpr = true;
18474 } Transformer(SemaRef, Rec.ReferenceToConsteval,
18475 Rec.ImmediateInvocationCandidates, It);
18476
18477 /// CXXConstructExpr with a single argument are getting skipped by
18478 /// TreeTransform in some situtation because they could be implicit. This
18479 /// can only occur for the top-level CXXConstructExpr because it is used
18480 /// nowhere in the expression being transformed therefore will not be rebuilt.
18481 /// Setting AllowSkippingFirstCXXConstructExpr to false will prevent from
18482 /// skipping the first CXXConstructExpr.
18483 if (isa<CXXConstructExpr>(Val: It->getPointer()->IgnoreImplicit()))
18484 Transformer.AllowSkippingFirstCXXConstructExpr = false;
18485
18486 ExprResult Res = Transformer.TransformExpr(E: It->getPointer()->getSubExpr());
18487 // The result may not be usable in case of previous compilation errors.
18488 // In this case evaluation of the expression may result in crash so just
18489 // don't do anything further with the result.
18490 if (Res.isUsable()) {
18491 Res = SemaRef.MaybeCreateExprWithCleanups(SubExpr: Res);
18492 It->getPointer()->setSubExpr(Res.get());
18493 }
18494}
18495
18496static void
18497HandleImmediateInvocations(Sema &SemaRef,
18498 Sema::ExpressionEvaluationContextRecord &Rec) {
18499 if ((Rec.ImmediateInvocationCandidates.size() == 0 &&
18500 Rec.ReferenceToConsteval.size() == 0) ||
18501 Rec.isImmediateFunctionContext() || SemaRef.RebuildingImmediateInvocation)
18502 return;
18503
18504 // An expression or conversion is 'manifestly constant-evaluated' if it is:
18505 // [...]
18506 // - the initializer of a variable that is usable in constant expressions or
18507 // has constant initialization.
18508 if (SemaRef.getLangOpts().CPlusPlus23 &&
18509 Rec.ExprContext ==
18510 Sema::ExpressionEvaluationContextRecord::EK_VariableInit) {
18511 auto *VD = dyn_cast<VarDecl>(Val: Rec.ManglingContextDecl);
18512 if (VD && (VD->isUsableInConstantExpressions(C: SemaRef.Context) ||
18513 VD->hasConstantInitialization())) {
18514 // An expression or conversion is in an 'immediate function context' if it
18515 // is potentially evaluated and either:
18516 // [...]
18517 // - it is a subexpression of a manifestly constant-evaluated expression
18518 // or conversion.
18519 return;
18520 }
18521 }
18522
18523 /// When we have more than 1 ImmediateInvocationCandidates or previously
18524 /// failed immediate invocations, we need to check for nested
18525 /// ImmediateInvocationCandidates in order to avoid duplicate diagnostics.
18526 /// Otherwise we only need to remove ReferenceToConsteval in the immediate
18527 /// invocation.
18528 if (Rec.ImmediateInvocationCandidates.size() > 1 ||
18529 !SemaRef.FailedImmediateInvocations.empty()) {
18530
18531 /// Prevent sema calls during the tree transform from adding pointers that
18532 /// are already in the sets.
18533 llvm::SaveAndRestore DisableIITracking(
18534 SemaRef.RebuildingImmediateInvocation, true);
18535
18536 /// Prevent diagnostic during tree transfrom as they are duplicates
18537 Sema::TentativeAnalysisScope DisableDiag(SemaRef);
18538
18539 for (auto It = Rec.ImmediateInvocationCandidates.rbegin();
18540 It != Rec.ImmediateInvocationCandidates.rend(); It++)
18541 if (!It->getInt())
18542 RemoveNestedImmediateInvocation(SemaRef, Rec, It);
18543 } else if (Rec.ImmediateInvocationCandidates.size() == 1 &&
18544 Rec.ReferenceToConsteval.size()) {
18545 struct SimpleRemove : DynamicRecursiveASTVisitor {
18546 llvm::SmallPtrSetImpl<DeclRefExpr *> &DRSet;
18547 SimpleRemove(llvm::SmallPtrSetImpl<DeclRefExpr *> &S) : DRSet(S) {}
18548 bool VisitDeclRefExpr(DeclRefExpr *E) override {
18549 DRSet.erase(Ptr: E);
18550 return DRSet.size();
18551 }
18552 } Visitor(Rec.ReferenceToConsteval);
18553 Visitor.TraverseStmt(
18554 S: Rec.ImmediateInvocationCandidates.front().getPointer()->getSubExpr());
18555 }
18556 for (auto CE : Rec.ImmediateInvocationCandidates)
18557 if (!CE.getInt())
18558 EvaluateAndDiagnoseImmediateInvocation(SemaRef, Candidate: CE);
18559 for (auto *DR : Rec.ReferenceToConsteval) {
18560 // If the expression is immediate escalating, it is not an error;
18561 // The outer context itself becomes immediate and further errors,
18562 // if any, will be handled by DiagnoseImmediateEscalatingReason.
18563 if (DR->isImmediateEscalating())
18564 continue;
18565 auto *FD = cast<FunctionDecl>(Val: DR->getDecl());
18566 const NamedDecl *ND = FD;
18567 if (const auto *MD = dyn_cast<CXXMethodDecl>(Val: ND);
18568 MD && (MD->isLambdaStaticInvoker() || isLambdaCallOperator(MD)))
18569 ND = MD->getParent();
18570
18571 // C++23 [expr.const]/p16
18572 // An expression or conversion is immediate-escalating if it is not
18573 // initially in an immediate function context and it is [...] a
18574 // potentially-evaluated id-expression that denotes an immediate function
18575 // that is not a subexpression of an immediate invocation.
18576 bool ImmediateEscalating = false;
18577 bool IsPotentiallyEvaluated =
18578 Rec.Context ==
18579 Sema::ExpressionEvaluationContext::PotentiallyEvaluated ||
18580 Rec.Context ==
18581 Sema::ExpressionEvaluationContext::PotentiallyEvaluatedIfUsed;
18582 if (SemaRef.inTemplateInstantiation() && IsPotentiallyEvaluated)
18583 ImmediateEscalating = Rec.InImmediateEscalatingFunctionContext;
18584
18585 if (!Rec.InImmediateEscalatingFunctionContext ||
18586 (SemaRef.inTemplateInstantiation() && !ImmediateEscalating)) {
18587 SemaRef.Diag(Loc: DR->getBeginLoc(), DiagID: diag::err_invalid_consteval_take_address)
18588 << ND << isa<CXXRecordDecl>(Val: ND) << FD->isConsteval();
18589 if (!FD->getBuiltinID())
18590 SemaRef.Diag(Loc: ND->getLocation(), DiagID: diag::note_declared_at);
18591 if (auto Context =
18592 SemaRef.InnermostDeclarationWithDelayedImmediateInvocations()) {
18593 SemaRef.Diag(Loc: Context->Loc, DiagID: diag::note_invalid_consteval_initializer)
18594 << Context->Decl;
18595 SemaRef.Diag(Loc: Context->Decl->getBeginLoc(), DiagID: diag::note_declared_at);
18596 }
18597 if (FD->isImmediateEscalating() && !FD->isConsteval())
18598 SemaRef.DiagnoseImmediateEscalatingReason(FD);
18599
18600 } else {
18601 SemaRef.MarkExpressionAsImmediateEscalating(E: DR);
18602 }
18603 }
18604}
18605
18606void Sema::PopExpressionEvaluationContext() {
18607 ExpressionEvaluationContextRecord& Rec = ExprEvalContexts.back();
18608 if (!Rec.Lambdas.empty()) {
18609 using ExpressionKind = ExpressionEvaluationContextRecord::ExpressionKind;
18610 if (!getLangOpts().CPlusPlus20 &&
18611 (Rec.ExprContext == ExpressionKind::EK_TemplateArgument ||
18612 Rec.isUnevaluated() ||
18613 (Rec.isConstantEvaluated() && !getLangOpts().CPlusPlus17))) {
18614 unsigned D;
18615 if (Rec.isUnevaluated()) {
18616 // C++11 [expr.prim.lambda]p2:
18617 // A lambda-expression shall not appear in an unevaluated operand
18618 // (Clause 5).
18619 D = diag::err_lambda_unevaluated_operand;
18620 } else if (Rec.isConstantEvaluated() && !getLangOpts().CPlusPlus17) {
18621 // C++1y [expr.const]p2:
18622 // A conditional-expression e is a core constant expression unless the
18623 // evaluation of e, following the rules of the abstract machine, would
18624 // evaluate [...] a lambda-expression.
18625 D = diag::err_lambda_in_constant_expression;
18626 } else if (Rec.ExprContext == ExpressionKind::EK_TemplateArgument) {
18627 // C++17 [expr.prim.lamda]p2:
18628 // A lambda-expression shall not appear [...] in a template-argument.
18629 D = diag::err_lambda_in_invalid_context;
18630 } else
18631 llvm_unreachable("Couldn't infer lambda error message.");
18632
18633 for (const auto *L : Rec.Lambdas)
18634 Diag(Loc: L->getBeginLoc(), DiagID: D);
18635 }
18636 }
18637
18638 // Append the collected materialized temporaries into previous context before
18639 // exit if the previous also is a lifetime extending context.
18640 if (getLangOpts().CPlusPlus23 && Rec.InLifetimeExtendingContext &&
18641 parentEvaluationContext().InLifetimeExtendingContext &&
18642 !Rec.ForRangeLifetimeExtendTemps.empty()) {
18643 parentEvaluationContext().ForRangeLifetimeExtendTemps.append(
18644 RHS: Rec.ForRangeLifetimeExtendTemps);
18645 }
18646
18647 WarnOnPendingNoDerefs(Rec);
18648 HandleImmediateInvocations(SemaRef&: *this, Rec);
18649
18650 // Warn on any volatile-qualified simple-assignments that are not discarded-
18651 // value expressions nor unevaluated operands (those cases get removed from
18652 // this list by CheckUnusedVolatileAssignment).
18653 for (auto *BO : Rec.VolatileAssignmentLHSs)
18654 Diag(Loc: BO->getBeginLoc(), DiagID: diag::warn_deprecated_simple_assign_volatile)
18655 << BO->getType();
18656
18657 // When are coming out of an unevaluated context, clear out any
18658 // temporaries that we may have created as part of the evaluation of
18659 // the expression in that context: they aren't relevant because they
18660 // will never be constructed.
18661 if (Rec.isUnevaluated() || Rec.isConstantEvaluated()) {
18662 ExprCleanupObjects.erase(CS: ExprCleanupObjects.begin() + Rec.NumCleanupObjects,
18663 CE: ExprCleanupObjects.end());
18664 Cleanup = Rec.ParentCleanup;
18665 CleanupVarDeclMarking();
18666 std::swap(LHS&: MaybeODRUseExprs, RHS&: Rec.SavedMaybeODRUseExprs);
18667 // Otherwise, merge the contexts together.
18668 } else {
18669 Cleanup.mergeFrom(Rhs: Rec.ParentCleanup);
18670 MaybeODRUseExprs.insert_range(R&: Rec.SavedMaybeODRUseExprs);
18671 }
18672
18673 DiagnoseMisalignedMembers();
18674
18675 // Pop the current expression evaluation context off the stack.
18676 ExprEvalContexts.pop_back();
18677}
18678
18679void Sema::DiscardCleanupsInEvaluationContext() {
18680 ExprCleanupObjects.erase(
18681 CS: ExprCleanupObjects.begin() + ExprEvalContexts.back().NumCleanupObjects,
18682 CE: ExprCleanupObjects.end());
18683 Cleanup.reset();
18684 MaybeODRUseExprs.clear();
18685}
18686
18687ExprResult Sema::HandleExprEvaluationContextForTypeof(Expr *E) {
18688 ExprResult Result = CheckPlaceholderExpr(E);
18689 if (Result.isInvalid())
18690 return ExprError();
18691 E = Result.get();
18692 if (!E->getType()->isVariablyModifiedType())
18693 return E;
18694 return TransformToPotentiallyEvaluated(E);
18695}
18696
18697/// Are we in a context that is potentially constant evaluated per C++20
18698/// [expr.const]p12?
18699static bool isPotentiallyConstantEvaluatedContext(Sema &SemaRef) {
18700 /// C++2a [expr.const]p12:
18701 // An expression or conversion is potentially constant evaluated if it is
18702 switch (SemaRef.ExprEvalContexts.back().Context) {
18703 case Sema::ExpressionEvaluationContext::ConstantEvaluated:
18704 case Sema::ExpressionEvaluationContext::ImmediateFunctionContext:
18705
18706 // -- a manifestly constant-evaluated expression,
18707 case Sema::ExpressionEvaluationContext::PotentiallyEvaluated:
18708 case Sema::ExpressionEvaluationContext::PotentiallyEvaluatedIfUsed:
18709 case Sema::ExpressionEvaluationContext::DiscardedStatement:
18710 // -- a potentially-evaluated expression,
18711 case Sema::ExpressionEvaluationContext::UnevaluatedList:
18712 // -- an immediate subexpression of a braced-init-list,
18713
18714 // -- [FIXME] an expression of the form & cast-expression that occurs
18715 // within a templated entity
18716 // -- a subexpression of one of the above that is not a subexpression of
18717 // a nested unevaluated operand.
18718 return true;
18719
18720 case Sema::ExpressionEvaluationContext::Unevaluated:
18721 case Sema::ExpressionEvaluationContext::UnevaluatedAbstract:
18722 // Expressions in this context are never evaluated.
18723 return false;
18724 }
18725 llvm_unreachable("Invalid context");
18726}
18727
18728/// Return true if this function has a calling convention that requires mangling
18729/// in the size of the parameter pack.
18730static bool funcHasParameterSizeMangling(Sema &S, FunctionDecl *FD) {
18731 // These manglings are only applicable for targets whcih use Microsoft
18732 // mangling scheme for C.
18733 if (!S.Context.getTargetInfo().shouldUseMicrosoftCCforMangling())
18734 return false;
18735
18736 // If this is C++ and this isn't an extern "C" function, parameters do not
18737 // need to be complete. In this case, C++ mangling will apply, which doesn't
18738 // use the size of the parameters.
18739 if (S.getLangOpts().CPlusPlus && !FD->isExternC())
18740 return false;
18741
18742 // Stdcall, fastcall, and vectorcall need this special treatment.
18743 CallingConv CC = FD->getType()->castAs<FunctionType>()->getCallConv();
18744 switch (CC) {
18745 case CC_X86StdCall:
18746 case CC_X86FastCall:
18747 case CC_X86VectorCall:
18748 return true;
18749 default:
18750 break;
18751 }
18752 return false;
18753}
18754
18755/// Require that all of the parameter types of function be complete. Normally,
18756/// parameter types are only required to be complete when a function is called
18757/// or defined, but to mangle functions with certain calling conventions, the
18758/// mangler needs to know the size of the parameter list. In this situation,
18759/// MSVC doesn't emit an error or instantiate templates. Instead, MSVC mangles
18760/// the function as _foo@0, i.e. zero bytes of parameters, which will usually
18761/// result in a linker error. Clang doesn't implement this behavior, and instead
18762/// attempts to error at compile time.
18763static void CheckCompleteParameterTypesForMangler(Sema &S, FunctionDecl *FD,
18764 SourceLocation Loc) {
18765 class ParamIncompleteTypeDiagnoser : public Sema::TypeDiagnoser {
18766 FunctionDecl *FD;
18767 ParmVarDecl *Param;
18768
18769 public:
18770 ParamIncompleteTypeDiagnoser(FunctionDecl *FD, ParmVarDecl *Param)
18771 : FD(FD), Param(Param) {}
18772
18773 void diagnose(Sema &S, SourceLocation Loc, QualType T) override {
18774 CallingConv CC = FD->getType()->castAs<FunctionType>()->getCallConv();
18775 StringRef CCName;
18776 switch (CC) {
18777 case CC_X86StdCall:
18778 CCName = "stdcall";
18779 break;
18780 case CC_X86FastCall:
18781 CCName = "fastcall";
18782 break;
18783 case CC_X86VectorCall:
18784 CCName = "vectorcall";
18785 break;
18786 default:
18787 llvm_unreachable("CC does not need mangling");
18788 }
18789
18790 S.Diag(Loc, DiagID: diag::err_cconv_incomplete_param_type)
18791 << Param->getDeclName() << FD->getDeclName() << CCName;
18792 }
18793 };
18794
18795 for (ParmVarDecl *Param : FD->parameters()) {
18796 ParamIncompleteTypeDiagnoser Diagnoser(FD, Param);
18797 S.RequireCompleteType(Loc, T: Param->getType(), Diagnoser);
18798 }
18799}
18800
18801namespace {
18802enum class OdrUseContext {
18803 /// Declarations in this context are not odr-used.
18804 None,
18805 /// Declarations in this context are formally odr-used, but this is a
18806 /// dependent context.
18807 Dependent,
18808 /// Declarations in this context are odr-used but not actually used (yet).
18809 FormallyOdrUsed,
18810 /// Declarations in this context are used.
18811 Used
18812};
18813}
18814
18815/// Are we within a context in which references to resolved functions or to
18816/// variables result in odr-use?
18817static OdrUseContext isOdrUseContext(Sema &SemaRef) {
18818 const Sema::ExpressionEvaluationContextRecord &Context =
18819 SemaRef.currentEvaluationContext();
18820
18821 if (Context.isUnevaluated())
18822 return OdrUseContext::None;
18823
18824 if (SemaRef.CurContext->isDependentContext())
18825 return OdrUseContext::Dependent;
18826
18827 if (Context.isDiscardedStatementContext())
18828 return OdrUseContext::FormallyOdrUsed;
18829
18830 else if (Context.Context ==
18831 Sema::ExpressionEvaluationContext::PotentiallyEvaluatedIfUsed)
18832 return OdrUseContext::FormallyOdrUsed;
18833
18834 return OdrUseContext::Used;
18835}
18836
18837static bool isImplicitlyDefinableConstexprFunction(FunctionDecl *Func) {
18838 if (!Func->isConstexpr())
18839 return false;
18840
18841 if (Func->isImplicitlyInstantiable() || !Func->isUserProvided())
18842 return true;
18843
18844 // Lambda conversion operators are never user provided.
18845 if (CXXConversionDecl *Conv = dyn_cast<CXXConversionDecl>(Val: Func))
18846 return isLambdaConversionOperator(C: Conv);
18847
18848 auto *CCD = dyn_cast<CXXConstructorDecl>(Val: Func);
18849 return CCD && CCD->getInheritedConstructor();
18850}
18851
18852void Sema::MarkFunctionReferenced(SourceLocation Loc, FunctionDecl *Func,
18853 bool MightBeOdrUse) {
18854 assert(Func && "No function?");
18855
18856 Func->setReferenced();
18857
18858 // Recursive functions aren't really used until they're used from some other
18859 // context.
18860 bool IsRecursiveCall = CurContext == Func;
18861
18862 // C++11 [basic.def.odr]p3:
18863 // A function whose name appears as a potentially-evaluated expression is
18864 // odr-used if it is the unique lookup result or the selected member of a
18865 // set of overloaded functions [...].
18866 //
18867 // We (incorrectly) mark overload resolution as an unevaluated context, so we
18868 // can just check that here.
18869 OdrUseContext OdrUse =
18870 MightBeOdrUse ? isOdrUseContext(SemaRef&: *this) : OdrUseContext::None;
18871 if (IsRecursiveCall && OdrUse == OdrUseContext::Used)
18872 OdrUse = OdrUseContext::FormallyOdrUsed;
18873
18874 // Trivial default constructors and destructors are never actually used.
18875 // FIXME: What about other special members?
18876 if (Func->isTrivial() && !Func->hasAttr<DLLExportAttr>() &&
18877 OdrUse == OdrUseContext::Used) {
18878 if (auto *Constructor = dyn_cast<CXXConstructorDecl>(Val: Func))
18879 if (Constructor->isDefaultConstructor())
18880 OdrUse = OdrUseContext::FormallyOdrUsed;
18881 if (isa<CXXDestructorDecl>(Val: Func))
18882 OdrUse = OdrUseContext::FormallyOdrUsed;
18883 }
18884
18885 // C++20 [expr.const]p12:
18886 // A function [...] is needed for constant evaluation if it is [...] a
18887 // constexpr function that is named by an expression that is potentially
18888 // constant evaluated
18889 bool NeededForConstantEvaluation =
18890 isPotentiallyConstantEvaluatedContext(SemaRef&: *this) &&
18891 isImplicitlyDefinableConstexprFunction(Func);
18892
18893 // Determine whether we require a function definition to exist, per
18894 // C++11 [temp.inst]p3:
18895 // Unless a function template specialization has been explicitly
18896 // instantiated or explicitly specialized, the function template
18897 // specialization is implicitly instantiated when the specialization is
18898 // referenced in a context that requires a function definition to exist.
18899 // C++20 [temp.inst]p7:
18900 // The existence of a definition of a [...] function is considered to
18901 // affect the semantics of the program if the [...] function is needed for
18902 // constant evaluation by an expression
18903 // C++20 [basic.def.odr]p10:
18904 // Every program shall contain exactly one definition of every non-inline
18905 // function or variable that is odr-used in that program outside of a
18906 // discarded statement
18907 // C++20 [special]p1:
18908 // The implementation will implicitly define [defaulted special members]
18909 // if they are odr-used or needed for constant evaluation.
18910 //
18911 // Note that we skip the implicit instantiation of templates that are only
18912 // used in unused default arguments or by recursive calls to themselves.
18913 // This is formally non-conforming, but seems reasonable in practice.
18914 bool NeedDefinition =
18915 !IsRecursiveCall &&
18916 (OdrUse == OdrUseContext::Used ||
18917 (NeededForConstantEvaluation && !Func->isPureVirtual()));
18918
18919 // C++14 [temp.expl.spec]p6:
18920 // If a template [...] is explicitly specialized then that specialization
18921 // shall be declared before the first use of that specialization that would
18922 // cause an implicit instantiation to take place, in every translation unit
18923 // in which such a use occurs
18924 if (NeedDefinition &&
18925 (Func->getTemplateSpecializationKind() != TSK_Undeclared ||
18926 Func->getMemberSpecializationInfo()))
18927 checkSpecializationReachability(Loc, Spec: Func);
18928
18929 if (getLangOpts().CUDA)
18930 CUDA().CheckCall(Loc, Callee: Func);
18931
18932 // If we need a definition, try to create one.
18933 if (NeedDefinition && !Func->getBody()) {
18934 runWithSufficientStackSpace(Loc, Fn: [&] {
18935 if (CXXConstructorDecl *Constructor =
18936 dyn_cast<CXXConstructorDecl>(Val: Func)) {
18937 Constructor = cast<CXXConstructorDecl>(Val: Constructor->getFirstDecl());
18938 if (Constructor->isDefaulted() && !Constructor->isDeleted()) {
18939 if (Constructor->isDefaultConstructor()) {
18940 if (Constructor->isTrivial() &&
18941 !Constructor->hasAttr<DLLExportAttr>())
18942 return;
18943 DefineImplicitDefaultConstructor(CurrentLocation: Loc, Constructor);
18944 } else if (Constructor->isCopyConstructor()) {
18945 DefineImplicitCopyConstructor(CurrentLocation: Loc, Constructor);
18946 } else if (Constructor->isMoveConstructor()) {
18947 DefineImplicitMoveConstructor(CurrentLocation: Loc, Constructor);
18948 }
18949 } else if (Constructor->getInheritedConstructor()) {
18950 DefineInheritingConstructor(UseLoc: Loc, Constructor);
18951 }
18952 } else if (CXXDestructorDecl *Destructor =
18953 dyn_cast<CXXDestructorDecl>(Val: Func)) {
18954 Destructor = cast<CXXDestructorDecl>(Val: Destructor->getFirstDecl());
18955 if (Destructor->isDefaulted() && !Destructor->isDeleted()) {
18956 if (Destructor->isTrivial() && !Destructor->hasAttr<DLLExportAttr>())
18957 return;
18958 DefineImplicitDestructor(CurrentLocation: Loc, Destructor);
18959 }
18960 if (Destructor->isVirtual() && getLangOpts().AppleKext)
18961 MarkVTableUsed(Loc, Class: Destructor->getParent());
18962 } else if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(Val: Func)) {
18963 if (MethodDecl->isOverloadedOperator() &&
18964 MethodDecl->getOverloadedOperator() == OO_Equal) {
18965 MethodDecl = cast<CXXMethodDecl>(Val: MethodDecl->getFirstDecl());
18966 if (MethodDecl->isDefaulted() && !MethodDecl->isDeleted()) {
18967 if (MethodDecl->isCopyAssignmentOperator())
18968 DefineImplicitCopyAssignment(CurrentLocation: Loc, MethodDecl);
18969 else if (MethodDecl->isMoveAssignmentOperator())
18970 DefineImplicitMoveAssignment(CurrentLocation: Loc, MethodDecl);
18971 }
18972 } else if (isa<CXXConversionDecl>(Val: MethodDecl) &&
18973 MethodDecl->getParent()->isLambda()) {
18974 CXXConversionDecl *Conversion =
18975 cast<CXXConversionDecl>(Val: MethodDecl->getFirstDecl());
18976 if (Conversion->isLambdaToBlockPointerConversion())
18977 DefineImplicitLambdaToBlockPointerConversion(CurrentLoc: Loc, Conv: Conversion);
18978 else
18979 DefineImplicitLambdaToFunctionPointerConversion(CurrentLoc: Loc, Conv: Conversion);
18980 } else if (MethodDecl->isVirtual() && getLangOpts().AppleKext)
18981 MarkVTableUsed(Loc, Class: MethodDecl->getParent());
18982 }
18983
18984 if (Func->isDefaulted() && !Func->isDeleted()) {
18985 DefaultedComparisonKind DCK = getDefaultedComparisonKind(FD: Func);
18986 if (DCK != DefaultedComparisonKind::None)
18987 DefineDefaultedComparison(Loc, FD: Func, DCK);
18988 }
18989
18990 // Implicit instantiation of function templates and member functions of
18991 // class templates.
18992 if (Func->isImplicitlyInstantiable()) {
18993 TemplateSpecializationKind TSK =
18994 Func->getTemplateSpecializationKindForInstantiation();
18995 SourceLocation PointOfInstantiation = Func->getPointOfInstantiation();
18996 bool FirstInstantiation = PointOfInstantiation.isInvalid();
18997 if (FirstInstantiation) {
18998 PointOfInstantiation = Loc;
18999 if (auto *MSI = Func->getMemberSpecializationInfo())
19000 MSI->setPointOfInstantiation(Loc);
19001 // FIXME: Notify listener.
19002 else
19003 Func->setTemplateSpecializationKind(TSK, PointOfInstantiation);
19004 } else if (TSK != TSK_ImplicitInstantiation) {
19005 // Use the point of use as the point of instantiation, instead of the
19006 // point of explicit instantiation (which we track as the actual point
19007 // of instantiation). This gives better backtraces in diagnostics.
19008 PointOfInstantiation = Loc;
19009 }
19010
19011 if (FirstInstantiation || TSK != TSK_ImplicitInstantiation ||
19012 Func->isConstexpr()) {
19013 if (isa<CXXRecordDecl>(Val: Func->getDeclContext()) &&
19014 cast<CXXRecordDecl>(Val: Func->getDeclContext())->isLocalClass() &&
19015 CodeSynthesisContexts.size())
19016 PendingLocalImplicitInstantiations.push_back(
19017 x: std::make_pair(x&: Func, y&: PointOfInstantiation));
19018 else if (Func->isConstexpr())
19019 // Do not defer instantiations of constexpr functions, to avoid the
19020 // expression evaluator needing to call back into Sema if it sees a
19021 // call to such a function.
19022 InstantiateFunctionDefinition(PointOfInstantiation, Function: Func);
19023 else {
19024 Func->setInstantiationIsPending(true);
19025 PendingInstantiations.push_back(
19026 x: std::make_pair(x&: Func, y&: PointOfInstantiation));
19027 if (llvm::isTimeTraceVerbose()) {
19028 llvm::timeTraceAddInstantEvent(Name: "DeferInstantiation", Detail: [&] {
19029 std::string Name;
19030 llvm::raw_string_ostream OS(Name);
19031 Func->getNameForDiagnostic(OS, Policy: getPrintingPolicy(),
19032 /*Qualified=*/true);
19033 return Name;
19034 });
19035 }
19036 // Notify the consumer that a function was implicitly instantiated.
19037 Consumer.HandleCXXImplicitFunctionInstantiation(D: Func);
19038 }
19039 }
19040 } else {
19041 // Walk redefinitions, as some of them may be instantiable.
19042 for (auto *i : Func->redecls()) {
19043 if (!i->isUsed(CheckUsedAttr: false) && i->isImplicitlyInstantiable())
19044 MarkFunctionReferenced(Loc, Func: i, MightBeOdrUse);
19045 }
19046 }
19047 });
19048 }
19049
19050 // If a constructor was defined in the context of a default parameter
19051 // or of another default member initializer (ie a PotentiallyEvaluatedIfUsed
19052 // context), its initializers may not be referenced yet.
19053 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Val: Func)) {
19054 EnterExpressionEvaluationContext EvalContext(
19055 *this,
19056 Constructor->isImmediateFunction()
19057 ? ExpressionEvaluationContext::ImmediateFunctionContext
19058 : ExpressionEvaluationContext::PotentiallyEvaluated,
19059 Constructor);
19060 for (CXXCtorInitializer *Init : Constructor->inits()) {
19061 if (Init->isInClassMemberInitializer())
19062 runWithSufficientStackSpace(Loc: Init->getSourceLocation(), Fn: [&]() {
19063 MarkDeclarationsReferencedInExpr(E: Init->getInit());
19064 });
19065 }
19066 }
19067
19068 // C++14 [except.spec]p17:
19069 // An exception-specification is considered to be needed when:
19070 // - the function is odr-used or, if it appears in an unevaluated operand,
19071 // would be odr-used if the expression were potentially-evaluated;
19072 //
19073 // Note, we do this even if MightBeOdrUse is false. That indicates that the
19074 // function is a pure virtual function we're calling, and in that case the
19075 // function was selected by overload resolution and we need to resolve its
19076 // exception specification for a different reason.
19077 const FunctionProtoType *FPT = Func->getType()->getAs<FunctionProtoType>();
19078 if (FPT && isUnresolvedExceptionSpec(ESpecType: FPT->getExceptionSpecType()))
19079 ResolveExceptionSpec(Loc, FPT);
19080
19081 // A callee could be called by a host function then by a device function.
19082 // If we only try recording once, we will miss recording the use on device
19083 // side. Therefore keep trying until it is recorded.
19084 if (LangOpts.OffloadImplicitHostDeviceTemplates && LangOpts.CUDAIsDevice &&
19085 !getASTContext().CUDAImplicitHostDeviceFunUsedByDevice.count(V: Func))
19086 CUDA().RecordImplicitHostDeviceFuncUsedByDevice(FD: Func);
19087
19088 // If this is the first "real" use, act on that.
19089 if (OdrUse == OdrUseContext::Used && !Func->isUsed(/*CheckUsedAttr=*/false)) {
19090 // Keep track of used but undefined functions.
19091 if (!Func->isDefined() && !Func->isInAnotherModuleUnit()) {
19092 if (mightHaveNonExternalLinkage(FD: Func))
19093 UndefinedButUsed.insert(KV: std::make_pair(x: Func->getCanonicalDecl(), y&: Loc));
19094 else if (Func->getMostRecentDecl()->isInlined() &&
19095 !LangOpts.GNUInline &&
19096 !Func->getMostRecentDecl()->hasAttr<GNUInlineAttr>())
19097 UndefinedButUsed.insert(KV: std::make_pair(x: Func->getCanonicalDecl(), y&: Loc));
19098 else if (isExternalWithNoLinkageType(VD: Func))
19099 UndefinedButUsed.insert(KV: std::make_pair(x: Func->getCanonicalDecl(), y&: Loc));
19100 }
19101
19102 // Some x86 Windows calling conventions mangle the size of the parameter
19103 // pack into the name. Computing the size of the parameters requires the
19104 // parameter types to be complete. Check that now.
19105 if (funcHasParameterSizeMangling(S&: *this, FD: Func))
19106 CheckCompleteParameterTypesForMangler(S&: *this, FD: Func, Loc);
19107
19108 // In the MS C++ ABI, the compiler emits destructor variants where they are
19109 // used. If the destructor is used here but defined elsewhere, mark the
19110 // virtual base destructors referenced. If those virtual base destructors
19111 // are inline, this will ensure they are defined when emitting the complete
19112 // destructor variant. This checking may be redundant if the destructor is
19113 // provided later in this TU.
19114 if (Context.getTargetInfo().getCXXABI().isMicrosoft()) {
19115 if (auto *Dtor = dyn_cast<CXXDestructorDecl>(Val: Func)) {
19116 CXXRecordDecl *Parent = Dtor->getParent();
19117 if (Parent->getNumVBases() > 0 && !Dtor->getBody())
19118 CheckCompleteDestructorVariant(CurrentLocation: Loc, Dtor);
19119 }
19120 }
19121
19122 Func->markUsed(C&: Context);
19123 }
19124}
19125
19126/// Directly mark a variable odr-used. Given a choice, prefer to use
19127/// MarkVariableReferenced since it does additional checks and then
19128/// calls MarkVarDeclODRUsed.
19129/// If the variable must be captured:
19130/// - if FunctionScopeIndexToStopAt is null, capture it in the CurContext
19131/// - else capture it in the DeclContext that maps to the
19132/// *FunctionScopeIndexToStopAt on the FunctionScopeInfo stack.
19133static void
19134MarkVarDeclODRUsed(ValueDecl *V, SourceLocation Loc, Sema &SemaRef,
19135 const unsigned *const FunctionScopeIndexToStopAt = nullptr) {
19136 // Keep track of used but undefined variables.
19137 // FIXME: We shouldn't suppress this warning for static data members.
19138 VarDecl *Var = V->getPotentiallyDecomposedVarDecl();
19139 assert(Var && "expected a capturable variable");
19140
19141 if (Var->hasDefinition(SemaRef.Context) == VarDecl::DeclarationOnly &&
19142 (!Var->isExternallyVisible() || Var->isInline() ||
19143 SemaRef.isExternalWithNoLinkageType(VD: Var)) &&
19144 !(Var->isStaticDataMember() && Var->hasInit())) {
19145 SourceLocation &old = SemaRef.UndefinedButUsed[Var->getCanonicalDecl()];
19146 if (old.isInvalid())
19147 old = Loc;
19148 }
19149 QualType CaptureType, DeclRefType;
19150 if (SemaRef.LangOpts.OpenMP)
19151 SemaRef.OpenMP().tryCaptureOpenMPLambdas(V);
19152 SemaRef.tryCaptureVariable(Var: V, Loc, Kind: TryCaptureKind::Implicit,
19153 /*EllipsisLoc*/ SourceLocation(),
19154 /*BuildAndDiagnose*/ true, CaptureType,
19155 DeclRefType, FunctionScopeIndexToStopAt);
19156
19157 if (SemaRef.LangOpts.CUDA && Var->hasGlobalStorage()) {
19158 auto *FD = dyn_cast_or_null<FunctionDecl>(Val: SemaRef.CurContext);
19159 auto VarTarget = SemaRef.CUDA().IdentifyTarget(D: Var);
19160 auto UserTarget = SemaRef.CUDA().IdentifyTarget(D: FD);
19161 if (VarTarget == SemaCUDA::CVT_Host &&
19162 (UserTarget == CUDAFunctionTarget::Device ||
19163 UserTarget == CUDAFunctionTarget::HostDevice ||
19164 UserTarget == CUDAFunctionTarget::Global)) {
19165 // Diagnose ODR-use of host global variables in device functions.
19166 // Reference of device global variables in host functions is allowed
19167 // through shadow variables therefore it is not diagnosed.
19168 if (SemaRef.LangOpts.CUDAIsDevice && !SemaRef.LangOpts.HIPStdPar) {
19169 SemaRef.targetDiag(Loc, DiagID: diag::err_ref_bad_target)
19170 << /*host*/ 2 << /*variable*/ 1 << Var << UserTarget;
19171 SemaRef.targetDiag(Loc: Var->getLocation(),
19172 DiagID: Var->getType().isConstQualified()
19173 ? diag::note_cuda_const_var_unpromoted
19174 : diag::note_cuda_host_var);
19175 }
19176 } else if ((VarTarget == SemaCUDA::CVT_Device ||
19177 // Also capture __device__ const variables, which are classified
19178 // as CVT_Both due to an implicit CUDAConstantAttr. We check for
19179 // an explicit CUDADeviceAttr to distinguish them from plain
19180 // const variables (no __device__), which also get CVT_Both but
19181 // only have an implicit CUDADeviceAttr.
19182 (VarTarget == SemaCUDA::CVT_Both &&
19183 Var->hasAttr<CUDADeviceAttr>() &&
19184 !Var->getAttr<CUDADeviceAttr>()->isImplicit())) &&
19185 !Var->hasAttr<CUDASharedAttr>() &&
19186 (UserTarget == CUDAFunctionTarget::Host ||
19187 UserTarget == CUDAFunctionTarget::HostDevice)) {
19188 // Record a CUDA/HIP device side variable if it is ODR-used
19189 // by host code. This is done conservatively, when the variable is
19190 // referenced in any of the following contexts:
19191 // - a non-function context
19192 // - a host function
19193 // - a host device function
19194 // This makes the ODR-use of the device side variable by host code to
19195 // be visible in the device compilation for the compiler to be able to
19196 // emit template variables instantiated by host code only and to
19197 // externalize the static device side variable ODR-used by host code.
19198 if (!Var->hasExternalStorage())
19199 SemaRef.getASTContext().CUDADeviceVarODRUsedByHost.insert(X: Var);
19200 else if (SemaRef.LangOpts.GPURelocatableDeviceCode &&
19201 (!FD || (!FD->getDescribedFunctionTemplate() &&
19202 SemaRef.getASTContext().GetGVALinkageForFunction(FD) ==
19203 GVA_StrongExternal)))
19204 SemaRef.getASTContext().CUDAExternalDeviceDeclODRUsedByHost.insert(X: Var);
19205 }
19206 }
19207
19208 V->markUsed(C&: SemaRef.Context);
19209}
19210
19211void Sema::MarkCaptureUsedInEnclosingContext(ValueDecl *Capture,
19212 SourceLocation Loc,
19213 unsigned CapturingScopeIndex) {
19214 MarkVarDeclODRUsed(V: Capture, Loc, SemaRef&: *this, FunctionScopeIndexToStopAt: &CapturingScopeIndex);
19215}
19216
19217static void diagnoseUncapturableValueReferenceOrBinding(Sema &S,
19218 SourceLocation loc,
19219 ValueDecl *var) {
19220 DeclContext *VarDC = var->getDeclContext();
19221
19222 // If the parameter still belongs to the translation unit, then
19223 // we're actually just using one parameter in the declaration of
19224 // the next.
19225 if (isa<ParmVarDecl>(Val: var) &&
19226 isa<TranslationUnitDecl>(Val: VarDC))
19227 return;
19228
19229 // For C code, don't diagnose about capture if we're not actually in code
19230 // right now; it's impossible to write a non-constant expression outside of
19231 // function context, so we'll get other (more useful) diagnostics later.
19232 //
19233 // For C++, things get a bit more nasty... it would be nice to suppress this
19234 // diagnostic for certain cases like using a local variable in an array bound
19235 // for a member of a local class, but the correct predicate is not obvious.
19236 if (!S.getLangOpts().CPlusPlus && !S.CurContext->isFunctionOrMethod())
19237 return;
19238
19239 unsigned ValueKind = isa<BindingDecl>(Val: var) ? 1 : 0;
19240 unsigned ContextKind = 3; // unknown
19241 if (isa<CXXMethodDecl>(Val: VarDC) &&
19242 cast<CXXRecordDecl>(Val: VarDC->getParent())->isLambda()) {
19243 ContextKind = 2;
19244 } else if (isa<FunctionDecl>(Val: VarDC)) {
19245 ContextKind = 0;
19246 } else if (isa<BlockDecl>(Val: VarDC)) {
19247 ContextKind = 1;
19248 }
19249
19250 S.Diag(Loc: loc, DiagID: diag::err_reference_to_local_in_enclosing_context)
19251 << var << ValueKind << ContextKind << VarDC;
19252 S.Diag(Loc: var->getLocation(), DiagID: diag::note_entity_declared_at)
19253 << var;
19254
19255 // FIXME: Add additional diagnostic info about class etc. which prevents
19256 // capture.
19257}
19258
19259static bool isVariableAlreadyCapturedInScopeInfo(CapturingScopeInfo *CSI,
19260 ValueDecl *Var,
19261 bool &SubCapturesAreNested,
19262 QualType &CaptureType,
19263 QualType &DeclRefType) {
19264 // Check whether we've already captured it.
19265 if (CSI->CaptureMap.count(Val: Var)) {
19266 // If we found a capture, any subcaptures are nested.
19267 SubCapturesAreNested = true;
19268
19269 // Retrieve the capture type for this variable.
19270 CaptureType = CSI->getCapture(Var).getCaptureType();
19271
19272 // Compute the type of an expression that refers to this variable.
19273 DeclRefType = CaptureType.getNonReferenceType();
19274
19275 // Similarly to mutable captures in lambda, all the OpenMP captures by copy
19276 // are mutable in the sense that user can change their value - they are
19277 // private instances of the captured declarations.
19278 const Capture &Cap = CSI->getCapture(Var);
19279 // C++ [expr.prim.lambda]p10:
19280 // The type of such a data member is [...] an lvalue reference to the
19281 // referenced function type if the entity is a reference to a function.
19282 // [...]
19283 if (Cap.isCopyCapture() && !DeclRefType->isFunctionType() &&
19284 !(isa<LambdaScopeInfo>(Val: CSI) &&
19285 !cast<LambdaScopeInfo>(Val: CSI)->lambdaCaptureShouldBeConst()) &&
19286 !(isa<CapturedRegionScopeInfo>(Val: CSI) &&
19287 cast<CapturedRegionScopeInfo>(Val: CSI)->CapRegionKind == CR_OpenMP))
19288 DeclRefType.addConst();
19289 return true;
19290 }
19291 return false;
19292}
19293
19294// Only block literals, captured statements, and lambda expressions can
19295// capture; other scopes don't work.
19296static DeclContext *getParentOfCapturingContextOrNull(DeclContext *DC,
19297 ValueDecl *Var,
19298 SourceLocation Loc,
19299 const bool Diagnose,
19300 Sema &S) {
19301 if (isa<BlockDecl>(Val: DC) || isa<CapturedDecl>(Val: DC) || isLambdaCallOperator(DC))
19302 return getLambdaAwareParentOfDeclContext(DC);
19303
19304 VarDecl *Underlying = Var->getPotentiallyDecomposedVarDecl();
19305 if (Underlying) {
19306 if (Underlying->hasLocalStorage() && Diagnose)
19307 diagnoseUncapturableValueReferenceOrBinding(S, loc: Loc, var: Var);
19308 }
19309 return nullptr;
19310}
19311
19312// Certain capturing entities (lambdas, blocks etc.) are not allowed to capture
19313// certain types of variables (unnamed, variably modified types etc.)
19314// so check for eligibility.
19315static bool isVariableCapturable(CapturingScopeInfo *CSI, ValueDecl *Var,
19316 SourceLocation Loc, const bool Diagnose,
19317 Sema &S) {
19318
19319 assert((isa<VarDecl, BindingDecl>(Var)) &&
19320 "Only variables and structured bindings can be captured");
19321
19322 bool IsBlock = isa<BlockScopeInfo>(Val: CSI);
19323 bool IsLambda = isa<LambdaScopeInfo>(Val: CSI);
19324
19325 // Lambdas are not allowed to capture unnamed variables
19326 // (e.g. anonymous unions).
19327 // FIXME: The C++11 rule don't actually state this explicitly, but I'm
19328 // assuming that's the intent.
19329 if (IsLambda && !Var->getDeclName()) {
19330 if (Diagnose) {
19331 S.Diag(Loc, DiagID: diag::err_lambda_capture_anonymous_var);
19332 S.Diag(Loc: Var->getLocation(), DiagID: diag::note_declared_at);
19333 }
19334 return false;
19335 }
19336
19337 // Prohibit variably-modified types in blocks; they're difficult to deal with.
19338 if (Var->getType()->isVariablyModifiedType() && IsBlock) {
19339 if (Diagnose) {
19340 S.Diag(Loc, DiagID: diag::err_ref_vm_type);
19341 S.Diag(Loc: Var->getLocation(), DiagID: diag::note_previous_decl) << Var;
19342 }
19343 return false;
19344 }
19345 // Prohibit structs with flexible array members too.
19346 // We cannot capture what is in the tail end of the struct.
19347 if (const auto *VTD = Var->getType()->getAsRecordDecl();
19348 VTD && VTD->hasFlexibleArrayMember()) {
19349 if (Diagnose) {
19350 if (IsBlock)
19351 S.Diag(Loc, DiagID: diag::err_ref_flexarray_type);
19352 else
19353 S.Diag(Loc, DiagID: diag::err_lambda_capture_flexarray_type) << Var;
19354 S.Diag(Loc: Var->getLocation(), DiagID: diag::note_previous_decl) << Var;
19355 }
19356 return false;
19357 }
19358 const bool HasBlocksAttr = Var->hasAttr<BlocksAttr>();
19359 // Lambdas and captured statements are not allowed to capture __block
19360 // variables; they don't support the expected semantics.
19361 if (HasBlocksAttr && (IsLambda || isa<CapturedRegionScopeInfo>(Val: CSI))) {
19362 if (Diagnose) {
19363 S.Diag(Loc, DiagID: diag::err_capture_block_variable) << Var << !IsLambda;
19364 S.Diag(Loc: Var->getLocation(), DiagID: diag::note_previous_decl) << Var;
19365 }
19366 return false;
19367 }
19368 // OpenCL v2.0 s6.12.5: Blocks cannot reference/capture other blocks
19369 if (S.getLangOpts().OpenCL && IsBlock &&
19370 Var->getType()->isBlockPointerType()) {
19371 if (Diagnose)
19372 S.Diag(Loc, DiagID: diag::err_opencl_block_ref_block);
19373 return false;
19374 }
19375
19376 if (isa<BindingDecl>(Val: Var)) {
19377 if (!IsLambda || !S.getLangOpts().CPlusPlus) {
19378 if (Diagnose)
19379 diagnoseUncapturableValueReferenceOrBinding(S, loc: Loc, var: Var);
19380 return false;
19381 } else if (Diagnose && S.getLangOpts().CPlusPlus) {
19382 S.Diag(Loc, DiagID: S.LangOpts.CPlusPlus20
19383 ? diag::warn_cxx17_compat_capture_binding
19384 : diag::ext_capture_binding)
19385 << Var;
19386 S.Diag(Loc: Var->getLocation(), DiagID: diag::note_entity_declared_at) << Var;
19387 }
19388 }
19389
19390 return true;
19391}
19392
19393// Returns true if the capture by block was successful.
19394static bool captureInBlock(BlockScopeInfo *BSI, ValueDecl *Var,
19395 SourceLocation Loc, const bool BuildAndDiagnose,
19396 QualType &CaptureType, QualType &DeclRefType,
19397 const bool Nested, Sema &S, bool Invalid) {
19398 bool ByRef = false;
19399
19400 // Blocks are not allowed to capture arrays, excepting OpenCL.
19401 // OpenCL v2.0 s1.12.5 (revision 40): arrays are captured by reference
19402 // (decayed to pointers).
19403 if (!Invalid && !S.getLangOpts().OpenCL && CaptureType->isArrayType()) {
19404 if (BuildAndDiagnose) {
19405 S.Diag(Loc, DiagID: diag::err_ref_array_type);
19406 S.Diag(Loc: Var->getLocation(), DiagID: diag::note_previous_decl) << Var;
19407 Invalid = true;
19408 } else {
19409 return false;
19410 }
19411 }
19412
19413 // Forbid the block-capture of autoreleasing variables.
19414 if (!Invalid &&
19415 CaptureType.getObjCLifetime() == Qualifiers::OCL_Autoreleasing) {
19416 if (BuildAndDiagnose) {
19417 S.Diag(Loc, DiagID: diag::err_arc_autoreleasing_capture)
19418 << /*block*/ 0;
19419 S.Diag(Loc: Var->getLocation(), DiagID: diag::note_previous_decl) << Var;
19420 Invalid = true;
19421 } else {
19422 return false;
19423 }
19424 }
19425
19426 // Warn about implicitly autoreleasing indirect parameters captured by blocks.
19427 if (const auto *PT = CaptureType->getAs<PointerType>()) {
19428 QualType PointeeTy = PT->getPointeeType();
19429
19430 if (!Invalid && PointeeTy->getAs<ObjCObjectPointerType>() &&
19431 PointeeTy.getObjCLifetime() == Qualifiers::OCL_Autoreleasing &&
19432 !S.Context.hasDirectOwnershipQualifier(Ty: PointeeTy)) {
19433 if (BuildAndDiagnose) {
19434 SourceLocation VarLoc = Var->getLocation();
19435 S.Diag(Loc, DiagID: diag::warn_block_capture_autoreleasing);
19436 S.Diag(Loc: VarLoc, DiagID: diag::note_declare_parameter_strong);
19437 }
19438 }
19439 }
19440
19441 const bool HasBlocksAttr = Var->hasAttr<BlocksAttr>();
19442 if (HasBlocksAttr || CaptureType->isReferenceType() ||
19443 (S.getLangOpts().OpenMP && S.OpenMP().isOpenMPCapturedDecl(D: Var))) {
19444 // Block capture by reference does not change the capture or
19445 // declaration reference types.
19446 ByRef = true;
19447 } else {
19448 // Block capture by copy introduces 'const'.
19449 CaptureType = CaptureType.getNonReferenceType().withConst();
19450 DeclRefType = CaptureType;
19451 }
19452
19453 // Actually capture the variable.
19454 if (BuildAndDiagnose)
19455 BSI->addCapture(Var, isBlock: HasBlocksAttr, isByref: ByRef, isNested: Nested, Loc, EllipsisLoc: SourceLocation(),
19456 CaptureType, Invalid);
19457
19458 return !Invalid;
19459}
19460
19461/// Capture the given variable in the captured region.
19462static bool captureInCapturedRegion(
19463 CapturedRegionScopeInfo *RSI, ValueDecl *Var, SourceLocation Loc,
19464 const bool BuildAndDiagnose, QualType &CaptureType, QualType &DeclRefType,
19465 const bool RefersToCapturedVariable, TryCaptureKind Kind, bool IsTopScope,
19466 Sema &S, bool Invalid) {
19467 // By default, capture variables by reference.
19468 bool ByRef = true;
19469 if (IsTopScope && Kind != TryCaptureKind::Implicit) {
19470 ByRef = (Kind == TryCaptureKind::ExplicitByRef);
19471 } else if (S.getLangOpts().OpenMP && RSI->CapRegionKind == CR_OpenMP) {
19472 // Using an LValue reference type is consistent with Lambdas (see below).
19473 if (S.OpenMP().isOpenMPCapturedDecl(D: Var)) {
19474 bool HasConst = DeclRefType.isConstQualified();
19475 DeclRefType = DeclRefType.getUnqualifiedType();
19476 // Don't lose diagnostics about assignments to const.
19477 if (HasConst)
19478 DeclRefType.addConst();
19479 }
19480 // Do not capture firstprivates in tasks.
19481 if (S.OpenMP().isOpenMPPrivateDecl(D: Var, Level: RSI->OpenMPLevel,
19482 CapLevel: RSI->OpenMPCaptureLevel) != OMPC_unknown)
19483 return true;
19484 ByRef = S.OpenMP().isOpenMPCapturedByRef(D: Var, Level: RSI->OpenMPLevel,
19485 OpenMPCaptureLevel: RSI->OpenMPCaptureLevel);
19486 }
19487
19488 if (ByRef)
19489 CaptureType = S.Context.getLValueReferenceType(T: DeclRefType);
19490 else
19491 CaptureType = DeclRefType;
19492
19493 // Actually capture the variable.
19494 if (BuildAndDiagnose)
19495 RSI->addCapture(Var, /*isBlock*/ false, isByref: ByRef, isNested: RefersToCapturedVariable,
19496 Loc, EllipsisLoc: SourceLocation(), CaptureType, Invalid);
19497
19498 return !Invalid;
19499}
19500
19501/// Capture the given variable in the lambda.
19502static bool captureInLambda(LambdaScopeInfo *LSI, ValueDecl *Var,
19503 SourceLocation Loc, const bool BuildAndDiagnose,
19504 QualType &CaptureType, QualType &DeclRefType,
19505 const bool RefersToCapturedVariable,
19506 const TryCaptureKind Kind,
19507 SourceLocation EllipsisLoc, const bool IsTopScope,
19508 Sema &S, bool Invalid) {
19509 // Determine whether we are capturing by reference or by value.
19510 bool ByRef = false;
19511 if (IsTopScope && Kind != TryCaptureKind::Implicit) {
19512 ByRef = (Kind == TryCaptureKind::ExplicitByRef);
19513 } else {
19514 ByRef = (LSI->ImpCaptureStyle == LambdaScopeInfo::ImpCap_LambdaByref);
19515 }
19516
19517 if (BuildAndDiagnose && S.Context.getTargetInfo().getTriple().isWasm() &&
19518 CaptureType.getNonReferenceType().isWebAssemblyReferenceType()) {
19519 S.Diag(Loc, DiagID: diag::err_wasm_ca_reference) << 0;
19520 Invalid = true;
19521 }
19522
19523 // Compute the type of the field that will capture this variable.
19524 if (ByRef) {
19525 // C++11 [expr.prim.lambda]p15:
19526 // An entity is captured by reference if it is implicitly or
19527 // explicitly captured but not captured by copy. It is
19528 // unspecified whether additional unnamed non-static data
19529 // members are declared in the closure type for entities
19530 // captured by reference.
19531 //
19532 // FIXME: It is not clear whether we want to build an lvalue reference
19533 // to the DeclRefType or to CaptureType.getNonReferenceType(). GCC appears
19534 // to do the former, while EDG does the latter. Core issue 1249 will
19535 // clarify, but for now we follow GCC because it's a more permissive and
19536 // easily defensible position.
19537 CaptureType = S.Context.getLValueReferenceType(T: DeclRefType);
19538 } else {
19539 // C++11 [expr.prim.lambda]p14:
19540 // For each entity captured by copy, an unnamed non-static
19541 // data member is declared in the closure type. The
19542 // declaration order of these members is unspecified. The type
19543 // of such a data member is the type of the corresponding
19544 // captured entity if the entity is not a reference to an
19545 // object, or the referenced type otherwise. [Note: If the
19546 // captured entity is a reference to a function, the
19547 // corresponding data member is also a reference to a
19548 // function. - end note ]
19549 if (const ReferenceType *RefType = CaptureType->getAs<ReferenceType>()){
19550 if (!RefType->getPointeeType()->isFunctionType())
19551 CaptureType = RefType->getPointeeType();
19552 }
19553
19554 // Forbid the lambda copy-capture of autoreleasing variables.
19555 if (!Invalid &&
19556 CaptureType.getObjCLifetime() == Qualifiers::OCL_Autoreleasing) {
19557 if (BuildAndDiagnose) {
19558 S.Diag(Loc, DiagID: diag::err_arc_autoreleasing_capture) << /*lambda*/ 1;
19559 S.Diag(Loc: Var->getLocation(), DiagID: diag::note_previous_decl)
19560 << Var->getDeclName();
19561 Invalid = true;
19562 } else {
19563 return false;
19564 }
19565 }
19566
19567 // Make sure that by-copy captures are of a complete and non-abstract type.
19568 if (!Invalid && BuildAndDiagnose) {
19569 if (!CaptureType->isDependentType() &&
19570 S.RequireCompleteSizedType(
19571 Loc, T: CaptureType,
19572 DiagID: diag::err_capture_of_incomplete_or_sizeless_type,
19573 Args: Var->getDeclName()))
19574 Invalid = true;
19575 else if (S.RequireNonAbstractType(Loc, T: CaptureType,
19576 DiagID: diag::err_capture_of_abstract_type))
19577 Invalid = true;
19578 }
19579 }
19580
19581 // Compute the type of a reference to this captured variable.
19582 if (ByRef)
19583 DeclRefType = CaptureType.getNonReferenceType();
19584 else {
19585 // C++ [expr.prim.lambda]p5:
19586 // The closure type for a lambda-expression has a public inline
19587 // function call operator [...]. This function call operator is
19588 // declared const (9.3.1) if and only if the lambda-expression's
19589 // parameter-declaration-clause is not followed by mutable.
19590 DeclRefType = CaptureType.getNonReferenceType();
19591 bool Const = LSI->lambdaCaptureShouldBeConst();
19592 // C++ [expr.prim.lambda]p10:
19593 // The type of such a data member is [...] an lvalue reference to the
19594 // referenced function type if the entity is a reference to a function.
19595 // [...]
19596 if (Const && !CaptureType->isReferenceType() &&
19597 !DeclRefType->isFunctionType())
19598 DeclRefType.addConst();
19599 }
19600
19601 // Add the capture.
19602 if (BuildAndDiagnose)
19603 LSI->addCapture(Var, /*isBlock=*/false, isByref: ByRef, isNested: RefersToCapturedVariable,
19604 Loc, EllipsisLoc, CaptureType, Invalid);
19605
19606 return !Invalid;
19607}
19608
19609static bool canCaptureVariableByCopy(ValueDecl *Var,
19610 const ASTContext &Context) {
19611 // Offer a Copy fix even if the type is dependent.
19612 if (Var->getType()->isDependentType())
19613 return true;
19614 QualType T = Var->getType().getNonReferenceType();
19615 if (T.isTriviallyCopyableType(Context))
19616 return true;
19617 if (CXXRecordDecl *RD = T->getAsCXXRecordDecl()) {
19618
19619 if (!(RD = RD->getDefinition()))
19620 return false;
19621 if (RD->hasSimpleCopyConstructor())
19622 return true;
19623 if (RD->hasUserDeclaredCopyConstructor())
19624 for (CXXConstructorDecl *Ctor : RD->ctors())
19625 if (Ctor->isCopyConstructor())
19626 return !Ctor->isDeleted();
19627 }
19628 return false;
19629}
19630
19631/// Create up to 4 fix-its for explicit reference and value capture of \p Var or
19632/// default capture. Fixes may be omitted if they aren't allowed by the
19633/// standard, for example we can't emit a default copy capture fix-it if we
19634/// already explicitly copy capture capture another variable.
19635static void buildLambdaCaptureFixit(Sema &Sema, LambdaScopeInfo *LSI,
19636 ValueDecl *Var) {
19637 assert(LSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_None);
19638 // Don't offer Capture by copy of default capture by copy fixes if Var is
19639 // known not to be copy constructible.
19640 bool ShouldOfferCopyFix = canCaptureVariableByCopy(Var, Context: Sema.getASTContext());
19641
19642 SmallString<32> FixBuffer;
19643 StringRef Separator = LSI->NumExplicitCaptures > 0 ? ", " : "";
19644 if (Var->getDeclName().isIdentifier() && !Var->getName().empty()) {
19645 SourceLocation VarInsertLoc = LSI->IntroducerRange.getEnd();
19646 if (ShouldOfferCopyFix) {
19647 // Offer fixes to insert an explicit capture for the variable.
19648 // [] -> [VarName]
19649 // [OtherCapture] -> [OtherCapture, VarName]
19650 FixBuffer.assign(Refs: {Separator, Var->getName()});
19651 Sema.Diag(Loc: VarInsertLoc, DiagID: diag::note_lambda_variable_capture_fixit)
19652 << Var << /*value*/ 0
19653 << FixItHint::CreateInsertion(InsertionLoc: VarInsertLoc, Code: FixBuffer);
19654 }
19655 // As above but capture by reference.
19656 FixBuffer.assign(Refs: {Separator, "&", Var->getName()});
19657 Sema.Diag(Loc: VarInsertLoc, DiagID: diag::note_lambda_variable_capture_fixit)
19658 << Var << /*reference*/ 1
19659 << FixItHint::CreateInsertion(InsertionLoc: VarInsertLoc, Code: FixBuffer);
19660 }
19661
19662 // Only try to offer default capture if there are no captures excluding this
19663 // and init captures.
19664 // [this]: OK.
19665 // [X = Y]: OK.
19666 // [&A, &B]: Don't offer.
19667 // [A, B]: Don't offer.
19668 if (llvm::any_of(Range&: LSI->Captures, P: [](Capture &C) {
19669 return !C.isThisCapture() && !C.isInitCapture();
19670 }))
19671 return;
19672
19673 // The default capture specifiers, '=' or '&', must appear first in the
19674 // capture body.
19675 SourceLocation DefaultInsertLoc =
19676 LSI->IntroducerRange.getBegin().getLocWithOffset(Offset: 1);
19677
19678 if (ShouldOfferCopyFix) {
19679 bool CanDefaultCopyCapture = true;
19680 // [=, *this] OK since c++17
19681 // [=, this] OK since c++20
19682 if (LSI->isCXXThisCaptured() && !Sema.getLangOpts().CPlusPlus20)
19683 CanDefaultCopyCapture = Sema.getLangOpts().CPlusPlus17
19684 ? LSI->getCXXThisCapture().isCopyCapture()
19685 : false;
19686 // We can't use default capture by copy if any captures already specified
19687 // capture by copy.
19688 if (CanDefaultCopyCapture && llvm::none_of(Range&: LSI->Captures, P: [](Capture &C) {
19689 return !C.isThisCapture() && !C.isInitCapture() && C.isCopyCapture();
19690 })) {
19691 FixBuffer.assign(Refs: {"=", Separator});
19692 Sema.Diag(Loc: DefaultInsertLoc, DiagID: diag::note_lambda_default_capture_fixit)
19693 << /*value*/ 0
19694 << FixItHint::CreateInsertion(InsertionLoc: DefaultInsertLoc, Code: FixBuffer);
19695 }
19696 }
19697
19698 // We can't use default capture by reference if any captures already specified
19699 // capture by reference.
19700 if (llvm::none_of(Range&: LSI->Captures, P: [](Capture &C) {
19701 return !C.isInitCapture() && C.isReferenceCapture() &&
19702 !C.isThisCapture();
19703 })) {
19704 FixBuffer.assign(Refs: {"&", Separator});
19705 Sema.Diag(Loc: DefaultInsertLoc, DiagID: diag::note_lambda_default_capture_fixit)
19706 << /*reference*/ 1
19707 << FixItHint::CreateInsertion(InsertionLoc: DefaultInsertLoc, Code: FixBuffer);
19708 }
19709}
19710
19711bool Sema::tryCaptureVariable(
19712 ValueDecl *Var, SourceLocation ExprLoc, TryCaptureKind Kind,
19713 SourceLocation EllipsisLoc, bool BuildAndDiagnose, QualType &CaptureType,
19714 QualType &DeclRefType, const unsigned *const FunctionScopeIndexToStopAt) {
19715 // An init-capture is notionally from the context surrounding its
19716 // declaration, but its parent DC is the lambda class.
19717 DeclContext *VarDC = Var->getDeclContext();
19718 DeclContext *DC = CurContext;
19719
19720 // Skip past RequiresExprBodys because they don't constitute function scopes.
19721 while (DC->isRequiresExprBody())
19722 DC = DC->getParent();
19723
19724 // tryCaptureVariable is called every time a DeclRef is formed,
19725 // it can therefore have non-negigible impact on performances.
19726 // For local variables and when there is no capturing scope,
19727 // we can bailout early.
19728 if (CapturingFunctionScopes == 0 && (!BuildAndDiagnose || VarDC == DC))
19729 return true;
19730
19731 // Exception: Function parameters are not tied to the function's DeclContext
19732 // until we enter the function definition. Capturing them anyway would result
19733 // in an out-of-bounds error while traversing DC and its parents.
19734 if (isa<ParmVarDecl>(Val: Var) && !VarDC->isFunctionOrMethod())
19735 return true;
19736
19737 const auto *VD = dyn_cast<VarDecl>(Val: Var);
19738 if (VD) {
19739 if (VD->isInitCapture())
19740 VarDC = VarDC->getParent();
19741 } else {
19742 VD = Var->getPotentiallyDecomposedVarDecl();
19743 }
19744 assert(VD && "Cannot capture a null variable");
19745
19746 const unsigned MaxFunctionScopesIndex = FunctionScopeIndexToStopAt
19747 ? *FunctionScopeIndexToStopAt : FunctionScopes.size() - 1;
19748 // We need to sync up the Declaration Context with the
19749 // FunctionScopeIndexToStopAt
19750 if (FunctionScopeIndexToStopAt) {
19751 assert(!FunctionScopes.empty() && "No function scopes to stop at?");
19752 unsigned FSIndex = FunctionScopes.size() - 1;
19753 // When we're parsing the lambda parameter list, the current DeclContext is
19754 // NOT the lambda but its parent. So move away the current LSI before
19755 // aligning DC and FunctionScopeIndexToStopAt.
19756 if (auto *LSI = dyn_cast<LambdaScopeInfo>(Val: FunctionScopes[FSIndex]);
19757 FSIndex && LSI && !LSI->AfterParameterList)
19758 --FSIndex;
19759 assert(MaxFunctionScopesIndex <= FSIndex &&
19760 "FunctionScopeIndexToStopAt should be no greater than FSIndex into "
19761 "FunctionScopes.");
19762 while (FSIndex != MaxFunctionScopesIndex) {
19763 DC = getLambdaAwareParentOfDeclContext(DC);
19764 --FSIndex;
19765 }
19766 }
19767
19768 // Capture global variables if it is required to use private copy of this
19769 // variable.
19770 bool IsGlobal = !VD->hasLocalStorage();
19771 if (IsGlobal && !(LangOpts.OpenMP &&
19772 OpenMP().isOpenMPCapturedDecl(D: Var, /*CheckScopeInfo=*/true,
19773 StopAt: MaxFunctionScopesIndex)))
19774 return true;
19775
19776 if (isa<VarDecl>(Val: Var))
19777 Var = cast<VarDecl>(Val: Var->getCanonicalDecl());
19778
19779 // Walk up the stack to determine whether we can capture the variable,
19780 // performing the "simple" checks that don't depend on type. We stop when
19781 // we've either hit the declared scope of the variable or find an existing
19782 // capture of that variable. We start from the innermost capturing-entity
19783 // (the DC) and ensure that all intervening capturing-entities
19784 // (blocks/lambdas etc.) between the innermost capturer and the variable`s
19785 // declcontext can either capture the variable or have already captured
19786 // the variable.
19787 CaptureType = Var->getType();
19788 DeclRefType = CaptureType.getNonReferenceType();
19789 bool Nested = false;
19790 bool Explicit = (Kind != TryCaptureKind::Implicit);
19791 unsigned FunctionScopesIndex = MaxFunctionScopesIndex;
19792 do {
19793
19794 LambdaScopeInfo *LSI = nullptr;
19795 if (!FunctionScopes.empty())
19796 LSI = dyn_cast_or_null<LambdaScopeInfo>(
19797 Val: FunctionScopes[FunctionScopesIndex]);
19798
19799 bool IsInScopeDeclarationContext =
19800 !LSI || LSI->AfterParameterList || CurContext == LSI->CallOperator;
19801
19802 if (LSI && !LSI->AfterParameterList) {
19803 // This allows capturing parameters from a default value which does not
19804 // seems correct
19805 if (isa<ParmVarDecl>(Val: Var) && !Var->getDeclContext()->isFunctionOrMethod())
19806 return true;
19807 }
19808 // If the variable is declared in the current context, there is no need to
19809 // capture it.
19810 if (IsInScopeDeclarationContext &&
19811 FunctionScopesIndex == MaxFunctionScopesIndex && VarDC == DC)
19812 return true;
19813
19814 // Only block literals, captured statements, and lambda expressions can
19815 // capture; other scopes don't work.
19816 DeclContext *ParentDC =
19817 !IsInScopeDeclarationContext
19818 ? DC->getParent()
19819 : getParentOfCapturingContextOrNull(DC, Var, Loc: ExprLoc,
19820 Diagnose: BuildAndDiagnose, S&: *this);
19821 // We need to check for the parent *first* because, if we *have*
19822 // private-captured a global variable, we need to recursively capture it in
19823 // intermediate blocks, lambdas, etc.
19824 if (!ParentDC) {
19825 if (IsGlobal) {
19826 FunctionScopesIndex = MaxFunctionScopesIndex - 1;
19827 break;
19828 }
19829 return true;
19830 }
19831
19832 FunctionScopeInfo *FSI = FunctionScopes[FunctionScopesIndex];
19833 CapturingScopeInfo *CSI = cast<CapturingScopeInfo>(Val: FSI);
19834
19835 // Check whether we've already captured it.
19836 if (isVariableAlreadyCapturedInScopeInfo(CSI, Var, SubCapturesAreNested&: Nested, CaptureType,
19837 DeclRefType)) {
19838 CSI->getCapture(Var).markUsed(IsODRUse: BuildAndDiagnose);
19839 break;
19840 }
19841
19842 // When evaluating some attributes (like enable_if) we might refer to a
19843 // function parameter appertaining to the same declaration as that
19844 // attribute.
19845 if (const auto *Parm = dyn_cast<ParmVarDecl>(Val: Var);
19846 Parm && Parm->getDeclContext() == DC)
19847 return true;
19848
19849 // If we are instantiating a generic lambda call operator body,
19850 // we do not want to capture new variables. What was captured
19851 // during either a lambdas transformation or initial parsing
19852 // should be used.
19853 if (isGenericLambdaCallOperatorSpecialization(DC)) {
19854 if (BuildAndDiagnose) {
19855 LambdaScopeInfo *LSI = cast<LambdaScopeInfo>(Val: CSI);
19856 if (LSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_None) {
19857 Diag(Loc: ExprLoc, DiagID: diag::err_lambda_impcap) << Var;
19858 Diag(Loc: Var->getLocation(), DiagID: diag::note_previous_decl) << Var;
19859 Diag(Loc: LSI->Lambda->getBeginLoc(), DiagID: diag::note_lambda_decl);
19860 buildLambdaCaptureFixit(Sema&: *this, LSI, Var);
19861 } else
19862 diagnoseUncapturableValueReferenceOrBinding(S&: *this, loc: ExprLoc, var: Var);
19863 }
19864 return true;
19865 }
19866
19867 // Try to capture variable-length arrays types.
19868 if (Var->getType()->isVariablyModifiedType()) {
19869 // We're going to walk down into the type and look for VLA
19870 // expressions.
19871 QualType QTy = Var->getType();
19872 if (ParmVarDecl *PVD = dyn_cast_or_null<ParmVarDecl>(Val: Var))
19873 QTy = PVD->getOriginalType();
19874 captureVariablyModifiedType(Context, T: QTy, CSI);
19875 }
19876
19877 if (getLangOpts().OpenMP) {
19878 if (auto *RSI = dyn_cast<CapturedRegionScopeInfo>(Val: CSI)) {
19879 // OpenMP private variables should not be captured in outer scope, so
19880 // just break here. Similarly, global variables that are captured in a
19881 // target region should not be captured outside the scope of the region.
19882 if (RSI->CapRegionKind == CR_OpenMP) {
19883 // FIXME: We should support capturing structured bindings in OpenMP.
19884 if (isa<BindingDecl>(Val: Var)) {
19885 if (BuildAndDiagnose) {
19886 Diag(Loc: ExprLoc, DiagID: diag::err_capture_binding_openmp) << Var;
19887 Diag(Loc: Var->getLocation(), DiagID: diag::note_entity_declared_at) << Var;
19888 }
19889 return true;
19890 }
19891 OpenMPClauseKind IsOpenMPPrivateDecl = OpenMP().isOpenMPPrivateDecl(
19892 D: Var, Level: RSI->OpenMPLevel, CapLevel: RSI->OpenMPCaptureLevel);
19893 // If the variable is private (i.e. not captured) and has variably
19894 // modified type, we still need to capture the type for correct
19895 // codegen in all regions, associated with the construct. Currently,
19896 // it is captured in the innermost captured region only.
19897 if (IsOpenMPPrivateDecl != OMPC_unknown &&
19898 Var->getType()->isVariablyModifiedType()) {
19899 QualType QTy = Var->getType();
19900 if (ParmVarDecl *PVD = dyn_cast_or_null<ParmVarDecl>(Val: Var))
19901 QTy = PVD->getOriginalType();
19902 for (int I = 1,
19903 E = OpenMP().getNumberOfConstructScopes(Level: RSI->OpenMPLevel);
19904 I < E; ++I) {
19905 auto *OuterRSI = cast<CapturedRegionScopeInfo>(
19906 Val: FunctionScopes[FunctionScopesIndex - I]);
19907 assert(RSI->OpenMPLevel == OuterRSI->OpenMPLevel &&
19908 "Wrong number of captured regions associated with the "
19909 "OpenMP construct.");
19910 captureVariablyModifiedType(Context, T: QTy, CSI: OuterRSI);
19911 }
19912 }
19913 bool IsTargetCap =
19914 IsOpenMPPrivateDecl != OMPC_private &&
19915 OpenMP().isOpenMPTargetCapturedDecl(D: Var, Level: RSI->OpenMPLevel,
19916 CaptureLevel: RSI->OpenMPCaptureLevel);
19917 // Do not capture global if it is not privatized in outer regions.
19918 bool IsGlobalCap =
19919 IsGlobal && OpenMP().isOpenMPGlobalCapturedDecl(
19920 D: Var, Level: RSI->OpenMPLevel, CaptureLevel: RSI->OpenMPCaptureLevel);
19921
19922 // When we detect target captures we are looking from inside the
19923 // target region, therefore we need to propagate the capture from the
19924 // enclosing region. Therefore, the capture is not initially nested.
19925 if (IsTargetCap)
19926 OpenMP().adjustOpenMPTargetScopeIndex(FunctionScopesIndex,
19927 Level: RSI->OpenMPLevel);
19928
19929 if (IsTargetCap || IsOpenMPPrivateDecl == OMPC_private ||
19930 (IsGlobal && !IsGlobalCap)) {
19931 Nested = !IsTargetCap;
19932 bool HasConst = DeclRefType.isConstQualified();
19933 DeclRefType = DeclRefType.getUnqualifiedType();
19934 // Don't lose diagnostics about assignments to const.
19935 if (HasConst)
19936 DeclRefType.addConst();
19937 CaptureType = Context.getLValueReferenceType(T: DeclRefType);
19938 break;
19939 }
19940 }
19941 }
19942 }
19943 if (CSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_None && !Explicit) {
19944 // No capture-default, and this is not an explicit capture
19945 // so cannot capture this variable.
19946 if (BuildAndDiagnose) {
19947 Diag(Loc: ExprLoc, DiagID: diag::err_lambda_impcap) << Var;
19948 Diag(Loc: Var->getLocation(), DiagID: diag::note_previous_decl) << Var;
19949 auto *LSI = cast<LambdaScopeInfo>(Val: CSI);
19950 if (LSI->Lambda) {
19951 Diag(Loc: LSI->Lambda->getBeginLoc(), DiagID: diag::note_lambda_decl);
19952 buildLambdaCaptureFixit(Sema&: *this, LSI, Var);
19953 }
19954 // FIXME: If we error out because an outer lambda can not implicitly
19955 // capture a variable that an inner lambda explicitly captures, we
19956 // should have the inner lambda do the explicit capture - because
19957 // it makes for cleaner diagnostics later. This would purely be done
19958 // so that the diagnostic does not misleadingly claim that a variable
19959 // can not be captured by a lambda implicitly even though it is captured
19960 // explicitly. Suggestion:
19961 // - create const bool VariableCaptureWasInitiallyExplicit = Explicit
19962 // at the function head
19963 // - cache the StartingDeclContext - this must be a lambda
19964 // - captureInLambda in the innermost lambda the variable.
19965 }
19966 return true;
19967 }
19968 Explicit = false;
19969 FunctionScopesIndex--;
19970 if (IsInScopeDeclarationContext)
19971 DC = ParentDC;
19972 } while (!VarDC->Equals(DC));
19973
19974 // Walk back down the scope stack, (e.g. from outer lambda to inner lambda)
19975 // computing the type of the capture at each step, checking type-specific
19976 // requirements, and adding captures if requested.
19977 // If the variable had already been captured previously, we start capturing
19978 // at the lambda nested within that one.
19979 bool Invalid = false;
19980 for (unsigned I = ++FunctionScopesIndex, N = MaxFunctionScopesIndex + 1; I != N;
19981 ++I) {
19982 CapturingScopeInfo *CSI = cast<CapturingScopeInfo>(Val: FunctionScopes[I]);
19983
19984 // Certain capturing entities (lambdas, blocks etc.) are not allowed to capture
19985 // certain types of variables (unnamed, variably modified types etc.)
19986 // so check for eligibility.
19987 if (!Invalid)
19988 Invalid =
19989 !isVariableCapturable(CSI, Var, Loc: ExprLoc, Diagnose: BuildAndDiagnose, S&: *this);
19990
19991 // After encountering an error, if we're actually supposed to capture, keep
19992 // capturing in nested contexts to suppress any follow-on diagnostics.
19993 if (Invalid && !BuildAndDiagnose)
19994 return true;
19995
19996 if (BlockScopeInfo *BSI = dyn_cast<BlockScopeInfo>(Val: CSI)) {
19997 Invalid = !captureInBlock(BSI, Var, Loc: ExprLoc, BuildAndDiagnose, CaptureType,
19998 DeclRefType, Nested, S&: *this, Invalid);
19999 Nested = true;
20000 } else if (CapturedRegionScopeInfo *RSI = dyn_cast<CapturedRegionScopeInfo>(Val: CSI)) {
20001 Invalid = !captureInCapturedRegion(
20002 RSI, Var, Loc: ExprLoc, BuildAndDiagnose, CaptureType, DeclRefType, RefersToCapturedVariable: Nested,
20003 Kind, /*IsTopScope*/ I == N - 1, S&: *this, Invalid);
20004 Nested = true;
20005 } else {
20006 LambdaScopeInfo *LSI = cast<LambdaScopeInfo>(Val: CSI);
20007 Invalid =
20008 !captureInLambda(LSI, Var, Loc: ExprLoc, BuildAndDiagnose, CaptureType,
20009 DeclRefType, RefersToCapturedVariable: Nested, Kind, EllipsisLoc,
20010 /*IsTopScope*/ I == N - 1, S&: *this, Invalid);
20011 Nested = true;
20012 }
20013
20014 if (Invalid && !BuildAndDiagnose)
20015 return true;
20016 }
20017 return Invalid;
20018}
20019
20020bool Sema::tryCaptureVariable(ValueDecl *Var, SourceLocation Loc,
20021 TryCaptureKind Kind, SourceLocation EllipsisLoc) {
20022 QualType CaptureType;
20023 QualType DeclRefType;
20024 return tryCaptureVariable(Var, ExprLoc: Loc, Kind, EllipsisLoc,
20025 /*BuildAndDiagnose=*/true, CaptureType,
20026 DeclRefType, FunctionScopeIndexToStopAt: nullptr);
20027}
20028
20029bool Sema::NeedToCaptureVariable(ValueDecl *Var, SourceLocation Loc) {
20030 QualType CaptureType;
20031 QualType DeclRefType;
20032 return !tryCaptureVariable(
20033 Var, ExprLoc: Loc, Kind: TryCaptureKind::Implicit, EllipsisLoc: SourceLocation(),
20034 /*BuildAndDiagnose=*/false, CaptureType, DeclRefType, FunctionScopeIndexToStopAt: nullptr);
20035}
20036
20037QualType Sema::getCapturedDeclRefType(ValueDecl *Var, SourceLocation Loc) {
20038 assert(Var && "Null value cannot be captured");
20039
20040 QualType CaptureType;
20041 QualType DeclRefType;
20042
20043 // Determine whether we can capture this variable.
20044 if (tryCaptureVariable(Var, ExprLoc: Loc, Kind: TryCaptureKind::Implicit, EllipsisLoc: SourceLocation(),
20045 /*BuildAndDiagnose=*/false, CaptureType, DeclRefType,
20046 FunctionScopeIndexToStopAt: nullptr))
20047 return QualType();
20048
20049 return DeclRefType;
20050}
20051
20052namespace {
20053// Helper to copy the template arguments from a DeclRefExpr or MemberExpr.
20054// The produced TemplateArgumentListInfo* points to data stored within this
20055// object, so should only be used in contexts where the pointer will not be
20056// used after the CopiedTemplateArgs object is destroyed.
20057class CopiedTemplateArgs {
20058 bool HasArgs;
20059 TemplateArgumentListInfo TemplateArgStorage;
20060public:
20061 template<typename RefExpr>
20062 CopiedTemplateArgs(RefExpr *E) : HasArgs(E->hasExplicitTemplateArgs()) {
20063 if (HasArgs)
20064 E->copyTemplateArgumentsInto(TemplateArgStorage);
20065 }
20066 operator TemplateArgumentListInfo*()
20067#ifdef __has_cpp_attribute
20068#if __has_cpp_attribute(clang::lifetimebound)
20069 [[clang::lifetimebound]]
20070#endif
20071#endif
20072 {
20073 return HasArgs ? &TemplateArgStorage : nullptr;
20074 }
20075};
20076}
20077
20078/// Walk the set of potential results of an expression and mark them all as
20079/// non-odr-uses if they satisfy the side-conditions of the NonOdrUseReason.
20080///
20081/// \return A new expression if we found any potential results, ExprEmpty() if
20082/// not, and ExprError() if we diagnosed an error.
20083static ExprResult rebuildPotentialResultsAsNonOdrUsed(Sema &S, Expr *E,
20084 NonOdrUseReason NOUR) {
20085 // Per C++11 [basic.def.odr], a variable is odr-used "unless it is
20086 // an object that satisfies the requirements for appearing in a
20087 // constant expression (5.19) and the lvalue-to-rvalue conversion (4.1)
20088 // is immediately applied." This function handles the lvalue-to-rvalue
20089 // conversion part.
20090 //
20091 // If we encounter a node that claims to be an odr-use but shouldn't be, we
20092 // transform it into the relevant kind of non-odr-use node and rebuild the
20093 // tree of nodes leading to it.
20094 //
20095 // This is a mini-TreeTransform that only transforms a restricted subset of
20096 // nodes (and only certain operands of them).
20097
20098 // Rebuild a subexpression.
20099 auto Rebuild = [&](Expr *Sub) {
20100 return rebuildPotentialResultsAsNonOdrUsed(S, E: Sub, NOUR);
20101 };
20102
20103 // Check whether a potential result satisfies the requirements of NOUR.
20104 auto IsPotentialResultOdrUsed = [&](NamedDecl *D) {
20105 // Any entity other than a VarDecl is always odr-used whenever it's named
20106 // in a potentially-evaluated expression.
20107 auto *VD = dyn_cast<VarDecl>(Val: D);
20108 if (!VD)
20109 return true;
20110
20111 // C++2a [basic.def.odr]p4:
20112 // A variable x whose name appears as a potentially-evalauted expression
20113 // e is odr-used by e unless
20114 // -- x is a reference that is usable in constant expressions, or
20115 // -- x is a variable of non-reference type that is usable in constant
20116 // expressions and has no mutable subobjects, and e is an element of
20117 // the set of potential results of an expression of
20118 // non-volatile-qualified non-class type to which the lvalue-to-rvalue
20119 // conversion is applied, or
20120 // -- x is a variable of non-reference type, and e is an element of the
20121 // set of potential results of a discarded-value expression to which
20122 // the lvalue-to-rvalue conversion is not applied
20123 //
20124 // We check the first bullet and the "potentially-evaluated" condition in
20125 // BuildDeclRefExpr. We check the type requirements in the second bullet
20126 // in CheckLValueToRValueConversionOperand below.
20127 switch (NOUR) {
20128 case NOUR_None:
20129 case NOUR_Unevaluated:
20130 llvm_unreachable("unexpected non-odr-use-reason");
20131
20132 case NOUR_Constant:
20133 // Constant references were handled when they were built.
20134 if (VD->getType()->isReferenceType())
20135 return true;
20136 if (auto *RD = VD->getType()->getAsCXXRecordDecl())
20137 if (RD->hasDefinition() && RD->hasMutableFields())
20138 return true;
20139 if (!VD->isUsableInConstantExpressions(C: S.Context))
20140 return true;
20141 break;
20142
20143 case NOUR_Discarded:
20144 if (VD->getType()->isReferenceType())
20145 return true;
20146 break;
20147 }
20148 return false;
20149 };
20150
20151 // Check whether this expression may be odr-used in CUDA/HIP.
20152 auto MaybeCUDAODRUsed = [&]() -> bool {
20153 if (!S.LangOpts.CUDA)
20154 return false;
20155 LambdaScopeInfo *LSI = S.getCurLambda();
20156 if (!LSI)
20157 return false;
20158 auto *DRE = dyn_cast<DeclRefExpr>(Val: E);
20159 if (!DRE)
20160 return false;
20161 auto *VD = dyn_cast<VarDecl>(Val: DRE->getDecl());
20162 if (!VD)
20163 return false;
20164 return LSI->CUDAPotentialODRUsedVars.count(Ptr: VD);
20165 };
20166
20167 // Mark that this expression does not constitute an odr-use.
20168 auto MarkNotOdrUsed = [&] {
20169 if (!MaybeCUDAODRUsed()) {
20170 S.MaybeODRUseExprs.remove(X: E);
20171 if (LambdaScopeInfo *LSI = S.getCurLambda())
20172 LSI->markVariableExprAsNonODRUsed(CapturingVarExpr: E);
20173 }
20174 };
20175
20176 // C++2a [basic.def.odr]p2:
20177 // The set of potential results of an expression e is defined as follows:
20178 switch (E->getStmtClass()) {
20179 // -- If e is an id-expression, ...
20180 case Expr::DeclRefExprClass: {
20181 auto *DRE = cast<DeclRefExpr>(Val: E);
20182 if (DRE->isNonOdrUse() || IsPotentialResultOdrUsed(DRE->getDecl()))
20183 break;
20184
20185 // Rebuild as a non-odr-use DeclRefExpr.
20186 MarkNotOdrUsed();
20187 return DeclRefExpr::Create(
20188 Context: S.Context, QualifierLoc: DRE->getQualifierLoc(), TemplateKWLoc: DRE->getTemplateKeywordLoc(),
20189 D: DRE->getDecl(), RefersToEnclosingVariableOrCapture: DRE->refersToEnclosingVariableOrCapture(),
20190 NameInfo: DRE->getNameInfo(), T: DRE->getType(), VK: DRE->getValueKind(),
20191 FoundD: DRE->getFoundDecl(), TemplateArgs: CopiedTemplateArgs(DRE), NOUR);
20192 }
20193
20194 case Expr::FunctionParmPackExprClass: {
20195 auto *FPPE = cast<FunctionParmPackExpr>(Val: E);
20196 // If any of the declarations in the pack is odr-used, then the expression
20197 // as a whole constitutes an odr-use.
20198 for (ValueDecl *D : *FPPE)
20199 if (IsPotentialResultOdrUsed(D))
20200 return ExprEmpty();
20201
20202 // FIXME: Rebuild as a non-odr-use FunctionParmPackExpr? In practice,
20203 // nothing cares about whether we marked this as an odr-use, but it might
20204 // be useful for non-compiler tools.
20205 MarkNotOdrUsed();
20206 break;
20207 }
20208
20209 // -- If e is a subscripting operation with an array operand...
20210 case Expr::ArraySubscriptExprClass: {
20211 auto *ASE = cast<ArraySubscriptExpr>(Val: E);
20212 Expr *OldBase = ASE->getBase()->IgnoreImplicit();
20213 if (!OldBase->getType()->isArrayType())
20214 break;
20215 ExprResult Base = Rebuild(OldBase);
20216 if (!Base.isUsable())
20217 return Base;
20218 Expr *LHS = ASE->getBase() == ASE->getLHS() ? Base.get() : ASE->getLHS();
20219 Expr *RHS = ASE->getBase() == ASE->getRHS() ? Base.get() : ASE->getRHS();
20220 SourceLocation LBracketLoc = ASE->getBeginLoc(); // FIXME: Not stored.
20221 return S.ActOnArraySubscriptExpr(S: nullptr, base: LHS, lbLoc: LBracketLoc, ArgExprs: RHS,
20222 rbLoc: ASE->getRBracketLoc());
20223 }
20224
20225 case Expr::MemberExprClass: {
20226 auto *ME = cast<MemberExpr>(Val: E);
20227 // -- If e is a class member access expression [...] naming a non-static
20228 // data member...
20229 if (isa<FieldDecl>(Val: ME->getMemberDecl())) {
20230 ExprResult Base = Rebuild(ME->getBase());
20231 if (!Base.isUsable())
20232 return Base;
20233 return MemberExpr::Create(
20234 C: S.Context, Base: Base.get(), IsArrow: ME->isArrow(), OperatorLoc: ME->getOperatorLoc(),
20235 QualifierLoc: ME->getQualifierLoc(), TemplateKWLoc: ME->getTemplateKeywordLoc(),
20236 MemberDecl: ME->getMemberDecl(), FoundDecl: ME->getFoundDecl(), MemberNameInfo: ME->getMemberNameInfo(),
20237 TemplateArgs: CopiedTemplateArgs(ME), T: ME->getType(), VK: ME->getValueKind(),
20238 OK: ME->getObjectKind(), NOUR: ME->isNonOdrUse());
20239 }
20240
20241 if (ME->getMemberDecl()->isCXXInstanceMember())
20242 break;
20243
20244 // -- If e is a class member access expression naming a static data member,
20245 // ...
20246 if (ME->isNonOdrUse() || IsPotentialResultOdrUsed(ME->getMemberDecl()))
20247 break;
20248
20249 // Rebuild as a non-odr-use MemberExpr.
20250 MarkNotOdrUsed();
20251 return MemberExpr::Create(
20252 C: S.Context, Base: ME->getBase(), IsArrow: ME->isArrow(), OperatorLoc: ME->getOperatorLoc(),
20253 QualifierLoc: ME->getQualifierLoc(), TemplateKWLoc: ME->getTemplateKeywordLoc(), MemberDecl: ME->getMemberDecl(),
20254 FoundDecl: ME->getFoundDecl(), MemberNameInfo: ME->getMemberNameInfo(), TemplateArgs: CopiedTemplateArgs(ME),
20255 T: ME->getType(), VK: ME->getValueKind(), OK: ME->getObjectKind(), NOUR);
20256 }
20257
20258 case Expr::BinaryOperatorClass: {
20259 auto *BO = cast<BinaryOperator>(Val: E);
20260 Expr *LHS = BO->getLHS();
20261 Expr *RHS = BO->getRHS();
20262 // -- If e is a pointer-to-member expression of the form e1 .* e2 ...
20263 if (BO->getOpcode() == BO_PtrMemD) {
20264 ExprResult Sub = Rebuild(LHS);
20265 if (!Sub.isUsable())
20266 return Sub;
20267 BO->setLHS(Sub.get());
20268 // -- If e is a comma expression, ...
20269 } else if (BO->getOpcode() == BO_Comma) {
20270 ExprResult Sub = Rebuild(RHS);
20271 if (!Sub.isUsable())
20272 return Sub;
20273 BO->setRHS(Sub.get());
20274 } else {
20275 break;
20276 }
20277 return ExprResult(BO);
20278 }
20279
20280 // -- If e has the form (e1)...
20281 case Expr::ParenExprClass: {
20282 auto *PE = cast<ParenExpr>(Val: E);
20283 ExprResult Sub = Rebuild(PE->getSubExpr());
20284 if (!Sub.isUsable())
20285 return Sub;
20286 return S.ActOnParenExpr(L: PE->getLParen(), R: PE->getRParen(), E: Sub.get());
20287 }
20288
20289 // -- If e is a glvalue conditional expression, ...
20290 // We don't apply this to a binary conditional operator. FIXME: Should we?
20291 case Expr::ConditionalOperatorClass: {
20292 auto *CO = cast<ConditionalOperator>(Val: E);
20293 ExprResult LHS = Rebuild(CO->getLHS());
20294 if (LHS.isInvalid())
20295 return ExprError();
20296 ExprResult RHS = Rebuild(CO->getRHS());
20297 if (RHS.isInvalid())
20298 return ExprError();
20299 if (!LHS.isUsable() && !RHS.isUsable())
20300 return ExprEmpty();
20301 if (!LHS.isUsable())
20302 LHS = CO->getLHS();
20303 if (!RHS.isUsable())
20304 RHS = CO->getRHS();
20305 return S.ActOnConditionalOp(QuestionLoc: CO->getQuestionLoc(), ColonLoc: CO->getColonLoc(),
20306 CondExpr: CO->getCond(), LHSExpr: LHS.get(), RHSExpr: RHS.get());
20307 }
20308
20309 // [Clang extension]
20310 // -- If e has the form __extension__ e1...
20311 case Expr::UnaryOperatorClass: {
20312 auto *UO = cast<UnaryOperator>(Val: E);
20313 if (UO->getOpcode() != UO_Extension)
20314 break;
20315 ExprResult Sub = Rebuild(UO->getSubExpr());
20316 if (!Sub.isUsable())
20317 return Sub;
20318 return S.BuildUnaryOp(S: nullptr, OpLoc: UO->getOperatorLoc(), Opc: UO_Extension,
20319 Input: Sub.get());
20320 }
20321
20322 // [Clang extension]
20323 // -- If e has the form _Generic(...), the set of potential results is the
20324 // union of the sets of potential results of the associated expressions.
20325 case Expr::GenericSelectionExprClass: {
20326 auto *GSE = cast<GenericSelectionExpr>(Val: E);
20327
20328 SmallVector<Expr *, 4> AssocExprs;
20329 bool AnyChanged = false;
20330 for (Expr *OrigAssocExpr : GSE->getAssocExprs()) {
20331 ExprResult AssocExpr = Rebuild(OrigAssocExpr);
20332 if (AssocExpr.isInvalid())
20333 return ExprError();
20334 if (AssocExpr.isUsable()) {
20335 AssocExprs.push_back(Elt: AssocExpr.get());
20336 AnyChanged = true;
20337 } else {
20338 AssocExprs.push_back(Elt: OrigAssocExpr);
20339 }
20340 }
20341
20342 void *ExOrTy = nullptr;
20343 bool IsExpr = GSE->isExprPredicate();
20344 if (IsExpr)
20345 ExOrTy = GSE->getControllingExpr();
20346 else
20347 ExOrTy = GSE->getControllingType();
20348 return AnyChanged ? S.CreateGenericSelectionExpr(
20349 KeyLoc: GSE->getGenericLoc(), DefaultLoc: GSE->getDefaultLoc(),
20350 RParenLoc: GSE->getRParenLoc(), PredicateIsExpr: IsExpr, ControllingExprOrType: ExOrTy,
20351 Types: GSE->getAssocTypeSourceInfos(), Exprs: AssocExprs)
20352 : ExprEmpty();
20353 }
20354
20355 // [Clang extension]
20356 // -- If e has the form __builtin_choose_expr(...), the set of potential
20357 // results is the union of the sets of potential results of the
20358 // second and third subexpressions.
20359 case Expr::ChooseExprClass: {
20360 auto *CE = cast<ChooseExpr>(Val: E);
20361
20362 ExprResult LHS = Rebuild(CE->getLHS());
20363 if (LHS.isInvalid())
20364 return ExprError();
20365
20366 ExprResult RHS = Rebuild(CE->getLHS());
20367 if (RHS.isInvalid())
20368 return ExprError();
20369
20370 if (!LHS.get() && !RHS.get())
20371 return ExprEmpty();
20372 if (!LHS.isUsable())
20373 LHS = CE->getLHS();
20374 if (!RHS.isUsable())
20375 RHS = CE->getRHS();
20376
20377 return S.ActOnChooseExpr(BuiltinLoc: CE->getBuiltinLoc(), CondExpr: CE->getCond(), LHSExpr: LHS.get(),
20378 RHSExpr: RHS.get(), RPLoc: CE->getRParenLoc());
20379 }
20380
20381 // Step through non-syntactic nodes.
20382 case Expr::ConstantExprClass: {
20383 auto *CE = cast<ConstantExpr>(Val: E);
20384 ExprResult Sub = Rebuild(CE->getSubExpr());
20385 if (!Sub.isUsable())
20386 return Sub;
20387 return ConstantExpr::Create(Context: S.Context, E: Sub.get());
20388 }
20389
20390 // We could mostly rely on the recursive rebuilding to rebuild implicit
20391 // casts, but not at the top level, so rebuild them here.
20392 case Expr::ImplicitCastExprClass: {
20393 auto *ICE = cast<ImplicitCastExpr>(Val: E);
20394 // Only step through the narrow set of cast kinds we expect to encounter.
20395 // Anything else suggests we've left the region in which potential results
20396 // can be found.
20397 switch (ICE->getCastKind()) {
20398 case CK_NoOp:
20399 case CK_DerivedToBase:
20400 case CK_UncheckedDerivedToBase: {
20401 ExprResult Sub = Rebuild(ICE->getSubExpr());
20402 if (!Sub.isUsable())
20403 return Sub;
20404 CXXCastPath Path(ICE->path());
20405 return S.ImpCastExprToType(E: Sub.get(), Type: ICE->getType(), CK: ICE->getCastKind(),
20406 VK: ICE->getValueKind(), BasePath: &Path);
20407 }
20408
20409 default:
20410 break;
20411 }
20412 break;
20413 }
20414
20415 default:
20416 break;
20417 }
20418
20419 // Can't traverse through this node. Nothing to do.
20420 return ExprEmpty();
20421}
20422
20423ExprResult Sema::CheckLValueToRValueConversionOperand(Expr *E) {
20424 // Check whether the operand is or contains an object of non-trivial C union
20425 // type.
20426 if (E->getType().isVolatileQualified() &&
20427 (E->getType().hasNonTrivialToPrimitiveDestructCUnion() ||
20428 E->getType().hasNonTrivialToPrimitiveCopyCUnion()))
20429 checkNonTrivialCUnion(QT: E->getType(), Loc: E->getExprLoc(),
20430 UseContext: NonTrivialCUnionContext::LValueToRValueVolatile,
20431 NonTrivialKind: NTCUK_Destruct | NTCUK_Copy);
20432
20433 // C++2a [basic.def.odr]p4:
20434 // [...] an expression of non-volatile-qualified non-class type to which
20435 // the lvalue-to-rvalue conversion is applied [...]
20436 if (E->getType().isVolatileQualified() || E->getType()->isRecordType())
20437 return E;
20438
20439 ExprResult Result =
20440 rebuildPotentialResultsAsNonOdrUsed(S&: *this, E, NOUR: NOUR_Constant);
20441 if (Result.isInvalid())
20442 return ExprError();
20443 return Result.get() ? Result : E;
20444}
20445
20446ExprResult Sema::ActOnConstantExpression(ExprResult Res) {
20447 if (!Res.isUsable())
20448 return Res;
20449
20450 // If a constant-expression is a reference to a variable where we delay
20451 // deciding whether it is an odr-use, just assume we will apply the
20452 // lvalue-to-rvalue conversion. In the one case where this doesn't happen
20453 // (a non-type template argument), we have special handling anyway.
20454 return CheckLValueToRValueConversionOperand(E: Res.get());
20455}
20456
20457void Sema::CleanupVarDeclMarking() {
20458 // Iterate through a local copy in case MarkVarDeclODRUsed makes a recursive
20459 // call.
20460 MaybeODRUseExprSet LocalMaybeODRUseExprs;
20461 std::swap(LHS&: LocalMaybeODRUseExprs, RHS&: MaybeODRUseExprs);
20462
20463 for (Expr *E : LocalMaybeODRUseExprs) {
20464 if (auto *DRE = dyn_cast<DeclRefExpr>(Val: E)) {
20465 MarkVarDeclODRUsed(V: cast<VarDecl>(Val: DRE->getDecl()),
20466 Loc: DRE->getLocation(), SemaRef&: *this);
20467 } else if (auto *ME = dyn_cast<MemberExpr>(Val: E)) {
20468 MarkVarDeclODRUsed(V: cast<VarDecl>(Val: ME->getMemberDecl()), Loc: ME->getMemberLoc(),
20469 SemaRef&: *this);
20470 } else if (auto *FP = dyn_cast<FunctionParmPackExpr>(Val: E)) {
20471 for (ValueDecl *VD : *FP)
20472 MarkVarDeclODRUsed(V: VD, Loc: FP->getParameterPackLocation(), SemaRef&: *this);
20473 } else {
20474 llvm_unreachable("Unexpected expression");
20475 }
20476 }
20477
20478 assert(MaybeODRUseExprs.empty() &&
20479 "MarkVarDeclODRUsed failed to cleanup MaybeODRUseExprs?");
20480}
20481
20482static void DoMarkPotentialCapture(Sema &SemaRef, SourceLocation Loc,
20483 ValueDecl *Var, Expr *E) {
20484 VarDecl *VD = Var->getPotentiallyDecomposedVarDecl();
20485 if (!VD)
20486 return;
20487
20488 const bool RefersToEnclosingScope =
20489 (SemaRef.CurContext != VD->getDeclContext() &&
20490 VD->getDeclContext()->isFunctionOrMethod() && VD->hasLocalStorage());
20491 if (RefersToEnclosingScope) {
20492 LambdaScopeInfo *const LSI =
20493 SemaRef.getCurLambda(/*IgnoreNonLambdaCapturingScope=*/true);
20494 if (LSI && (!LSI->CallOperator ||
20495 !LSI->CallOperator->Encloses(DC: Var->getDeclContext()))) {
20496 // If a variable could potentially be odr-used, defer marking it so
20497 // until we finish analyzing the full expression for any
20498 // lvalue-to-rvalue
20499 // or discarded value conversions that would obviate odr-use.
20500 // Add it to the list of potential captures that will be analyzed
20501 // later (ActOnFinishFullExpr) for eventual capture and odr-use marking
20502 // unless the variable is a reference that was initialized by a constant
20503 // expression (this will never need to be captured or odr-used).
20504 //
20505 // FIXME: We can simplify this a lot after implementing P0588R1.
20506 assert(E && "Capture variable should be used in an expression.");
20507 if (!Var->getType()->isReferenceType() ||
20508 !VD->isUsableInConstantExpressions(C: SemaRef.Context))
20509 LSI->addPotentialCapture(VarExpr: E->IgnoreParens());
20510 }
20511 }
20512}
20513
20514static void DoMarkVarDeclReferenced(
20515 Sema &SemaRef, SourceLocation Loc, VarDecl *Var, Expr *E,
20516 llvm::DenseMap<const VarDecl *, int> &RefsMinusAssignments) {
20517 assert((!E || isa<DeclRefExpr>(E) || isa<MemberExpr>(E) ||
20518 isa<FunctionParmPackExpr>(E)) &&
20519 "Invalid Expr argument to DoMarkVarDeclReferenced");
20520 Var->setReferenced();
20521
20522 if (Var->isInvalidDecl())
20523 return;
20524
20525 auto *MSI = Var->getMemberSpecializationInfo();
20526 TemplateSpecializationKind TSK = MSI ? MSI->getTemplateSpecializationKind()
20527 : Var->getTemplateSpecializationKind();
20528
20529 OdrUseContext OdrUse = isOdrUseContext(SemaRef);
20530 bool UsableInConstantExpr =
20531 Var->mightBeUsableInConstantExpressions(C: SemaRef.Context);
20532
20533 // Only track variables with internal linkage or local scope.
20534 // Use canonical decl so in-class declarations and out-of-class definitions
20535 // of static data members in anonymous namespaces are tracked as a single
20536 // entry.
20537 const VarDecl *CanonVar = Var->getCanonicalDecl();
20538 if ((CanonVar->isLocalVarDeclOrParm() ||
20539 CanonVar->isInternalLinkageFileVar()) &&
20540 !CanonVar->hasExternalStorage()) {
20541 RefsMinusAssignments.insert(KV: {CanonVar, 0}).first->getSecond()++;
20542 }
20543
20544 // C++20 [expr.const]p12:
20545 // A variable [...] is needed for constant evaluation if it is [...] a
20546 // variable whose name appears as a potentially constant evaluated
20547 // expression that is either a contexpr variable or is of non-volatile
20548 // const-qualified integral type or of reference type
20549 bool NeededForConstantEvaluation =
20550 isPotentiallyConstantEvaluatedContext(SemaRef) && UsableInConstantExpr;
20551
20552 bool NeedDefinition =
20553 OdrUse == OdrUseContext::Used || NeededForConstantEvaluation ||
20554 (TSK != clang::TSK_Undeclared && !UsableInConstantExpr &&
20555 Var->getType()->isUndeducedType());
20556
20557 assert(!isa<VarTemplatePartialSpecializationDecl>(Var) &&
20558 "Can't instantiate a partial template specialization.");
20559
20560 // If this might be a member specialization of a static data member, check
20561 // the specialization is visible. We already did the checks for variable
20562 // template specializations when we created them.
20563 if (NeedDefinition && TSK != TSK_Undeclared &&
20564 !isa<VarTemplateSpecializationDecl>(Val: Var))
20565 SemaRef.checkSpecializationVisibility(Loc, Spec: Var);
20566
20567 // Perform implicit instantiation of static data members, static data member
20568 // templates of class templates, and variable template specializations. Delay
20569 // instantiations of variable templates, except for those that could be used
20570 // in a constant expression.
20571 if (NeedDefinition && isTemplateInstantiation(Kind: TSK)) {
20572 // Per C++17 [temp.explicit]p10, we may instantiate despite an explicit
20573 // instantiation declaration if a variable is usable in a constant
20574 // expression (among other cases).
20575 bool TryInstantiating =
20576 TSK == TSK_ImplicitInstantiation ||
20577 (TSK == TSK_ExplicitInstantiationDeclaration && UsableInConstantExpr);
20578
20579 if (TryInstantiating) {
20580 SourceLocation PointOfInstantiation =
20581 MSI ? MSI->getPointOfInstantiation() : Var->getPointOfInstantiation();
20582 bool FirstInstantiation = PointOfInstantiation.isInvalid();
20583 if (FirstInstantiation) {
20584 PointOfInstantiation = Loc;
20585 if (MSI)
20586 MSI->setPointOfInstantiation(PointOfInstantiation);
20587 // FIXME: Notify listener.
20588 else
20589 Var->setTemplateSpecializationKind(TSK, PointOfInstantiation);
20590 }
20591
20592 if (UsableInConstantExpr || Var->getType()->isUndeducedType()) {
20593 // Do not defer instantiations of variables that could be used in a
20594 // constant expression.
20595 // The type deduction also needs a complete initializer.
20596 SemaRef.runWithSufficientStackSpace(Loc: PointOfInstantiation, Fn: [&] {
20597 SemaRef.InstantiateVariableDefinition(PointOfInstantiation, Var);
20598 });
20599
20600 // The size of an incomplete array type can be updated by
20601 // instantiating the initializer. The DeclRefExpr's type should be
20602 // updated accordingly too, or users of it would be confused!
20603 if (E)
20604 SemaRef.getCompletedType(E);
20605
20606 // Re-set the member to trigger a recomputation of the dependence bits
20607 // for the expression.
20608 if (auto *DRE = dyn_cast_or_null<DeclRefExpr>(Val: E))
20609 DRE->setDecl(DRE->getDecl());
20610 else if (auto *ME = dyn_cast_or_null<MemberExpr>(Val: E))
20611 ME->setMemberDecl(ME->getMemberDecl());
20612 } else if (FirstInstantiation) {
20613 SemaRef.PendingInstantiations
20614 .push_back(x: std::make_pair(x&: Var, y&: PointOfInstantiation));
20615 } else {
20616 bool Inserted = false;
20617 for (auto &I : SemaRef.SavedPendingInstantiations) {
20618 auto Iter = llvm::find_if(
20619 Range&: I, P: [Var](const Sema::PendingImplicitInstantiation &P) {
20620 return P.first == Var;
20621 });
20622 if (Iter != I.end()) {
20623 SemaRef.PendingInstantiations.push_back(x: *Iter);
20624 I.erase(position: Iter);
20625 Inserted = true;
20626 break;
20627 }
20628 }
20629
20630 // FIXME: For a specialization of a variable template, we don't
20631 // distinguish between "declaration and type implicitly instantiated"
20632 // and "implicit instantiation of definition requested", so we have
20633 // no direct way to avoid enqueueing the pending instantiation
20634 // multiple times.
20635 if (isa<VarTemplateSpecializationDecl>(Val: Var) && !Inserted)
20636 SemaRef.PendingInstantiations
20637 .push_back(x: std::make_pair(x&: Var, y&: PointOfInstantiation));
20638 }
20639 }
20640 }
20641
20642 // C++2a [basic.def.odr]p4:
20643 // A variable x whose name appears as a potentially-evaluated expression e
20644 // is odr-used by e unless
20645 // -- x is a reference that is usable in constant expressions
20646 // -- x is a variable of non-reference type that is usable in constant
20647 // expressions and has no mutable subobjects [FIXME], and e is an
20648 // element of the set of potential results of an expression of
20649 // non-volatile-qualified non-class type to which the lvalue-to-rvalue
20650 // conversion is applied
20651 // -- x is a variable of non-reference type, and e is an element of the set
20652 // of potential results of a discarded-value expression to which the
20653 // lvalue-to-rvalue conversion is not applied [FIXME]
20654 //
20655 // We check the first part of the second bullet here, and
20656 // Sema::CheckLValueToRValueConversionOperand deals with the second part.
20657 // FIXME: To get the third bullet right, we need to delay this even for
20658 // variables that are not usable in constant expressions.
20659
20660 // If we already know this isn't an odr-use, there's nothing more to do.
20661 if (DeclRefExpr *DRE = dyn_cast_or_null<DeclRefExpr>(Val: E))
20662 if (DRE->isNonOdrUse())
20663 return;
20664 if (MemberExpr *ME = dyn_cast_or_null<MemberExpr>(Val: E))
20665 if (ME->isNonOdrUse())
20666 return;
20667
20668 switch (OdrUse) {
20669 case OdrUseContext::None:
20670 // In some cases, a variable may not have been marked unevaluated, if it
20671 // appears in a defaukt initializer.
20672 assert((!E || isa<FunctionParmPackExpr>(E) ||
20673 SemaRef.isUnevaluatedContext()) &&
20674 "missing non-odr-use marking for unevaluated decl ref");
20675 break;
20676
20677 case OdrUseContext::FormallyOdrUsed:
20678 // FIXME: Ignoring formal odr-uses results in incorrect lambda capture
20679 // behavior.
20680 break;
20681
20682 case OdrUseContext::Used:
20683 // If we might later find that this expression isn't actually an odr-use,
20684 // delay the marking.
20685 if (E && Var->isUsableInConstantExpressions(C: SemaRef.Context))
20686 SemaRef.MaybeODRUseExprs.insert(X: E);
20687 else
20688 MarkVarDeclODRUsed(V: Var, Loc, SemaRef);
20689 break;
20690
20691 case OdrUseContext::Dependent:
20692 // If this is a dependent context, we don't need to mark variables as
20693 // odr-used, but we may still need to track them for lambda capture.
20694 // FIXME: Do we also need to do this inside dependent typeid expressions
20695 // (which are modeled as unevaluated at this point)?
20696 DoMarkPotentialCapture(SemaRef, Loc, Var, E);
20697 break;
20698 }
20699}
20700
20701static void DoMarkBindingDeclReferenced(Sema &SemaRef, SourceLocation Loc,
20702 BindingDecl *BD, Expr *E) {
20703 BD->setReferenced();
20704
20705 if (BD->isInvalidDecl())
20706 return;
20707
20708 OdrUseContext OdrUse = isOdrUseContext(SemaRef);
20709 if (OdrUse == OdrUseContext::Used) {
20710 QualType CaptureType, DeclRefType;
20711 SemaRef.tryCaptureVariable(Var: BD, ExprLoc: Loc, Kind: TryCaptureKind::Implicit,
20712 /*EllipsisLoc*/ SourceLocation(),
20713 /*BuildAndDiagnose*/ true, CaptureType,
20714 DeclRefType,
20715 /*FunctionScopeIndexToStopAt*/ nullptr);
20716 } else if (OdrUse == OdrUseContext::Dependent) {
20717 DoMarkPotentialCapture(SemaRef, Loc, Var: BD, E);
20718 }
20719}
20720
20721void Sema::MarkVariableReferenced(SourceLocation Loc, VarDecl *Var) {
20722 DoMarkVarDeclReferenced(SemaRef&: *this, Loc, Var, E: nullptr, RefsMinusAssignments);
20723}
20724
20725// C++ [temp.dep.expr]p3:
20726// An id-expression is type-dependent if it contains:
20727// - an identifier associated by name lookup with an entity captured by copy
20728// in a lambda-expression that has an explicit object parameter whose type
20729// is dependent ([dcl.fct]),
20730static void FixDependencyOfIdExpressionsInLambdaWithDependentObjectParameter(
20731 Sema &SemaRef, ValueDecl *D, Expr *E) {
20732 auto *ID = dyn_cast<DeclRefExpr>(Val: E);
20733 if (!ID || ID->isTypeDependent() || !ID->refersToEnclosingVariableOrCapture())
20734 return;
20735
20736 // If any enclosing lambda with a dependent explicit object parameter either
20737 // explicitly captures the variable by value, or has a capture default of '='
20738 // and does not capture the variable by reference, then the type of the DRE
20739 // is dependent on the type of that lambda's explicit object parameter.
20740 auto IsDependent = [&]() {
20741 for (auto *Scope : llvm::reverse(C&: SemaRef.FunctionScopes)) {
20742 auto *LSI = dyn_cast<sema::LambdaScopeInfo>(Val: Scope);
20743 if (!LSI)
20744 continue;
20745
20746 if (LSI->Lambda && !LSI->Lambda->Encloses(DC: SemaRef.CurContext) &&
20747 LSI->AfterParameterList)
20748 return false;
20749
20750 const auto *MD = LSI->CallOperator;
20751 if (MD->getType().isNull())
20752 continue;
20753
20754 const auto *Ty = MD->getType()->getAs<FunctionProtoType>();
20755 if (!Ty || !MD->isExplicitObjectMemberFunction() ||
20756 !Ty->getParamType(i: 0)->isDependentType())
20757 continue;
20758
20759 if (auto *C = LSI->CaptureMap.count(Val: D) ? &LSI->getCapture(Var: D) : nullptr) {
20760 if (C->isCopyCapture())
20761 return true;
20762 continue;
20763 }
20764
20765 if (LSI->ImpCaptureStyle == LambdaScopeInfo::ImpCap_LambdaByval)
20766 return true;
20767 }
20768 return false;
20769 }();
20770
20771 ID->setCapturedByCopyInLambdaWithExplicitObjectParameter(
20772 Set: IsDependent, Context: SemaRef.getASTContext());
20773}
20774
20775static void
20776MarkExprReferenced(Sema &SemaRef, SourceLocation Loc, Decl *D, Expr *E,
20777 bool MightBeOdrUse,
20778 llvm::DenseMap<const VarDecl *, int> &RefsMinusAssignments) {
20779 if (SemaRef.OpenMP().isInOpenMPDeclareTargetContext())
20780 SemaRef.OpenMP().checkDeclIsAllowedInOpenMPTarget(E, D);
20781
20782 if (SemaRef.getLangOpts().OpenACC)
20783 SemaRef.OpenACC().CheckDeclReference(Loc, E, D);
20784
20785 if (VarDecl *Var = dyn_cast<VarDecl>(Val: D)) {
20786 DoMarkVarDeclReferenced(SemaRef, Loc, Var, E, RefsMinusAssignments);
20787 if (SemaRef.getLangOpts().CPlusPlus)
20788 FixDependencyOfIdExpressionsInLambdaWithDependentObjectParameter(SemaRef,
20789 D: Var, E);
20790 return;
20791 }
20792
20793 if (BindingDecl *Decl = dyn_cast<BindingDecl>(Val: D)) {
20794 DoMarkBindingDeclReferenced(SemaRef, Loc, BD: Decl, E);
20795 if (SemaRef.getLangOpts().CPlusPlus)
20796 FixDependencyOfIdExpressionsInLambdaWithDependentObjectParameter(SemaRef,
20797 D: Decl, E);
20798 return;
20799 }
20800 SemaRef.MarkAnyDeclReferenced(Loc, D, MightBeOdrUse);
20801
20802 // If this is a call to a method via a cast, also mark the method in the
20803 // derived class used in case codegen can devirtualize the call.
20804 const MemberExpr *ME = dyn_cast<MemberExpr>(Val: E);
20805 if (!ME)
20806 return;
20807 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Val: ME->getMemberDecl());
20808 if (!MD)
20809 return;
20810 // Only attempt to devirtualize if this is truly a virtual call.
20811 bool IsVirtualCall = MD->isVirtual() &&
20812 ME->performsVirtualDispatch(LO: SemaRef.getLangOpts());
20813 if (!IsVirtualCall)
20814 return;
20815
20816 // If it's possible to devirtualize the call, mark the called function
20817 // referenced.
20818 CXXMethodDecl *DM = MD->getDevirtualizedMethod(
20819 Base: ME->getBase(), IsAppleKext: SemaRef.getLangOpts().AppleKext);
20820 if (DM)
20821 SemaRef.MarkAnyDeclReferenced(Loc, D: DM, MightBeOdrUse);
20822}
20823
20824void Sema::MarkDeclRefReferenced(DeclRefExpr *E, const Expr *Base) {
20825 // [basic.def.odr] (CWG 1614)
20826 // A function is named by an expression or conversion [...]
20827 // unless it is a pure virtual function and either the expression is not an
20828 // id-expression naming the function with an explicitly qualified name or
20829 // the expression forms a pointer to member
20830 bool OdrUse = true;
20831 if (const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Val: E->getDecl()))
20832 if (Method->isVirtual() &&
20833 !Method->getDevirtualizedMethod(Base, IsAppleKext: getLangOpts().AppleKext))
20834 OdrUse = false;
20835
20836 if (auto *FD = dyn_cast<FunctionDecl>(Val: E->getDecl())) {
20837 if (!isUnevaluatedContext() && !isConstantEvaluatedContext() &&
20838 !isImmediateFunctionContext() &&
20839 !isCheckingDefaultArgumentOrInitializer() &&
20840 FD->isImmediateFunction() && !RebuildingImmediateInvocation &&
20841 !FD->isDependentContext())
20842 ExprEvalContexts.back().ReferenceToConsteval.insert(Ptr: E);
20843 }
20844 MarkExprReferenced(SemaRef&: *this, Loc: E->getLocation(), D: E->getDecl(), E, MightBeOdrUse: OdrUse,
20845 RefsMinusAssignments);
20846}
20847
20848void Sema::MarkMemberReferenced(MemberExpr *E) {
20849 // C++11 [basic.def.odr]p2:
20850 // A non-overloaded function whose name appears as a potentially-evaluated
20851 // expression or a member of a set of candidate functions, if selected by
20852 // overload resolution when referred to from a potentially-evaluated
20853 // expression, is odr-used, unless it is a pure virtual function and its
20854 // name is not explicitly qualified.
20855 bool MightBeOdrUse = true;
20856 if (E->performsVirtualDispatch(LO: getLangOpts())) {
20857 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Val: E->getMemberDecl()))
20858 if (Method->isPureVirtual())
20859 MightBeOdrUse = false;
20860 }
20861 SourceLocation Loc =
20862 E->getMemberLoc().isValid() ? E->getMemberLoc() : E->getBeginLoc();
20863 MarkExprReferenced(SemaRef&: *this, Loc, D: E->getMemberDecl(), E, MightBeOdrUse,
20864 RefsMinusAssignments);
20865}
20866
20867void Sema::MarkFunctionParmPackReferenced(FunctionParmPackExpr *E) {
20868 for (ValueDecl *VD : *E)
20869 MarkExprReferenced(SemaRef&: *this, Loc: E->getParameterPackLocation(), D: VD, E, MightBeOdrUse: true,
20870 RefsMinusAssignments);
20871}
20872
20873/// Perform marking for a reference to an arbitrary declaration. It
20874/// marks the declaration referenced, and performs odr-use checking for
20875/// functions and variables. This method should not be used when building a
20876/// normal expression which refers to a variable.
20877void Sema::MarkAnyDeclReferenced(SourceLocation Loc, Decl *D,
20878 bool MightBeOdrUse) {
20879 if (MightBeOdrUse) {
20880 if (auto *VD = dyn_cast<VarDecl>(Val: D)) {
20881 MarkVariableReferenced(Loc, Var: VD);
20882 return;
20883 }
20884 }
20885 if (auto *FD = dyn_cast<FunctionDecl>(Val: D)) {
20886 MarkFunctionReferenced(Loc, Func: FD, MightBeOdrUse);
20887 return;
20888 }
20889 D->setReferenced();
20890}
20891
20892namespace {
20893 // Mark all of the declarations used by a type as referenced.
20894 // FIXME: Not fully implemented yet! We need to have a better understanding
20895 // of when we're entering a context we should not recurse into.
20896 // FIXME: This is and EvaluatedExprMarker are more-or-less equivalent to
20897 // TreeTransforms rebuilding the type in a new context. Rather than
20898 // duplicating the TreeTransform logic, we should consider reusing it here.
20899 // Currently that causes problems when rebuilding LambdaExprs.
20900class MarkReferencedDecls : public DynamicRecursiveASTVisitor {
20901 Sema &S;
20902 SourceLocation Loc;
20903
20904public:
20905 MarkReferencedDecls(Sema &S, SourceLocation Loc) : S(S), Loc(Loc) {}
20906
20907 bool TraverseTemplateArgument(const TemplateArgument &Arg) override;
20908};
20909}
20910
20911bool MarkReferencedDecls::TraverseTemplateArgument(
20912 const TemplateArgument &Arg) {
20913 {
20914 // A non-type template argument is a constant-evaluated context.
20915 EnterExpressionEvaluationContext Evaluated(
20916 S, Sema::ExpressionEvaluationContext::ConstantEvaluated);
20917 if (Arg.getKind() == TemplateArgument::Declaration) {
20918 if (Decl *D = Arg.getAsDecl())
20919 S.MarkAnyDeclReferenced(Loc, D, MightBeOdrUse: true);
20920 } else if (Arg.getKind() == TemplateArgument::Expression) {
20921 S.MarkDeclarationsReferencedInExpr(E: Arg.getAsExpr(), SkipLocalVariables: false);
20922 }
20923 }
20924
20925 return DynamicRecursiveASTVisitor::TraverseTemplateArgument(Arg);
20926}
20927
20928void Sema::MarkDeclarationsReferencedInType(SourceLocation Loc, QualType T) {
20929 MarkReferencedDecls Marker(*this, Loc);
20930 Marker.TraverseType(T);
20931}
20932
20933namespace {
20934/// Helper class that marks all of the declarations referenced by
20935/// potentially-evaluated subexpressions as "referenced".
20936class EvaluatedExprMarker : public UsedDeclVisitor<EvaluatedExprMarker> {
20937public:
20938 typedef UsedDeclVisitor<EvaluatedExprMarker> Inherited;
20939 bool SkipLocalVariables;
20940 ArrayRef<const Expr *> StopAt;
20941
20942 EvaluatedExprMarker(Sema &S, bool SkipLocalVariables,
20943 ArrayRef<const Expr *> StopAt)
20944 : Inherited(S), SkipLocalVariables(SkipLocalVariables), StopAt(StopAt) {}
20945
20946 void visitUsedDecl(SourceLocation Loc, Decl *D) {
20947 S.MarkFunctionReferenced(Loc, Func: cast<FunctionDecl>(Val: D));
20948 }
20949
20950 void Visit(Expr *E) {
20951 if (llvm::is_contained(Range&: StopAt, Element: E))
20952 return;
20953 Inherited::Visit(S: E);
20954 }
20955
20956 void VisitConstantExpr(ConstantExpr *E) {
20957 // Don't mark declarations within a ConstantExpression, as this expression
20958 // will be evaluated and folded to a value.
20959 }
20960
20961 void VisitDeclRefExpr(DeclRefExpr *E) {
20962 // If we were asked not to visit local variables, don't.
20963 if (SkipLocalVariables) {
20964 if (VarDecl *VD = dyn_cast<VarDecl>(Val: E->getDecl()))
20965 if (VD->hasLocalStorage())
20966 return;
20967 }
20968
20969 // FIXME: This can trigger the instantiation of the initializer of a
20970 // variable, which can cause the expression to become value-dependent
20971 // or error-dependent. Do we need to propagate the new dependence bits?
20972 S.MarkDeclRefReferenced(E);
20973 }
20974
20975 void VisitMemberExpr(MemberExpr *E) {
20976 S.MarkMemberReferenced(E);
20977 Visit(E: E->getBase());
20978 }
20979};
20980} // namespace
20981
20982void Sema::MarkDeclarationsReferencedInExpr(Expr *E,
20983 bool SkipLocalVariables,
20984 ArrayRef<const Expr*> StopAt) {
20985 EvaluatedExprMarker(*this, SkipLocalVariables, StopAt).Visit(E);
20986}
20987
20988/// Emit a diagnostic when statements are reachable.
20989bool Sema::DiagIfReachable(SourceLocation Loc, ArrayRef<const Stmt *> Stmts,
20990 const PartialDiagnostic &PD) {
20991 VarDecl *Decl = ExprEvalContexts.back().DeclForInitializer;
20992 // The initializer of a constexpr variable or of the first declaration of a
20993 // static data member is not syntactically a constant evaluated constant,
20994 // but nonetheless is always required to be a constant expression, so we
20995 // can skip diagnosing.
20996 if (Decl &&
20997 (Decl->isConstexpr() || (Decl->isStaticDataMember() &&
20998 Decl->isFirstDecl() && !Decl->isInline())))
20999 return false;
21000
21001 if (Stmts.empty()) {
21002 Diag(Loc, PD);
21003 return true;
21004 }
21005
21006 if (getCurFunction()) {
21007 FunctionScopes.back()->PossiblyUnreachableDiags.push_back(
21008 Elt: sema::PossiblyUnreachableDiag(PD, Loc, Stmts));
21009 return true;
21010 }
21011
21012 // For non-constexpr file-scope variables with reachability context (non-empty
21013 // Stmts), build a CFG for the initializer and check whether the context in
21014 // question is reachable.
21015 if (Decl && Decl->isFileVarDecl()) {
21016 AnalysisWarnings.registerVarDeclWarning(
21017 VD: Decl, PUD: sema::PossiblyUnreachableDiag(PD, Loc, Stmts));
21018 return true;
21019 }
21020
21021 Diag(Loc, PD);
21022 return true;
21023}
21024
21025/// Emit a diagnostic that describes an effect on the run-time behavior
21026/// of the program being compiled.
21027///
21028/// This routine emits the given diagnostic when the code currently being
21029/// type-checked is "potentially evaluated", meaning that there is a
21030/// possibility that the code will actually be executable. Code in sizeof()
21031/// expressions, code used only during overload resolution, etc., are not
21032/// potentially evaluated. This routine will suppress such diagnostics or,
21033/// in the absolutely nutty case of potentially potentially evaluated
21034/// expressions (C++ typeid), queue the diagnostic to potentially emit it
21035/// later.
21036///
21037/// This routine should be used for all diagnostics that describe the run-time
21038/// behavior of a program, such as passing a non-POD value through an ellipsis.
21039/// Failure to do so will likely result in spurious diagnostics or failures
21040/// during overload resolution or within sizeof/alignof/typeof/typeid.
21041bool Sema::DiagRuntimeBehavior(SourceLocation Loc, ArrayRef<const Stmt*> Stmts,
21042 const PartialDiagnostic &PD) {
21043
21044 if (ExprEvalContexts.back().isDiscardedStatementContext())
21045 return false;
21046
21047 switch (ExprEvalContexts.back().Context) {
21048 case ExpressionEvaluationContext::Unevaluated:
21049 case ExpressionEvaluationContext::UnevaluatedList:
21050 case ExpressionEvaluationContext::UnevaluatedAbstract:
21051 case ExpressionEvaluationContext::DiscardedStatement:
21052 // The argument will never be evaluated, so don't complain.
21053 break;
21054
21055 case ExpressionEvaluationContext::ConstantEvaluated:
21056 case ExpressionEvaluationContext::ImmediateFunctionContext:
21057 // Relevant diagnostics should be produced by constant evaluation.
21058 break;
21059
21060 case ExpressionEvaluationContext::PotentiallyEvaluated:
21061 case ExpressionEvaluationContext::PotentiallyEvaluatedIfUsed:
21062 return DiagIfReachable(Loc, Stmts, PD);
21063 }
21064
21065 return false;
21066}
21067
21068bool Sema::DiagRuntimeBehavior(SourceLocation Loc, const Stmt *Statement,
21069 const PartialDiagnostic &PD) {
21070 return DiagRuntimeBehavior(
21071 Loc, Stmts: Statement ? llvm::ArrayRef(Statement) : llvm::ArrayRef<Stmt *>(),
21072 PD);
21073}
21074
21075bool Sema::CheckCallReturnType(QualType ReturnType, SourceLocation Loc,
21076 CallExpr *CE, FunctionDecl *FD) {
21077 if (ReturnType->isVoidType() || !ReturnType->isIncompleteType())
21078 return false;
21079
21080 // If we're inside a decltype's expression, don't check for a valid return
21081 // type or construct temporaries until we know whether this is the last call.
21082 if (ExprEvalContexts.back().ExprContext ==
21083 ExpressionEvaluationContextRecord::EK_Decltype) {
21084 ExprEvalContexts.back().DelayedDecltypeCalls.push_back(Elt: CE);
21085 return false;
21086 }
21087
21088 class CallReturnIncompleteDiagnoser : public TypeDiagnoser {
21089 FunctionDecl *FD;
21090 CallExpr *CE;
21091
21092 public:
21093 CallReturnIncompleteDiagnoser(FunctionDecl *FD, CallExpr *CE)
21094 : FD(FD), CE(CE) { }
21095
21096 void diagnose(Sema &S, SourceLocation Loc, QualType T) override {
21097 if (!FD) {
21098 S.Diag(Loc, DiagID: diag::err_call_incomplete_return)
21099 << T << CE->getSourceRange();
21100 return;
21101 }
21102
21103 S.Diag(Loc, DiagID: diag::err_call_function_incomplete_return)
21104 << CE->getSourceRange() << FD << T;
21105 S.Diag(Loc: FD->getLocation(), DiagID: diag::note_entity_declared_at)
21106 << FD->getDeclName();
21107 }
21108 } Diagnoser(FD, CE);
21109
21110 if (RequireCompleteType(Loc, T: ReturnType, Diagnoser))
21111 return true;
21112
21113 return false;
21114}
21115
21116// Diagnose the s/=/==/ and s/\|=/!=/ typos. Note that adding parentheses
21117// will prevent this condition from triggering, which is what we want.
21118void Sema::DiagnoseAssignmentAsCondition(Expr *E) {
21119 SourceLocation Loc;
21120
21121 unsigned diagnostic = diag::warn_condition_is_assignment;
21122 bool IsOrAssign = false;
21123
21124 if (BinaryOperator *Op = dyn_cast<BinaryOperator>(Val: E)) {
21125 if (Op->getOpcode() != BO_Assign && Op->getOpcode() != BO_OrAssign)
21126 return;
21127
21128 IsOrAssign = Op->getOpcode() == BO_OrAssign;
21129
21130 // Greylist some idioms by putting them into a warning subcategory.
21131 if (ObjCMessageExpr *ME
21132 = dyn_cast<ObjCMessageExpr>(Val: Op->getRHS()->IgnoreParenCasts())) {
21133 Selector Sel = ME->getSelector();
21134
21135 // self = [<foo> init...]
21136 if (ObjC().isSelfExpr(RExpr: Op->getLHS()) && ME->getMethodFamily() == OMF_init)
21137 diagnostic = diag::warn_condition_is_idiomatic_assignment;
21138
21139 // <foo> = [<bar> nextObject]
21140 else if (Sel.isUnarySelector() && Sel.getNameForSlot(argIndex: 0) == "nextObject")
21141 diagnostic = diag::warn_condition_is_idiomatic_assignment;
21142 }
21143
21144 Loc = Op->getOperatorLoc();
21145 } else if (CXXOperatorCallExpr *Op = dyn_cast<CXXOperatorCallExpr>(Val: E)) {
21146 if (Op->getOperator() != OO_Equal && Op->getOperator() != OO_PipeEqual)
21147 return;
21148
21149 IsOrAssign = Op->getOperator() == OO_PipeEqual;
21150 Loc = Op->getOperatorLoc();
21151 } else if (PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(Val: E))
21152 return DiagnoseAssignmentAsCondition(E: POE->getSyntacticForm());
21153 else {
21154 // Not an assignment.
21155 return;
21156 }
21157
21158 Diag(Loc, DiagID: diagnostic) << E->getSourceRange();
21159
21160 SourceLocation Open = E->getBeginLoc();
21161 SourceLocation Close = getLocForEndOfToken(Loc: E->getSourceRange().getEnd());
21162 Diag(Loc, DiagID: diag::note_condition_assign_silence)
21163 << FixItHint::CreateInsertion(InsertionLoc: Open, Code: "(")
21164 << FixItHint::CreateInsertion(InsertionLoc: Close, Code: ")");
21165
21166 if (IsOrAssign)
21167 Diag(Loc, DiagID: diag::note_condition_or_assign_to_comparison)
21168 << FixItHint::CreateReplacement(RemoveRange: Loc, Code: "!=");
21169 else
21170 Diag(Loc, DiagID: diag::note_condition_assign_to_comparison)
21171 << FixItHint::CreateReplacement(RemoveRange: Loc, Code: "==");
21172}
21173
21174void Sema::DiagnoseEqualityWithExtraParens(ParenExpr *ParenE) {
21175 // Don't warn if the parens came from a macro.
21176 SourceLocation parenLoc = ParenE->getBeginLoc();
21177 if (parenLoc.isInvalid() || parenLoc.isMacroID())
21178 return;
21179 // Don't warn for dependent expressions.
21180 if (ParenE->isTypeDependent())
21181 return;
21182
21183 Expr *E = ParenE->IgnoreParens();
21184 if (ParenE->isProducedByFoldExpansion() && ParenE->getSubExpr() == E)
21185 return;
21186
21187 if (BinaryOperator *opE = dyn_cast<BinaryOperator>(Val: E))
21188 if (opE->getOpcode() == BO_EQ &&
21189 opE->getLHS()->IgnoreParenImpCasts()->isModifiableLvalue(Ctx&: Context)
21190 == Expr::MLV_Valid) {
21191 SourceLocation Loc = opE->getOperatorLoc();
21192
21193 Diag(Loc, DiagID: diag::warn_equality_with_extra_parens) << E->getSourceRange();
21194 SourceRange ParenERange = ParenE->getSourceRange();
21195 Diag(Loc, DiagID: diag::note_equality_comparison_silence)
21196 << FixItHint::CreateRemoval(RemoveRange: ParenERange.getBegin())
21197 << FixItHint::CreateRemoval(RemoveRange: ParenERange.getEnd());
21198 Diag(Loc, DiagID: diag::note_equality_comparison_to_assign)
21199 << FixItHint::CreateReplacement(RemoveRange: Loc, Code: "=");
21200 }
21201}
21202
21203ExprResult Sema::CheckBooleanCondition(SourceLocation Loc, Expr *E,
21204 bool IsConstexpr) {
21205 DiagnoseAssignmentAsCondition(E);
21206 if (ParenExpr *parenE = dyn_cast<ParenExpr>(Val: E))
21207 DiagnoseEqualityWithExtraParens(ParenE: parenE);
21208
21209 ExprResult result = CheckPlaceholderExpr(E);
21210 if (result.isInvalid()) return ExprError();
21211 E = result.get();
21212
21213 if (!E->isTypeDependent()) {
21214 if (E->getType() == Context.AMDGPUFeaturePredicateTy)
21215 return AMDGPU().ExpandAMDGPUPredicateBuiltIn(CE: E);
21216
21217 if (getLangOpts().CPlusPlus)
21218 return CheckCXXBooleanCondition(CondExpr: E, IsConstexpr); // C++ 6.4p4
21219
21220 ExprResult ERes = DefaultFunctionArrayLvalueConversion(E);
21221 if (ERes.isInvalid())
21222 return ExprError();
21223 E = ERes.get();
21224
21225 QualType T = E->getType();
21226 if (!T->isScalarType()) { // C99 6.8.4.1p1
21227 Diag(Loc, DiagID: diag::err_typecheck_statement_requires_scalar)
21228 << T << E->getSourceRange();
21229 return ExprError();
21230 }
21231 CheckBoolLikeConversion(E, CC: Loc);
21232 }
21233
21234 return E;
21235}
21236
21237Sema::ConditionResult Sema::ActOnCondition(Scope *S, SourceLocation Loc,
21238 Expr *SubExpr, ConditionKind CK,
21239 bool MissingOK) {
21240 // MissingOK indicates whether having no condition expression is valid
21241 // (for loop) or invalid (e.g. while loop).
21242 if (!SubExpr)
21243 return MissingOK ? ConditionResult() : ConditionError();
21244
21245 ExprResult Cond;
21246 switch (CK) {
21247 case ConditionKind::Boolean:
21248 Cond = CheckBooleanCondition(Loc, E: SubExpr);
21249 break;
21250
21251 case ConditionKind::ConstexprIf:
21252 // Note: this might produce a FullExpr
21253 Cond = CheckBooleanCondition(Loc, E: SubExpr, IsConstexpr: true);
21254 break;
21255
21256 case ConditionKind::Switch:
21257 Cond = CheckSwitchCondition(SwitchLoc: Loc, Cond: SubExpr);
21258 break;
21259 }
21260 if (Cond.isInvalid()) {
21261 Cond = CreateRecoveryExpr(Begin: SubExpr->getBeginLoc(), End: SubExpr->getEndLoc(),
21262 SubExprs: {SubExpr}, T: PreferredConditionType(K: CK));
21263 if (!Cond.get())
21264 return ConditionError();
21265 } else if (Cond.isUsable() && !isa<FullExpr>(Val: Cond.get()))
21266 Cond = ActOnFinishFullExpr(Expr: Cond.get(), CC: Loc, /*DiscardedValue*/ false);
21267
21268 if (!Cond.isUsable())
21269 return ConditionError();
21270
21271 return ConditionResult(*this, nullptr, Cond,
21272 CK == ConditionKind::ConstexprIf);
21273}
21274
21275namespace {
21276 /// A visitor for rebuilding a call to an __unknown_any expression
21277 /// to have an appropriate type.
21278 struct RebuildUnknownAnyFunction
21279 : StmtVisitor<RebuildUnknownAnyFunction, ExprResult> {
21280
21281 Sema &S;
21282
21283 RebuildUnknownAnyFunction(Sema &S) : S(S) {}
21284
21285 ExprResult VisitStmt(Stmt *S) {
21286 llvm_unreachable("unexpected statement!");
21287 }
21288
21289 ExprResult VisitExpr(Expr *E) {
21290 S.Diag(Loc: E->getExprLoc(), DiagID: diag::err_unsupported_unknown_any_call)
21291 << E->getSourceRange();
21292 return ExprError();
21293 }
21294
21295 /// Rebuild an expression which simply semantically wraps another
21296 /// expression which it shares the type and value kind of.
21297 template <class T> ExprResult rebuildSugarExpr(T *E) {
21298 ExprResult SubResult = Visit(S: E->getSubExpr());
21299 if (SubResult.isInvalid()) return ExprError();
21300
21301 Expr *SubExpr = SubResult.get();
21302 E->setSubExpr(SubExpr);
21303 E->setType(SubExpr->getType());
21304 E->setValueKind(SubExpr->getValueKind());
21305 assert(E->getObjectKind() == OK_Ordinary);
21306 return E;
21307 }
21308
21309 ExprResult VisitParenExpr(ParenExpr *E) {
21310 return rebuildSugarExpr(E);
21311 }
21312
21313 ExprResult VisitUnaryExtension(UnaryOperator *E) {
21314 return rebuildSugarExpr(E);
21315 }
21316
21317 ExprResult VisitUnaryAddrOf(UnaryOperator *E) {
21318 ExprResult SubResult = Visit(S: E->getSubExpr());
21319 if (SubResult.isInvalid()) return ExprError();
21320
21321 Expr *SubExpr = SubResult.get();
21322 E->setSubExpr(SubExpr);
21323 E->setType(S.Context.getPointerType(T: SubExpr->getType()));
21324 assert(E->isPRValue());
21325 assert(E->getObjectKind() == OK_Ordinary);
21326 return E;
21327 }
21328
21329 ExprResult resolveDecl(Expr *E, ValueDecl *VD) {
21330 if (!isa<FunctionDecl>(Val: VD)) return VisitExpr(E);
21331
21332 E->setType(VD->getType());
21333
21334 assert(E->isPRValue());
21335 if (S.getLangOpts().CPlusPlus &&
21336 !(isa<CXXMethodDecl>(Val: VD) &&
21337 cast<CXXMethodDecl>(Val: VD)->isInstance()))
21338 E->setValueKind(VK_LValue);
21339
21340 return E;
21341 }
21342
21343 ExprResult VisitMemberExpr(MemberExpr *E) {
21344 return resolveDecl(E, VD: E->getMemberDecl());
21345 }
21346
21347 ExprResult VisitDeclRefExpr(DeclRefExpr *E) {
21348 return resolveDecl(E, VD: E->getDecl());
21349 }
21350 };
21351}
21352
21353/// Given a function expression of unknown-any type, try to rebuild it
21354/// to have a function type.
21355static ExprResult rebuildUnknownAnyFunction(Sema &S, Expr *FunctionExpr) {
21356 ExprResult Result = RebuildUnknownAnyFunction(S).Visit(S: FunctionExpr);
21357 if (Result.isInvalid()) return ExprError();
21358 return S.DefaultFunctionArrayConversion(E: Result.get());
21359}
21360
21361namespace {
21362 /// A visitor for rebuilding an expression of type __unknown_anytype
21363 /// into one which resolves the type directly on the referring
21364 /// expression. Strict preservation of the original source
21365 /// structure is not a goal.
21366 struct RebuildUnknownAnyExpr
21367 : StmtVisitor<RebuildUnknownAnyExpr, ExprResult> {
21368
21369 Sema &S;
21370
21371 /// The current destination type.
21372 QualType DestType;
21373
21374 RebuildUnknownAnyExpr(Sema &S, QualType CastType)
21375 : S(S), DestType(CastType) {}
21376
21377 ExprResult VisitStmt(Stmt *S) {
21378 llvm_unreachable("unexpected statement!");
21379 }
21380
21381 ExprResult VisitExpr(Expr *E) {
21382 S.Diag(Loc: E->getExprLoc(), DiagID: diag::err_unsupported_unknown_any_expr)
21383 << E->getSourceRange();
21384 return ExprError();
21385 }
21386
21387 ExprResult VisitCallExpr(CallExpr *E);
21388 ExprResult VisitObjCMessageExpr(ObjCMessageExpr *E);
21389
21390 /// Rebuild an expression which simply semantically wraps another
21391 /// expression which it shares the type and value kind of.
21392 template <class T> ExprResult rebuildSugarExpr(T *E) {
21393 ExprResult SubResult = Visit(S: E->getSubExpr());
21394 if (SubResult.isInvalid()) return ExprError();
21395 Expr *SubExpr = SubResult.get();
21396 E->setSubExpr(SubExpr);
21397 E->setType(SubExpr->getType());
21398 E->setValueKind(SubExpr->getValueKind());
21399 assert(E->getObjectKind() == OK_Ordinary);
21400 return E;
21401 }
21402
21403 ExprResult VisitParenExpr(ParenExpr *E) {
21404 return rebuildSugarExpr(E);
21405 }
21406
21407 ExprResult VisitUnaryExtension(UnaryOperator *E) {
21408 return rebuildSugarExpr(E);
21409 }
21410
21411 ExprResult VisitUnaryAddrOf(UnaryOperator *E) {
21412 const PointerType *Ptr = DestType->getAs<PointerType>();
21413 if (!Ptr) {
21414 S.Diag(Loc: E->getOperatorLoc(), DiagID: diag::err_unknown_any_addrof)
21415 << E->getSourceRange();
21416 return ExprError();
21417 }
21418
21419 if (isa<CallExpr>(Val: E->getSubExpr())) {
21420 S.Diag(Loc: E->getOperatorLoc(), DiagID: diag::err_unknown_any_addrof_call)
21421 << E->getSourceRange();
21422 return ExprError();
21423 }
21424
21425 assert(E->isPRValue());
21426 assert(E->getObjectKind() == OK_Ordinary);
21427 E->setType(DestType);
21428
21429 // Build the sub-expression as if it were an object of the pointee type.
21430 DestType = Ptr->getPointeeType();
21431 ExprResult SubResult = Visit(S: E->getSubExpr());
21432 if (SubResult.isInvalid()) return ExprError();
21433 E->setSubExpr(SubResult.get());
21434 return E;
21435 }
21436
21437 ExprResult VisitImplicitCastExpr(ImplicitCastExpr *E);
21438
21439 ExprResult resolveDecl(Expr *E, ValueDecl *VD);
21440
21441 ExprResult VisitMemberExpr(MemberExpr *E) {
21442 return resolveDecl(E, VD: E->getMemberDecl());
21443 }
21444
21445 ExprResult VisitDeclRefExpr(DeclRefExpr *E) {
21446 return resolveDecl(E, VD: E->getDecl());
21447 }
21448 };
21449}
21450
21451/// Rebuilds a call expression which yielded __unknown_anytype.
21452ExprResult RebuildUnknownAnyExpr::VisitCallExpr(CallExpr *E) {
21453 Expr *CalleeExpr = E->getCallee();
21454
21455 enum FnKind {
21456 FK_MemberFunction,
21457 FK_FunctionPointer,
21458 FK_BlockPointer
21459 };
21460
21461 FnKind Kind;
21462 QualType CalleeType = CalleeExpr->getType();
21463 if (CalleeType == S.Context.BoundMemberTy) {
21464 assert(isa<CXXMemberCallExpr>(E) || isa<CXXOperatorCallExpr>(E));
21465 Kind = FK_MemberFunction;
21466 CalleeType = Expr::findBoundMemberType(expr: CalleeExpr);
21467 } else if (const PointerType *Ptr = CalleeType->getAs<PointerType>()) {
21468 CalleeType = Ptr->getPointeeType();
21469 Kind = FK_FunctionPointer;
21470 } else {
21471 CalleeType = CalleeType->castAs<BlockPointerType>()->getPointeeType();
21472 Kind = FK_BlockPointer;
21473 }
21474 const FunctionType *FnType = CalleeType->castAs<FunctionType>();
21475
21476 // Verify that this is a legal result type of a function.
21477 if ((DestType->isArrayType() && !S.getLangOpts().allowArrayReturnTypes()) ||
21478 DestType->isFunctionType()) {
21479 unsigned diagID = diag::err_func_returning_array_function;
21480 if (Kind == FK_BlockPointer)
21481 diagID = diag::err_block_returning_array_function;
21482
21483 S.Diag(Loc: E->getExprLoc(), DiagID: diagID)
21484 << DestType->isFunctionType() << DestType;
21485 return ExprError();
21486 }
21487
21488 // Otherwise, go ahead and set DestType as the call's result.
21489 E->setType(DestType.getNonLValueExprType(Context: S.Context));
21490 E->setValueKind(Expr::getValueKindForType(T: DestType));
21491 assert(E->getObjectKind() == OK_Ordinary);
21492
21493 // Rebuild the function type, replacing the result type with DestType.
21494 const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(Val: FnType);
21495 if (Proto) {
21496 // __unknown_anytype(...) is a special case used by the debugger when
21497 // it has no idea what a function's signature is.
21498 //
21499 // We want to build this call essentially under the K&R
21500 // unprototyped rules, but making a FunctionNoProtoType in C++
21501 // would foul up all sorts of assumptions. However, we cannot
21502 // simply pass all arguments as variadic arguments, nor can we
21503 // portably just call the function under a non-variadic type; see
21504 // the comment on IR-gen's TargetInfo::isNoProtoCallVariadic.
21505 // However, it turns out that in practice it is generally safe to
21506 // call a function declared as "A foo(B,C,D);" under the prototype
21507 // "A foo(B,C,D,...);". The only known exception is with the
21508 // Windows ABI, where any variadic function is implicitly cdecl
21509 // regardless of its normal CC. Therefore we change the parameter
21510 // types to match the types of the arguments.
21511 //
21512 // This is a hack, but it is far superior to moving the
21513 // corresponding target-specific code from IR-gen to Sema/AST.
21514
21515 ArrayRef<QualType> ParamTypes = Proto->getParamTypes();
21516 SmallVector<QualType, 8> ArgTypes;
21517 if (ParamTypes.empty() && Proto->isVariadic()) { // the special case
21518 ArgTypes.reserve(N: E->getNumArgs());
21519 for (unsigned i = 0, e = E->getNumArgs(); i != e; ++i) {
21520 ArgTypes.push_back(Elt: S.Context.getReferenceQualifiedType(e: E->getArg(Arg: i)));
21521 }
21522 ParamTypes = ArgTypes;
21523 }
21524 DestType = S.Context.getFunctionType(ResultTy: DestType, Args: ParamTypes,
21525 EPI: Proto->getExtProtoInfo());
21526 } else {
21527 DestType = S.Context.getFunctionNoProtoType(ResultTy: DestType,
21528 Info: FnType->getExtInfo());
21529 }
21530
21531 // Rebuild the appropriate pointer-to-function type.
21532 switch (Kind) {
21533 case FK_MemberFunction:
21534 // Nothing to do.
21535 break;
21536
21537 case FK_FunctionPointer:
21538 DestType = S.Context.getPointerType(T: DestType);
21539 break;
21540
21541 case FK_BlockPointer:
21542 DestType = S.Context.getBlockPointerType(T: DestType);
21543 break;
21544 }
21545
21546 // Finally, we can recurse.
21547 ExprResult CalleeResult = Visit(S: CalleeExpr);
21548 if (!CalleeResult.isUsable()) return ExprError();
21549 E->setCallee(CalleeResult.get());
21550
21551 // Bind a temporary if necessary.
21552 return S.MaybeBindToTemporary(E);
21553}
21554
21555ExprResult RebuildUnknownAnyExpr::VisitObjCMessageExpr(ObjCMessageExpr *E) {
21556 // Verify that this is a legal result type of a call.
21557 if (DestType->isArrayType() || DestType->isFunctionType()) {
21558 S.Diag(Loc: E->getExprLoc(), DiagID: diag::err_func_returning_array_function)
21559 << DestType->isFunctionType() << DestType;
21560 return ExprError();
21561 }
21562
21563 // Rewrite the method result type if available.
21564 if (ObjCMethodDecl *Method = E->getMethodDecl()) {
21565 assert(Method->getReturnType() == S.Context.UnknownAnyTy);
21566 Method->setReturnType(DestType);
21567 }
21568
21569 // Change the type of the message.
21570 E->setType(DestType.getNonReferenceType());
21571 E->setValueKind(Expr::getValueKindForType(T: DestType));
21572
21573 return S.MaybeBindToTemporary(E);
21574}
21575
21576ExprResult RebuildUnknownAnyExpr::VisitImplicitCastExpr(ImplicitCastExpr *E) {
21577 // The only case we should ever see here is a function-to-pointer decay.
21578 if (E->getCastKind() == CK_FunctionToPointerDecay) {
21579 assert(E->isPRValue());
21580 assert(E->getObjectKind() == OK_Ordinary);
21581
21582 E->setType(DestType);
21583
21584 // Rebuild the sub-expression as the pointee (function) type.
21585 DestType = DestType->castAs<PointerType>()->getPointeeType();
21586
21587 ExprResult Result = Visit(S: E->getSubExpr());
21588 if (!Result.isUsable()) return ExprError();
21589
21590 E->setSubExpr(Result.get());
21591 return E;
21592 } else if (E->getCastKind() == CK_LValueToRValue) {
21593 assert(E->isPRValue());
21594 assert(E->getObjectKind() == OK_Ordinary);
21595
21596 assert(isa<BlockPointerType>(E->getType()));
21597
21598 E->setType(DestType);
21599
21600 // The sub-expression has to be a lvalue reference, so rebuild it as such.
21601 DestType = S.Context.getLValueReferenceType(T: DestType);
21602
21603 ExprResult Result = Visit(S: E->getSubExpr());
21604 if (!Result.isUsable()) return ExprError();
21605
21606 E->setSubExpr(Result.get());
21607 return E;
21608 } else {
21609 llvm_unreachable("Unhandled cast type!");
21610 }
21611}
21612
21613ExprResult RebuildUnknownAnyExpr::resolveDecl(Expr *E, ValueDecl *VD) {
21614 ExprValueKind ValueKind = VK_LValue;
21615 QualType Type = DestType;
21616
21617 // We know how to make this work for certain kinds of decls:
21618
21619 // - functions
21620 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Val: VD)) {
21621 if (const PointerType *Ptr = Type->getAs<PointerType>()) {
21622 DestType = Ptr->getPointeeType();
21623 ExprResult Result = resolveDecl(E, VD);
21624 if (Result.isInvalid()) return ExprError();
21625 return S.ImpCastExprToType(E: Result.get(), Type, CK: CK_FunctionToPointerDecay,
21626 VK: VK_PRValue);
21627 }
21628
21629 if (!Type->isFunctionType()) {
21630 S.Diag(Loc: E->getExprLoc(), DiagID: diag::err_unknown_any_function)
21631 << VD << E->getSourceRange();
21632 return ExprError();
21633 }
21634 if (const FunctionProtoType *FT = Type->getAs<FunctionProtoType>()) {
21635 // We must match the FunctionDecl's type to the hack introduced in
21636 // RebuildUnknownAnyExpr::VisitCallExpr to vararg functions of unknown
21637 // type. See the lengthy commentary in that routine.
21638 QualType FDT = FD->getType();
21639 const FunctionType *FnType = FDT->castAs<FunctionType>();
21640 const FunctionProtoType *Proto = dyn_cast_or_null<FunctionProtoType>(Val: FnType);
21641 DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Val: E);
21642 if (DRE && Proto && Proto->getParamTypes().empty() && Proto->isVariadic()) {
21643 SourceLocation Loc = FD->getLocation();
21644 FunctionDecl *NewFD = FunctionDecl::Create(
21645 C&: S.Context, DC: FD->getDeclContext(), StartLoc: Loc, NLoc: Loc,
21646 N: FD->getNameInfo().getName(), T: DestType, TInfo: FD->getTypeSourceInfo(),
21647 SC: SC_None, UsesFPIntrin: S.getCurFPFeatures().isFPConstrained(),
21648 isInlineSpecified: false /*isInlineSpecified*/, hasWrittenPrototype: FD->hasPrototype(),
21649 /*ConstexprKind*/ ConstexprSpecKind::Unspecified);
21650
21651 if (FD->getQualifier())
21652 NewFD->setQualifierInfo(FD->getQualifierLoc());
21653
21654 SmallVector<ParmVarDecl*, 16> Params;
21655 for (const auto &AI : FT->param_types()) {
21656 ParmVarDecl *Param =
21657 S.BuildParmVarDeclForTypedef(DC: FD, Loc, T: AI);
21658 Param->setScopeInfo(scopeDepth: 0, parameterIndex: Params.size());
21659 Params.push_back(Elt: Param);
21660 }
21661 NewFD->setParams(Params);
21662 DRE->setDecl(NewFD);
21663 VD = DRE->getDecl();
21664 }
21665 }
21666
21667 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Val: FD))
21668 if (MD->isInstance()) {
21669 ValueKind = VK_PRValue;
21670 Type = S.Context.BoundMemberTy;
21671 }
21672
21673 // Function references aren't l-values in C.
21674 if (!S.getLangOpts().CPlusPlus)
21675 ValueKind = VK_PRValue;
21676
21677 // - variables
21678 } else if (isa<VarDecl>(Val: VD)) {
21679 if (const ReferenceType *RefTy = Type->getAs<ReferenceType>()) {
21680 Type = RefTy->getPointeeType();
21681 } else if (Type->isFunctionType()) {
21682 S.Diag(Loc: E->getExprLoc(), DiagID: diag::err_unknown_any_var_function_type)
21683 << VD << E->getSourceRange();
21684 return ExprError();
21685 }
21686
21687 // - nothing else
21688 } else {
21689 S.Diag(Loc: E->getExprLoc(), DiagID: diag::err_unsupported_unknown_any_decl)
21690 << VD << E->getSourceRange();
21691 return ExprError();
21692 }
21693
21694 // Modifying the declaration like this is friendly to IR-gen but
21695 // also really dangerous.
21696 VD->setType(DestType);
21697 E->setType(Type);
21698 E->setValueKind(ValueKind);
21699 return E;
21700}
21701
21702ExprResult Sema::checkUnknownAnyCast(SourceRange TypeRange, QualType CastType,
21703 Expr *CastExpr, CastKind &CastKind,
21704 ExprValueKind &VK, CXXCastPath &Path) {
21705 // The type we're casting to must be either void or complete.
21706 if (!CastType->isVoidType() &&
21707 RequireCompleteType(Loc: TypeRange.getBegin(), T: CastType,
21708 DiagID: diag::err_typecheck_cast_to_incomplete))
21709 return ExprError();
21710
21711 // Rewrite the casted expression from scratch.
21712 ExprResult result = RebuildUnknownAnyExpr(*this, CastType).Visit(S: CastExpr);
21713 if (!result.isUsable()) return ExprError();
21714
21715 CastExpr = result.get();
21716 VK = CastExpr->getValueKind();
21717 CastKind = CK_NoOp;
21718
21719 return CastExpr;
21720}
21721
21722ExprResult Sema::forceUnknownAnyToType(Expr *E, QualType ToType) {
21723 return RebuildUnknownAnyExpr(*this, ToType).Visit(S: E);
21724}
21725
21726ExprResult Sema::checkUnknownAnyArg(SourceLocation callLoc,
21727 Expr *arg, QualType &paramType) {
21728 // If the syntactic form of the argument is not an explicit cast of
21729 // any sort, just do default argument promotion.
21730 ExplicitCastExpr *castArg = dyn_cast<ExplicitCastExpr>(Val: arg->IgnoreParens());
21731 if (!castArg) {
21732 ExprResult result = DefaultArgumentPromotion(E: arg);
21733 if (result.isInvalid()) return ExprError();
21734 paramType = result.get()->getType();
21735 return result;
21736 }
21737
21738 // Otherwise, use the type that was written in the explicit cast.
21739 assert(!arg->hasPlaceholderType());
21740 paramType = castArg->getTypeAsWritten();
21741
21742 // Copy-initialize a parameter of that type.
21743 InitializedEntity entity =
21744 InitializedEntity::InitializeParameter(Context, Type: paramType,
21745 /*consumed*/ Consumed: false);
21746 return PerformCopyInitialization(Entity: entity, EqualLoc: callLoc, Init: arg);
21747}
21748
21749static ExprResult diagnoseUnknownAnyExpr(Sema &S, Expr *E) {
21750 Expr *orig = E;
21751 unsigned diagID = diag::err_uncasted_use_of_unknown_any;
21752 while (true) {
21753 E = E->IgnoreParenImpCasts();
21754 if (CallExpr *call = dyn_cast<CallExpr>(Val: E)) {
21755 E = call->getCallee();
21756 diagID = diag::err_uncasted_call_of_unknown_any;
21757 } else {
21758 break;
21759 }
21760 }
21761
21762 SourceLocation loc;
21763 NamedDecl *d;
21764 if (DeclRefExpr *ref = dyn_cast<DeclRefExpr>(Val: E)) {
21765 loc = ref->getLocation();
21766 d = ref->getDecl();
21767 } else if (MemberExpr *mem = dyn_cast<MemberExpr>(Val: E)) {
21768 loc = mem->getMemberLoc();
21769 d = mem->getMemberDecl();
21770 } else if (ObjCMessageExpr *msg = dyn_cast<ObjCMessageExpr>(Val: E)) {
21771 diagID = diag::err_uncasted_call_of_unknown_any;
21772 loc = msg->getSelectorStartLoc();
21773 d = msg->getMethodDecl();
21774 if (!d) {
21775 S.Diag(Loc: loc, DiagID: diag::err_uncasted_send_to_unknown_any_method)
21776 << static_cast<unsigned>(msg->isClassMessage()) << msg->getSelector()
21777 << orig->getSourceRange();
21778 return ExprError();
21779 }
21780 } else {
21781 S.Diag(Loc: E->getExprLoc(), DiagID: diag::err_unsupported_unknown_any_expr)
21782 << E->getSourceRange();
21783 return ExprError();
21784 }
21785
21786 S.Diag(Loc: loc, DiagID: diagID) << d << orig->getSourceRange();
21787
21788 // Never recoverable.
21789 return ExprError();
21790}
21791
21792ExprResult Sema::CheckPlaceholderExpr(Expr *E) {
21793 const BuiltinType *placeholderType = E->getType()->getAsPlaceholderType();
21794 if (!placeholderType) return E;
21795
21796 switch (placeholderType->getKind()) {
21797 case BuiltinType::UnresolvedTemplate: {
21798 auto *ULE = cast<UnresolvedLookupExpr>(Val: E->IgnoreParens());
21799 const DeclarationNameInfo &NameInfo = ULE->getNameInfo();
21800 // There's only one FoundDecl for UnresolvedTemplate type. See
21801 // BuildTemplateIdExpr.
21802 NamedDecl *Temp = *ULE->decls_begin();
21803 const bool IsTypeAliasTemplateDecl = isa<TypeAliasTemplateDecl>(Val: Temp);
21804
21805 NestedNameSpecifier NNS = ULE->getQualifierLoc().getNestedNameSpecifier();
21806 // FIXME: AssumedTemplate is not very appropriate for error recovery here,
21807 // as it models only the unqualified-id case, where this case can clearly be
21808 // qualified. Thus we can't just qualify an assumed template.
21809 TemplateName TN;
21810 if (auto *TD = dyn_cast<TemplateDecl>(Val: Temp))
21811 TN = Context.getQualifiedTemplateName(Qualifier: NNS, TemplateKeyword: ULE->hasTemplateKeyword(),
21812 Template: TemplateName(TD));
21813 else
21814 TN = Context.getAssumedTemplateName(Name: NameInfo.getName());
21815
21816 Diag(Loc: NameInfo.getLoc(), DiagID: diag::err_template_kw_refers_to_type_template)
21817 << TN << ULE->getSourceRange() << IsTypeAliasTemplateDecl;
21818 Diag(Loc: Temp->getLocation(), DiagID: diag::note_referenced_type_template)
21819 << IsTypeAliasTemplateDecl;
21820
21821 TemplateArgumentListInfo TAL(ULE->getLAngleLoc(), ULE->getRAngleLoc());
21822 bool HasAnyDependentTA = false;
21823 for (const TemplateArgumentLoc &Arg : ULE->template_arguments()) {
21824 HasAnyDependentTA |= Arg.getArgument().isDependent();
21825 TAL.addArgument(Loc: Arg);
21826 }
21827
21828 QualType TST;
21829 {
21830 SFINAETrap Trap(*this);
21831 TST = CheckTemplateIdType(
21832 Keyword: ElaboratedTypeKeyword::None, Template: TN, TemplateLoc: NameInfo.getBeginLoc(), TemplateArgs&: TAL,
21833 /*Scope=*/nullptr, /*ForNestedNameSpecifier=*/false);
21834 }
21835 if (TST.isNull())
21836 TST = Context.getTemplateSpecializationType(
21837 Keyword: ElaboratedTypeKeyword::None, T: TN, SpecifiedArgs: ULE->template_arguments(),
21838 /*CanonicalArgs=*/{},
21839 Canon: HasAnyDependentTA ? Context.DependentTy : Context.IntTy);
21840 return CreateRecoveryExpr(Begin: NameInfo.getBeginLoc(), End: NameInfo.getEndLoc(), SubExprs: {},
21841 T: TST);
21842 }
21843
21844 // Overloaded expressions.
21845 case BuiltinType::Overload: {
21846 // Try to resolve a single function template specialization.
21847 // This is obligatory.
21848 ExprResult Result = E;
21849 if (ResolveAndFixSingleFunctionTemplateSpecialization(SrcExpr&: Result, DoFunctionPointerConversion: false))
21850 return Result;
21851
21852 // No guarantees that ResolveAndFixSingleFunctionTemplateSpecialization
21853 // leaves Result unchanged on failure.
21854 Result = E;
21855 if (resolveAndFixAddressOfSingleOverloadCandidate(SrcExpr&: Result))
21856 return Result;
21857
21858 // If that failed, try to recover with a call.
21859 tryToRecoverWithCall(E&: Result, PD: PDiag(DiagID: diag::err_ovl_unresolvable),
21860 /*complain*/ ForceComplain: true);
21861 return Result;
21862 }
21863
21864 // Bound member functions.
21865 case BuiltinType::BoundMember: {
21866 ExprResult result = E;
21867 const Expr *BME = E->IgnoreParens();
21868 PartialDiagnostic PD = PDiag(DiagID: diag::err_bound_member_function);
21869 // Try to give a nicer diagnostic if it is a bound member that we recognize.
21870 if (isa<CXXPseudoDestructorExpr>(Val: BME)) {
21871 PD = PDiag(DiagID: diag::err_dtor_expr_without_call) << /*pseudo-destructor*/ 1;
21872 } else if (const auto *ME = dyn_cast<MemberExpr>(Val: BME)) {
21873 if (ME->getMemberNameInfo().getName().getNameKind() ==
21874 DeclarationName::CXXDestructorName)
21875 PD = PDiag(DiagID: diag::err_dtor_expr_without_call) << /*destructor*/ 0;
21876 }
21877 tryToRecoverWithCall(E&: result, PD,
21878 /*complain*/ ForceComplain: true);
21879 return result;
21880 }
21881
21882 // ARC unbridged casts.
21883 case BuiltinType::ARCUnbridgedCast: {
21884 Expr *realCast = ObjC().stripARCUnbridgedCast(e: E);
21885 ObjC().diagnoseARCUnbridgedCast(e: realCast);
21886 return realCast;
21887 }
21888
21889 // Expressions of unknown type.
21890 case BuiltinType::UnknownAny:
21891 return diagnoseUnknownAnyExpr(S&: *this, E);
21892
21893 // Pseudo-objects.
21894 case BuiltinType::PseudoObject:
21895 return PseudoObject().checkRValue(E);
21896
21897 case BuiltinType::BuiltinFn: {
21898 // Accept __noop without parens by implicitly converting it to a call expr.
21899 auto *DRE = dyn_cast<DeclRefExpr>(Val: E->IgnoreParenImpCasts());
21900 if (DRE) {
21901 auto *FD = cast<FunctionDecl>(Val: DRE->getDecl());
21902 unsigned BuiltinID = FD->getBuiltinID();
21903 if (BuiltinID == Builtin::BI__noop) {
21904 E = ImpCastExprToType(E, Type: Context.getPointerType(T: FD->getType()),
21905 CK: CK_BuiltinFnToFnPtr)
21906 .get();
21907 return CallExpr::Create(Ctx: Context, Fn: E, /*Args=*/{}, Ty: Context.IntTy,
21908 VK: VK_PRValue, RParenLoc: SourceLocation(),
21909 FPFeatures: FPOptionsOverride());
21910 }
21911
21912 if (Context.BuiltinInfo.isInStdNamespace(ID: BuiltinID)) {
21913 // Any use of these other than a direct call is ill-formed as of C++20,
21914 // because they are not addressable functions. In earlier language
21915 // modes, warn and force an instantiation of the real body.
21916 Diag(Loc: E->getBeginLoc(),
21917 DiagID: getLangOpts().CPlusPlus20
21918 ? diag::err_use_of_unaddressable_function
21919 : diag::warn_cxx20_compat_use_of_unaddressable_function);
21920 if (FD->isImplicitlyInstantiable()) {
21921 // Require a definition here because a normal attempt at
21922 // instantiation for a builtin will be ignored, and we won't try
21923 // again later. We assume that the definition of the template
21924 // precedes this use.
21925 InstantiateFunctionDefinition(PointOfInstantiation: E->getBeginLoc(), Function: FD,
21926 /*Recursive=*/false,
21927 /*DefinitionRequired=*/true,
21928 /*AtEndOfTU=*/false);
21929 }
21930 // Produce a properly-typed reference to the function.
21931 CXXScopeSpec SS;
21932 SS.Adopt(Other: DRE->getQualifierLoc());
21933 TemplateArgumentListInfo TemplateArgs;
21934 DRE->copyTemplateArgumentsInto(List&: TemplateArgs);
21935 return BuildDeclRefExpr(
21936 D: FD, Ty: FD->getType(), VK: VK_LValue, NameInfo: DRE->getNameInfo(),
21937 SS: DRE->hasQualifier() ? &SS : nullptr, FoundD: DRE->getFoundDecl(),
21938 TemplateKWLoc: DRE->getTemplateKeywordLoc(),
21939 TemplateArgs: DRE->hasExplicitTemplateArgs() ? &TemplateArgs : nullptr);
21940 }
21941 }
21942
21943 Diag(Loc: E->getBeginLoc(), DiagID: diag::err_builtin_fn_use);
21944 return ExprError();
21945 }
21946
21947 case BuiltinType::IncompleteMatrixIdx: {
21948 auto *MS = cast<MatrixSubscriptExpr>(Val: E->IgnoreParens());
21949 // At this point, we know there was no second [] to complete the operator.
21950 // In HLSL, treat "m[row]" as selecting a row lane of column sized vector.
21951 if (getLangOpts().HLSL) {
21952 return CreateBuiltinMatrixSingleSubscriptExpr(
21953 Base: MS->getBase(), RowIdx: MS->getRowIdx(), RBLoc: E->getExprLoc());
21954 }
21955 Diag(Loc: MS->getRowIdx()->getBeginLoc(), DiagID: diag::err_matrix_incomplete_index);
21956 return ExprError();
21957 }
21958
21959 // Expressions of unknown type.
21960 case BuiltinType::ArraySection:
21961 // If we've already diagnosed something on the array section type, we
21962 // shouldn't need to do any further diagnostic here.
21963 if (!E->containsErrors())
21964 Diag(Loc: E->getBeginLoc(), DiagID: diag::err_array_section_use)
21965 << cast<ArraySectionExpr>(Val: E->IgnoreParens())->isOMPArraySection();
21966 return ExprError();
21967
21968 // Expressions of unknown type.
21969 case BuiltinType::OMPArrayShaping:
21970 return ExprError(Diag(Loc: E->getBeginLoc(), DiagID: diag::err_omp_array_shaping_use));
21971
21972 case BuiltinType::OMPIterator:
21973 return ExprError(Diag(Loc: E->getBeginLoc(), DiagID: diag::err_omp_iterator_use));
21974
21975 // Everything else should be impossible.
21976#define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
21977 case BuiltinType::Id:
21978#include "clang/Basic/OpenCLImageTypes.def"
21979#define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \
21980 case BuiltinType::Id:
21981#include "clang/Basic/OpenCLExtensionTypes.def"
21982#define SVE_TYPE(Name, Id, SingletonId) \
21983 case BuiltinType::Id:
21984#include "clang/Basic/AArch64ACLETypes.def"
21985#define PPC_VECTOR_TYPE(Name, Id, Size) \
21986 case BuiltinType::Id:
21987#include "clang/Basic/PPCTypes.def"
21988#define RVV_TYPE(Name, Id, SingletonId) case BuiltinType::Id:
21989#include "clang/Basic/RISCVVTypes.def"
21990#define WASM_TYPE(Name, Id, SingletonId) case BuiltinType::Id:
21991#include "clang/Basic/WebAssemblyReferenceTypes.def"
21992#define AMDGPU_TYPE(Name, Id, SingletonId, Width, Align) case BuiltinType::Id:
21993#include "clang/Basic/AMDGPUTypes.def"
21994#define HLSL_INTANGIBLE_TYPE(Name, Id, SingletonId) case BuiltinType::Id:
21995#include "clang/Basic/HLSLIntangibleTypes.def"
21996#define BUILTIN_TYPE(Id, SingletonId) case BuiltinType::Id:
21997#define PLACEHOLDER_TYPE(Id, SingletonId)
21998#include "clang/AST/BuiltinTypes.def"
21999 break;
22000 }
22001
22002 llvm_unreachable("invalid placeholder type!");
22003}
22004
22005bool Sema::CheckCaseExpression(Expr *E) {
22006 if (E->isTypeDependent())
22007 return true;
22008 if (E->isValueDependent() || E->isIntegerConstantExpr(Ctx: Context))
22009 return E->getType()->isIntegralOrEnumerationType();
22010 return false;
22011}
22012
22013ExprResult Sema::CreateRecoveryExpr(SourceLocation Begin, SourceLocation End,
22014 ArrayRef<Expr *> SubExprs, QualType T) {
22015 if (!Context.getLangOpts().RecoveryAST)
22016 return ExprError();
22017
22018 if (isSFINAEContext())
22019 return ExprError();
22020
22021 if (T.isNull() || T->isUndeducedType() ||
22022 !Context.getLangOpts().RecoveryASTType)
22023 // We don't know the concrete type, fallback to dependent type.
22024 T = Context.DependentTy;
22025
22026 return RecoveryExpr::Create(Ctx&: Context, T, BeginLoc: Begin, EndLoc: End, SubExprs);
22027}
22028