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/SemaARM.h"
57#include "clang/Sema/SemaCUDA.h"
58#include "clang/Sema/SemaFixItUtils.h"
59#include "clang/Sema/SemaHLSL.h"
60#include "clang/Sema/SemaObjC.h"
61#include "clang/Sema/SemaOpenMP.h"
62#include "clang/Sema/SemaPseudoObject.h"
63#include "clang/Sema/Template.h"
64#include "llvm/ADT/STLExtras.h"
65#include "llvm/ADT/StringExtras.h"
66#include "llvm/Support/ConvertUTF.h"
67#include "llvm/Support/SaveAndRestore.h"
68#include "llvm/Support/TimeProfiler.h"
69#include "llvm/Support/TypeSize.h"
70#include <limits>
71#include <optional>
72
73using namespace clang;
74using namespace sema;
75
76bool Sema::CanUseDecl(NamedDecl *D, bool TreatUnavailableAsInvalid) {
77 // See if this is an auto-typed variable whose initializer we are parsing.
78 if (ParsingInitForAutoVars.count(Ptr: D))
79 return false;
80
81 // See if this is a deleted function.
82 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Val: D)) {
83 if (FD->isDeleted())
84 return false;
85
86 // If the function has a deduced return type, and we can't deduce it,
87 // then we can't use it either.
88 if (getLangOpts().CPlusPlus14 && FD->getReturnType()->isUndeducedType() &&
89 DeduceReturnType(FD, Loc: SourceLocation(), /*Diagnose*/ false))
90 return false;
91
92 // See if this is an aligned allocation/deallocation function that is
93 // unavailable.
94 if (TreatUnavailableAsInvalid &&
95 isUnavailableAlignedAllocationFunction(FD: *FD))
96 return false;
97 }
98
99 // See if this function is unavailable.
100 if (TreatUnavailableAsInvalid && D->getAvailability() == AR_Unavailable &&
101 cast<Decl>(Val: CurContext)->getAvailability() != AR_Unavailable)
102 return false;
103
104 if (isa<UnresolvedUsingIfExistsDecl>(Val: D))
105 return false;
106
107 return true;
108}
109
110static void DiagnoseUnusedOfDecl(Sema &S, NamedDecl *D, SourceLocation Loc) {
111 // Warn if this is used but marked unused.
112 if (const auto *A = D->getAttr<UnusedAttr>()) {
113 // [[maybe_unused]] should not diagnose uses, but __attribute__((unused))
114 // should diagnose them.
115 if (A->getSemanticSpelling() != UnusedAttr::CXX11_maybe_unused &&
116 A->getSemanticSpelling() != UnusedAttr::C23_maybe_unused) {
117 const Decl *DC = cast_or_null<Decl>(Val: S.ObjC().getCurObjCLexicalContext());
118 if (DC && !DC->hasAttr<UnusedAttr>())
119 S.Diag(Loc, DiagID: diag::warn_used_but_marked_unused) << D;
120 }
121 }
122}
123
124void Sema::NoteDeletedFunction(FunctionDecl *Decl) {
125 assert(Decl && Decl->isDeleted());
126
127 if (Decl->isDefaulted()) {
128 // If the method was explicitly defaulted, point at that declaration.
129 if (!Decl->isImplicit())
130 Diag(Loc: Decl->getLocation(), DiagID: diag::note_implicitly_deleted);
131
132 // Try to diagnose why this special member function was implicitly
133 // deleted. This might fail, if that reason no longer applies.
134 DiagnoseDeletedDefaultedFunction(FD: Decl);
135 return;
136 }
137
138 auto *Ctor = dyn_cast<CXXConstructorDecl>(Val: Decl);
139 if (Ctor && Ctor->isInheritingConstructor())
140 return NoteDeletedInheritingConstructor(CD: Ctor);
141
142 Diag(Loc: Decl->getLocation(), DiagID: diag::note_availability_specified_here)
143 << Decl << 1;
144}
145
146/// Determine whether a FunctionDecl was ever declared with an
147/// explicit storage class.
148static bool hasAnyExplicitStorageClass(const FunctionDecl *D) {
149 for (auto *I : D->redecls()) {
150 if (I->getStorageClass() != SC_None)
151 return true;
152 }
153 return false;
154}
155
156/// Check whether we're in an extern inline function and referring to a
157/// variable or function with internal linkage (C11 6.7.4p3).
158///
159/// This is only a warning because we used to silently accept this code, but
160/// in many cases it will not behave correctly. This is not enabled in C++ mode
161/// because the restriction language is a bit weaker (C++11 [basic.def.odr]p6)
162/// and so while there may still be user mistakes, most of the time we can't
163/// prove that there are errors.
164static void diagnoseUseOfInternalDeclInInlineFunction(Sema &S,
165 const NamedDecl *D,
166 SourceLocation Loc) {
167 // This is disabled under C++; there are too many ways for this to fire in
168 // contexts where the warning is a false positive, or where it is technically
169 // correct but benign.
170 //
171 // WG14 N3622 which removed the constraint entirely in C2y. It is left
172 // enabled in earlier language modes because this is a constraint in those
173 // language modes. But in C2y mode, we still want to issue the "incompatible
174 // with previous standards" diagnostic, too.
175 if (S.getLangOpts().CPlusPlus)
176 return;
177
178 // Check if this is an inlined function or method.
179 FunctionDecl *Current = S.getCurFunctionDecl();
180 if (!Current)
181 return;
182 if (!Current->isInlined())
183 return;
184 if (!Current->isExternallyVisible())
185 return;
186
187 // Check if the decl has internal linkage.
188 if (D->getFormalLinkage() != Linkage::Internal)
189 return;
190
191 // Downgrade from ExtWarn to Extension if
192 // (1) the supposedly external inline function is in the main file,
193 // and probably won't be included anywhere else.
194 // (2) the thing we're referencing is a pure function.
195 // (3) the thing we're referencing is another inline function.
196 // This last can give us false negatives, but it's better than warning on
197 // wrappers for simple C library functions.
198 const FunctionDecl *UsedFn = dyn_cast<FunctionDecl>(Val: D);
199 unsigned DiagID;
200 if (S.getLangOpts().C2y)
201 DiagID = diag::warn_c2y_compat_internal_in_extern_inline;
202 else if ((UsedFn && (UsedFn->isInlined() || UsedFn->hasAttr<ConstAttr>())) ||
203 S.getSourceManager().isInMainFile(Loc))
204 DiagID = diag::ext_internal_in_extern_inline_quiet;
205 else
206 DiagID = diag::ext_internal_in_extern_inline;
207
208 S.Diag(Loc, DiagID) << /*IsVar=*/!UsedFn << D;
209 S.MaybeSuggestAddingStaticToDecl(D: Current);
210 S.Diag(Loc: D->getCanonicalDecl()->getLocation(), DiagID: diag::note_entity_declared_at)
211 << D;
212}
213
214void Sema::MaybeSuggestAddingStaticToDecl(const FunctionDecl *Cur) {
215 const FunctionDecl *First = Cur->getFirstDecl();
216
217 // Suggest "static" on the function, if possible.
218 if (!hasAnyExplicitStorageClass(D: First)) {
219 SourceLocation DeclBegin = First->getSourceRange().getBegin();
220 Diag(Loc: DeclBegin, DiagID: diag::note_convert_inline_to_static)
221 << Cur << FixItHint::CreateInsertion(InsertionLoc: DeclBegin, Code: "static ");
222 }
223}
224
225bool Sema::DiagnoseUseOfDecl(NamedDecl *D, ArrayRef<SourceLocation> Locs,
226 const ObjCInterfaceDecl *UnknownObjCClass,
227 bool ObjCPropertyAccess,
228 bool AvoidPartialAvailabilityChecks,
229 ObjCInterfaceDecl *ClassReceiver,
230 bool SkipTrailingRequiresClause) {
231 SourceLocation Loc = Locs.front();
232 if (getLangOpts().CPlusPlus && isa<FunctionDecl>(Val: D)) {
233 // If there were any diagnostics suppressed by template argument deduction,
234 // emit them now.
235 auto Pos = SuppressedDiagnostics.find(Val: D->getCanonicalDecl());
236 if (Pos != SuppressedDiagnostics.end()) {
237 for (const auto &[DiagLoc, PD] : Pos->second) {
238 DiagnosticBuilder Builder(Diags.Report(Loc: DiagLoc, DiagID: PD.getDiagID()));
239 PD.Emit(DB: Builder);
240 }
241 // Clear out the list of suppressed diagnostics, so that we don't emit
242 // them again for this specialization. However, we don't obsolete this
243 // entry from the table, because we want to avoid ever emitting these
244 // diagnostics again.
245 Pos->second.clear();
246 }
247
248 // C++ [basic.start.main]p3:
249 // The function 'main' shall not be used within a program.
250 if (cast<FunctionDecl>(Val: D)->isMain())
251 Diag(Loc, DiagID: diag::ext_main_used);
252
253 diagnoseUnavailableAlignedAllocation(FD: *cast<FunctionDecl>(Val: D), Loc);
254 }
255
256 // See if this is an auto-typed variable whose initializer we are parsing.
257 if (ParsingInitForAutoVars.count(Ptr: D)) {
258 if (isa<BindingDecl>(Val: D)) {
259 Diag(Loc, DiagID: diag::err_binding_cannot_appear_in_own_initializer)
260 << D->getDeclName();
261 } else {
262 Diag(Loc, DiagID: diag::err_auto_variable_cannot_appear_in_own_initializer)
263 << diag::ParsingInitFor::Var << D->getDeclName()
264 << cast<VarDecl>(Val: D)->getType();
265 }
266 return true;
267 }
268
269 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Val: D)) {
270 // See if this is a deleted function.
271 if (FD->isDeleted()) {
272 auto *Ctor = dyn_cast<CXXConstructorDecl>(Val: FD);
273 if (Ctor && Ctor->isInheritingConstructor())
274 Diag(Loc, DiagID: diag::err_deleted_inherited_ctor_use)
275 << Ctor->getParent()
276 << Ctor->getInheritedConstructor().getConstructor()->getParent();
277 else {
278 StringLiteral *Msg = FD->getDeletedMessage();
279 Diag(Loc, DiagID: diag::err_deleted_function_use)
280 << (Msg != nullptr) << (Msg ? Msg->getString() : StringRef());
281 }
282 NoteDeletedFunction(Decl: FD);
283 return true;
284 }
285
286 // [expr.prim.id]p4
287 // A program that refers explicitly or implicitly to a function with a
288 // trailing requires-clause whose constraint-expression is not satisfied,
289 // other than to declare it, is ill-formed. [...]
290 //
291 // See if this is a function with constraints that need to be satisfied.
292 // Check this before deducing the return type, as it might instantiate the
293 // definition.
294 if (!SkipTrailingRequiresClause && FD->getTrailingRequiresClause()) {
295 ConstraintSatisfaction Satisfaction;
296 if (CheckFunctionConstraints(FD, Satisfaction, UsageLoc: Loc,
297 /*ForOverloadResolution*/ true))
298 // A diagnostic will have already been generated (non-constant
299 // constraint expression, for example)
300 return true;
301 if (!Satisfaction.IsSatisfied) {
302 Diag(Loc,
303 DiagID: diag::err_reference_to_function_with_unsatisfied_constraints)
304 << D;
305 DiagnoseUnsatisfiedConstraint(Satisfaction);
306 return true;
307 }
308 }
309
310 // If the function has a deduced return type, and we can't deduce it,
311 // then we can't use it either.
312 if (getLangOpts().CPlusPlus14 && FD->getReturnType()->isUndeducedType() &&
313 DeduceReturnType(FD, Loc))
314 return true;
315
316 if (getLangOpts().CUDA && !CUDA().CheckCall(Loc, Callee: FD))
317 return true;
318
319 }
320
321 if (auto *Concept = dyn_cast<ConceptDecl>(Val: D);
322 Concept && CheckConceptUseInDefinition(Concept, Loc))
323 return true;
324
325 if (auto *MD = dyn_cast<CXXMethodDecl>(Val: D)) {
326 // Lambdas are only default-constructible or assignable in C++2a onwards.
327 if (MD->getParent()->isLambda() &&
328 ((isa<CXXConstructorDecl>(Val: MD) &&
329 cast<CXXConstructorDecl>(Val: MD)->isDefaultConstructor()) ||
330 MD->isCopyAssignmentOperator() || MD->isMoveAssignmentOperator())) {
331 Diag(Loc, DiagID: diag::warn_cxx17_compat_lambda_def_ctor_assign)
332 << !isa<CXXConstructorDecl>(Val: MD);
333 }
334 }
335
336 auto getReferencedObjCProp = [](const NamedDecl *D) ->
337 const ObjCPropertyDecl * {
338 if (const auto *MD = dyn_cast<ObjCMethodDecl>(Val: D))
339 return MD->findPropertyDecl();
340 return nullptr;
341 };
342 if (const ObjCPropertyDecl *ObjCPDecl = getReferencedObjCProp(D)) {
343 if (diagnoseArgIndependentDiagnoseIfAttrs(ND: ObjCPDecl, Loc))
344 return true;
345 } else if (diagnoseArgIndependentDiagnoseIfAttrs(ND: D, Loc)) {
346 return true;
347 }
348
349 // [OpenMP 4.0], 2.15 declare reduction Directive, Restrictions
350 // Only the variables omp_in and omp_out are allowed in the combiner.
351 // Only the variables omp_priv and omp_orig are allowed in the
352 // initializer-clause.
353 auto *DRD = dyn_cast<OMPDeclareReductionDecl>(Val: CurContext);
354 if (LangOpts.OpenMP && DRD && !CurContext->containsDecl(D) &&
355 isa<VarDecl>(Val: D)) {
356 Diag(Loc, DiagID: diag::err_omp_wrong_var_in_declare_reduction)
357 << getCurFunction()->HasOMPDeclareReductionCombiner;
358 Diag(Loc: D->getLocation(), DiagID: diag::note_entity_declared_at) << D;
359 return true;
360 }
361
362 // [OpenMP 5.0], 2.19.7.3. declare mapper Directive, Restrictions
363 // List-items in map clauses on this construct may only refer to the declared
364 // variable var and entities that could be referenced by a procedure defined
365 // at the same location.
366 // [OpenMP 5.2] Also allow iterator declared variables.
367 if (LangOpts.OpenMP && isa<VarDecl>(Val: D) &&
368 !OpenMP().isOpenMPDeclareMapperVarDeclAllowed(VD: cast<VarDecl>(Val: D))) {
369 Diag(Loc, DiagID: diag::err_omp_declare_mapper_wrong_var)
370 << OpenMP().getOpenMPDeclareMapperVarName();
371 Diag(Loc: D->getLocation(), DiagID: diag::note_entity_declared_at) << D;
372 return true;
373 }
374
375 if (const auto *EmptyD = dyn_cast<UnresolvedUsingIfExistsDecl>(Val: D)) {
376 Diag(Loc, DiagID: diag::err_use_of_empty_using_if_exists);
377 Diag(Loc: EmptyD->getLocation(), DiagID: diag::note_empty_using_if_exists_here);
378 return true;
379 }
380
381 DiagnoseAvailabilityOfDecl(D, Locs, UnknownObjCClass, ObjCPropertyAccess,
382 AvoidPartialAvailabilityChecks, ClassReceiver);
383
384 DiagnoseUnusedOfDecl(S&: *this, D, Loc);
385
386 diagnoseUseOfInternalDeclInInlineFunction(S&: *this, D, Loc);
387
388 if (D->hasAttr<AvailableOnlyInDefaultEvalMethodAttr>()) {
389 if (getLangOpts().getFPEvalMethod() !=
390 LangOptions::FPEvalMethodKind::FEM_UnsetOnCommandLine &&
391 PP.getLastFPEvalPragmaLocation().isValid() &&
392 PP.getCurrentFPEvalMethod() != getLangOpts().getFPEvalMethod())
393 Diag(Loc: D->getLocation(),
394 DiagID: diag::err_type_available_only_in_default_eval_method)
395 << D->getName();
396 }
397
398 if (auto *VD = dyn_cast<ValueDecl>(Val: D))
399 checkTypeSupport(Ty: VD->getType(), Loc, D: VD);
400
401 if (LangOpts.SYCLIsDevice ||
402 (LangOpts.OpenMP && LangOpts.OpenMPIsTargetDevice)) {
403 if (!Context.getTargetInfo().isTLSSupported())
404 if (const auto *VD = dyn_cast<VarDecl>(Val: D))
405 if (VD->getTLSKind() != VarDecl::TLS_None)
406 targetDiag(Loc: *Locs.begin(), DiagID: diag::err_thread_unsupported);
407 }
408
409 return false;
410}
411
412void Sema::DiagnoseSentinelCalls(const NamedDecl *D, SourceLocation Loc,
413 ArrayRef<Expr *> Args) {
414 const SentinelAttr *Attr = D->getAttr<SentinelAttr>();
415 if (!Attr)
416 return;
417
418 // The number of formal parameters of the declaration.
419 unsigned NumFormalParams;
420
421 // The kind of declaration. This is also an index into a %select in
422 // the diagnostic.
423 enum { CK_Function, CK_Method, CK_Block } CalleeKind;
424
425 if (const auto *MD = dyn_cast<ObjCMethodDecl>(Val: D)) {
426 NumFormalParams = MD->param_size();
427 CalleeKind = CK_Method;
428 } else if (const auto *FD = dyn_cast<FunctionDecl>(Val: D)) {
429 NumFormalParams = FD->param_size();
430 CalleeKind = CK_Function;
431 } else if (const auto *VD = dyn_cast<VarDecl>(Val: D)) {
432 QualType Ty = VD->getType();
433 const FunctionType *Fn = nullptr;
434 if (const auto *PtrTy = Ty->getAs<PointerType>()) {
435 Fn = PtrTy->getPointeeType()->getAs<FunctionType>();
436 if (!Fn)
437 return;
438 CalleeKind = CK_Function;
439 } else if (const auto *PtrTy = Ty->getAs<BlockPointerType>()) {
440 Fn = PtrTy->getPointeeType()->castAs<FunctionType>();
441 CalleeKind = CK_Block;
442 } else {
443 return;
444 }
445
446 if (const auto *proto = dyn_cast<FunctionProtoType>(Val: Fn))
447 NumFormalParams = proto->getNumParams();
448 else
449 NumFormalParams = 0;
450 } else {
451 return;
452 }
453
454 // "NullPos" is the number of formal parameters at the end which
455 // effectively count as part of the variadic arguments. This is
456 // useful if you would prefer to not have *any* formal parameters,
457 // but the language forces you to have at least one.
458 unsigned NullPos = Attr->getNullPos();
459 assert((NullPos == 0 || NullPos == 1) && "invalid null position on sentinel");
460 NumFormalParams = (NullPos > NumFormalParams ? 0 : NumFormalParams - NullPos);
461
462 // The number of arguments which should follow the sentinel.
463 unsigned NumArgsAfterSentinel = Attr->getSentinel();
464
465 // If there aren't enough arguments for all the formal parameters,
466 // the sentinel, and the args after the sentinel, complain.
467 if (Args.size() < NumFormalParams + NumArgsAfterSentinel + 1) {
468 Diag(Loc, DiagID: diag::warn_not_enough_argument) << D->getDeclName();
469 Diag(Loc: D->getLocation(), DiagID: diag::note_sentinel_here) << int(CalleeKind);
470 return;
471 }
472
473 // Otherwise, find the sentinel expression.
474 const Expr *SentinelExpr = Args[Args.size() - NumArgsAfterSentinel - 1];
475 if (!SentinelExpr)
476 return;
477 if (SentinelExpr->isValueDependent())
478 return;
479 if (Context.isSentinelNullExpr(E: SentinelExpr))
480 return;
481
482 // Pick a reasonable string to insert. Optimistically use 'nil', 'nullptr',
483 // or 'NULL' if those are actually defined in the context. Only use
484 // 'nil' for ObjC methods, where it's much more likely that the
485 // variadic arguments form a list of object pointers.
486 SourceLocation MissingNilLoc = getLocForEndOfToken(Loc: SentinelExpr->getEndLoc());
487 std::string NullValue;
488 if (CalleeKind == CK_Method && PP.isMacroDefined(Id: "nil"))
489 NullValue = "nil";
490 else if (getLangOpts().CPlusPlus11)
491 NullValue = "nullptr";
492 else if (PP.isMacroDefined(Id: "NULL"))
493 NullValue = "NULL";
494 else
495 NullValue = "(void*) 0";
496
497 if (MissingNilLoc.isInvalid())
498 Diag(Loc, DiagID: diag::warn_missing_sentinel) << int(CalleeKind);
499 else
500 Diag(Loc: MissingNilLoc, DiagID: diag::warn_missing_sentinel)
501 << int(CalleeKind)
502 << FixItHint::CreateInsertion(InsertionLoc: MissingNilLoc, Code: ", " + NullValue);
503 Diag(Loc: D->getLocation(), DiagID: diag::note_sentinel_here)
504 << int(CalleeKind) << Attr->getRange();
505}
506
507SourceRange Sema::getExprRange(Expr *E) const {
508 return E ? E->getSourceRange() : SourceRange();
509}
510
511//===----------------------------------------------------------------------===//
512// Standard Promotions and Conversions
513//===----------------------------------------------------------------------===//
514
515/// DefaultFunctionArrayConversion (C99 6.3.2.1p3, C99 6.3.2.1p4).
516ExprResult Sema::DefaultFunctionArrayConversion(Expr *E, bool Diagnose) {
517 // Handle any placeholder expressions which made it here.
518 if (E->hasPlaceholderType()) {
519 ExprResult result = CheckPlaceholderExpr(E);
520 if (result.isInvalid()) return ExprError();
521 E = result.get();
522 }
523
524 QualType Ty = E->getType();
525 assert(!Ty.isNull() && "DefaultFunctionArrayConversion - missing type");
526
527 if (Ty->isFunctionType()) {
528 if (auto *DRE = dyn_cast<DeclRefExpr>(Val: E->IgnoreParenCasts()))
529 if (auto *FD = dyn_cast<FunctionDecl>(Val: DRE->getDecl()))
530 if (!checkAddressOfFunctionIsAvailable(Function: FD, Complain: Diagnose, Loc: E->getExprLoc()))
531 return ExprError();
532
533 E = ImpCastExprToType(E, Type: Context.getPointerType(T: Ty),
534 CK: CK_FunctionToPointerDecay).get();
535 } else if (Ty->isArrayType()) {
536 // In C90 mode, arrays only promote to pointers if the array expression is
537 // an lvalue. The relevant legalese is C90 6.2.2.1p3: "an lvalue that has
538 // type 'array of type' is converted to an expression that has type 'pointer
539 // to type'...". In C99 this was changed to: C99 6.3.2.1p3: "an expression
540 // that has type 'array of type' ...". The relevant change is "an lvalue"
541 // (C90) to "an expression" (C99).
542 //
543 // C++ 4.2p1:
544 // An lvalue or rvalue of type "array of N T" or "array of unknown bound of
545 // T" can be converted to an rvalue of type "pointer to T".
546 //
547 if (getLangOpts().C99 || getLangOpts().CPlusPlus || E->isLValue()) {
548 ExprResult Res = ImpCastExprToType(E, Type: Context.getArrayDecayedType(T: Ty),
549 CK: CK_ArrayToPointerDecay);
550 if (Res.isInvalid())
551 return ExprError();
552 E = Res.get();
553 }
554 }
555 return E;
556}
557
558static void CheckForNullPointerDereference(Sema &S, Expr *E) {
559 // Check to see if we are dereferencing a null pointer. If so,
560 // and if not volatile-qualified, this is undefined behavior that the
561 // optimizer will delete, so warn about it. People sometimes try to use this
562 // to get a deterministic trap and are surprised by clang's behavior. This
563 // only handles the pattern "*null", which is a very syntactic check.
564 const auto *UO = dyn_cast<UnaryOperator>(Val: E->IgnoreParenCasts());
565 if (UO && UO->getOpcode() == UO_Deref &&
566 UO->getSubExpr()->getType()->isPointerType()) {
567 const LangAS AS =
568 UO->getSubExpr()->getType()->getPointeeType().getAddressSpace();
569 if ((!isTargetAddressSpace(AS) ||
570 (isTargetAddressSpace(AS) && toTargetAddressSpace(AS) == 0)) &&
571 UO->getSubExpr()->IgnoreParenCasts()->isNullPointerConstant(
572 Ctx&: S.Context, NPC: Expr::NPC_ValueDependentIsNotNull) &&
573 !UO->getType().isVolatileQualified()) {
574 S.DiagRuntimeBehavior(Loc: UO->getOperatorLoc(), Statement: UO,
575 PD: S.PDiag(DiagID: diag::warn_indirection_through_null)
576 << UO->getSubExpr()->getSourceRange());
577 S.DiagRuntimeBehavior(Loc: UO->getOperatorLoc(), Statement: UO,
578 PD: S.PDiag(DiagID: diag::note_indirection_through_null));
579 }
580 }
581}
582
583static void DiagnoseDirectIsaAccess(Sema &S, const ObjCIvarRefExpr *OIRE,
584 SourceLocation AssignLoc,
585 const Expr* RHS) {
586 const ObjCIvarDecl *IV = OIRE->getDecl();
587 if (!IV)
588 return;
589
590 DeclarationName MemberName = IV->getDeclName();
591 IdentifierInfo *Member = MemberName.getAsIdentifierInfo();
592 if (!Member || !Member->isStr(Str: "isa"))
593 return;
594
595 const Expr *Base = OIRE->getBase();
596 QualType BaseType = Base->getType();
597 if (OIRE->isArrow())
598 BaseType = BaseType->getPointeeType();
599 if (const ObjCObjectType *OTy = BaseType->getAs<ObjCObjectType>())
600 if (ObjCInterfaceDecl *IDecl = OTy->getInterface()) {
601 ObjCInterfaceDecl *ClassDeclared = nullptr;
602 ObjCIvarDecl *IV = IDecl->lookupInstanceVariable(IVarName: Member, ClassDeclared);
603 if (!ClassDeclared->getSuperClass()
604 && (*ClassDeclared->ivar_begin()) == IV) {
605 if (RHS) {
606 NamedDecl *ObjectSetClass =
607 S.LookupSingleName(S: S.TUScope,
608 Name: &S.Context.Idents.get(Name: "object_setClass"),
609 Loc: SourceLocation(), NameKind: S.LookupOrdinaryName);
610 if (ObjectSetClass) {
611 SourceLocation RHSLocEnd = S.getLocForEndOfToken(Loc: RHS->getEndLoc());
612 S.Diag(Loc: OIRE->getExprLoc(), DiagID: diag::warn_objc_isa_assign)
613 << FixItHint::CreateInsertion(InsertionLoc: OIRE->getBeginLoc(),
614 Code: "object_setClass(")
615 << FixItHint::CreateReplacement(
616 RemoveRange: SourceRange(OIRE->getOpLoc(), AssignLoc), Code: ",")
617 << FixItHint::CreateInsertion(InsertionLoc: RHSLocEnd, Code: ")");
618 }
619 else
620 S.Diag(Loc: OIRE->getLocation(), DiagID: diag::warn_objc_isa_assign);
621 } else {
622 NamedDecl *ObjectGetClass =
623 S.LookupSingleName(S: S.TUScope,
624 Name: &S.Context.Idents.get(Name: "object_getClass"),
625 Loc: SourceLocation(), NameKind: S.LookupOrdinaryName);
626 if (ObjectGetClass)
627 S.Diag(Loc: OIRE->getExprLoc(), DiagID: diag::warn_objc_isa_use)
628 << FixItHint::CreateInsertion(InsertionLoc: OIRE->getBeginLoc(),
629 Code: "object_getClass(")
630 << FixItHint::CreateReplacement(
631 RemoveRange: SourceRange(OIRE->getOpLoc(), OIRE->getEndLoc()), Code: ")");
632 else
633 S.Diag(Loc: OIRE->getLocation(), DiagID: diag::warn_objc_isa_use);
634 }
635 S.Diag(Loc: IV->getLocation(), DiagID: diag::note_ivar_decl);
636 }
637 }
638}
639
640ExprResult Sema::DefaultLvalueConversion(Expr *E) {
641 // Handle any placeholder expressions which made it here.
642 if (E->hasPlaceholderType()) {
643 ExprResult result = CheckPlaceholderExpr(E);
644 if (result.isInvalid()) return ExprError();
645 E = result.get();
646 }
647
648 // C++ [conv.lval]p1:
649 // A glvalue of a non-function, non-array type T can be
650 // converted to a prvalue.
651 if (!E->isGLValue()) return E;
652
653 QualType T = E->getType();
654 assert(!T.isNull() && "r-value conversion on typeless expression?");
655
656 // lvalue-to-rvalue conversion cannot be applied to types that decay to
657 // pointers (i.e. function or array types).
658 if (T->canDecayToPointerType())
659 return E;
660
661 // We don't want to throw lvalue-to-rvalue casts on top of
662 // expressions of certain types in C++.
663 if (getLangOpts().CPlusPlus) {
664 if (T == Context.OverloadTy || T->isRecordType() ||
665 (T->isDependentType() && !T->isAnyPointerType() &&
666 !T->isMemberPointerType()))
667 return E;
668 }
669
670 // The C standard is actually really unclear on this point, and
671 // DR106 tells us what the result should be but not why. It's
672 // generally best to say that void types just doesn't undergo
673 // lvalue-to-rvalue at all. Note that expressions of unqualified
674 // 'void' type are never l-values, but qualified void can be.
675 if (T->isVoidType())
676 return E;
677
678 // OpenCL usually rejects direct accesses to values of 'half' type.
679 if (getLangOpts().OpenCL &&
680 !getOpenCLOptions().isAvailableOption(Ext: "cl_khr_fp16", LO: getLangOpts()) &&
681 T->isHalfType()) {
682 Diag(Loc: E->getExprLoc(), DiagID: diag::err_opencl_half_load_store)
683 << 0 << T;
684 return ExprError();
685 }
686
687 CheckForNullPointerDereference(S&: *this, E);
688 if (const ObjCIsaExpr *OISA = dyn_cast<ObjCIsaExpr>(Val: E->IgnoreParenCasts())) {
689 NamedDecl *ObjectGetClass = LookupSingleName(S: TUScope,
690 Name: &Context.Idents.get(Name: "object_getClass"),
691 Loc: SourceLocation(), NameKind: LookupOrdinaryName);
692 if (ObjectGetClass)
693 Diag(Loc: E->getExprLoc(), DiagID: diag::warn_objc_isa_use)
694 << FixItHint::CreateInsertion(InsertionLoc: OISA->getBeginLoc(), Code: "object_getClass(")
695 << FixItHint::CreateReplacement(
696 RemoveRange: SourceRange(OISA->getOpLoc(), OISA->getIsaMemberLoc()), Code: ")");
697 else
698 Diag(Loc: E->getExprLoc(), DiagID: diag::warn_objc_isa_use);
699 }
700 else if (const ObjCIvarRefExpr *OIRE =
701 dyn_cast<ObjCIvarRefExpr>(Val: E->IgnoreParenCasts()))
702 DiagnoseDirectIsaAccess(S&: *this, OIRE, AssignLoc: SourceLocation(), /* Expr*/RHS: nullptr);
703
704 // C++ [conv.lval]p1:
705 // [...] If T is a non-class type, the type of the prvalue is the
706 // cv-unqualified version of T. Otherwise, the type of the
707 // rvalue is T.
708 //
709 // C99 6.3.2.1p2:
710 // If the lvalue has qualified type, the value has the unqualified
711 // version of the type of the lvalue; otherwise, the value has the
712 // type of the lvalue.
713 if (T.hasQualifiers())
714 T = T.getUnqualifiedType();
715
716 // Under the MS ABI, lock down the inheritance model now.
717 if (T->isMemberPointerType() &&
718 Context.getTargetInfo().getCXXABI().isMicrosoft())
719 (void)isCompleteType(Loc: E->getExprLoc(), T);
720
721 ExprResult Res = CheckLValueToRValueConversionOperand(E);
722 if (Res.isInvalid())
723 return Res;
724 E = Res.get();
725
726 // Loading a __weak object implicitly retains the value, so we need a cleanup to
727 // balance that.
728 if (E->getType().getObjCLifetime() == Qualifiers::OCL_Weak)
729 Cleanup.setExprNeedsCleanups(true);
730
731 if (E->getType().isDestructedType() == QualType::DK_nontrivial_c_struct)
732 Cleanup.setExprNeedsCleanups(true);
733
734 if (!BoundsSafetyCheckUseOfCountAttrPtr(E: Res.get()))
735 return ExprError();
736
737 // C++ [conv.lval]p3:
738 // If T is cv std::nullptr_t, the result is a null pointer constant.
739 CastKind CK = T->isNullPtrType() ? CK_NullToPointer : CK_LValueToRValue;
740 Res = ImplicitCastExpr::Create(Context, T, Kind: CK, Operand: E, BasePath: nullptr, Cat: VK_PRValue,
741 FPO: CurFPFeatureOverrides());
742
743 // C11 6.3.2.1p2:
744 // ... if the lvalue has atomic type, the value has the non-atomic version
745 // of the type of the lvalue ...
746 if (const AtomicType *Atomic = T->getAs<AtomicType>()) {
747 T = Atomic->getValueType().getUnqualifiedType();
748 Res = ImplicitCastExpr::Create(Context, T, Kind: CK_AtomicToNonAtomic, Operand: Res.get(),
749 BasePath: nullptr, Cat: VK_PRValue, FPO: FPOptionsOverride());
750 }
751
752 return Res;
753}
754
755ExprResult Sema::DefaultFunctionArrayLvalueConversion(Expr *E, bool Diagnose) {
756 ExprResult Res = DefaultFunctionArrayConversion(E, Diagnose);
757 if (Res.isInvalid())
758 return ExprError();
759 Res = DefaultLvalueConversion(E: Res.get());
760 if (Res.isInvalid())
761 return ExprError();
762 return Res;
763}
764
765ExprResult Sema::CallExprUnaryConversions(Expr *E) {
766 QualType Ty = E->getType();
767 ExprResult Res = E;
768 // Only do implicit cast for a function type, but not for a pointer
769 // to function type.
770 if (Ty->isFunctionType()) {
771 Res = ImpCastExprToType(E, Type: Context.getPointerType(T: Ty),
772 CK: CK_FunctionToPointerDecay);
773 if (Res.isInvalid())
774 return ExprError();
775 }
776 Res = DefaultLvalueConversion(E: Res.get());
777 if (Res.isInvalid())
778 return ExprError();
779 return Res.get();
780}
781
782/// UsualUnaryFPConversions - Promotes floating-point types according to the
783/// current language semantics.
784ExprResult Sema::UsualUnaryFPConversions(Expr *E) {
785 QualType Ty = E->getType();
786 assert(!Ty.isNull() && "UsualUnaryFPConversions - missing type");
787
788 LangOptions::FPEvalMethodKind EvalMethod = CurFPFeatures.getFPEvalMethod();
789 if (EvalMethod != LangOptions::FEM_Source && Ty->isFloatingType() &&
790 (getLangOpts().getFPEvalMethod() !=
791 LangOptions::FPEvalMethodKind::FEM_UnsetOnCommandLine ||
792 PP.getLastFPEvalPragmaLocation().isValid())) {
793 switch (EvalMethod) {
794 default:
795 llvm_unreachable("Unrecognized float evaluation method");
796 break;
797 case LangOptions::FEM_UnsetOnCommandLine:
798 llvm_unreachable("Float evaluation method should be set by now");
799 break;
800 case LangOptions::FEM_Double:
801 if (Context.getFloatingTypeOrder(LHS: Context.DoubleTy, RHS: Ty) > 0)
802 // Widen the expression to double.
803 return Ty->isComplexType()
804 ? ImpCastExprToType(E,
805 Type: Context.getComplexType(T: Context.DoubleTy),
806 CK: CK_FloatingComplexCast)
807 : ImpCastExprToType(E, Type: Context.DoubleTy, CK: CK_FloatingCast);
808 break;
809 case LangOptions::FEM_Extended:
810 if (Context.getFloatingTypeOrder(LHS: Context.LongDoubleTy, RHS: Ty) > 0)
811 // Widen the expression to long double.
812 return Ty->isComplexType()
813 ? ImpCastExprToType(
814 E, Type: Context.getComplexType(T: Context.LongDoubleTy),
815 CK: CK_FloatingComplexCast)
816 : ImpCastExprToType(E, Type: Context.LongDoubleTy,
817 CK: CK_FloatingCast);
818 break;
819 }
820 }
821
822 // Half FP have to be promoted to float unless it is natively supported
823 if (Ty->isHalfType() && !getLangOpts().NativeHalfType)
824 return ImpCastExprToType(E, Type: Context.FloatTy, CK: CK_FloatingCast);
825
826 return E;
827}
828
829/// UsualUnaryConversions - Performs various conversions that are common to most
830/// operators (C99 6.3). The conversions of array and function types are
831/// sometimes suppressed. For example, the array->pointer conversion doesn't
832/// apply if the array is an argument to the sizeof or address (&) operators.
833/// In these instances, this routine should *not* be called.
834ExprResult Sema::UsualUnaryConversions(Expr *E) {
835 // First, convert to an r-value.
836 ExprResult Res = DefaultFunctionArrayLvalueConversion(E);
837 if (Res.isInvalid())
838 return ExprError();
839
840 // Promote floating-point types.
841 Res = UsualUnaryFPConversions(E: Res.get());
842 if (Res.isInvalid())
843 return ExprError();
844 E = Res.get();
845
846 QualType Ty = E->getType();
847 assert(!Ty.isNull() && "UsualUnaryConversions - missing type");
848
849 // Try to perform integral promotions if the object has a theoretically
850 // promotable type.
851 if (Ty->isIntegralOrUnscopedEnumerationType()) {
852 // C99 6.3.1.1p2:
853 //
854 // The following may be used in an expression wherever an int or
855 // unsigned int may be used:
856 // - an object or expression with an integer type whose integer
857 // conversion rank is less than or equal to the rank of int
858 // and unsigned int.
859 // - A bit-field of type _Bool, int, signed int, or unsigned int.
860 //
861 // If an int can represent all values of the original type, the
862 // value is converted to an int; otherwise, it is converted to an
863 // unsigned int. These are called the integer promotions. All
864 // other types are unchanged by the integer promotions.
865
866 QualType PTy = Context.isPromotableBitField(E);
867 if (!PTy.isNull()) {
868 E = ImpCastExprToType(E, Type: PTy, CK: CK_IntegralCast).get();
869 return E;
870 }
871 if (Context.isPromotableIntegerType(T: Ty)) {
872 QualType PT = Context.getPromotedIntegerType(PromotableType: Ty);
873 E = ImpCastExprToType(E, Type: PT, CK: CK_IntegralCast).get();
874 return E;
875 }
876 }
877 return E;
878}
879
880/// DefaultArgumentPromotion (C99 6.5.2.2p6). Used for function calls that
881/// do not have a prototype. Arguments that have type float or __fp16
882/// are promoted to double. All other argument types are converted by
883/// UsualUnaryConversions().
884ExprResult Sema::DefaultArgumentPromotion(Expr *E) {
885 QualType Ty = E->getType();
886 assert(!Ty.isNull() && "DefaultArgumentPromotion - missing type");
887
888 ExprResult Res = UsualUnaryConversions(E);
889 if (Res.isInvalid())
890 return ExprError();
891 E = Res.get();
892
893 // If this is a 'float' or '__fp16' (CVR qualified or typedef)
894 // promote to double.
895 // Note that default argument promotion applies only to float (and
896 // half/fp16); it does not apply to _Float16.
897 const BuiltinType *BTy = Ty->getAs<BuiltinType>();
898 if (BTy && (BTy->getKind() == BuiltinType::Half ||
899 BTy->getKind() == BuiltinType::Float)) {
900 if (getLangOpts().OpenCL &&
901 !getOpenCLOptions().isAvailableOption(Ext: "cl_khr_fp64", LO: getLangOpts())) {
902 if (BTy->getKind() == BuiltinType::Half) {
903 E = ImpCastExprToType(E, Type: Context.FloatTy, CK: CK_FloatingCast).get();
904 }
905 } else {
906 E = ImpCastExprToType(E, Type: Context.DoubleTy, CK: CK_FloatingCast).get();
907 }
908 }
909 if (BTy &&
910 getLangOpts().getExtendIntArgs() ==
911 LangOptions::ExtendArgsKind::ExtendTo64 &&
912 Context.getTargetInfo().supportsExtendIntArgs() && Ty->isIntegerType() &&
913 Context.getTypeSizeInChars(T: BTy) <
914 Context.getTypeSizeInChars(T: Context.LongLongTy)) {
915 E = (Ty->isUnsignedIntegerType())
916 ? ImpCastExprToType(E, Type: Context.UnsignedLongLongTy, CK: CK_IntegralCast)
917 .get()
918 : ImpCastExprToType(E, Type: Context.LongLongTy, CK: CK_IntegralCast).get();
919 assert(8 == Context.getTypeSizeInChars(Context.LongLongTy).getQuantity() &&
920 "Unexpected typesize for LongLongTy");
921 }
922
923 // C++ performs lvalue-to-rvalue conversion as a default argument
924 // promotion, even on class types, but note:
925 // C++11 [conv.lval]p2:
926 // When an lvalue-to-rvalue conversion occurs in an unevaluated
927 // operand or a subexpression thereof the value contained in the
928 // referenced object is not accessed. Otherwise, if the glvalue
929 // has a class type, the conversion copy-initializes a temporary
930 // of type T from the glvalue and the result of the conversion
931 // is a prvalue for the temporary.
932 // FIXME: add some way to gate this entire thing for correctness in
933 // potentially potentially evaluated contexts.
934 if (getLangOpts().CPlusPlus && E->isGLValue() && !isUnevaluatedContext()) {
935 ExprResult Temp = PerformCopyInitialization(
936 Entity: InitializedEntity::InitializeTemporary(Type: E->getType()),
937 EqualLoc: E->getExprLoc(), Init: E);
938 if (Temp.isInvalid())
939 return ExprError();
940 E = Temp.get();
941 }
942
943 // C++ [expr.call]p7, per CWG722:
944 // An argument that has (possibly cv-qualified) type std::nullptr_t is
945 // converted to void* ([conv.ptr]).
946 // (This does not apply to C23 nullptr)
947 if (getLangOpts().CPlusPlus && E->getType()->isNullPtrType())
948 E = ImpCastExprToType(E, Type: Context.VoidPtrTy, CK: CK_NullToPointer).get();
949
950 return E;
951}
952
953VarArgKind Sema::isValidVarArgType(const QualType &Ty) {
954 if (Ty->isIncompleteType()) {
955 // C++11 [expr.call]p7:
956 // After these conversions, if the argument does not have arithmetic,
957 // enumeration, pointer, pointer to member, or class type, the program
958 // is ill-formed.
959 //
960 // Since we've already performed null pointer conversion, array-to-pointer
961 // decay and function-to-pointer decay, the only such type in C++ is cv
962 // void. This also handles initializer lists as variadic arguments.
963 if (Ty->isVoidType())
964 return VarArgKind::Invalid;
965
966 if (Ty->isObjCObjectType())
967 return VarArgKind::Invalid;
968 return VarArgKind::Valid;
969 }
970
971 if (Ty.isDestructedType() == QualType::DK_nontrivial_c_struct)
972 return VarArgKind::Invalid;
973
974 if (Context.getTargetInfo().getTriple().isWasm() &&
975 Ty.isWebAssemblyReferenceType()) {
976 return VarArgKind::Invalid;
977 }
978
979 if (Ty.isCXX98PODType(Context))
980 return VarArgKind::Valid;
981
982 // C++11 [expr.call]p7:
983 // Passing a potentially-evaluated argument of class type (Clause 9)
984 // having a non-trivial copy constructor, a non-trivial move constructor,
985 // or a non-trivial destructor, with no corresponding parameter,
986 // is conditionally-supported with implementation-defined semantics.
987 if (getLangOpts().CPlusPlus11 && !Ty->isDependentType())
988 if (CXXRecordDecl *Record = Ty->getAsCXXRecordDecl())
989 if (!Record->hasNonTrivialCopyConstructor() &&
990 !Record->hasNonTrivialMoveConstructor() &&
991 !Record->hasNonTrivialDestructor())
992 return VarArgKind::ValidInCXX11;
993
994 if (getLangOpts().ObjCAutoRefCount && Ty->isObjCLifetimeType())
995 return VarArgKind::Valid;
996
997 if (Ty->isObjCObjectType())
998 return VarArgKind::Invalid;
999
1000 if (getLangOpts().HLSL && Ty->getAs<HLSLAttributedResourceType>())
1001 return VarArgKind::Valid;
1002
1003 if (getLangOpts().MSVCCompat)
1004 return VarArgKind::MSVCUndefined;
1005
1006 if (getLangOpts().HLSL && Ty->getAs<HLSLAttributedResourceType>())
1007 return VarArgKind::Valid;
1008
1009 // FIXME: In C++11, these cases are conditionally-supported, meaning we're
1010 // permitted to reject them. We should consider doing so.
1011 return VarArgKind::Undefined;
1012}
1013
1014void Sema::checkVariadicArgument(const Expr *E, VariadicCallType CT) {
1015 // Don't allow one to pass an Objective-C interface to a vararg.
1016 const QualType &Ty = E->getType();
1017 VarArgKind VAK = isValidVarArgType(Ty);
1018
1019 // Complain about passing non-POD types through varargs.
1020 switch (VAK) {
1021 case VarArgKind::ValidInCXX11:
1022 DiagRuntimeBehavior(
1023 Loc: E->getBeginLoc(), Statement: nullptr,
1024 PD: PDiag(DiagID: diag::warn_cxx98_compat_pass_non_pod_arg_to_vararg) << Ty << CT);
1025 [[fallthrough]];
1026 case VarArgKind::Valid:
1027 if (Ty->isRecordType()) {
1028 // This is unlikely to be what the user intended. If the class has a
1029 // 'c_str' member function, the user probably meant to call that.
1030 DiagRuntimeBehavior(Loc: E->getBeginLoc(), Statement: nullptr,
1031 PD: PDiag(DiagID: diag::warn_pass_class_arg_to_vararg)
1032 << Ty << CT << hasCStrMethod(E) << ".c_str()");
1033 }
1034 break;
1035
1036 case VarArgKind::Undefined:
1037 case VarArgKind::MSVCUndefined:
1038 DiagRuntimeBehavior(Loc: E->getBeginLoc(), Statement: nullptr,
1039 PD: PDiag(DiagID: diag::warn_cannot_pass_non_pod_arg_to_vararg)
1040 << getLangOpts().CPlusPlus11 << Ty << CT);
1041 break;
1042
1043 case VarArgKind::Invalid:
1044 if (Ty.isDestructedType() == QualType::DK_nontrivial_c_struct)
1045 Diag(Loc: E->getBeginLoc(),
1046 DiagID: diag::err_cannot_pass_non_trivial_c_struct_to_vararg)
1047 << Ty << CT;
1048 else if (Ty->isObjCObjectType())
1049 DiagRuntimeBehavior(Loc: E->getBeginLoc(), Statement: nullptr,
1050 PD: PDiag(DiagID: diag::err_cannot_pass_objc_interface_to_vararg)
1051 << Ty << CT);
1052 else
1053 Diag(Loc: E->getBeginLoc(), DiagID: diag::err_cannot_pass_to_vararg)
1054 << isa<InitListExpr>(Val: E) << Ty << CT;
1055 break;
1056 }
1057}
1058
1059ExprResult Sema::DefaultVariadicArgumentPromotion(Expr *E, VariadicCallType CT,
1060 FunctionDecl *FDecl) {
1061 if (const BuiltinType *PlaceholderTy = E->getType()->getAsPlaceholderType()) {
1062 // Strip the unbridged-cast placeholder expression off, if applicable.
1063 if (PlaceholderTy->getKind() == BuiltinType::ARCUnbridgedCast &&
1064 (CT == VariadicCallType::Method ||
1065 (FDecl && FDecl->hasAttr<CFAuditedTransferAttr>()))) {
1066 E = ObjC().stripARCUnbridgedCast(e: E);
1067
1068 // Otherwise, do normal placeholder checking.
1069 } else {
1070 ExprResult ExprRes = CheckPlaceholderExpr(E);
1071 if (ExprRes.isInvalid())
1072 return ExprError();
1073 E = ExprRes.get();
1074 }
1075 }
1076
1077 ExprResult ExprRes = DefaultArgumentPromotion(E);
1078 if (ExprRes.isInvalid())
1079 return ExprError();
1080
1081 // Copy blocks to the heap.
1082 if (ExprRes.get()->getType()->isBlockPointerType())
1083 maybeExtendBlockObject(E&: ExprRes);
1084
1085 E = ExprRes.get();
1086
1087 // Diagnostics regarding non-POD argument types are
1088 // emitted along with format string checking in Sema::CheckFunctionCall().
1089 if (isValidVarArgType(Ty: E->getType()) == VarArgKind::Undefined) {
1090 // Turn this into a trap.
1091 CXXScopeSpec SS;
1092 SourceLocation TemplateKWLoc;
1093 UnqualifiedId Name;
1094 Name.setIdentifier(Id: PP.getIdentifierInfo(Name: "__builtin_trap"),
1095 IdLoc: E->getBeginLoc());
1096 ExprResult TrapFn = ActOnIdExpression(S: TUScope, SS, TemplateKWLoc, Id&: Name,
1097 /*HasTrailingLParen=*/true,
1098 /*IsAddressOfOperand=*/false);
1099 if (TrapFn.isInvalid())
1100 return ExprError();
1101
1102 ExprResult Call = BuildCallExpr(S: TUScope, Fn: TrapFn.get(), LParenLoc: E->getBeginLoc(), ArgExprs: {},
1103 RParenLoc: E->getEndLoc());
1104 if (Call.isInvalid())
1105 return ExprError();
1106
1107 ExprResult Comma =
1108 ActOnBinOp(S: TUScope, TokLoc: E->getBeginLoc(), Kind: tok::comma, LHSExpr: Call.get(), RHSExpr: E);
1109 if (Comma.isInvalid())
1110 return ExprError();
1111 return Comma.get();
1112 }
1113
1114 if (!getLangOpts().CPlusPlus &&
1115 RequireCompleteType(Loc: E->getExprLoc(), T: E->getType(),
1116 DiagID: diag::err_call_incomplete_argument))
1117 return ExprError();
1118
1119 return E;
1120}
1121
1122/// Convert complex integers to complex floats and real integers to
1123/// real floats as required for complex arithmetic. Helper function of
1124/// UsualArithmeticConversions()
1125///
1126/// \return false if the integer expression is an integer type and is
1127/// successfully converted to the (complex) float type.
1128static bool handleComplexIntegerToFloatConversion(Sema &S, ExprResult &IntExpr,
1129 ExprResult &ComplexExpr,
1130 QualType IntTy,
1131 QualType ComplexTy,
1132 bool SkipCast) {
1133 if (IntTy->isComplexType() || IntTy->isRealFloatingType()) return true;
1134 if (SkipCast) return false;
1135 if (IntTy->isIntegerType()) {
1136 QualType fpTy = ComplexTy->castAs<ComplexType>()->getElementType();
1137 IntExpr = S.ImpCastExprToType(E: IntExpr.get(), Type: fpTy, CK: CK_IntegralToFloating);
1138 } else {
1139 assert(IntTy->isComplexIntegerType());
1140 IntExpr = S.ImpCastExprToType(E: IntExpr.get(), Type: ComplexTy,
1141 CK: CK_IntegralComplexToFloatingComplex);
1142 }
1143 return false;
1144}
1145
1146// This handles complex/complex, complex/float, or float/complex.
1147// When both operands are complex, the shorter operand is converted to the
1148// type of the longer, and that is the type of the result. This corresponds
1149// to what is done when combining two real floating-point operands.
1150// The fun begins when size promotion occur across type domains.
1151// From H&S 6.3.4: When one operand is complex and the other is a real
1152// floating-point type, the less precise type is converted, within it's
1153// real or complex domain, to the precision of the other type. For example,
1154// when combining a "long double" with a "double _Complex", the
1155// "double _Complex" is promoted to "long double _Complex".
1156static QualType handleComplexFloatConversion(Sema &S, ExprResult &Shorter,
1157 QualType ShorterType,
1158 QualType LongerType,
1159 bool PromotePrecision) {
1160 bool LongerIsComplex = isa<ComplexType>(Val: LongerType.getCanonicalType());
1161 QualType Result =
1162 LongerIsComplex ? LongerType : S.Context.getComplexType(T: LongerType);
1163
1164 if (PromotePrecision) {
1165 if (isa<ComplexType>(Val: ShorterType.getCanonicalType())) {
1166 Shorter =
1167 S.ImpCastExprToType(E: Shorter.get(), Type: Result, CK: CK_FloatingComplexCast);
1168 } else {
1169 if (LongerIsComplex)
1170 LongerType = LongerType->castAs<ComplexType>()->getElementType();
1171 Shorter = S.ImpCastExprToType(E: Shorter.get(), Type: LongerType, CK: CK_FloatingCast);
1172 }
1173 }
1174 return Result;
1175}
1176
1177/// Handle arithmetic conversion with complex types. Helper function of
1178/// UsualArithmeticConversions()
1179static QualType handleComplexConversion(Sema &S, ExprResult &LHS,
1180 ExprResult &RHS, QualType LHSType,
1181 QualType RHSType, bool IsCompAssign) {
1182 // Handle (complex) integer types.
1183 if (!handleComplexIntegerToFloatConversion(S, IntExpr&: RHS, ComplexExpr&: LHS, IntTy: RHSType, ComplexTy: LHSType,
1184 /*SkipCast=*/false))
1185 return LHSType;
1186 if (!handleComplexIntegerToFloatConversion(S, IntExpr&: LHS, ComplexExpr&: RHS, IntTy: LHSType, ComplexTy: RHSType,
1187 /*SkipCast=*/IsCompAssign))
1188 return RHSType;
1189
1190 // Compute the rank of the two types, regardless of whether they are complex.
1191 int Order = S.Context.getFloatingTypeOrder(LHS: LHSType, RHS: RHSType);
1192 if (Order < 0)
1193 // Promote the precision of the LHS if not an assignment.
1194 return handleComplexFloatConversion(S, Shorter&: LHS, ShorterType: LHSType, LongerType: RHSType,
1195 /*PromotePrecision=*/!IsCompAssign);
1196 // Promote the precision of the RHS unless it is already the same as the LHS.
1197 return handleComplexFloatConversion(S, Shorter&: RHS, ShorterType: RHSType, LongerType: LHSType,
1198 /*PromotePrecision=*/Order > 0);
1199}
1200
1201/// Handle arithmetic conversion from integer to float. Helper function
1202/// of UsualArithmeticConversions()
1203static QualType handleIntToFloatConversion(Sema &S, ExprResult &FloatExpr,
1204 ExprResult &IntExpr,
1205 QualType FloatTy, QualType IntTy,
1206 bool ConvertFloat, bool ConvertInt) {
1207 if (IntTy->isIntegerType()) {
1208 if (ConvertInt)
1209 // Convert intExpr to the lhs floating point type.
1210 IntExpr = S.ImpCastExprToType(E: IntExpr.get(), Type: FloatTy,
1211 CK: CK_IntegralToFloating);
1212 return FloatTy;
1213 }
1214
1215 // Convert both sides to the appropriate complex float.
1216 assert(IntTy->isComplexIntegerType());
1217 QualType result = S.Context.getComplexType(T: FloatTy);
1218
1219 // _Complex int -> _Complex float
1220 if (ConvertInt)
1221 IntExpr = S.ImpCastExprToType(E: IntExpr.get(), Type: result,
1222 CK: CK_IntegralComplexToFloatingComplex);
1223
1224 // float -> _Complex float
1225 if (ConvertFloat)
1226 FloatExpr = S.ImpCastExprToType(E: FloatExpr.get(), Type: result,
1227 CK: CK_FloatingRealToComplex);
1228
1229 return result;
1230}
1231
1232/// Handle arithmethic conversion with floating point types. Helper
1233/// function of UsualArithmeticConversions()
1234static QualType handleFloatConversion(Sema &S, ExprResult &LHS,
1235 ExprResult &RHS, QualType LHSType,
1236 QualType RHSType, bool IsCompAssign) {
1237 bool LHSFloat = LHSType->isRealFloatingType();
1238 bool RHSFloat = RHSType->isRealFloatingType();
1239
1240 // N1169 4.1.4: If one of the operands has a floating type and the other
1241 // operand has a fixed-point type, the fixed-point operand
1242 // is converted to the floating type [...]
1243 if (LHSType->isFixedPointType() || RHSType->isFixedPointType()) {
1244 if (LHSFloat)
1245 RHS = S.ImpCastExprToType(E: RHS.get(), Type: LHSType, CK: CK_FixedPointToFloating);
1246 else if (!IsCompAssign)
1247 LHS = S.ImpCastExprToType(E: LHS.get(), Type: RHSType, CK: CK_FixedPointToFloating);
1248 return LHSFloat ? LHSType : RHSType;
1249 }
1250
1251 // If we have two real floating types, convert the smaller operand
1252 // to the bigger result.
1253 if (LHSFloat && RHSFloat) {
1254 int order = S.Context.getFloatingTypeOrder(LHS: LHSType, RHS: RHSType);
1255 if (order > 0) {
1256 RHS = S.ImpCastExprToType(E: RHS.get(), Type: LHSType, CK: CK_FloatingCast);
1257 return LHSType;
1258 }
1259
1260 assert(order < 0 && "illegal float comparison");
1261 if (!IsCompAssign)
1262 LHS = S.ImpCastExprToType(E: LHS.get(), Type: RHSType, CK: CK_FloatingCast);
1263 return RHSType;
1264 }
1265
1266 if (LHSFloat) {
1267 // Half FP has to be promoted to float unless it is natively supported
1268 if (LHSType->isHalfType() && !S.getLangOpts().NativeHalfType)
1269 LHSType = S.Context.FloatTy;
1270
1271 return handleIntToFloatConversion(S, FloatExpr&: LHS, IntExpr&: RHS, FloatTy: LHSType, IntTy: RHSType,
1272 /*ConvertFloat=*/!IsCompAssign,
1273 /*ConvertInt=*/ true);
1274 }
1275 assert(RHSFloat);
1276 return handleIntToFloatConversion(S, FloatExpr&: RHS, IntExpr&: LHS, FloatTy: RHSType, IntTy: LHSType,
1277 /*ConvertFloat=*/ true,
1278 /*ConvertInt=*/!IsCompAssign);
1279}
1280
1281/// Diagnose attempts to convert between __float128, __ibm128 and
1282/// long double if there is no support for such conversion.
1283/// Helper function of UsualArithmeticConversions().
1284static bool unsupportedTypeConversion(const Sema &S, QualType LHSType,
1285 QualType RHSType) {
1286 // No issue if either is not a floating point type.
1287 if (!LHSType->isFloatingType() || !RHSType->isFloatingType())
1288 return false;
1289
1290 // No issue if both have the same 128-bit float semantics.
1291 auto *LHSComplex = LHSType->getAs<ComplexType>();
1292 auto *RHSComplex = RHSType->getAs<ComplexType>();
1293
1294 QualType LHSElem = LHSComplex ? LHSComplex->getElementType() : LHSType;
1295 QualType RHSElem = RHSComplex ? RHSComplex->getElementType() : RHSType;
1296
1297 const llvm::fltSemantics &LHSSem = S.Context.getFloatTypeSemantics(T: LHSElem);
1298 const llvm::fltSemantics &RHSSem = S.Context.getFloatTypeSemantics(T: RHSElem);
1299
1300 if ((&LHSSem != &llvm::APFloat::PPCDoubleDouble() ||
1301 &RHSSem != &llvm::APFloat::IEEEquad()) &&
1302 (&LHSSem != &llvm::APFloat::IEEEquad() ||
1303 &RHSSem != &llvm::APFloat::PPCDoubleDouble()))
1304 return false;
1305
1306 return true;
1307}
1308
1309typedef ExprResult PerformCastFn(Sema &S, Expr *operand, QualType toType);
1310
1311namespace {
1312/// These helper callbacks are placed in an anonymous namespace to
1313/// permit their use as function template parameters.
1314ExprResult doIntegralCast(Sema &S, Expr *op, QualType toType) {
1315 return S.ImpCastExprToType(E: op, Type: toType, CK: CK_IntegralCast);
1316}
1317
1318ExprResult doComplexIntegralCast(Sema &S, Expr *op, QualType toType) {
1319 return S.ImpCastExprToType(E: op, Type: S.Context.getComplexType(T: toType),
1320 CK: CK_IntegralComplexCast);
1321}
1322}
1323
1324/// Handle integer arithmetic conversions. Helper function of
1325/// UsualArithmeticConversions()
1326template <PerformCastFn doLHSCast, PerformCastFn doRHSCast>
1327static QualType handleIntegerConversion(Sema &S, ExprResult &LHS,
1328 ExprResult &RHS, QualType LHSType,
1329 QualType RHSType, bool IsCompAssign) {
1330 // The rules for this case are in C99 6.3.1.8
1331 int order = S.Context.getIntegerTypeOrder(LHS: LHSType, RHS: RHSType);
1332 bool LHSSigned = LHSType->hasSignedIntegerRepresentation();
1333 bool RHSSigned = RHSType->hasSignedIntegerRepresentation();
1334 if (LHSSigned == RHSSigned) {
1335 // Same signedness; use the higher-ranked type
1336 if (order >= 0) {
1337 RHS = (*doRHSCast)(S, RHS.get(), LHSType);
1338 return LHSType;
1339 } else if (!IsCompAssign)
1340 LHS = (*doLHSCast)(S, LHS.get(), RHSType);
1341 return RHSType;
1342 } else if (order != (LHSSigned ? 1 : -1)) {
1343 // The unsigned type has greater than or equal rank to the
1344 // signed type, so use the unsigned type
1345 if (RHSSigned) {
1346 RHS = (*doRHSCast)(S, RHS.get(), LHSType);
1347 return LHSType;
1348 } else if (!IsCompAssign)
1349 LHS = (*doLHSCast)(S, LHS.get(), RHSType);
1350 return RHSType;
1351 } else if (S.Context.getIntWidth(T: LHSType) != S.Context.getIntWidth(T: RHSType)) {
1352 // The two types are different widths; if we are here, that
1353 // means the signed type is larger than the unsigned type, so
1354 // use the signed type.
1355 if (LHSSigned) {
1356 RHS = (*doRHSCast)(S, RHS.get(), LHSType);
1357 return LHSType;
1358 } else if (!IsCompAssign)
1359 LHS = (*doLHSCast)(S, LHS.get(), RHSType);
1360 return RHSType;
1361 } else {
1362 // The signed type is higher-ranked than the unsigned type,
1363 // but isn't actually any bigger (like unsigned int and long
1364 // on most 32-bit systems). Use the unsigned type corresponding
1365 // to the signed type.
1366 QualType result =
1367 S.Context.getCorrespondingUnsignedType(T: LHSSigned ? LHSType : RHSType);
1368 RHS = (*doRHSCast)(S, RHS.get(), result);
1369 if (!IsCompAssign)
1370 LHS = (*doLHSCast)(S, LHS.get(), result);
1371 return result;
1372 }
1373}
1374
1375/// Handle conversions with GCC complex int extension. Helper function
1376/// of UsualArithmeticConversions()
1377static QualType handleComplexIntConversion(Sema &S, ExprResult &LHS,
1378 ExprResult &RHS, QualType LHSType,
1379 QualType RHSType,
1380 bool IsCompAssign) {
1381 const ComplexType *LHSComplexInt = LHSType->getAsComplexIntegerType();
1382 const ComplexType *RHSComplexInt = RHSType->getAsComplexIntegerType();
1383
1384 if (LHSComplexInt && RHSComplexInt) {
1385 QualType LHSEltType = LHSComplexInt->getElementType();
1386 QualType RHSEltType = RHSComplexInt->getElementType();
1387 QualType ScalarType =
1388 handleIntegerConversion<doComplexIntegralCast, doComplexIntegralCast>
1389 (S, LHS, RHS, LHSType: LHSEltType, RHSType: RHSEltType, IsCompAssign);
1390
1391 return S.Context.getComplexType(T: ScalarType);
1392 }
1393
1394 if (LHSComplexInt) {
1395 QualType LHSEltType = LHSComplexInt->getElementType();
1396 QualType ScalarType =
1397 handleIntegerConversion<doComplexIntegralCast, doIntegralCast>
1398 (S, LHS, RHS, LHSType: LHSEltType, RHSType, IsCompAssign);
1399 QualType ComplexType = S.Context.getComplexType(T: ScalarType);
1400 RHS = S.ImpCastExprToType(E: RHS.get(), Type: ComplexType,
1401 CK: CK_IntegralRealToComplex);
1402
1403 return ComplexType;
1404 }
1405
1406 assert(RHSComplexInt);
1407
1408 QualType RHSEltType = RHSComplexInt->getElementType();
1409 QualType ScalarType =
1410 handleIntegerConversion<doIntegralCast, doComplexIntegralCast>
1411 (S, LHS, RHS, LHSType, RHSType: RHSEltType, IsCompAssign);
1412 QualType ComplexType = S.Context.getComplexType(T: ScalarType);
1413
1414 if (!IsCompAssign)
1415 LHS = S.ImpCastExprToType(E: LHS.get(), Type: ComplexType,
1416 CK: CK_IntegralRealToComplex);
1417 return ComplexType;
1418}
1419
1420static QualType handleOverflowBehaviorTypeConversion(Sema &S, ExprResult &LHS,
1421 ExprResult &RHS,
1422 QualType LHSType,
1423 QualType RHSType,
1424 bool IsCompAssign) {
1425
1426 const auto *LhsOBT = LHSType->getAs<OverflowBehaviorType>();
1427 const auto *RhsOBT = RHSType->getAs<OverflowBehaviorType>();
1428
1429 assert(LHSType->isIntegerType() && RHSType->isIntegerType() &&
1430 "Non-integer type conversion not supported for OverflowBehaviorTypes");
1431
1432 bool LHSHasTrap =
1433 LhsOBT && LhsOBT->getBehaviorKind() ==
1434 OverflowBehaviorType::OverflowBehaviorKind::Trap;
1435 bool RHSHasTrap =
1436 RhsOBT && RhsOBT->getBehaviorKind() ==
1437 OverflowBehaviorType::OverflowBehaviorKind::Trap;
1438 bool LHSHasWrap =
1439 LhsOBT && LhsOBT->getBehaviorKind() ==
1440 OverflowBehaviorType::OverflowBehaviorKind::Wrap;
1441 bool RHSHasWrap =
1442 RhsOBT && RhsOBT->getBehaviorKind() ==
1443 OverflowBehaviorType::OverflowBehaviorKind::Wrap;
1444
1445 QualType LHSUnderlyingType = LhsOBT ? LhsOBT->getUnderlyingType() : LHSType;
1446 QualType RHSUnderlyingType = RhsOBT ? RhsOBT->getUnderlyingType() : RHSType;
1447
1448 std::optional<OverflowBehaviorType::OverflowBehaviorKind> DominantBehavior;
1449 if (LHSHasTrap || RHSHasTrap)
1450 DominantBehavior = OverflowBehaviorType::OverflowBehaviorKind::Trap;
1451 else if (LHSHasWrap || RHSHasWrap)
1452 DominantBehavior = OverflowBehaviorType::OverflowBehaviorKind::Wrap;
1453
1454 QualType LHSConvType = LHSUnderlyingType;
1455 QualType RHSConvType = RHSUnderlyingType;
1456 if (DominantBehavior) {
1457 if (!LhsOBT || LhsOBT->getBehaviorKind() != *DominantBehavior)
1458 LHSConvType = S.Context.getOverflowBehaviorType(Kind: *DominantBehavior,
1459 Wrapped: LHSUnderlyingType);
1460 else
1461 LHSConvType = LHSType;
1462
1463 if (!RhsOBT || RhsOBT->getBehaviorKind() != *DominantBehavior)
1464 RHSConvType = S.Context.getOverflowBehaviorType(Kind: *DominantBehavior,
1465 Wrapped: RHSUnderlyingType);
1466 else
1467 RHSConvType = RHSType;
1468 }
1469
1470 return handleIntegerConversion<doIntegralCast, doIntegralCast>(
1471 S, LHS, RHS, LHSType: LHSConvType, RHSType: RHSConvType, IsCompAssign);
1472}
1473
1474/// Return the rank of a given fixed point or integer type. The value itself
1475/// doesn't matter, but the values must be increasing with proper increasing
1476/// rank as described in N1169 4.1.1.
1477static unsigned GetFixedPointRank(QualType Ty) {
1478 const auto *BTy = Ty->getAs<BuiltinType>();
1479 assert(BTy && "Expected a builtin type.");
1480
1481 switch (BTy->getKind()) {
1482 case BuiltinType::ShortFract:
1483 case BuiltinType::UShortFract:
1484 case BuiltinType::SatShortFract:
1485 case BuiltinType::SatUShortFract:
1486 return 1;
1487 case BuiltinType::Fract:
1488 case BuiltinType::UFract:
1489 case BuiltinType::SatFract:
1490 case BuiltinType::SatUFract:
1491 return 2;
1492 case BuiltinType::LongFract:
1493 case BuiltinType::ULongFract:
1494 case BuiltinType::SatLongFract:
1495 case BuiltinType::SatULongFract:
1496 return 3;
1497 case BuiltinType::ShortAccum:
1498 case BuiltinType::UShortAccum:
1499 case BuiltinType::SatShortAccum:
1500 case BuiltinType::SatUShortAccum:
1501 return 4;
1502 case BuiltinType::Accum:
1503 case BuiltinType::UAccum:
1504 case BuiltinType::SatAccum:
1505 case BuiltinType::SatUAccum:
1506 return 5;
1507 case BuiltinType::LongAccum:
1508 case BuiltinType::ULongAccum:
1509 case BuiltinType::SatLongAccum:
1510 case BuiltinType::SatULongAccum:
1511 return 6;
1512 default:
1513 if (BTy->isInteger())
1514 return 0;
1515 llvm_unreachable("Unexpected fixed point or integer type");
1516 }
1517}
1518
1519/// handleFixedPointConversion - Fixed point operations between fixed
1520/// point types and integers or other fixed point types do not fall under
1521/// usual arithmetic conversion since these conversions could result in loss
1522/// of precsision (N1169 4.1.4). These operations should be calculated with
1523/// the full precision of their result type (N1169 4.1.6.2.1).
1524static QualType handleFixedPointConversion(Sema &S, QualType LHSTy,
1525 QualType RHSTy) {
1526 assert((LHSTy->isFixedPointType() || RHSTy->isFixedPointType()) &&
1527 "Expected at least one of the operands to be a fixed point type");
1528 assert((LHSTy->isFixedPointOrIntegerType() ||
1529 RHSTy->isFixedPointOrIntegerType()) &&
1530 "Special fixed point arithmetic operation conversions are only "
1531 "applied to ints or other fixed point types");
1532
1533 // If one operand has signed fixed-point type and the other operand has
1534 // unsigned fixed-point type, then the unsigned fixed-point operand is
1535 // converted to its corresponding signed fixed-point type and the resulting
1536 // type is the type of the converted operand.
1537 if (RHSTy->isSignedFixedPointType() && LHSTy->isUnsignedFixedPointType())
1538 LHSTy = S.Context.getCorrespondingSignedFixedPointType(Ty: LHSTy);
1539 else if (RHSTy->isUnsignedFixedPointType() && LHSTy->isSignedFixedPointType())
1540 RHSTy = S.Context.getCorrespondingSignedFixedPointType(Ty: RHSTy);
1541
1542 // The result type is the type with the highest rank, whereby a fixed-point
1543 // conversion rank is always greater than an integer conversion rank; if the
1544 // type of either of the operands is a saturating fixedpoint type, the result
1545 // type shall be the saturating fixed-point type corresponding to the type
1546 // with the highest rank; the resulting value is converted (taking into
1547 // account rounding and overflow) to the precision of the resulting type.
1548 // Same ranks between signed and unsigned types are resolved earlier, so both
1549 // types are either signed or both unsigned at this point.
1550 unsigned LHSTyRank = GetFixedPointRank(Ty: LHSTy);
1551 unsigned RHSTyRank = GetFixedPointRank(Ty: RHSTy);
1552
1553 QualType ResultTy = LHSTyRank > RHSTyRank ? LHSTy : RHSTy;
1554
1555 if (LHSTy->isSaturatedFixedPointType() || RHSTy->isSaturatedFixedPointType())
1556 ResultTy = S.Context.getCorrespondingSaturatedType(Ty: ResultTy);
1557
1558 return ResultTy;
1559}
1560
1561/// Check that the usual arithmetic conversions can be performed on this pair of
1562/// expressions that might be of enumeration type.
1563void Sema::checkEnumArithmeticConversions(Expr *LHS, Expr *RHS,
1564 SourceLocation Loc,
1565 ArithConvKind ACK) {
1566 // C++2a [expr.arith.conv]p1:
1567 // If one operand is of enumeration type and the other operand is of a
1568 // different enumeration type or a floating-point type, this behavior is
1569 // deprecated ([depr.arith.conv.enum]).
1570 //
1571 // Warn on this in all language modes. Produce a deprecation warning in C++20.
1572 // Eventually we will presumably reject these cases (in C++23 onwards?).
1573 QualType L = LHS->getEnumCoercedType(Ctx: Context),
1574 R = RHS->getEnumCoercedType(Ctx: Context);
1575 bool LEnum = L->isUnscopedEnumerationType(),
1576 REnum = R->isUnscopedEnumerationType();
1577 bool IsCompAssign = ACK == ArithConvKind::CompAssign;
1578 if ((!IsCompAssign && LEnum && R->isFloatingType()) ||
1579 (REnum && L->isFloatingType())) {
1580 Diag(Loc, DiagID: getLangOpts().CPlusPlus26 ? diag::err_arith_conv_enum_float_cxx26
1581 : getLangOpts().CPlusPlus20
1582 ? diag::warn_arith_conv_enum_float_cxx20
1583 : diag::warn_arith_conv_enum_float)
1584 << LHS->getSourceRange() << RHS->getSourceRange() << (int)ACK << LEnum
1585 << L << R;
1586 } else if (!IsCompAssign && LEnum && REnum &&
1587 !Context.hasSameUnqualifiedType(T1: L, T2: R)) {
1588 unsigned DiagID;
1589 // In C++ 26, usual arithmetic conversions between 2 different enum types
1590 // are ill-formed.
1591 if (getLangOpts().CPlusPlus26)
1592 DiagID = diag::warn_conv_mixed_enum_types_cxx26;
1593 else if (!L->castAsCanonical<EnumType>()->getDecl()->hasNameForLinkage() ||
1594 !R->castAsCanonical<EnumType>()->getDecl()->hasNameForLinkage()) {
1595 // If either enumeration type is unnamed, it's less likely that the
1596 // user cares about this, but this situation is still deprecated in
1597 // C++2a. Use a different warning group.
1598 DiagID = getLangOpts().CPlusPlus20
1599 ? diag::warn_arith_conv_mixed_anon_enum_types_cxx20
1600 : diag::warn_arith_conv_mixed_anon_enum_types;
1601 } else if (ACK == ArithConvKind::Conditional) {
1602 // Conditional expressions are separated out because they have
1603 // historically had a different warning flag.
1604 DiagID = getLangOpts().CPlusPlus20
1605 ? diag::warn_conditional_mixed_enum_types_cxx20
1606 : diag::warn_conditional_mixed_enum_types;
1607 } else if (ACK == ArithConvKind::Comparison) {
1608 // Comparison expressions are separated out because they have
1609 // historically had a different warning flag.
1610 DiagID = getLangOpts().CPlusPlus20
1611 ? diag::warn_comparison_mixed_enum_types_cxx20
1612 : diag::warn_comparison_mixed_enum_types;
1613 } else {
1614 DiagID = getLangOpts().CPlusPlus20
1615 ? diag::warn_arith_conv_mixed_enum_types_cxx20
1616 : diag::warn_arith_conv_mixed_enum_types;
1617 }
1618 Diag(Loc, DiagID) << LHS->getSourceRange() << RHS->getSourceRange()
1619 << (int)ACK << L << R;
1620 }
1621}
1622
1623static void CheckUnicodeArithmeticConversions(Sema &SemaRef, Expr *LHS,
1624 Expr *RHS, SourceLocation Loc,
1625 ArithConvKind ACK) {
1626 QualType LHSType = LHS->getType().getUnqualifiedType();
1627 QualType RHSType = RHS->getType().getUnqualifiedType();
1628
1629 if (!SemaRef.getLangOpts().CPlusPlus || !LHSType->isUnicodeCharacterType() ||
1630 !RHSType->isUnicodeCharacterType())
1631 return;
1632
1633 if (ACK == ArithConvKind::Comparison) {
1634 if (SemaRef.getASTContext().hasSameType(T1: LHSType, T2: RHSType))
1635 return;
1636
1637 auto IsSingleCodeUnitCP = [](const QualType &T, const llvm::APSInt &Value) {
1638 if (T->isChar8Type())
1639 return llvm::IsSingleCodeUnitUTF8Codepoint(Value.getExtValue());
1640 if (T->isChar16Type())
1641 return llvm::IsSingleCodeUnitUTF16Codepoint(Value.getExtValue());
1642 assert(T->isChar32Type());
1643 return llvm::IsSingleCodeUnitUTF32Codepoint(Value.getExtValue());
1644 };
1645
1646 Expr::EvalResult LHSRes, RHSRes;
1647 bool LHSSuccess = LHS->EvaluateAsInt(Result&: LHSRes, Ctx: SemaRef.getASTContext(),
1648 AllowSideEffects: Expr::SE_AllowSideEffects,
1649 InConstantContext: SemaRef.isConstantEvaluatedContext());
1650 bool RHSuccess = RHS->EvaluateAsInt(Result&: RHSRes, Ctx: SemaRef.getASTContext(),
1651 AllowSideEffects: Expr::SE_AllowSideEffects,
1652 InConstantContext: SemaRef.isConstantEvaluatedContext());
1653
1654 // Don't warn if the one known value is a representable
1655 // in the type of both expressions.
1656 if (LHSSuccess != RHSuccess) {
1657 Expr::EvalResult &Res = LHSSuccess ? LHSRes : RHSRes;
1658 if (IsSingleCodeUnitCP(LHSType, Res.Val.getInt()) &&
1659 IsSingleCodeUnitCP(RHSType, Res.Val.getInt()))
1660 return;
1661 }
1662
1663 if (!LHSSuccess || !RHSuccess) {
1664 SemaRef.Diag(Loc, DiagID: diag::warn_comparison_unicode_mixed_types)
1665 << LHS->getSourceRange() << RHS->getSourceRange() << LHSType
1666 << RHSType;
1667 return;
1668 }
1669
1670 llvm::APSInt LHSValue(32);
1671 LHSValue = LHSRes.Val.getInt();
1672 llvm::APSInt RHSValue(32);
1673 RHSValue = RHSRes.Val.getInt();
1674
1675 bool LHSSafe = IsSingleCodeUnitCP(LHSType, LHSValue);
1676 bool RHSSafe = IsSingleCodeUnitCP(RHSType, RHSValue);
1677 if (LHSSafe && RHSSafe)
1678 return;
1679
1680 SemaRef.Diag(Loc, DiagID: diag::warn_comparison_unicode_mixed_types_constant)
1681 << LHS->getSourceRange() << RHS->getSourceRange() << LHSType << RHSType
1682 << FormatUTFCodeUnitAsCodepoint(Value: LHSValue.getExtValue(), T: LHSType)
1683 << FormatUTFCodeUnitAsCodepoint(Value: RHSValue.getExtValue(), T: RHSType);
1684 return;
1685 }
1686
1687 if (SemaRef.getASTContext().hasSameType(T1: LHSType, T2: RHSType))
1688 return;
1689
1690 SemaRef.Diag(Loc, DiagID: diag::warn_arith_conv_mixed_unicode_types)
1691 << LHS->getSourceRange() << RHS->getSourceRange() << ACK << LHSType
1692 << RHSType;
1693}
1694
1695/// UsualArithmeticConversions - Performs various conversions that are common to
1696/// binary operators (C99 6.3.1.8). If both operands aren't arithmetic, this
1697/// routine returns the first non-arithmetic type found. The client is
1698/// responsible for emitting appropriate error diagnostics.
1699QualType Sema::UsualArithmeticConversions(ExprResult &LHS, ExprResult &RHS,
1700 SourceLocation Loc,
1701 ArithConvKind ACK) {
1702
1703 checkEnumArithmeticConversions(LHS: LHS.get(), RHS: RHS.get(), Loc, ACK);
1704
1705 CheckUnicodeArithmeticConversions(SemaRef&: *this, LHS: LHS.get(), RHS: RHS.get(), Loc, ACK);
1706
1707 if (ACK != ArithConvKind::CompAssign) {
1708 LHS = UsualUnaryConversions(E: LHS.get());
1709 if (LHS.isInvalid())
1710 return QualType();
1711 }
1712
1713 RHS = UsualUnaryConversions(E: RHS.get());
1714 if (RHS.isInvalid())
1715 return QualType();
1716
1717 // For conversion purposes, we ignore any qualifiers.
1718 // For example, "const float" and "float" are equivalent.
1719 QualType LHSType = LHS.get()->getType().getUnqualifiedType();
1720 QualType RHSType = RHS.get()->getType().getUnqualifiedType();
1721
1722 // For conversion purposes, we ignore any atomic qualifier on the LHS.
1723 if (const AtomicType *AtomicLHS = LHSType->getAs<AtomicType>())
1724 LHSType = AtomicLHS->getValueType();
1725
1726 // If both types are identical, no conversion is needed.
1727 if (Context.hasSameType(T1: LHSType, T2: RHSType))
1728 return Context.getCommonSugaredType(X: LHSType, Y: RHSType);
1729
1730 // If either side is a non-arithmetic type (e.g. a pointer), we are done.
1731 // The caller can deal with this (e.g. pointer + int).
1732 if (!LHSType->isArithmeticType() || !RHSType->isArithmeticType())
1733 return QualType();
1734
1735 // Apply unary and bitfield promotions to the LHS's type.
1736 QualType LHSUnpromotedType = LHSType;
1737 if (Context.isPromotableIntegerType(T: LHSType))
1738 LHSType = Context.getPromotedIntegerType(PromotableType: LHSType);
1739 QualType LHSBitfieldPromoteTy = Context.isPromotableBitField(E: LHS.get());
1740 if (!LHSBitfieldPromoteTy.isNull())
1741 LHSType = LHSBitfieldPromoteTy;
1742 if (LHSType != LHSUnpromotedType && ACK != ArithConvKind::CompAssign)
1743 LHS = ImpCastExprToType(E: LHS.get(), Type: LHSType, CK: CK_IntegralCast);
1744
1745 // If both types are identical, no conversion is needed.
1746 if (Context.hasSameType(T1: LHSType, T2: RHSType))
1747 return Context.getCommonSugaredType(X: LHSType, Y: RHSType);
1748
1749 // At this point, we have two different arithmetic types.
1750
1751 // Diagnose attempts to convert between __ibm128, __float128 and long double
1752 // where such conversions currently can't be handled.
1753 if (unsupportedTypeConversion(S: *this, LHSType, RHSType))
1754 return QualType();
1755
1756 // Handle complex types first (C99 6.3.1.8p1).
1757 if (LHSType->isComplexType() || RHSType->isComplexType())
1758 return handleComplexConversion(S&: *this, LHS, RHS, LHSType, RHSType,
1759 IsCompAssign: ACK == ArithConvKind::CompAssign);
1760
1761 // Now handle "real" floating types (i.e. float, double, long double).
1762 if (LHSType->isRealFloatingType() || RHSType->isRealFloatingType())
1763 return handleFloatConversion(S&: *this, LHS, RHS, LHSType, RHSType,
1764 IsCompAssign: ACK == ArithConvKind::CompAssign);
1765
1766 // Handle GCC complex int extension.
1767 if (LHSType->isComplexIntegerType() || RHSType->isComplexIntegerType())
1768 return handleComplexIntConversion(S&: *this, LHS, RHS, LHSType, RHSType,
1769 IsCompAssign: ACK == ArithConvKind::CompAssign);
1770
1771 if (LHSType->isFixedPointType() || RHSType->isFixedPointType())
1772 return handleFixedPointConversion(S&: *this, LHSTy: LHSType, RHSTy: RHSType);
1773
1774 if (LHSType->isOverflowBehaviorType() || RHSType->isOverflowBehaviorType())
1775 return handleOverflowBehaviorTypeConversion(
1776 S&: *this, LHS, RHS, LHSType, RHSType, IsCompAssign: ACK == ArithConvKind::CompAssign);
1777
1778 // Finally, we have two differing integer types.
1779 return handleIntegerConversion<doIntegralCast, doIntegralCast>(
1780 S&: *this, LHS, RHS, LHSType, RHSType, IsCompAssign: ACK == ArithConvKind::CompAssign);
1781}
1782
1783//===----------------------------------------------------------------------===//
1784// Semantic Analysis for various Expression Types
1785//===----------------------------------------------------------------------===//
1786
1787
1788ExprResult Sema::ActOnGenericSelectionExpr(
1789 SourceLocation KeyLoc, SourceLocation DefaultLoc, SourceLocation RParenLoc,
1790 bool PredicateIsExpr, void *ControllingExprOrType,
1791 ArrayRef<ParsedType> ArgTypes, ArrayRef<Expr *> ArgExprs) {
1792 unsigned NumAssocs = ArgTypes.size();
1793 assert(NumAssocs == ArgExprs.size());
1794
1795 TypeSourceInfo **Types = new TypeSourceInfo*[NumAssocs];
1796 for (unsigned i = 0; i < NumAssocs; ++i) {
1797 if (ArgTypes[i])
1798 (void) GetTypeFromParser(Ty: ArgTypes[i], TInfo: &Types[i]);
1799 else
1800 Types[i] = nullptr;
1801 }
1802
1803 // If we have a controlling type, we need to convert it from a parsed type
1804 // into a semantic type and then pass that along.
1805 if (!PredicateIsExpr) {
1806 TypeSourceInfo *ControllingType;
1807 (void)GetTypeFromParser(Ty: ParsedType::getFromOpaquePtr(P: ControllingExprOrType),
1808 TInfo: &ControllingType);
1809 assert(ControllingType && "couldn't get the type out of the parser");
1810 ControllingExprOrType = ControllingType;
1811 }
1812
1813 ExprResult ER = CreateGenericSelectionExpr(
1814 KeyLoc, DefaultLoc, RParenLoc, PredicateIsExpr, ControllingExprOrType,
1815 Types: llvm::ArrayRef(Types, NumAssocs), Exprs: ArgExprs);
1816 delete [] Types;
1817 return ER;
1818}
1819
1820// Helper function to determine type compatibility for C _Generic expressions.
1821// Multiple compatible types within the same _Generic expression is ambiguous
1822// and not valid.
1823static bool areTypesCompatibleForGeneric(ASTContext &Ctx, QualType T,
1824 QualType U) {
1825 // Try to handle special types like OverflowBehaviorTypes
1826 const auto *TOBT = T->getAs<OverflowBehaviorType>();
1827 const auto *UOBT = U.getCanonicalType()->getAs<OverflowBehaviorType>();
1828
1829 if (TOBT || UOBT) {
1830 if (TOBT && UOBT) {
1831 if (TOBT->getBehaviorKind() == UOBT->getBehaviorKind())
1832 return Ctx.typesAreCompatible(T1: TOBT->getUnderlyingType(),
1833 T2: UOBT->getUnderlyingType());
1834 return false;
1835 }
1836 return false;
1837 }
1838
1839 // We're dealing with types that don't require special handling.
1840 return Ctx.typesAreCompatible(T1: T, T2: U);
1841}
1842
1843ExprResult Sema::CreateGenericSelectionExpr(
1844 SourceLocation KeyLoc, SourceLocation DefaultLoc, SourceLocation RParenLoc,
1845 bool PredicateIsExpr, void *ControllingExprOrType,
1846 ArrayRef<TypeSourceInfo *> Types, ArrayRef<Expr *> Exprs) {
1847 unsigned NumAssocs = Types.size();
1848 assert(NumAssocs == Exprs.size());
1849 assert(ControllingExprOrType &&
1850 "Must have either a controlling expression or a controlling type");
1851
1852 Expr *ControllingExpr = nullptr;
1853 TypeSourceInfo *ControllingType = nullptr;
1854 if (PredicateIsExpr) {
1855 // Decay and strip qualifiers for the controlling expression type, and
1856 // handle placeholder type replacement. See committee discussion from WG14
1857 // DR423.
1858 EnterExpressionEvaluationContext Unevaluated(
1859 *this, Sema::ExpressionEvaluationContext::Unevaluated);
1860 ExprResult R = DefaultFunctionArrayLvalueConversion(
1861 E: reinterpret_cast<Expr *>(ControllingExprOrType));
1862 if (R.isInvalid())
1863 return ExprError();
1864 ControllingExpr = R.get();
1865 } else {
1866 // The extension form uses the type directly rather than converting it.
1867 ControllingType = reinterpret_cast<TypeSourceInfo *>(ControllingExprOrType);
1868 if (!ControllingType)
1869 return ExprError();
1870 }
1871
1872 bool TypeErrorFound = false,
1873 IsResultDependent = ControllingExpr
1874 ? ControllingExpr->isTypeDependent()
1875 : ControllingType->getType()->isDependentType(),
1876 ContainsUnexpandedParameterPack =
1877 ControllingExpr
1878 ? ControllingExpr->containsUnexpandedParameterPack()
1879 : ControllingType->getType()->containsUnexpandedParameterPack();
1880
1881 // The controlling expression is an unevaluated operand, so side effects are
1882 // likely unintended.
1883 if (!inTemplateInstantiation() && !IsResultDependent && ControllingExpr &&
1884 ControllingExpr->HasSideEffects(Ctx: Context, IncludePossibleEffects: false))
1885 Diag(Loc: ControllingExpr->getExprLoc(),
1886 DiagID: diag::warn_side_effects_unevaluated_context);
1887
1888 for (unsigned i = 0; i < NumAssocs; ++i) {
1889 if (Exprs[i]->containsUnexpandedParameterPack())
1890 ContainsUnexpandedParameterPack = true;
1891
1892 if (Types[i]) {
1893 if (Types[i]->getType()->containsUnexpandedParameterPack())
1894 ContainsUnexpandedParameterPack = true;
1895
1896 if (Types[i]->getType()->isDependentType()) {
1897 IsResultDependent = true;
1898 } else {
1899 // We relax the restriction on use of incomplete types and non-object
1900 // types with the type-based extension of _Generic. Allowing incomplete
1901 // objects means those can be used as "tags" for a type-safe way to map
1902 // to a value. Similarly, matching on function types rather than
1903 // function pointer types can be useful. However, the restriction on VM
1904 // types makes sense to retain as there are open questions about how
1905 // the selection can be made at compile time.
1906 //
1907 // C11 6.5.1.1p2 "The type name in a generic association shall specify a
1908 // complete object type other than a variably modified type."
1909 // C2y removed the requirement that an expression form must
1910 // use a complete type, though it's still as-if the type has undergone
1911 // lvalue conversion. We support this as an extension in C23 and
1912 // earlier because GCC does so.
1913 unsigned D = 0;
1914 if (ControllingExpr && Types[i]->getType()->isIncompleteType())
1915 D = LangOpts.C2y ? diag::warn_c2y_compat_assoc_type_incomplete
1916 : diag::ext_assoc_type_incomplete;
1917 else if (ControllingExpr && !Types[i]->getType()->isObjectType())
1918 D = diag::err_assoc_type_nonobject;
1919 else if (Types[i]->getType()->isVariablyModifiedType())
1920 D = diag::err_assoc_type_variably_modified;
1921 else if (ControllingExpr) {
1922 // Because the controlling expression undergoes lvalue conversion,
1923 // array conversion, and function conversion, an association which is
1924 // of array type, function type, or is qualified can never be
1925 // reached. We will warn about this so users are less surprised by
1926 // the unreachable association. However, we don't have to handle
1927 // function types; that's not an object type, so it's handled above.
1928 //
1929 // The logic is somewhat different for C++ because C++ has different
1930 // lvalue to rvalue conversion rules than C. [conv.lvalue]p1 says,
1931 // If T is a non-class type, the type of the prvalue is the cv-
1932 // unqualified version of T. Otherwise, the type of the prvalue is T.
1933 // The result of these rules is that all qualified types in an
1934 // association in C are unreachable, and in C++, only qualified non-
1935 // class types are unreachable.
1936 //
1937 // NB: this does not apply when the first operand is a type rather
1938 // than an expression, because the type form does not undergo
1939 // conversion.
1940 unsigned Reason = 0;
1941 QualType QT = Types[i]->getType();
1942 if (QT->isArrayType())
1943 Reason = 1;
1944 else if (QT.hasQualifiers() &&
1945 (!LangOpts.CPlusPlus || !QT->isRecordType()))
1946 Reason = 2;
1947
1948 if (Reason)
1949 Diag(Loc: Types[i]->getTypeLoc().getBeginLoc(),
1950 DiagID: diag::warn_unreachable_association)
1951 << QT << (Reason - 1);
1952 }
1953
1954 if (D != 0) {
1955 Diag(Loc: Types[i]->getTypeLoc().getBeginLoc(), DiagID: D)
1956 << Types[i]->getTypeLoc().getSourceRange() << Types[i]->getType();
1957 if (getDiagnostics().getDiagnosticLevel(
1958 DiagID: D, Loc: Types[i]->getTypeLoc().getBeginLoc()) >=
1959 DiagnosticsEngine::Error)
1960 TypeErrorFound = true;
1961 }
1962
1963 // C11 6.5.1.1p2 "No two generic associations in the same generic
1964 // selection shall specify compatible types."
1965 for (unsigned j = i+1; j < NumAssocs; ++j)
1966 if (Types[j] && !Types[j]->getType()->isDependentType() &&
1967 areTypesCompatibleForGeneric(Ctx&: Context, T: Types[i]->getType(),
1968 U: Types[j]->getType())) {
1969 Diag(Loc: Types[j]->getTypeLoc().getBeginLoc(),
1970 DiagID: diag::err_assoc_compatible_types)
1971 << Types[j]->getTypeLoc().getSourceRange()
1972 << Types[j]->getType()
1973 << Types[i]->getType();
1974 Diag(Loc: Types[i]->getTypeLoc().getBeginLoc(),
1975 DiagID: diag::note_compat_assoc)
1976 << Types[i]->getTypeLoc().getSourceRange()
1977 << Types[i]->getType();
1978 TypeErrorFound = true;
1979 }
1980 }
1981 }
1982 }
1983 if (TypeErrorFound)
1984 return ExprError();
1985
1986 // If we determined that the generic selection is result-dependent, don't
1987 // try to compute the result expression.
1988 if (IsResultDependent) {
1989 if (ControllingExpr)
1990 return GenericSelectionExpr::Create(Context, GenericLoc: KeyLoc, ControllingExpr,
1991 AssocTypes: Types, AssocExprs: Exprs, DefaultLoc, RParenLoc,
1992 ContainsUnexpandedParameterPack);
1993 return GenericSelectionExpr::Create(Context, GenericLoc: KeyLoc, ControllingType, AssocTypes: Types,
1994 AssocExprs: Exprs, DefaultLoc, RParenLoc,
1995 ContainsUnexpandedParameterPack);
1996 }
1997
1998 SmallVector<unsigned, 1> CompatIndices;
1999 unsigned DefaultIndex = std::numeric_limits<unsigned>::max();
2000 // Look at the canonical type of the controlling expression in case it was a
2001 // deduced type like __auto_type. However, when issuing diagnostics, use the
2002 // type the user wrote in source rather than the canonical one.
2003 for (unsigned i = 0; i < NumAssocs; ++i) {
2004 if (!Types[i])
2005 DefaultIndex = i;
2006 else {
2007 bool Compatible;
2008 QualType ControllingQT =
2009 ControllingExpr ? ControllingExpr->getType().getCanonicalType()
2010 : ControllingType->getType().getCanonicalType();
2011 QualType AssocQT = Types[i]->getType();
2012
2013 Compatible =
2014 areTypesCompatibleForGeneric(Ctx&: Context, T: ControllingQT, U: AssocQT);
2015
2016 if (Compatible)
2017 CompatIndices.push_back(Elt: i);
2018 }
2019 }
2020
2021 auto GetControllingRangeAndType = [](Expr *ControllingExpr,
2022 TypeSourceInfo *ControllingType) {
2023 // We strip parens here because the controlling expression is typically
2024 // parenthesized in macro definitions.
2025 if (ControllingExpr)
2026 ControllingExpr = ControllingExpr->IgnoreParens();
2027
2028 SourceRange SR = ControllingExpr
2029 ? ControllingExpr->getSourceRange()
2030 : ControllingType->getTypeLoc().getSourceRange();
2031 QualType QT = ControllingExpr ? ControllingExpr->getType()
2032 : ControllingType->getType();
2033
2034 return std::make_pair(x&: SR, y&: QT);
2035 };
2036
2037 // C11 6.5.1.1p2 "The controlling expression of a generic selection shall have
2038 // type compatible with at most one of the types named in its generic
2039 // association list."
2040 if (CompatIndices.size() > 1) {
2041 auto P = GetControllingRangeAndType(ControllingExpr, ControllingType);
2042 SourceRange SR = P.first;
2043 Diag(Loc: SR.getBegin(), DiagID: diag::err_generic_sel_multi_match)
2044 << SR << P.second << (unsigned)CompatIndices.size();
2045 for (unsigned I : CompatIndices) {
2046 Diag(Loc: Types[I]->getTypeLoc().getBeginLoc(),
2047 DiagID: diag::note_compat_assoc)
2048 << Types[I]->getTypeLoc().getSourceRange()
2049 << Types[I]->getType();
2050 }
2051 return ExprError();
2052 }
2053
2054 // C11 6.5.1.1p2 "If a generic selection has no default generic association,
2055 // its controlling expression shall have type compatible with exactly one of
2056 // the types named in its generic association list."
2057 if (DefaultIndex == std::numeric_limits<unsigned>::max() &&
2058 CompatIndices.size() == 0) {
2059 auto P = GetControllingRangeAndType(ControllingExpr, ControllingType);
2060 SourceRange SR = P.first;
2061 Diag(Loc: SR.getBegin(), DiagID: diag::err_generic_sel_no_match) << SR << P.second;
2062 return ExprError();
2063 }
2064
2065 // C11 6.5.1.1p3 "If a generic selection has a generic association with a
2066 // type name that is compatible with the type of the controlling expression,
2067 // then the result expression of the generic selection is the expression
2068 // in that generic association. Otherwise, the result expression of the
2069 // generic selection is the expression in the default generic association."
2070 unsigned ResultIndex =
2071 CompatIndices.size() ? CompatIndices[0] : DefaultIndex;
2072
2073 if (ControllingExpr) {
2074 return GenericSelectionExpr::Create(
2075 Context, GenericLoc: KeyLoc, ControllingExpr, AssocTypes: Types, AssocExprs: Exprs, DefaultLoc, RParenLoc,
2076 ContainsUnexpandedParameterPack, ResultIndex);
2077 }
2078 return GenericSelectionExpr::Create(
2079 Context, GenericLoc: KeyLoc, ControllingType, AssocTypes: Types, AssocExprs: Exprs, DefaultLoc, RParenLoc,
2080 ContainsUnexpandedParameterPack, ResultIndex);
2081}
2082
2083static PredefinedIdentKind getPredefinedExprKind(tok::TokenKind Kind) {
2084 switch (Kind) {
2085 default:
2086 llvm_unreachable("unexpected TokenKind");
2087 case tok::kw___func__:
2088 return PredefinedIdentKind::Func; // [C99 6.4.2.2]
2089 case tok::kw___FUNCTION__:
2090 return PredefinedIdentKind::Function;
2091 case tok::kw___FUNCDNAME__:
2092 return PredefinedIdentKind::FuncDName; // [MS]
2093 case tok::kw___FUNCSIG__:
2094 return PredefinedIdentKind::FuncSig; // [MS]
2095 case tok::kw_L__FUNCTION__:
2096 return PredefinedIdentKind::LFunction; // [MS]
2097 case tok::kw_L__FUNCSIG__:
2098 return PredefinedIdentKind::LFuncSig; // [MS]
2099 case tok::kw___PRETTY_FUNCTION__:
2100 return PredefinedIdentKind::PrettyFunction; // [GNU]
2101 }
2102}
2103
2104/// getPredefinedExprDecl - Returns Decl of a given DeclContext that can be used
2105/// to determine the value of a PredefinedExpr. This can be either a
2106/// block, lambda, captured statement, function, otherwise a nullptr.
2107static Decl *getPredefinedExprDecl(DeclContext *DC) {
2108 while (DC && !isa<BlockDecl, CapturedDecl, FunctionDecl, ObjCMethodDecl>(Val: DC))
2109 DC = DC->getParent();
2110 return cast_or_null<Decl>(Val: DC);
2111}
2112
2113/// getUDSuffixLoc - Create a SourceLocation for a ud-suffix, given the
2114/// location of the token and the offset of the ud-suffix within it.
2115static SourceLocation getUDSuffixLoc(Sema &S, SourceLocation TokLoc,
2116 unsigned Offset) {
2117 return Lexer::AdvanceToTokenCharacter(TokStart: TokLoc, Characters: Offset, SM: S.getSourceManager(),
2118 LangOpts: S.getLangOpts());
2119}
2120
2121/// BuildCookedLiteralOperatorCall - A user-defined literal was found. Look up
2122/// the corresponding cooked (non-raw) literal operator, and build a call to it.
2123static ExprResult BuildCookedLiteralOperatorCall(Sema &S, Scope *Scope,
2124 IdentifierInfo *UDSuffix,
2125 SourceLocation UDSuffixLoc,
2126 ArrayRef<Expr*> Args,
2127 SourceLocation LitEndLoc) {
2128 assert(Args.size() <= 2 && "too many arguments for literal operator");
2129
2130 QualType ArgTy[2];
2131 for (unsigned ArgIdx = 0; ArgIdx != Args.size(); ++ArgIdx) {
2132 ArgTy[ArgIdx] = Args[ArgIdx]->getType();
2133 if (ArgTy[ArgIdx]->isArrayType())
2134 ArgTy[ArgIdx] = S.Context.getArrayDecayedType(T: ArgTy[ArgIdx]);
2135 }
2136
2137 DeclarationName OpName =
2138 S.Context.DeclarationNames.getCXXLiteralOperatorName(II: UDSuffix);
2139 DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc);
2140 OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc);
2141
2142 LookupResult R(S, OpName, UDSuffixLoc, Sema::LookupOrdinaryName);
2143 if (S.LookupLiteralOperator(S: Scope, R, ArgTys: llvm::ArrayRef(ArgTy, Args.size()),
2144 /*AllowRaw*/ false, /*AllowTemplate*/ false,
2145 /*AllowStringTemplatePack*/ AllowStringTemplate: false,
2146 /*DiagnoseMissing*/ true) == Sema::LOLR_Error)
2147 return ExprError();
2148
2149 return S.BuildLiteralOperatorCall(R, SuffixInfo&: OpNameInfo, Args, LitEndLoc);
2150}
2151
2152ExprResult Sema::ActOnUnevaluatedStringLiteral(ArrayRef<Token> StringToks) {
2153 // StringToks needs backing storage as it doesn't hold array elements itself
2154 std::vector<Token> ExpandedToks;
2155 if (getLangOpts().MicrosoftExt)
2156 StringToks = ExpandedToks = ExpandFunctionLocalPredefinedMacros(Toks: StringToks);
2157
2158 StringLiteralParser Literal(StringToks, PP,
2159 StringLiteralEvalMethod::Unevaluated);
2160 if (Literal.hadError)
2161 return ExprError();
2162
2163 SmallVector<SourceLocation, 4> StringTokLocs;
2164 for (const Token &Tok : StringToks)
2165 StringTokLocs.push_back(Elt: Tok.getLocation());
2166
2167 StringLiteral *Lit = StringLiteral::Create(Ctx: Context, Str: Literal.GetString(),
2168 Kind: StringLiteralKind::Unevaluated,
2169 Pascal: false, Ty: {}, Locs: StringTokLocs);
2170
2171 if (!Literal.getUDSuffix().empty()) {
2172 SourceLocation UDSuffixLoc =
2173 getUDSuffixLoc(S&: *this, TokLoc: StringTokLocs[Literal.getUDSuffixToken()],
2174 Offset: Literal.getUDSuffixOffset());
2175 return ExprError(Diag(Loc: UDSuffixLoc, DiagID: diag::err_invalid_string_udl));
2176 }
2177
2178 return Lit;
2179}
2180
2181std::vector<Token>
2182Sema::ExpandFunctionLocalPredefinedMacros(ArrayRef<Token> Toks) {
2183 // MSVC treats some predefined identifiers (e.g. __FUNCTION__) as function
2184 // local macros that expand to string literals that may be concatenated.
2185 // These macros are expanded here (in Sema), because StringLiteralParser
2186 // (in Lex) doesn't know the enclosing function (because it hasn't been
2187 // parsed yet).
2188 assert(getLangOpts().MicrosoftExt);
2189
2190 // Note: Although function local macros are defined only inside functions,
2191 // we ensure a valid `CurrentDecl` even outside of a function. This allows
2192 // expansion of macros into empty string literals without additional checks.
2193 Decl *CurrentDecl = getPredefinedExprDecl(DC: CurContext);
2194 if (!CurrentDecl)
2195 CurrentDecl = Context.getTranslationUnitDecl();
2196
2197 std::vector<Token> ExpandedToks;
2198 ExpandedToks.reserve(n: Toks.size());
2199 for (const Token &Tok : Toks) {
2200 if (!isFunctionLocalStringLiteralMacro(K: Tok.getKind(), LO: getLangOpts())) {
2201 assert(tok::isStringLiteral(Tok.getKind()));
2202 ExpandedToks.emplace_back(args: Tok);
2203 continue;
2204 }
2205 if (isa<TranslationUnitDecl>(Val: CurrentDecl))
2206 Diag(Loc: Tok.getLocation(), DiagID: diag::ext_predef_outside_function);
2207 // Stringify predefined expression
2208 Diag(Loc: Tok.getLocation(), DiagID: diag::ext_string_literal_from_predefined)
2209 << Tok.getKind();
2210 SmallString<64> Str;
2211 llvm::raw_svector_ostream OS(Str);
2212 Token &Exp = ExpandedToks.emplace_back();
2213 Exp.startToken();
2214 if (Tok.getKind() == tok::kw_L__FUNCTION__ ||
2215 Tok.getKind() == tok::kw_L__FUNCSIG__) {
2216 OS << 'L';
2217 Exp.setKind(tok::wide_string_literal);
2218 } else {
2219 Exp.setKind(tok::string_literal);
2220 }
2221 OS << '"'
2222 << Lexer::Stringify(Str: PredefinedExpr::ComputeName(
2223 IK: getPredefinedExprKind(Kind: Tok.getKind()), CurrentDecl))
2224 << '"';
2225 PP.CreateString(Str: OS.str(), Tok&: Exp, ExpansionLocStart: Tok.getLocation(), ExpansionLocEnd: Tok.getEndLoc());
2226 }
2227 return ExpandedToks;
2228}
2229
2230ExprResult
2231Sema::ActOnStringLiteral(ArrayRef<Token> StringToks, Scope *UDLScope) {
2232 assert(!StringToks.empty() && "Must have at least one string!");
2233
2234 // StringToks needs backing storage as it doesn't hold array elements itself
2235 std::vector<Token> ExpandedToks;
2236 if (getLangOpts().MicrosoftExt)
2237 StringToks = ExpandedToks = ExpandFunctionLocalPredefinedMacros(Toks: StringToks);
2238
2239 StringLiteralParser Literal(StringToks, PP);
2240 if (Literal.hadError)
2241 return ExprError();
2242
2243 SmallVector<SourceLocation, 4> StringTokLocs;
2244 for (const Token &Tok : StringToks)
2245 StringTokLocs.push_back(Elt: Tok.getLocation());
2246
2247 QualType CharTy = Context.CharTy;
2248 StringLiteralKind Kind = StringLiteralKind::Ordinary;
2249 if (Literal.isWide()) {
2250 CharTy = Context.getWideCharType();
2251 Kind = StringLiteralKind::Wide;
2252 } else if (Literal.isUTF8()) {
2253 if (getLangOpts().Char8)
2254 CharTy = Context.Char8Ty;
2255 else if (getLangOpts().C23)
2256 CharTy = Context.UnsignedCharTy;
2257 Kind = StringLiteralKind::UTF8;
2258 } else if (Literal.isUTF16()) {
2259 CharTy = Context.Char16Ty;
2260 Kind = StringLiteralKind::UTF16;
2261 } else if (Literal.isUTF32()) {
2262 CharTy = Context.Char32Ty;
2263 Kind = StringLiteralKind::UTF32;
2264 } else if (Literal.isPascal()) {
2265 CharTy = Context.UnsignedCharTy;
2266 }
2267
2268 // Warn on u8 string literals before C++20 and C23, whose type
2269 // was an array of char before but becomes an array of char8_t.
2270 // In C++20, it cannot be used where a pointer to char is expected.
2271 // In C23, it might have an unexpected value if char was signed.
2272 if (Kind == StringLiteralKind::UTF8 &&
2273 (getLangOpts().CPlusPlus
2274 ? !getLangOpts().CPlusPlus20 && !getLangOpts().Char8
2275 : !getLangOpts().C23)) {
2276 Diag(Loc: StringTokLocs.front(), DiagID: getLangOpts().CPlusPlus
2277 ? diag::warn_cxx20_compat_utf8_string
2278 : diag::warn_c23_compat_utf8_string);
2279
2280 // Create removals for all 'u8' prefixes in the string literal(s). This
2281 // ensures C++20/C23 compatibility (but may change the program behavior when
2282 // built by non-Clang compilers for which the execution character set is
2283 // not always UTF-8).
2284 auto RemovalDiag = PDiag(DiagID: diag::note_cxx20_c23_compat_utf8_string_remove_u8);
2285 SourceLocation RemovalDiagLoc;
2286 for (const Token &Tok : StringToks) {
2287 if (Tok.getKind() == tok::utf8_string_literal) {
2288 if (RemovalDiagLoc.isInvalid())
2289 RemovalDiagLoc = Tok.getLocation();
2290 RemovalDiag << FixItHint::CreateRemoval(RemoveRange: CharSourceRange::getCharRange(
2291 B: Tok.getLocation(),
2292 E: Lexer::AdvanceToTokenCharacter(TokStart: Tok.getLocation(), Characters: 2,
2293 SM: getSourceManager(), LangOpts: getLangOpts())));
2294 }
2295 }
2296 Diag(Loc: RemovalDiagLoc, PD: RemovalDiag);
2297 }
2298
2299 QualType StrTy =
2300 Context.getStringLiteralArrayType(EltTy: CharTy, Length: Literal.GetNumStringChars());
2301
2302 // Pass &StringTokLocs[0], StringTokLocs.size() to factory!
2303 StringLiteral *Lit = StringLiteral::Create(
2304 Ctx: Context, Str: Literal.GetString(), Kind, Pascal: Literal.Pascal, Ty: StrTy, Locs: StringTokLocs);
2305 if (Literal.getUDSuffix().empty())
2306 return Lit;
2307
2308 // We're building a user-defined literal.
2309 IdentifierInfo *UDSuffix = &Context.Idents.get(Name: Literal.getUDSuffix());
2310 SourceLocation UDSuffixLoc =
2311 getUDSuffixLoc(S&: *this, TokLoc: StringTokLocs[Literal.getUDSuffixToken()],
2312 Offset: Literal.getUDSuffixOffset());
2313
2314 // Make sure we're allowed user-defined literals here.
2315 if (!UDLScope)
2316 return ExprError(Diag(Loc: UDSuffixLoc, DiagID: diag::err_invalid_string_udl));
2317
2318 // C++11 [lex.ext]p5: The literal L is treated as a call of the form
2319 // operator "" X (str, len)
2320 QualType SizeType = Context.getSizeType();
2321
2322 DeclarationName OpName =
2323 Context.DeclarationNames.getCXXLiteralOperatorName(II: UDSuffix);
2324 DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc);
2325 OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc);
2326
2327 QualType ArgTy[] = {
2328 Context.getArrayDecayedType(T: StrTy), SizeType
2329 };
2330
2331 LookupResult R(*this, OpName, UDSuffixLoc, LookupOrdinaryName);
2332 switch (LookupLiteralOperator(S: UDLScope, R, ArgTys: ArgTy,
2333 /*AllowRaw*/ false, /*AllowTemplate*/ true,
2334 /*AllowStringTemplatePack*/ AllowStringTemplate: true,
2335 /*DiagnoseMissing*/ true, StringLit: Lit)) {
2336
2337 case LOLR_Cooked: {
2338 llvm::APInt Len(Context.getIntWidth(T: SizeType), Literal.GetNumStringChars());
2339 IntegerLiteral *LenArg = IntegerLiteral::Create(C: Context, V: Len, type: SizeType,
2340 l: StringTokLocs[0]);
2341 Expr *Args[] = { Lit, LenArg };
2342
2343 return BuildLiteralOperatorCall(R, SuffixInfo&: OpNameInfo, Args, LitEndLoc: StringTokLocs.back());
2344 }
2345
2346 case LOLR_Template: {
2347 TemplateArgumentListInfo ExplicitArgs;
2348 TemplateArgument Arg(Lit, /*IsCanonical=*/false);
2349 TemplateArgumentLocInfo ArgInfo(Lit);
2350 ExplicitArgs.addArgument(Loc: TemplateArgumentLoc(Arg, ArgInfo));
2351 return BuildLiteralOperatorCall(R, SuffixInfo&: OpNameInfo, Args: {}, LitEndLoc: StringTokLocs.back(),
2352 ExplicitTemplateArgs: &ExplicitArgs);
2353 }
2354
2355 case LOLR_StringTemplatePack: {
2356 TemplateArgumentListInfo ExplicitArgs;
2357
2358 unsigned CharBits = Context.getIntWidth(T: CharTy);
2359 bool CharIsUnsigned = CharTy->isUnsignedIntegerType();
2360 llvm::APSInt Value(CharBits, CharIsUnsigned);
2361
2362 TemplateArgument TypeArg(CharTy);
2363 TemplateArgumentLocInfo TypeArgInfo(Context.getTrivialTypeSourceInfo(T: CharTy));
2364 ExplicitArgs.addArgument(Loc: TemplateArgumentLoc(TypeArg, TypeArgInfo));
2365
2366 for (unsigned I = 0, N = Lit->getLength(); I != N; ++I) {
2367 Value = Lit->getCodeUnit(i: I);
2368 TemplateArgument Arg(Context, Value, CharTy);
2369 TemplateArgumentLocInfo ArgInfo;
2370 ExplicitArgs.addArgument(Loc: TemplateArgumentLoc(Arg, ArgInfo));
2371 }
2372 return BuildLiteralOperatorCall(R, SuffixInfo&: OpNameInfo, Args: {}, LitEndLoc: StringTokLocs.back(),
2373 ExplicitTemplateArgs: &ExplicitArgs);
2374 }
2375 case LOLR_Raw:
2376 case LOLR_ErrorNoDiagnostic:
2377 llvm_unreachable("unexpected literal operator lookup result");
2378 case LOLR_Error:
2379 return ExprError();
2380 }
2381 llvm_unreachable("unexpected literal operator lookup result");
2382}
2383
2384DeclRefExpr *
2385Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK,
2386 SourceLocation Loc,
2387 const CXXScopeSpec *SS) {
2388 DeclarationNameInfo NameInfo(D->getDeclName(), Loc);
2389 return BuildDeclRefExpr(D, Ty, VK, NameInfo, SS);
2390}
2391
2392DeclRefExpr *
2393Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK,
2394 const DeclarationNameInfo &NameInfo,
2395 const CXXScopeSpec *SS, NamedDecl *FoundD,
2396 SourceLocation TemplateKWLoc,
2397 const TemplateArgumentListInfo *TemplateArgs) {
2398 NestedNameSpecifierLoc NNS =
2399 SS ? SS->getWithLocInContext(Context) : NestedNameSpecifierLoc();
2400 return BuildDeclRefExpr(D, Ty, VK, NameInfo, NNS, FoundD, TemplateKWLoc,
2401 TemplateArgs);
2402}
2403
2404// CUDA/HIP: Check whether a captured reference variable is referencing a
2405// host variable in a device or host device lambda.
2406static bool isCapturingReferenceToHostVarInCUDADeviceLambda(const Sema &S,
2407 VarDecl *VD) {
2408 if (!S.getLangOpts().CUDA || !VD->hasInit())
2409 return false;
2410 assert(VD->getType()->isReferenceType());
2411
2412 // Check whether the reference variable is referencing a host variable.
2413 auto *DRE = dyn_cast<DeclRefExpr>(Val: VD->getInit());
2414 if (!DRE)
2415 return false;
2416 auto *Referee = dyn_cast<VarDecl>(Val: DRE->getDecl());
2417 if (!Referee || !Referee->hasGlobalStorage() ||
2418 Referee->hasAttr<CUDADeviceAttr>())
2419 return false;
2420
2421 // Check whether the current function is a device or host device lambda.
2422 // Check whether the reference variable is a capture by getDeclContext()
2423 // since refersToEnclosingVariableOrCapture() is not ready at this point.
2424 auto *MD = dyn_cast_or_null<CXXMethodDecl>(Val: S.CurContext);
2425 if (MD && MD->getParent()->isLambda() &&
2426 MD->getOverloadedOperator() == OO_Call && MD->hasAttr<CUDADeviceAttr>() &&
2427 VD->getDeclContext() != MD)
2428 return true;
2429
2430 return false;
2431}
2432
2433NonOdrUseReason Sema::getNonOdrUseReasonInCurrentContext(ValueDecl *D) {
2434 // A declaration named in an unevaluated operand never constitutes an odr-use.
2435 if (isUnevaluatedContext())
2436 return NOUR_Unevaluated;
2437
2438 // C++2a [basic.def.odr]p4:
2439 // A variable x whose name appears as a potentially-evaluated expression e
2440 // is odr-used by e unless [...] x is a reference that is usable in
2441 // constant expressions.
2442 // CUDA/HIP:
2443 // If a reference variable referencing a host variable is captured in a
2444 // device or host device lambda, the value of the referee must be copied
2445 // to the capture and the reference variable must be treated as odr-use
2446 // since the value of the referee is not known at compile time and must
2447 // be loaded from the captured.
2448 if (VarDecl *VD = dyn_cast<VarDecl>(Val: D)) {
2449 if (VD->getType()->isReferenceType() &&
2450 !(getLangOpts().OpenMP && OpenMP().isOpenMPCapturedDecl(D)) &&
2451 !isCapturingReferenceToHostVarInCUDADeviceLambda(S: *this, VD) &&
2452 VD->isUsableInConstantExpressions(C: Context))
2453 return NOUR_Constant;
2454 }
2455
2456 // All remaining non-variable cases constitute an odr-use. For variables, we
2457 // need to wait and see how the expression is used.
2458 return NOUR_None;
2459}
2460
2461DeclRefExpr *
2462Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK,
2463 const DeclarationNameInfo &NameInfo,
2464 NestedNameSpecifierLoc NNS, NamedDecl *FoundD,
2465 SourceLocation TemplateKWLoc,
2466 const TemplateArgumentListInfo *TemplateArgs) {
2467 bool RefersToCapturedVariable = isa<VarDecl, BindingDecl>(Val: D) &&
2468 NeedToCaptureVariable(Var: D, Loc: NameInfo.getLoc());
2469
2470 DeclRefExpr *E = DeclRefExpr::Create(
2471 Context, QualifierLoc: NNS, TemplateKWLoc, D, RefersToEnclosingVariableOrCapture: RefersToCapturedVariable, NameInfo, T: Ty,
2472 VK, FoundD, TemplateArgs, NOUR: getNonOdrUseReasonInCurrentContext(D));
2473 MarkDeclRefReferenced(E);
2474
2475 // C++ [except.spec]p17:
2476 // An exception-specification is considered to be needed when:
2477 // - in an expression, the function is the unique lookup result or
2478 // the selected member of a set of overloaded functions.
2479 //
2480 // We delay doing this until after we've built the function reference and
2481 // marked it as used so that:
2482 // a) if the function is defaulted, we get errors from defining it before /
2483 // instead of errors from computing its exception specification, and
2484 // b) if the function is a defaulted comparison, we can use the body we
2485 // build when defining it as input to the exception specification
2486 // computation rather than computing a new body.
2487 if (const auto *FPT = Ty->getAs<FunctionProtoType>()) {
2488 if (isUnresolvedExceptionSpec(ESpecType: FPT->getExceptionSpecType())) {
2489 if (const auto *NewFPT = ResolveExceptionSpec(Loc: NameInfo.getLoc(), FPT))
2490 E->setType(Context.getQualifiedType(T: NewFPT, Qs: Ty.getQualifiers()));
2491 }
2492 }
2493
2494 if (getLangOpts().ObjCWeak && isa<VarDecl>(Val: D) &&
2495 Ty.getObjCLifetime() == Qualifiers::OCL_Weak && !isUnevaluatedContext() &&
2496 !Diags.isIgnored(DiagID: diag::warn_arc_repeated_use_of_weak, Loc: E->getBeginLoc()))
2497 getCurFunction()->recordUseOfWeak(E);
2498
2499 const auto *FD = dyn_cast<FieldDecl>(Val: D);
2500 if (const auto *IFD = dyn_cast<IndirectFieldDecl>(Val: D))
2501 FD = IFD->getAnonField();
2502 if (FD) {
2503 UnusedPrivateFields.remove(X: FD);
2504 // Just in case we're building an illegal pointer-to-member.
2505 if (FD->isBitField())
2506 E->setObjectKind(OK_BitField);
2507 }
2508
2509 // C++ [expr.prim]/8: The expression [...] is a bit-field if the identifier
2510 // designates a bit-field.
2511 if (const auto *BD = dyn_cast<BindingDecl>(Val: D))
2512 if (const auto *BE = BD->getBinding())
2513 E->setObjectKind(BE->getObjectKind());
2514
2515 return E;
2516}
2517
2518void
2519Sema::DecomposeUnqualifiedId(const UnqualifiedId &Id,
2520 TemplateArgumentListInfo &Buffer,
2521 DeclarationNameInfo &NameInfo,
2522 const TemplateArgumentListInfo *&TemplateArgs) {
2523 if (Id.getKind() == UnqualifiedIdKind::IK_TemplateId) {
2524 Buffer.setLAngleLoc(Id.TemplateId->LAngleLoc);
2525 Buffer.setRAngleLoc(Id.TemplateId->RAngleLoc);
2526
2527 ASTTemplateArgsPtr TemplateArgsPtr(Id.TemplateId->getTemplateArgs(),
2528 Id.TemplateId->NumArgs);
2529 translateTemplateArguments(In: TemplateArgsPtr, Out&: Buffer);
2530
2531 TemplateName TName = Id.TemplateId->Template.get();
2532 SourceLocation TNameLoc = Id.TemplateId->TemplateNameLoc;
2533 NameInfo = Context.getNameForTemplate(Name: TName, NameLoc: TNameLoc);
2534 TemplateArgs = &Buffer;
2535 } else {
2536 NameInfo = GetNameFromUnqualifiedId(Name: Id);
2537 TemplateArgs = nullptr;
2538 }
2539}
2540
2541bool Sema::DiagnoseDependentMemberLookup(const LookupResult &R) {
2542 // During a default argument instantiation the CurContext points
2543 // to a CXXMethodDecl; but we can't apply a this-> fixit inside a
2544 // function parameter list, hence add an explicit check.
2545 bool isDefaultArgument =
2546 !CodeSynthesisContexts.empty() &&
2547 CodeSynthesisContexts.back().Kind ==
2548 CodeSynthesisContext::DefaultFunctionArgumentInstantiation;
2549 const auto *CurMethod = dyn_cast<CXXMethodDecl>(Val: CurContext);
2550 bool isInstance = CurMethod && CurMethod->isInstance() &&
2551 R.getNamingClass() == CurMethod->getParent() &&
2552 !isDefaultArgument;
2553
2554 // There are two ways we can find a class-scope declaration during template
2555 // instantiation that we did not find in the template definition: if it is a
2556 // member of a dependent base class, or if it is declared after the point of
2557 // use in the same class. Distinguish these by comparing the class in which
2558 // the member was found to the naming class of the lookup.
2559 unsigned DiagID = diag::err_found_in_dependent_base;
2560 unsigned NoteID = diag::note_member_declared_at;
2561 if (R.getRepresentativeDecl()->getDeclContext()->Equals(DC: R.getNamingClass())) {
2562 DiagID = getLangOpts().MSVCCompat ? diag::ext_found_later_in_class
2563 : diag::err_found_later_in_class;
2564 } else if (getLangOpts().MSVCCompat) {
2565 DiagID = diag::ext_found_in_dependent_base;
2566 NoteID = diag::note_dependent_member_use;
2567 }
2568
2569 if (isInstance) {
2570 // Give a code modification hint to insert 'this->'.
2571 Diag(Loc: R.getNameLoc(), DiagID)
2572 << R.getLookupName()
2573 << FixItHint::CreateInsertion(InsertionLoc: R.getNameLoc(), Code: "this->");
2574 CheckCXXThisCapture(Loc: R.getNameLoc());
2575 } else {
2576 // FIXME: Add a FixItHint to insert 'Base::' or 'Derived::' (assuming
2577 // they're not shadowed).
2578 Diag(Loc: R.getNameLoc(), DiagID) << R.getLookupName();
2579 }
2580
2581 for (const NamedDecl *D : R)
2582 Diag(Loc: D->getLocation(), DiagID: NoteID);
2583
2584 // Return true if we are inside a default argument instantiation
2585 // and the found name refers to an instance member function, otherwise
2586 // the caller will try to create an implicit member call and this is wrong
2587 // for default arguments.
2588 //
2589 // FIXME: Is this special case necessary? We could allow the caller to
2590 // diagnose this.
2591 if (isDefaultArgument && ((*R.begin())->isCXXInstanceMember())) {
2592 Diag(Loc: R.getNameLoc(), DiagID: diag::err_member_call_without_object) << 0;
2593 return true;
2594 }
2595
2596 // Tell the callee to try to recover.
2597 return false;
2598}
2599
2600bool Sema::DiagnoseEmptyLookup(Scope *S, CXXScopeSpec &SS, LookupResult &R,
2601 CorrectionCandidateCallback &CCC,
2602 TemplateArgumentListInfo *ExplicitTemplateArgs,
2603 ArrayRef<Expr *> Args, DeclContext *LookupCtx) {
2604 DeclarationName Name = R.getLookupName();
2605 SourceRange NameRange = R.getLookupNameInfo().getSourceRange();
2606
2607 unsigned diagnostic = diag::err_undeclared_var_use;
2608 unsigned diagnostic_suggest = diag::err_undeclared_var_use_suggest;
2609 if (Name.getNameKind() == DeclarationName::CXXOperatorName ||
2610 Name.getNameKind() == DeclarationName::CXXLiteralOperatorName ||
2611 Name.getNameKind() == DeclarationName::CXXConversionFunctionName) {
2612 diagnostic = diag::err_undeclared_use;
2613 diagnostic_suggest = diag::err_undeclared_use_suggest;
2614 }
2615
2616 // If the original lookup was an unqualified lookup, fake an
2617 // unqualified lookup. This is useful when (for example) the
2618 // original lookup would not have found something because it was a
2619 // dependent name.
2620 DeclContext *DC =
2621 LookupCtx ? LookupCtx : (SS.isEmpty() ? CurContext : nullptr);
2622 while (DC) {
2623 if (isa<CXXRecordDecl>(Val: DC)) {
2624 if (ExplicitTemplateArgs) {
2625 if (LookupTemplateName(
2626 R, S, SS, ObjectType: Context.getCanonicalTagType(TD: cast<CXXRecordDecl>(Val: DC)),
2627 /*EnteringContext*/ false, RequiredTemplate: TemplateNameIsRequired,
2628 /*RequiredTemplateKind*/ ATK: nullptr, /*AllowTypoCorrection*/ true))
2629 return true;
2630 } else {
2631 LookupQualifiedName(R, LookupCtx: DC);
2632 }
2633
2634 if (!R.empty()) {
2635 // Don't give errors about ambiguities in this lookup.
2636 R.suppressDiagnostics();
2637
2638 // If there's a best viable function among the results, only mention
2639 // that one in the notes.
2640 OverloadCandidateSet Candidates(R.getNameLoc(),
2641 OverloadCandidateSet::CSK_Normal);
2642 AddOverloadedCallCandidates(R, ExplicitTemplateArgs, Args, CandidateSet&: Candidates);
2643 OverloadCandidateSet::iterator Best;
2644 if (Candidates.BestViableFunction(S&: *this, Loc: R.getNameLoc(), Best) ==
2645 OR_Success) {
2646 R.clear();
2647 R.addDecl(D: Best->FoundDecl.getDecl(), AS: Best->FoundDecl.getAccess());
2648 R.resolveKind();
2649 }
2650
2651 return DiagnoseDependentMemberLookup(R);
2652 }
2653
2654 R.clear();
2655 }
2656
2657 DC = DC->getLookupParent();
2658 }
2659
2660 // We didn't find anything, so try to correct for a typo.
2661 TypoCorrection Corrected;
2662 if (S && (Corrected =
2663 CorrectTypo(Typo: R.getLookupNameInfo(), LookupKind: R.getLookupKind(), S, SS: &SS,
2664 CCC, Mode: CorrectTypoKind::ErrorRecovery, MemberContext: LookupCtx))) {
2665 std::string CorrectedStr(Corrected.getAsString(LO: getLangOpts()));
2666 bool DroppedSpecifier =
2667 Corrected.WillReplaceSpecifier() && Name.getAsString() == CorrectedStr;
2668 R.setLookupName(Corrected.getCorrection());
2669
2670 bool AcceptableWithRecovery = false;
2671 bool AcceptableWithoutRecovery = false;
2672 NamedDecl *ND = Corrected.getFoundDecl();
2673 if (ND) {
2674 if (Corrected.isOverloaded()) {
2675 OverloadCandidateSet OCS(R.getNameLoc(),
2676 OverloadCandidateSet::CSK_Normal);
2677 OverloadCandidateSet::iterator Best;
2678 for (NamedDecl *CD : Corrected) {
2679 if (FunctionTemplateDecl *FTD =
2680 dyn_cast<FunctionTemplateDecl>(Val: CD))
2681 AddTemplateOverloadCandidate(
2682 FunctionTemplate: FTD, FoundDecl: DeclAccessPair::make(D: FTD, AS: AS_none), ExplicitTemplateArgs,
2683 Args, CandidateSet&: OCS);
2684 else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Val: CD))
2685 if (!ExplicitTemplateArgs || ExplicitTemplateArgs->size() == 0)
2686 AddOverloadCandidate(Function: FD, FoundDecl: DeclAccessPair::make(D: FD, AS: AS_none),
2687 Args, CandidateSet&: OCS);
2688 }
2689 switch (OCS.BestViableFunction(S&: *this, Loc: R.getNameLoc(), Best)) {
2690 case OR_Success:
2691 ND = Best->FoundDecl;
2692 Corrected.setCorrectionDecl(ND);
2693 break;
2694 default:
2695 // FIXME: Arbitrarily pick the first declaration for the note.
2696 Corrected.setCorrectionDecl(ND);
2697 break;
2698 }
2699 }
2700 R.addDecl(D: ND);
2701 if (getLangOpts().CPlusPlus && ND->isCXXClassMember()) {
2702 CXXRecordDecl *Record =
2703 Corrected.getCorrectionSpecifier().getAsRecordDecl();
2704 if (!Record)
2705 Record = cast<CXXRecordDecl>(
2706 Val: ND->getDeclContext()->getRedeclContext());
2707 R.setNamingClass(Record);
2708 }
2709
2710 auto *UnderlyingND = ND->getUnderlyingDecl();
2711 AcceptableWithRecovery = isa<ValueDecl>(Val: UnderlyingND) ||
2712 isa<FunctionTemplateDecl>(Val: UnderlyingND);
2713 // FIXME: If we ended up with a typo for a type name or
2714 // Objective-C class name, we're in trouble because the parser
2715 // is in the wrong place to recover. Suggest the typo
2716 // correction, but don't make it a fix-it since we're not going
2717 // to recover well anyway.
2718 AcceptableWithoutRecovery = isa<TypeDecl>(Val: UnderlyingND) ||
2719 getAsTypeTemplateDecl(D: UnderlyingND) ||
2720 isa<ObjCInterfaceDecl>(Val: UnderlyingND);
2721 } else {
2722 // FIXME: We found a keyword. Suggest it, but don't provide a fix-it
2723 // because we aren't able to recover.
2724 AcceptableWithoutRecovery = true;
2725 }
2726
2727 if (AcceptableWithRecovery || AcceptableWithoutRecovery) {
2728 unsigned NoteID = Corrected.getCorrectionDeclAs<ImplicitParamDecl>()
2729 ? diag::note_implicit_param_decl
2730 : diag::note_previous_decl;
2731 if (SS.isEmpty())
2732 diagnoseTypo(Correction: Corrected, TypoDiag: PDiag(DiagID: diagnostic_suggest) << Name << NameRange,
2733 PrevNote: PDiag(DiagID: NoteID), ErrorRecovery: AcceptableWithRecovery);
2734 else
2735 diagnoseTypo(Correction: Corrected,
2736 TypoDiag: PDiag(DiagID: diag::err_no_member_suggest)
2737 << Name << computeDeclContext(SS, EnteringContext: false)
2738 << DroppedSpecifier << NameRange,
2739 PrevNote: PDiag(DiagID: NoteID), ErrorRecovery: AcceptableWithRecovery);
2740
2741 // Tell the callee whether to try to recover.
2742 return !AcceptableWithRecovery;
2743 }
2744 }
2745 R.clear();
2746
2747 // Emit a special diagnostic for failed member lookups.
2748 // FIXME: computing the declaration context might fail here (?)
2749 if (!SS.isEmpty()) {
2750 Diag(Loc: R.getNameLoc(), DiagID: diag::err_no_member)
2751 << Name << computeDeclContext(SS, EnteringContext: false) << NameRange;
2752 return true;
2753 }
2754
2755 // Give up, we can't recover.
2756 Diag(Loc: R.getNameLoc(), DiagID: diagnostic) << Name << NameRange;
2757 return true;
2758}
2759
2760/// In Microsoft mode, if we are inside a template class whose parent class has
2761/// dependent base classes, and we can't resolve an unqualified identifier, then
2762/// assume the identifier is a member of a dependent base class. We can only
2763/// recover successfully in static methods, instance methods, and other contexts
2764/// where 'this' is available. This doesn't precisely match MSVC's
2765/// instantiation model, but it's close enough.
2766static Expr *
2767recoverFromMSUnqualifiedLookup(Sema &S, ASTContext &Context,
2768 DeclarationNameInfo &NameInfo,
2769 SourceLocation TemplateKWLoc,
2770 const TemplateArgumentListInfo *TemplateArgs) {
2771 // Only try to recover from lookup into dependent bases in static methods or
2772 // contexts where 'this' is available.
2773 QualType ThisType = S.getCurrentThisType();
2774 const CXXRecordDecl *RD = nullptr;
2775 if (!ThisType.isNull())
2776 RD = ThisType->getPointeeType()->getAsCXXRecordDecl();
2777 else if (auto *MD = dyn_cast<CXXMethodDecl>(Val: S.CurContext))
2778 RD = MD->getParent();
2779 if (!RD || !RD->hasDefinition() || !RD->hasAnyDependentBases())
2780 return nullptr;
2781
2782 // Diagnose this as unqualified lookup into a dependent base class. If 'this'
2783 // is available, suggest inserting 'this->' as a fixit.
2784 SourceLocation Loc = NameInfo.getLoc();
2785 auto DB = S.Diag(Loc, DiagID: diag::ext_undeclared_unqual_id_with_dependent_base);
2786 DB << NameInfo.getName() << RD;
2787
2788 if (!ThisType.isNull()) {
2789 DB << FixItHint::CreateInsertion(InsertionLoc: Loc, Code: "this->");
2790 return CXXDependentScopeMemberExpr::Create(
2791 Ctx: Context, /*This=*/Base: nullptr, BaseType: ThisType, /*IsArrow=*/true,
2792 /*Op=*/OperatorLoc: SourceLocation(), QualifierLoc: NestedNameSpecifierLoc(), TemplateKWLoc,
2793 /*FirstQualifierFoundInScope=*/nullptr, MemberNameInfo: NameInfo, TemplateArgs);
2794 }
2795
2796 // Synthesize a fake NNS that points to the derived class. This will
2797 // perform name lookup during template instantiation.
2798 CXXScopeSpec SS;
2799 NestedNameSpecifier NNS(Context.getCanonicalTagType(TD: RD)->getTypePtr());
2800 SS.MakeTrivial(Context, Qualifier: NNS, R: SourceRange(Loc, Loc));
2801 return DependentScopeDeclRefExpr::Create(
2802 Context, QualifierLoc: SS.getWithLocInContext(Context), TemplateKWLoc, NameInfo,
2803 TemplateArgs);
2804}
2805
2806ExprResult
2807Sema::ActOnIdExpression(Scope *S, CXXScopeSpec &SS,
2808 SourceLocation TemplateKWLoc, UnqualifiedId &Id,
2809 bool HasTrailingLParen, bool IsAddressOfOperand,
2810 CorrectionCandidateCallback *CCC,
2811 bool IsInlineAsmIdentifier, Token *KeywordReplacement) {
2812 assert(!(IsAddressOfOperand && HasTrailingLParen) &&
2813 "cannot be direct & operand and have a trailing lparen");
2814 if (SS.isInvalid())
2815 return ExprError();
2816
2817 TemplateArgumentListInfo TemplateArgsBuffer;
2818
2819 // Decompose the UnqualifiedId into the following data.
2820 DeclarationNameInfo NameInfo;
2821 const TemplateArgumentListInfo *TemplateArgs;
2822 DecomposeUnqualifiedId(Id, Buffer&: TemplateArgsBuffer, NameInfo, TemplateArgs);
2823
2824 DeclarationName Name = NameInfo.getName();
2825 IdentifierInfo *II = Name.getAsIdentifierInfo();
2826 SourceLocation NameLoc = NameInfo.getLoc();
2827
2828 if (II && II->isEditorPlaceholder()) {
2829 // FIXME: When typed placeholders are supported we can create a typed
2830 // placeholder expression node.
2831 return ExprError();
2832 }
2833
2834 // This specially handles arguments of attributes appertains to a type of C
2835 // struct field such that the name lookup within a struct finds the member
2836 // name, which is not the case for other contexts in C.
2837 if (isAttrContext() && !getLangOpts().CPlusPlus && S->isClassScope()) {
2838 // See if this is reference to a field of struct.
2839 LookupResult R(*this, NameInfo, LookupMemberName);
2840 // LookupName handles a name lookup from within anonymous struct.
2841 if (LookupName(R, S)) {
2842 if (auto *VD = dyn_cast<ValueDecl>(Val: R.getFoundDecl())) {
2843 QualType type = VD->getType().getNonReferenceType();
2844 // This will eventually be translated into MemberExpr upon
2845 // the use of instantiated struct fields.
2846 return BuildDeclRefExpr(D: VD, Ty: type, VK: VK_LValue, Loc: NameLoc);
2847 }
2848 }
2849 }
2850
2851 // Perform the required lookup.
2852 LookupResult R(*this, NameInfo,
2853 (Id.getKind() == UnqualifiedIdKind::IK_ImplicitSelfParam)
2854 ? LookupObjCImplicitSelfParam
2855 : LookupOrdinaryName);
2856 if (TemplateKWLoc.isValid() || TemplateArgs) {
2857 // Lookup the template name again to correctly establish the context in
2858 // which it was found. This is really unfortunate as we already did the
2859 // lookup to determine that it was a template name in the first place. If
2860 // this becomes a performance hit, we can work harder to preserve those
2861 // results until we get here but it's likely not worth it.
2862 AssumedTemplateKind AssumedTemplate;
2863 if (LookupTemplateName(R, S, SS, /*ObjectType=*/QualType(),
2864 /*EnteringContext=*/false, RequiredTemplate: TemplateKWLoc,
2865 ATK: &AssumedTemplate))
2866 return ExprError();
2867
2868 if (R.wasNotFoundInCurrentInstantiation() || SS.isInvalid())
2869 return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo,
2870 isAddressOfOperand: IsAddressOfOperand, TemplateArgs);
2871 } else {
2872 bool IvarLookupFollowUp = II && !SS.isSet() && getCurMethodDecl();
2873 LookupParsedName(R, S, SS: &SS, /*ObjectType=*/QualType(),
2874 /*AllowBuiltinCreation=*/!IvarLookupFollowUp);
2875
2876 // If the result might be in a dependent base class, this is a dependent
2877 // id-expression.
2878 if (R.wasNotFoundInCurrentInstantiation() || SS.isInvalid())
2879 return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo,
2880 isAddressOfOperand: IsAddressOfOperand, TemplateArgs);
2881
2882 // If this reference is in an Objective-C method, then we need to do
2883 // some special Objective-C lookup, too.
2884 if (IvarLookupFollowUp) {
2885 ExprResult E(ObjC().LookupInObjCMethod(LookUp&: R, S, II, AllowBuiltinCreation: true));
2886 if (E.isInvalid())
2887 return ExprError();
2888
2889 if (Expr *Ex = E.getAs<Expr>())
2890 return Ex;
2891 }
2892 }
2893
2894 if (R.isAmbiguous())
2895 return ExprError();
2896
2897 // This could be an implicitly declared function reference if the language
2898 // mode allows it as a feature.
2899 if (R.empty() && HasTrailingLParen && II &&
2900 getLangOpts().implicitFunctionsAllowed()) {
2901 NamedDecl *D = ImplicitlyDefineFunction(Loc: NameLoc, II&: *II, S);
2902 if (D) R.addDecl(D);
2903 }
2904
2905 // Determine whether this name might be a candidate for
2906 // argument-dependent lookup.
2907 bool ADL = UseArgumentDependentLookup(SS, R, HasTrailingLParen);
2908
2909 if (R.empty() && !ADL) {
2910 if (SS.isEmpty() && getLangOpts().MSVCCompat) {
2911 if (Expr *E = recoverFromMSUnqualifiedLookup(S&: *this, Context, NameInfo,
2912 TemplateKWLoc, TemplateArgs))
2913 return E;
2914 }
2915
2916 // Don't diagnose an empty lookup for inline assembly.
2917 if (IsInlineAsmIdentifier)
2918 return ExprError();
2919
2920 // If this name wasn't predeclared and if this is not a function
2921 // call, diagnose the problem.
2922 DefaultFilterCCC DefaultValidator(II, SS.getScopeRep());
2923 DefaultValidator.IsAddressOfOperand = IsAddressOfOperand;
2924 assert((!CCC || CCC->IsAddressOfOperand == IsAddressOfOperand) &&
2925 "Typo correction callback misconfigured");
2926 if (CCC) {
2927 // Make sure the callback knows what the typo being diagnosed is.
2928 CCC->setTypoName(II);
2929 if (SS.isValid())
2930 CCC->setTypoNNS(SS.getScopeRep());
2931 }
2932 // FIXME: DiagnoseEmptyLookup produces bad diagnostics if we're looking for
2933 // a template name, but we happen to have always already looked up the name
2934 // before we get here if it must be a template name.
2935 if (DiagnoseEmptyLookup(S, SS, R, CCC&: CCC ? *CCC : DefaultValidator, ExplicitTemplateArgs: nullptr,
2936 Args: {}, LookupCtx: nullptr))
2937 return ExprError();
2938
2939 assert(!R.empty() &&
2940 "DiagnoseEmptyLookup returned false but added no results");
2941
2942 // If we found an Objective-C instance variable, let
2943 // LookupInObjCMethod build the appropriate expression to
2944 // reference the ivar.
2945 if (ObjCIvarDecl *Ivar = R.getAsSingle<ObjCIvarDecl>()) {
2946 R.clear();
2947 ExprResult E(ObjC().LookupInObjCMethod(LookUp&: R, S, II: Ivar->getIdentifier()));
2948 // In a hopelessly buggy code, Objective-C instance variable
2949 // lookup fails and no expression will be built to reference it.
2950 if (!E.isInvalid() && !E.get())
2951 return ExprError();
2952 return E;
2953 }
2954 }
2955
2956 // This is guaranteed from this point on.
2957 assert(!R.empty() || ADL);
2958
2959 // Check whether this might be a C++ implicit instance member access.
2960 // C++ [class.mfct.non-static]p3:
2961 // When an id-expression that is not part of a class member access
2962 // syntax and not used to form a pointer to member is used in the
2963 // body of a non-static member function of class X, if name lookup
2964 // resolves the name in the id-expression to a non-static non-type
2965 // member of some class C, the id-expression is transformed into a
2966 // class member access expression using (*this) as the
2967 // postfix-expression to the left of the . operator.
2968 //
2969 // But we don't actually need to do this for '&' operands if R
2970 // resolved to a function or overloaded function set, because the
2971 // expression is ill-formed if it actually works out to be a
2972 // non-static member function:
2973 //
2974 // C++ [expr.ref]p4:
2975 // Otherwise, if E1.E2 refers to a non-static member function. . .
2976 // [t]he expression can be used only as the left-hand operand of a
2977 // member function call.
2978 //
2979 // There are other safeguards against such uses, but it's important
2980 // to get this right here so that we don't end up making a
2981 // spuriously dependent expression if we're inside a dependent
2982 // instance method.
2983 if (isPotentialImplicitMemberAccess(SS, R, IsAddressOfOperand))
2984 return BuildPossibleImplicitMemberExpr(SS, TemplateKWLoc, R, TemplateArgs,
2985 S);
2986
2987 if (TemplateArgs || TemplateKWLoc.isValid()) {
2988
2989 // In C++1y, if this is a variable template id, then check it
2990 // in BuildTemplateIdExpr().
2991 // The single lookup result must be a variable template declaration.
2992 if (Id.getKind() == UnqualifiedIdKind::IK_TemplateId && Id.TemplateId &&
2993 (Id.TemplateId->Kind == TNK_Var_template ||
2994 Id.TemplateId->Kind == TNK_Concept_template)) {
2995 assert(R.getAsSingle<TemplateDecl>() &&
2996 "There should only be one declaration found.");
2997 }
2998
2999 return BuildTemplateIdExpr(SS, TemplateKWLoc, R, RequiresADL: ADL, TemplateArgs);
3000 }
3001
3002 return BuildDeclarationNameExpr(SS, R, NeedsADL: ADL);
3003}
3004
3005ExprResult Sema::BuildQualifiedDeclarationNameExpr(
3006 CXXScopeSpec &SS, const DeclarationNameInfo &NameInfo,
3007 bool IsAddressOfOperand, TypeSourceInfo **RecoveryTSI) {
3008 LookupResult R(*this, NameInfo, LookupOrdinaryName);
3009 LookupParsedName(R, /*S=*/nullptr, SS: &SS, /*ObjectType=*/QualType());
3010
3011 if (R.isAmbiguous())
3012 return ExprError();
3013
3014 if (R.wasNotFoundInCurrentInstantiation() || SS.isInvalid())
3015 return BuildDependentDeclRefExpr(SS, /*TemplateKWLoc=*/SourceLocation(),
3016 NameInfo, /*TemplateArgs=*/nullptr);
3017
3018 if (R.empty()) {
3019 // Don't diagnose problems with invalid record decl, the secondary no_member
3020 // diagnostic during template instantiation is likely bogus, e.g. if a class
3021 // is invalid because it's derived from an invalid base class, then missing
3022 // members were likely supposed to be inherited.
3023 DeclContext *DC = computeDeclContext(SS);
3024 if (const auto *CD = dyn_cast<CXXRecordDecl>(Val: DC))
3025 if (CD->isInvalidDecl() || CD->isBeingDefined())
3026 return ExprError();
3027 Diag(Loc: NameInfo.getLoc(), DiagID: diag::err_no_member)
3028 << NameInfo.getName() << DC << SS.getRange();
3029 return ExprError();
3030 }
3031
3032 if (const TypeDecl *TD = R.getAsSingle<TypeDecl>()) {
3033 QualType ET;
3034 TypeLocBuilder TLB;
3035 if (auto *TagD = dyn_cast<TagDecl>(Val: TD)) {
3036 ET = SemaRef.Context.getTagType(Keyword: ElaboratedTypeKeyword::None,
3037 Qualifier: SS.getScopeRep(), TD: TagD,
3038 /*OwnsTag=*/false);
3039 auto TL = TLB.push<TagTypeLoc>(T: ET);
3040 TL.setElaboratedKeywordLoc(SourceLocation());
3041 TL.setQualifierLoc(SS.getWithLocInContext(Context));
3042 TL.setNameLoc(NameInfo.getLoc());
3043 } else if (auto *TypedefD = dyn_cast<TypedefNameDecl>(Val: TD)) {
3044 ET = SemaRef.Context.getTypedefType(Keyword: ElaboratedTypeKeyword::None,
3045 Qualifier: SS.getScopeRep(), Decl: TypedefD);
3046 TLB.push<TypedefTypeLoc>(T: ET).set(
3047 /*ElaboratedKeywordLoc=*/SourceLocation(),
3048 QualifierLoc: SS.getWithLocInContext(Context), NameLoc: NameInfo.getLoc());
3049 } else {
3050 // FIXME: What else can appear here?
3051 ET = SemaRef.Context.getTypeDeclType(Decl: TD);
3052 TLB.pushTypeSpec(T: ET).setNameLoc(NameInfo.getLoc());
3053 assert(SS.isEmpty());
3054 }
3055
3056 // Diagnose a missing typename if this resolved unambiguously to a type in
3057 // a dependent context. If we can recover with a type, downgrade this to
3058 // a warning in Microsoft compatibility mode.
3059 unsigned DiagID = diag::err_typename_missing;
3060 if (RecoveryTSI && getLangOpts().MSVCCompat)
3061 DiagID = diag::ext_typename_missing;
3062 SourceLocation Loc = SS.getBeginLoc();
3063 auto D = Diag(Loc, DiagID);
3064 D << ET << SourceRange(Loc, NameInfo.getEndLoc());
3065
3066 // Don't recover if the caller isn't expecting us to or if we're in a SFINAE
3067 // context.
3068 if (!RecoveryTSI)
3069 return ExprError();
3070
3071 // Only issue the fixit if we're prepared to recover.
3072 D << FixItHint::CreateInsertion(InsertionLoc: Loc, Code: "typename ");
3073
3074 // Recover by pretending this was an elaborated type.
3075 *RecoveryTSI = TLB.getTypeSourceInfo(Context, T: ET);
3076
3077 return ExprEmpty();
3078 }
3079
3080 // If necessary, build an implicit class member access.
3081 if (isPotentialImplicitMemberAccess(SS, R, IsAddressOfOperand))
3082 return BuildPossibleImplicitMemberExpr(SS,
3083 /*TemplateKWLoc=*/SourceLocation(),
3084 R, /*TemplateArgs=*/nullptr,
3085 /*S=*/nullptr);
3086
3087 return BuildDeclarationNameExpr(SS, R, /*ADL=*/NeedsADL: false);
3088}
3089
3090ExprResult Sema::PerformObjectMemberConversion(Expr *From,
3091 NestedNameSpecifier Qualifier,
3092 NamedDecl *FoundDecl,
3093 NamedDecl *Member) {
3094 const auto *RD = dyn_cast<CXXRecordDecl>(Val: Member->getDeclContext());
3095 if (!RD)
3096 return From;
3097
3098 QualType DestRecordType;
3099 QualType DestType;
3100 QualType FromRecordType;
3101 QualType FromType = From->getType();
3102 bool PointerConversions = false;
3103 if (isa<FieldDecl>(Val: Member)) {
3104 DestRecordType = Context.getCanonicalTagType(TD: RD);
3105 auto FromPtrType = FromType->getAs<PointerType>();
3106 DestRecordType = Context.getAddrSpaceQualType(
3107 T: DestRecordType, AddressSpace: FromPtrType
3108 ? FromType->getPointeeType().getAddressSpace()
3109 : FromType.getAddressSpace());
3110
3111 if (FromPtrType) {
3112 DestType = Context.getPointerType(T: DestRecordType);
3113 FromRecordType = FromPtrType->getPointeeType();
3114 PointerConversions = true;
3115 } else {
3116 DestType = DestRecordType;
3117 FromRecordType = FromType;
3118 }
3119 } else if (const auto *Method = dyn_cast<CXXMethodDecl>(Val: Member)) {
3120 if (!Method->isImplicitObjectMemberFunction())
3121 return From;
3122
3123 DestType = Method->getThisType().getNonReferenceType();
3124 DestRecordType = Method->getFunctionObjectParameterType();
3125
3126 if (FromType->getAs<PointerType>()) {
3127 FromRecordType = FromType->getPointeeType();
3128 PointerConversions = true;
3129 } else {
3130 FromRecordType = FromType;
3131 DestType = DestRecordType;
3132 }
3133
3134 LangAS FromAS = FromRecordType.getAddressSpace();
3135 LangAS DestAS = DestRecordType.getAddressSpace();
3136 if (FromAS != DestAS) {
3137 QualType FromRecordTypeWithoutAS =
3138 Context.removeAddrSpaceQualType(T: FromRecordType);
3139 QualType FromTypeWithDestAS =
3140 Context.getAddrSpaceQualType(T: FromRecordTypeWithoutAS, AddressSpace: DestAS);
3141 if (PointerConversions)
3142 FromTypeWithDestAS = Context.getPointerType(T: FromTypeWithDestAS);
3143 From = ImpCastExprToType(E: From, Type: FromTypeWithDestAS,
3144 CK: CK_AddressSpaceConversion, VK: From->getValueKind())
3145 .get();
3146 }
3147 } else {
3148 // No conversion necessary.
3149 return From;
3150 }
3151
3152 if (DestType->isDependentType() || FromType->isDependentType())
3153 return From;
3154
3155 // If the unqualified types are the same, no conversion is necessary.
3156 if (Context.hasSameUnqualifiedType(T1: FromRecordType, T2: DestRecordType))
3157 return From;
3158
3159 SourceRange FromRange = From->getSourceRange();
3160 SourceLocation FromLoc = FromRange.getBegin();
3161
3162 ExprValueKind VK = From->getValueKind();
3163
3164 // C++ [class.member.lookup]p8:
3165 // [...] Ambiguities can often be resolved by qualifying a name with its
3166 // class name.
3167 //
3168 // If the member was a qualified name and the qualified referred to a
3169 // specific base subobject type, we'll cast to that intermediate type
3170 // first and then to the object in which the member is declared. That allows
3171 // one to resolve ambiguities in, e.g., a diamond-shaped hierarchy such as:
3172 //
3173 // class Base { public: int x; };
3174 // class Derived1 : public Base { };
3175 // class Derived2 : public Base { };
3176 // class VeryDerived : public Derived1, public Derived2 { void f(); };
3177 //
3178 // void VeryDerived::f() {
3179 // x = 17; // error: ambiguous base subobjects
3180 // Derived1::x = 17; // okay, pick the Base subobject of Derived1
3181 // }
3182 if (Qualifier.getKind() == NestedNameSpecifier::Kind::Type) {
3183 QualType QType = QualType(Qualifier.getAsType(), 0);
3184 assert(QType->isRecordType() && "lookup done with non-record type");
3185
3186 QualType QRecordType = QualType(QType->castAs<RecordType>(), 0);
3187
3188 // In C++98, the qualifier type doesn't actually have to be a base
3189 // type of the object type, in which case we just ignore it.
3190 // Otherwise build the appropriate casts.
3191 if (IsDerivedFrom(Loc: FromLoc, Derived: FromRecordType, Base: QRecordType)) {
3192 CXXCastPath BasePath;
3193 if (CheckDerivedToBaseConversion(Derived: FromRecordType, Base: QRecordType,
3194 Loc: FromLoc, Range: FromRange, BasePath: &BasePath))
3195 return ExprError();
3196
3197 if (PointerConversions)
3198 QType = Context.getPointerType(T: QType);
3199 From = ImpCastExprToType(E: From, Type: QType, CK: CK_UncheckedDerivedToBase,
3200 VK, BasePath: &BasePath).get();
3201
3202 FromType = QType;
3203 FromRecordType = QRecordType;
3204
3205 // If the qualifier type was the same as the destination type,
3206 // we're done.
3207 if (Context.hasSameUnqualifiedType(T1: FromRecordType, T2: DestRecordType))
3208 return From;
3209 }
3210 }
3211
3212 CXXCastPath BasePath;
3213 if (CheckDerivedToBaseConversion(Derived: FromRecordType, Base: DestRecordType,
3214 Loc: FromLoc, Range: FromRange, BasePath: &BasePath,
3215 /*IgnoreAccess=*/true))
3216 return ExprError();
3217
3218 // Propagate qualifiers to base subobjects as per:
3219 // C++ [basic.type.qualifier]p1.2:
3220 // A volatile object is [...] a subobject of a volatile object.
3221 Qualifiers FromTypeQuals = FromType.getQualifiers();
3222 FromTypeQuals.setAddressSpace(DestType.getAddressSpace());
3223 DestType = Context.getQualifiedType(T: DestType, Qs: FromTypeQuals);
3224
3225 return ImpCastExprToType(E: From, Type: DestType, CK: CK_UncheckedDerivedToBase, VK,
3226 BasePath: &BasePath);
3227}
3228
3229bool Sema::UseArgumentDependentLookup(const CXXScopeSpec &SS,
3230 const LookupResult &R,
3231 bool HasTrailingLParen) {
3232 // Only when used directly as the postfix-expression of a call.
3233 if (!HasTrailingLParen)
3234 return false;
3235
3236 // Never if a scope specifier was provided.
3237 if (SS.isNotEmpty())
3238 return false;
3239
3240 // Only in C++ or ObjC++.
3241 if (!getLangOpts().CPlusPlus)
3242 return false;
3243
3244 // Turn off ADL when we find certain kinds of declarations during
3245 // normal lookup:
3246 for (const NamedDecl *D : R) {
3247 // C++0x [basic.lookup.argdep]p3:
3248 // -- a declaration of a class member
3249 // Since using decls preserve this property, we check this on the
3250 // original decl.
3251 if (D->isCXXClassMember())
3252 return false;
3253
3254 // C++0x [basic.lookup.argdep]p3:
3255 // -- a block-scope function declaration that is not a
3256 // using-declaration
3257 // NOTE: we also trigger this for function templates (in fact, we
3258 // don't check the decl type at all, since all other decl types
3259 // turn off ADL anyway).
3260 if (isa<UsingShadowDecl>(Val: D))
3261 D = cast<UsingShadowDecl>(Val: D)->getTargetDecl();
3262 else if (D->getLexicalDeclContext()->isFunctionOrMethod())
3263 return false;
3264
3265 // C++0x [basic.lookup.argdep]p3:
3266 // -- a declaration that is neither a function or a function
3267 // template
3268 // And also for builtin functions.
3269 if (const auto *FDecl = dyn_cast<FunctionDecl>(Val: D)) {
3270 // But also builtin functions.
3271 if (FDecl->getBuiltinID() && FDecl->isImplicit())
3272 return false;
3273 } else if (!isa<FunctionTemplateDecl>(Val: D))
3274 return false;
3275 }
3276
3277 return true;
3278}
3279
3280
3281/// Diagnoses obvious problems with the use of the given declaration
3282/// as an expression. This is only actually called for lookups that
3283/// were not overloaded, and it doesn't promise that the declaration
3284/// will in fact be used.
3285static bool CheckDeclInExpr(Sema &S, SourceLocation Loc, NamedDecl *D,
3286 bool AcceptInvalid) {
3287 if (D->isInvalidDecl() && !AcceptInvalid)
3288 return true;
3289
3290 if (isa<TypedefNameDecl>(Val: D)) {
3291 S.Diag(Loc, DiagID: diag::err_unexpected_typedef) << D->getDeclName();
3292 return true;
3293 }
3294
3295 if (isa<ObjCInterfaceDecl>(Val: D)) {
3296 S.Diag(Loc, DiagID: diag::err_unexpected_interface) << D->getDeclName();
3297 return true;
3298 }
3299
3300 if (isa<NamespaceDecl>(Val: D)) {
3301 S.Diag(Loc, DiagID: diag::err_unexpected_namespace) << D->getDeclName();
3302 return true;
3303 }
3304
3305 return false;
3306}
3307
3308// Certain multiversion types should be treated as overloaded even when there is
3309// only one result.
3310static bool ShouldLookupResultBeMultiVersionOverload(const LookupResult &R) {
3311 assert(R.isSingleResult() && "Expected only a single result");
3312 const auto *FD = dyn_cast<FunctionDecl>(Val: R.getFoundDecl());
3313 return FD &&
3314 (FD->isCPUDispatchMultiVersion() || FD->isCPUSpecificMultiVersion());
3315}
3316
3317ExprResult Sema::BuildDeclarationNameExpr(const CXXScopeSpec &SS,
3318 LookupResult &R, bool NeedsADL,
3319 bool AcceptInvalidDecl) {
3320 // If this is a single, fully-resolved result and we don't need ADL,
3321 // just build an ordinary singleton decl ref.
3322 if (!NeedsADL && R.isSingleResult() &&
3323 !R.getAsSingle<FunctionTemplateDecl>() &&
3324 !ShouldLookupResultBeMultiVersionOverload(R))
3325 return BuildDeclarationNameExpr(SS, NameInfo: R.getLookupNameInfo(), D: R.getFoundDecl(),
3326 FoundD: R.getRepresentativeDecl(), TemplateArgs: nullptr,
3327 AcceptInvalidDecl);
3328
3329 // We only need to check the declaration if there's exactly one
3330 // result, because in the overloaded case the results can only be
3331 // functions and function templates.
3332 if (R.isSingleResult() && !ShouldLookupResultBeMultiVersionOverload(R) &&
3333 CheckDeclInExpr(S&: *this, Loc: R.getNameLoc(), D: R.getFoundDecl(),
3334 AcceptInvalid: AcceptInvalidDecl))
3335 return ExprError();
3336
3337 // Otherwise, just build an unresolved lookup expression. Suppress
3338 // any lookup-related diagnostics; we'll hash these out later, when
3339 // we've picked a target.
3340 R.suppressDiagnostics();
3341
3342 UnresolvedLookupExpr *ULE = UnresolvedLookupExpr::Create(
3343 Context, NamingClass: R.getNamingClass(), QualifierLoc: SS.getWithLocInContext(Context),
3344 NameInfo: R.getLookupNameInfo(), RequiresADL: NeedsADL, Begin: R.begin(), End: R.end(),
3345 /*KnownDependent=*/false, /*KnownInstantiationDependent=*/false);
3346
3347 return ULE;
3348}
3349
3350ExprResult Sema::BuildDeclarationNameExpr(
3351 const CXXScopeSpec &SS, const DeclarationNameInfo &NameInfo, NamedDecl *D,
3352 NamedDecl *FoundD, const TemplateArgumentListInfo *TemplateArgs,
3353 bool AcceptInvalidDecl) {
3354 assert(D && "Cannot refer to a NULL declaration");
3355 assert(!isa<FunctionTemplateDecl>(D) &&
3356 "Cannot refer unambiguously to a function template");
3357
3358 SourceLocation Loc = NameInfo.getLoc();
3359 if (CheckDeclInExpr(S&: *this, Loc, D, AcceptInvalid: AcceptInvalidDecl)) {
3360 // Recovery from invalid cases (e.g. D is an invalid Decl).
3361 // We use the dependent type for the RecoveryExpr to prevent bogus follow-up
3362 // diagnostics, as invalid decls use int as a fallback type.
3363 return CreateRecoveryExpr(Begin: NameInfo.getBeginLoc(), End: NameInfo.getEndLoc(), SubExprs: {});
3364 }
3365
3366 if (TemplateDecl *TD = dyn_cast<TemplateDecl>(Val: D)) {
3367 // Specifically diagnose references to class templates that are missing
3368 // a template argument list.
3369 diagnoseMissingTemplateArguments(SS, /*TemplateKeyword=*/false, TD, Loc);
3370 return ExprError();
3371 }
3372
3373 // Make sure that we're referring to a value.
3374 if (!isa<ValueDecl, UnresolvedUsingIfExistsDecl>(Val: D)) {
3375 Diag(Loc, DiagID: diag::err_ref_non_value) << D << SS.getRange();
3376 Diag(Loc: D->getLocation(), DiagID: diag::note_declared_at);
3377 return ExprError();
3378 }
3379
3380 // Check whether this declaration can be used. Note that we suppress
3381 // this check when we're going to perform argument-dependent lookup
3382 // on this function name, because this might not be the function
3383 // that overload resolution actually selects.
3384 if (DiagnoseUseOfDecl(D, Locs: Loc))
3385 return ExprError();
3386
3387 auto *VD = cast<ValueDecl>(Val: D);
3388
3389 // Only create DeclRefExpr's for valid Decl's.
3390 if (VD->isInvalidDecl() && !AcceptInvalidDecl)
3391 return ExprError();
3392
3393 // Handle members of anonymous structs and unions. If we got here,
3394 // and the reference is to a class member indirect field, then this
3395 // must be the subject of a pointer-to-member expression.
3396 if (auto *IndirectField = dyn_cast<IndirectFieldDecl>(Val: VD);
3397 IndirectField && !IndirectField->isCXXClassMember())
3398 return BuildAnonymousStructUnionMemberReference(SS, nameLoc: NameInfo.getLoc(),
3399 indirectField: IndirectField);
3400
3401 QualType type = VD->getType();
3402 if (type.isNull())
3403 return ExprError();
3404 ExprValueKind valueKind = VK_PRValue;
3405
3406 // In 'T ...V;', the type of the declaration 'V' is 'T...', but the type of
3407 // a reference to 'V' is simply (unexpanded) 'T'. The type, like the value,
3408 // is expanded by some outer '...' in the context of the use.
3409 type = type.getNonPackExpansionType();
3410
3411 switch (D->getKind()) {
3412 // Ignore all the non-ValueDecl kinds.
3413#define ABSTRACT_DECL(kind)
3414#define VALUE(type, base)
3415#define DECL(type, base) case Decl::type:
3416#include "clang/AST/DeclNodes.inc"
3417 llvm_unreachable("invalid value decl kind");
3418
3419 // These shouldn't make it here.
3420 case Decl::ObjCAtDefsField:
3421 llvm_unreachable("forming non-member reference to ivar?");
3422
3423 // Enum constants are always r-values and never references.
3424 // Unresolved using declarations are dependent.
3425 case Decl::EnumConstant:
3426 case Decl::UnresolvedUsingValue:
3427 case Decl::OMPDeclareReduction:
3428 case Decl::OMPDeclareMapper:
3429 valueKind = VK_PRValue;
3430 break;
3431
3432 // Fields and indirect fields that got here must be for
3433 // pointer-to-member expressions; we just call them l-values for
3434 // internal consistency, because this subexpression doesn't really
3435 // exist in the high-level semantics.
3436 case Decl::Field:
3437 case Decl::IndirectField:
3438 case Decl::ObjCIvar:
3439 assert((getLangOpts().CPlusPlus || isAttrContext()) &&
3440 "building reference to field in C?");
3441
3442 // These can't have reference type in well-formed programs, but
3443 // for internal consistency we do this anyway.
3444 type = type.getNonReferenceType();
3445 valueKind = VK_LValue;
3446 break;
3447
3448 // Non-type template parameters are either l-values or r-values
3449 // depending on the type.
3450 case Decl::NonTypeTemplateParm: {
3451 if (const ReferenceType *reftype = type->getAs<ReferenceType>()) {
3452 type = reftype->getPointeeType();
3453 valueKind = VK_LValue; // even if the parameter is an r-value reference
3454 break;
3455 }
3456
3457 // [expr.prim.id.unqual]p2:
3458 // If the entity is a template parameter object for a template
3459 // parameter of type T, the type of the expression is const T.
3460 // [...] The expression is an lvalue if the entity is a [...] template
3461 // parameter object.
3462 if (type->isRecordType()) {
3463 type = type.getUnqualifiedType().withConst();
3464 valueKind = VK_LValue;
3465 break;
3466 }
3467
3468 // For non-references, we need to strip qualifiers just in case
3469 // the template parameter was declared as 'const int' or whatever.
3470 valueKind = VK_PRValue;
3471 type = type.getUnqualifiedType();
3472 break;
3473 }
3474
3475 case Decl::Var:
3476 case Decl::VarTemplateSpecialization:
3477 case Decl::VarTemplatePartialSpecialization:
3478 case Decl::Decomposition:
3479 case Decl::Binding:
3480 case Decl::OMPCapturedExpr:
3481 // In C, "extern void blah;" is valid and is an r-value.
3482 if (!getLangOpts().CPlusPlus && !type.hasQualifiers() &&
3483 type->isVoidType()) {
3484 valueKind = VK_PRValue;
3485 break;
3486 }
3487 [[fallthrough]];
3488
3489 case Decl::ImplicitParam:
3490 case Decl::ParmVar: {
3491 // These are always l-values.
3492 valueKind = VK_LValue;
3493 type = type.getNonReferenceType();
3494
3495 // FIXME: Does the addition of const really only apply in
3496 // potentially-evaluated contexts? Since the variable isn't actually
3497 // captured in an unevaluated context, it seems that the answer is no.
3498 if (!isUnevaluatedContext()) {
3499 QualType CapturedType = getCapturedDeclRefType(Var: cast<ValueDecl>(Val: VD), Loc);
3500 if (!CapturedType.isNull())
3501 type = CapturedType;
3502 }
3503 break;
3504 }
3505
3506 case Decl::Function: {
3507 if (unsigned BID = cast<FunctionDecl>(Val: VD)->getBuiltinID()) {
3508 if (!Context.BuiltinInfo.isDirectlyAddressable(ID: BID)) {
3509 type = Context.BuiltinFnTy;
3510 valueKind = VK_PRValue;
3511 break;
3512 }
3513 }
3514
3515 const FunctionType *fty = type->castAs<FunctionType>();
3516
3517 // If we're referring to a function with an __unknown_anytype
3518 // result type, make the entire expression __unknown_anytype.
3519 if (fty->getReturnType() == Context.UnknownAnyTy) {
3520 type = Context.UnknownAnyTy;
3521 valueKind = VK_PRValue;
3522 break;
3523 }
3524
3525 // Functions are l-values in C++.
3526 if (getLangOpts().CPlusPlus) {
3527 valueKind = VK_LValue;
3528 break;
3529 }
3530
3531 // C99 DR 316 says that, if a function type comes from a
3532 // function definition (without a prototype), that type is only
3533 // used for checking compatibility. Therefore, when referencing
3534 // the function, we pretend that we don't have the full function
3535 // type.
3536 if (!cast<FunctionDecl>(Val: VD)->hasPrototype() && isa<FunctionProtoType>(Val: fty))
3537 type = Context.getFunctionNoProtoType(ResultTy: fty->getReturnType(),
3538 Info: fty->getExtInfo());
3539
3540 // Functions are r-values in C.
3541 valueKind = VK_PRValue;
3542 break;
3543 }
3544
3545 case Decl::CXXDeductionGuide:
3546 llvm_unreachable("building reference to deduction guide");
3547
3548 case Decl::MSProperty:
3549 case Decl::MSGuid:
3550 case Decl::TemplateParamObject:
3551 // FIXME: Should MSGuidDecl and template parameter objects be subject to
3552 // capture in OpenMP, or duplicated between host and device?
3553 valueKind = VK_LValue;
3554 break;
3555
3556 case Decl::UnnamedGlobalConstant:
3557 valueKind = VK_LValue;
3558 break;
3559
3560 case Decl::CXXMethod:
3561 // If we're referring to a method with an __unknown_anytype
3562 // result type, make the entire expression __unknown_anytype.
3563 // This should only be possible with a type written directly.
3564 if (const FunctionProtoType *proto =
3565 dyn_cast<FunctionProtoType>(Val: VD->getType()))
3566 if (proto->getReturnType() == Context.UnknownAnyTy) {
3567 type = Context.UnknownAnyTy;
3568 valueKind = VK_PRValue;
3569 break;
3570 }
3571
3572 // C++ methods are l-values if static, r-values if non-static.
3573 if (cast<CXXMethodDecl>(Val: VD)->isStatic()) {
3574 valueKind = VK_LValue;
3575 break;
3576 }
3577 [[fallthrough]];
3578
3579 case Decl::CXXConversion:
3580 case Decl::CXXDestructor:
3581 case Decl::CXXConstructor:
3582 valueKind = VK_PRValue;
3583 break;
3584 }
3585
3586 auto *E =
3587 BuildDeclRefExpr(D: VD, Ty: type, VK: valueKind, NameInfo, SS: &SS, FoundD,
3588 /*FIXME: TemplateKWLoc*/ TemplateKWLoc: SourceLocation(), TemplateArgs);
3589 // Clang AST consumers assume a DeclRefExpr refers to a valid decl. We
3590 // wrap a DeclRefExpr referring to an invalid decl with a dependent-type
3591 // RecoveryExpr to avoid follow-up semantic analysis (thus prevent bogus
3592 // diagnostics).
3593 if (VD->isInvalidDecl() && E)
3594 return CreateRecoveryExpr(Begin: E->getBeginLoc(), End: E->getEndLoc(), SubExprs: {E});
3595 return E;
3596}
3597
3598static void ConvertUTF8ToWideString(unsigned CharByteWidth, StringRef Source,
3599 SmallString<32> &Target) {
3600 Target.resize(N: CharByteWidth * (Source.size() + 1));
3601 char *ResultPtr = &Target[0];
3602 const llvm::UTF8 *ErrorPtr;
3603 bool success =
3604 llvm::ConvertUTF8toWide(WideCharWidth: CharByteWidth, Source, ResultPtr, ErrorPtr);
3605 (void)success;
3606 assert(success);
3607 Target.resize(N: ResultPtr - &Target[0]);
3608}
3609
3610ExprResult Sema::BuildPredefinedExpr(SourceLocation Loc,
3611 PredefinedIdentKind IK) {
3612 Decl *currentDecl = getPredefinedExprDecl(DC: CurContext);
3613 if (!currentDecl) {
3614 Diag(Loc, DiagID: diag::ext_predef_outside_function);
3615 currentDecl = Context.getTranslationUnitDecl();
3616 }
3617
3618 QualType ResTy;
3619 StringLiteral *SL = nullptr;
3620 if (cast<DeclContext>(Val: currentDecl)->isDependentContext())
3621 ResTy = Context.DependentTy;
3622 else {
3623 // Pre-defined identifiers are of type char[x], where x is the length of
3624 // the string.
3625 bool ForceElaboratedPrinting =
3626 IK == PredefinedIdentKind::Function && getLangOpts().MSVCCompat;
3627 auto Str =
3628 PredefinedExpr::ComputeName(IK, CurrentDecl: currentDecl, ForceElaboratedPrinting);
3629 unsigned Length = Str.length();
3630
3631 llvm::APInt LengthI(32, Length + 1);
3632 if (IK == PredefinedIdentKind::LFunction ||
3633 IK == PredefinedIdentKind::LFuncSig) {
3634 ResTy =
3635 Context.adjustStringLiteralBaseType(StrLTy: Context.WideCharTy.withConst());
3636 SmallString<32> RawChars;
3637 ConvertUTF8ToWideString(CharByteWidth: Context.getTypeSizeInChars(T: ResTy).getQuantity(),
3638 Source: Str, Target&: RawChars);
3639 ResTy = Context.getConstantArrayType(EltTy: ResTy, ArySize: LengthI, SizeExpr: nullptr,
3640 ASM: ArraySizeModifier::Normal,
3641 /*IndexTypeQuals*/ 0);
3642 SL = StringLiteral::Create(Ctx: Context, Str: RawChars, Kind: StringLiteralKind::Wide,
3643 /*Pascal*/ false, Ty: ResTy, Locs: Loc);
3644 } else {
3645 ResTy = Context.adjustStringLiteralBaseType(StrLTy: Context.CharTy.withConst());
3646 ResTy = Context.getConstantArrayType(EltTy: ResTy, ArySize: LengthI, SizeExpr: nullptr,
3647 ASM: ArraySizeModifier::Normal,
3648 /*IndexTypeQuals*/ 0);
3649 SL = StringLiteral::Create(Ctx: Context, Str, Kind: StringLiteralKind::Ordinary,
3650 /*Pascal*/ false, Ty: ResTy, Locs: Loc);
3651 }
3652 }
3653
3654 return PredefinedExpr::Create(Ctx: Context, L: Loc, FNTy: ResTy, IK, IsTransparent: LangOpts.MicrosoftExt,
3655 SL);
3656}
3657
3658ExprResult Sema::ActOnPredefinedExpr(SourceLocation Loc, tok::TokenKind Kind) {
3659 return BuildPredefinedExpr(Loc, IK: getPredefinedExprKind(Kind));
3660}
3661
3662ExprResult Sema::ActOnCharacterConstant(const Token &Tok, Scope *UDLScope) {
3663 SmallString<16> CharBuffer;
3664 bool Invalid = false;
3665 StringRef ThisTok = PP.getSpelling(Tok, Buffer&: CharBuffer, Invalid: &Invalid);
3666 if (Invalid)
3667 return ExprError();
3668
3669 CharLiteralParser Literal(ThisTok.begin(), ThisTok.end(), Tok.getLocation(),
3670 PP, Tok.getKind());
3671 if (Literal.hadError())
3672 return ExprError();
3673
3674 QualType Ty;
3675 if (Literal.isWide())
3676 Ty = Context.WideCharTy; // L'x' -> wchar_t in C and C++.
3677 else if (Literal.isUTF8() && getLangOpts().C23)
3678 Ty = Context.UnsignedCharTy; // u8'x' -> unsigned char in C23
3679 else if (Literal.isUTF8() && getLangOpts().Char8)
3680 Ty = Context.Char8Ty; // u8'x' -> char8_t when it exists.
3681 else if (Literal.isUTF16())
3682 Ty = Context.Char16Ty; // u'x' -> char16_t in C11 and C++11.
3683 else if (Literal.isUTF32())
3684 Ty = Context.Char32Ty; // U'x' -> char32_t in C11 and C++11.
3685 else if (!getLangOpts().CPlusPlus || Literal.isMultiChar())
3686 Ty = Context.IntTy; // 'x' -> int in C, 'wxyz' -> int in C++.
3687 else
3688 Ty = Context.CharTy; // 'x' -> char in C++;
3689 // u8'x' -> char in C11-C17 and in C++ without char8_t.
3690
3691 CharacterLiteralKind Kind = CharacterLiteralKind::Ascii;
3692 if (Literal.isWide())
3693 Kind = CharacterLiteralKind::Wide;
3694 else if (Literal.isUTF16())
3695 Kind = CharacterLiteralKind::UTF16;
3696 else if (Literal.isUTF32())
3697 Kind = CharacterLiteralKind::UTF32;
3698 else if (Literal.isUTF8())
3699 Kind = CharacterLiteralKind::UTF8;
3700
3701 Expr *Lit = new (Context) CharacterLiteral(Literal.getValue(), Kind, Ty,
3702 Tok.getLocation());
3703
3704 if (Literal.getUDSuffix().empty())
3705 return Lit;
3706
3707 // We're building a user-defined literal.
3708 IdentifierInfo *UDSuffix = &Context.Idents.get(Name: Literal.getUDSuffix());
3709 SourceLocation UDSuffixLoc =
3710 getUDSuffixLoc(S&: *this, TokLoc: Tok.getLocation(), Offset: Literal.getUDSuffixOffset());
3711
3712 // Make sure we're allowed user-defined literals here.
3713 if (!UDLScope)
3714 return ExprError(Diag(Loc: UDSuffixLoc, DiagID: diag::err_invalid_character_udl));
3715
3716 // C++11 [lex.ext]p6: The literal L is treated as a call of the form
3717 // operator "" X (ch)
3718 return BuildCookedLiteralOperatorCall(S&: *this, Scope: UDLScope, UDSuffix, UDSuffixLoc,
3719 Args: Lit, LitEndLoc: Tok.getLocation());
3720}
3721
3722ExprResult Sema::ActOnIntegerConstant(SourceLocation Loc, int64_t Val) {
3723 unsigned IntSize = Context.getTargetInfo().getIntWidth();
3724 return IntegerLiteral::Create(C: Context,
3725 V: llvm::APInt(IntSize, Val, /*isSigned=*/true),
3726 type: Context.IntTy, l: Loc);
3727}
3728
3729static Expr *BuildFloatingLiteral(Sema &S, NumericLiteralParser &Literal,
3730 QualType Ty, SourceLocation Loc) {
3731 const llvm::fltSemantics &Format = S.Context.getFloatTypeSemantics(T: Ty);
3732
3733 using llvm::APFloat;
3734 APFloat Val(Format);
3735
3736 llvm::RoundingMode RM = S.CurFPFeatures.getRoundingMode();
3737 if (RM == llvm::RoundingMode::Dynamic)
3738 RM = llvm::RoundingMode::NearestTiesToEven;
3739 APFloat::opStatus result = Literal.GetFloatValue(Result&: Val, RM);
3740
3741 // Overflow is always an error, but underflow is only an error if
3742 // we underflowed to zero (APFloat reports denormals as underflow).
3743 if ((result & APFloat::opOverflow) ||
3744 ((result & APFloat::opUnderflow) && Val.isZero())) {
3745 unsigned diagnostic;
3746 SmallString<20> buffer;
3747 if (result & APFloat::opOverflow) {
3748 diagnostic = diag::warn_float_overflow;
3749 APFloat::getLargest(Sem: Format).toString(Str&: buffer);
3750 } else {
3751 diagnostic = diag::warn_float_underflow;
3752 APFloat::getSmallest(Sem: Format).toString(Str&: buffer);
3753 }
3754
3755 S.Diag(Loc, DiagID: diagnostic) << Ty << buffer.str();
3756 }
3757
3758 bool isExact = (result == APFloat::opOK);
3759 return FloatingLiteral::Create(C: S.Context, V: Val, isexact: isExact, Type: Ty, L: Loc);
3760}
3761
3762bool Sema::CheckLoopHintExpr(Expr *E, SourceLocation Loc, bool AllowZero) {
3763 assert(E && "Invalid expression");
3764
3765 if (E->isValueDependent())
3766 return false;
3767
3768 QualType QT = E->getType();
3769 if (!QT->isIntegerType() || QT->isBooleanType() || QT->isCharType()) {
3770 Diag(Loc: E->getExprLoc(), DiagID: diag::err_pragma_loop_invalid_argument_type) << QT;
3771 return true;
3772 }
3773
3774 llvm::APSInt ValueAPS;
3775 ExprResult R = VerifyIntegerConstantExpression(E, Result: &ValueAPS);
3776
3777 if (R.isInvalid())
3778 return true;
3779
3780 // GCC allows the value of unroll count to be 0.
3781 // https://gcc.gnu.org/onlinedocs/gcc/Loop-Specific-Pragmas.html says
3782 // "The values of 0 and 1 block any unrolling of the loop."
3783 // The values doesn't have to be strictly positive in '#pragma GCC unroll' and
3784 // '#pragma unroll' cases.
3785 bool ValueIsPositive =
3786 AllowZero ? ValueAPS.isNonNegative() : ValueAPS.isStrictlyPositive();
3787 if (!ValueIsPositive || ValueAPS.getActiveBits() > 31) {
3788 Diag(Loc: E->getExprLoc(), DiagID: diag::err_requires_positive_value)
3789 << toString(I: ValueAPS, Radix: 10) << ValueIsPositive;
3790 return true;
3791 }
3792
3793 return false;
3794}
3795
3796ExprResult Sema::ActOnNumericConstant(const Token &Tok, Scope *UDLScope) {
3797 // Fast path for a single digit (which is quite common). A single digit
3798 // cannot have a trigraph, escaped newline, radix prefix, or suffix.
3799 if (Tok.getLength() == 1 || Tok.getKind() == tok::binary_data) {
3800 const uint8_t Val = PP.getSpellingOfSingleCharacterNumericConstant(Tok);
3801 return ActOnIntegerConstant(Loc: Tok.getLocation(), Val);
3802 }
3803
3804 SmallString<128> SpellingBuffer;
3805 // NumericLiteralParser wants to overread by one character. Add padding to
3806 // the buffer in case the token is copied to the buffer. If getSpelling()
3807 // returns a StringRef to the memory buffer, it should have a null char at
3808 // the EOF, so it is also safe.
3809 SpellingBuffer.resize(N: Tok.getLength() + 1);
3810
3811 // Get the spelling of the token, which eliminates trigraphs, etc.
3812 bool Invalid = false;
3813 StringRef TokSpelling = PP.getSpelling(Tok, Buffer&: SpellingBuffer, Invalid: &Invalid);
3814 if (Invalid)
3815 return ExprError();
3816
3817 NumericLiteralParser Literal(TokSpelling, Tok.getLocation(),
3818 PP.getSourceManager(), PP.getLangOpts(),
3819 PP.getTargetInfo(), PP.getDiagnostics());
3820 if (Literal.hadError)
3821 return ExprError();
3822
3823 if (Literal.hasUDSuffix()) {
3824 // We're building a user-defined literal.
3825 const IdentifierInfo *UDSuffix = &Context.Idents.get(Name: Literal.getUDSuffix());
3826 SourceLocation UDSuffixLoc =
3827 getUDSuffixLoc(S&: *this, TokLoc: Tok.getLocation(), Offset: Literal.getUDSuffixOffset());
3828
3829 // Make sure we're allowed user-defined literals here.
3830 if (!UDLScope)
3831 return ExprError(Diag(Loc: UDSuffixLoc, DiagID: diag::err_invalid_numeric_udl));
3832
3833 QualType CookedTy;
3834 if (Literal.isFloatingLiteral()) {
3835 // C++11 [lex.ext]p4: If S contains a literal operator with parameter type
3836 // long double, the literal is treated as a call of the form
3837 // operator "" X (f L)
3838 CookedTy = Context.LongDoubleTy;
3839 } else {
3840 // C++11 [lex.ext]p3: If S contains a literal operator with parameter type
3841 // unsigned long long, the literal is treated as a call of the form
3842 // operator "" X (n ULL)
3843 CookedTy = Context.UnsignedLongLongTy;
3844 }
3845
3846 DeclarationName OpName =
3847 Context.DeclarationNames.getCXXLiteralOperatorName(II: UDSuffix);
3848 DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc);
3849 OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc);
3850
3851 SourceLocation TokLoc = Tok.getLocation();
3852
3853 // Perform literal operator lookup to determine if we're building a raw
3854 // literal or a cooked one.
3855 LookupResult R(*this, OpName, UDSuffixLoc, LookupOrdinaryName);
3856 switch (LookupLiteralOperator(S: UDLScope, R, ArgTys: CookedTy,
3857 /*AllowRaw*/ true, /*AllowTemplate*/ true,
3858 /*AllowStringTemplatePack*/ AllowStringTemplate: false,
3859 /*DiagnoseMissing*/ !Literal.isImaginary)) {
3860 case LOLR_ErrorNoDiagnostic:
3861 // Lookup failure for imaginary constants isn't fatal, there's still the
3862 // GNU extension producing _Complex types.
3863 break;
3864 case LOLR_Error:
3865 return ExprError();
3866 case LOLR_Cooked: {
3867 Expr *Lit;
3868 if (Literal.isFloatingLiteral()) {
3869 Lit = BuildFloatingLiteral(S&: *this, Literal, Ty: CookedTy, Loc: Tok.getLocation());
3870 } else {
3871 llvm::APInt ResultVal(Context.getTargetInfo().getLongLongWidth(), 0);
3872 if (Literal.GetIntegerValue(Val&: ResultVal))
3873 Diag(Loc: Tok.getLocation(), DiagID: diag::err_integer_literal_too_large)
3874 << /* Unsigned */ 1;
3875 Lit = IntegerLiteral::Create(C: Context, V: ResultVal, type: CookedTy,
3876 l: Tok.getLocation());
3877 }
3878 return BuildLiteralOperatorCall(R, SuffixInfo&: OpNameInfo, Args: Lit, LitEndLoc: TokLoc);
3879 }
3880
3881 case LOLR_Raw: {
3882 // C++11 [lit.ext]p3, p4: If S contains a raw literal operator, the
3883 // literal is treated as a call of the form
3884 // operator "" X ("n")
3885 unsigned Length = Literal.getUDSuffixOffset();
3886 QualType StrTy = Context.getConstantArrayType(
3887 EltTy: Context.adjustStringLiteralBaseType(StrLTy: Context.CharTy.withConst()),
3888 ArySize: llvm::APInt(32, Length + 1), SizeExpr: nullptr, ASM: ArraySizeModifier::Normal, IndexTypeQuals: 0);
3889 Expr *Lit =
3890 StringLiteral::Create(Ctx: Context, Str: StringRef(TokSpelling.data(), Length),
3891 Kind: StringLiteralKind::Ordinary,
3892 /*Pascal*/ false, Ty: StrTy, Locs: TokLoc);
3893 return BuildLiteralOperatorCall(R, SuffixInfo&: OpNameInfo, Args: Lit, LitEndLoc: TokLoc);
3894 }
3895
3896 case LOLR_Template: {
3897 // C++11 [lit.ext]p3, p4: Otherwise (S contains a literal operator
3898 // template), L is treated as a call fo the form
3899 // operator "" X <'c1', 'c2', ... 'ck'>()
3900 // where n is the source character sequence c1 c2 ... ck.
3901 TemplateArgumentListInfo ExplicitArgs;
3902 unsigned CharBits = Context.getIntWidth(T: Context.CharTy);
3903 bool CharIsUnsigned = Context.CharTy->isUnsignedIntegerType();
3904 llvm::APSInt Value(CharBits, CharIsUnsigned);
3905 for (unsigned I = 0, N = Literal.getUDSuffixOffset(); I != N; ++I) {
3906 Value = TokSpelling[I];
3907 TemplateArgument Arg(Context, Value, Context.CharTy);
3908 TemplateArgumentLocInfo ArgInfo;
3909 ExplicitArgs.addArgument(Loc: TemplateArgumentLoc(Arg, ArgInfo));
3910 }
3911 return BuildLiteralOperatorCall(R, SuffixInfo&: OpNameInfo, Args: {}, LitEndLoc: TokLoc, ExplicitTemplateArgs: &ExplicitArgs);
3912 }
3913 case LOLR_StringTemplatePack:
3914 llvm_unreachable("unexpected literal operator lookup result");
3915 }
3916 }
3917
3918 Expr *Res;
3919
3920 if (Literal.isFixedPointLiteral()) {
3921 QualType Ty;
3922
3923 if (Literal.isAccum) {
3924 if (Literal.isHalf) {
3925 Ty = Context.ShortAccumTy;
3926 } else if (Literal.isLong) {
3927 Ty = Context.LongAccumTy;
3928 } else {
3929 Ty = Context.AccumTy;
3930 }
3931 } else if (Literal.isFract) {
3932 if (Literal.isHalf) {
3933 Ty = Context.ShortFractTy;
3934 } else if (Literal.isLong) {
3935 Ty = Context.LongFractTy;
3936 } else {
3937 Ty = Context.FractTy;
3938 }
3939 }
3940
3941 if (Literal.isUnsigned) Ty = Context.getCorrespondingUnsignedType(T: Ty);
3942
3943 bool isSigned = !Literal.isUnsigned;
3944 unsigned scale = Context.getFixedPointScale(Ty);
3945 unsigned bit_width = Context.getTypeInfo(T: Ty).Width;
3946
3947 llvm::APInt Val(bit_width, 0, isSigned);
3948 bool Overflowed = Literal.GetFixedPointValue(StoreVal&: Val, Scale: scale);
3949 bool ValIsZero = Val.isZero() && !Overflowed;
3950
3951 auto MaxVal = Context.getFixedPointMax(Ty).getValue();
3952 if (Literal.isFract && Val == MaxVal + 1 && !ValIsZero)
3953 // Clause 6.4.4 - The value of a constant shall be in the range of
3954 // representable values for its type, with exception for constants of a
3955 // fract type with a value of exactly 1; such a constant shall denote
3956 // the maximal value for the type.
3957 --Val;
3958 else if (Val.ugt(RHS: MaxVal) || Overflowed)
3959 Diag(Loc: Tok.getLocation(), DiagID: diag::err_too_large_for_fixed_point);
3960
3961 Res = FixedPointLiteral::CreateFromRawInt(C: Context, V: Val, type: Ty,
3962 l: Tok.getLocation(), Scale: scale);
3963 } else if (Literal.isFloatingLiteral()) {
3964 QualType Ty;
3965 if (Literal.isHalf){
3966 if (getLangOpts().HLSL ||
3967 getOpenCLOptions().isAvailableOption(Ext: "cl_khr_fp16", LO: getLangOpts()))
3968 Ty = Context.HalfTy;
3969 else {
3970 Diag(Loc: Tok.getLocation(), DiagID: diag::err_half_const_requires_fp16);
3971 return ExprError();
3972 }
3973 } else if (Literal.isFloat)
3974 Ty = Context.FloatTy;
3975 else if (Literal.isLong)
3976 Ty = !getLangOpts().HLSL ? Context.LongDoubleTy : Context.DoubleTy;
3977 else if (Literal.isFloat16)
3978 Ty = Context.Float16Ty;
3979 else if (Literal.isFloat128)
3980 Ty = Context.Float128Ty;
3981 else if (getLangOpts().HLSL)
3982 Ty = Context.FloatTy;
3983 else
3984 Ty = Context.DoubleTy;
3985
3986 Res = BuildFloatingLiteral(S&: *this, Literal, Ty, Loc: Tok.getLocation());
3987
3988 if (Ty == Context.DoubleTy) {
3989 if (getLangOpts().SinglePrecisionConstants) {
3990 if (Ty->castAs<BuiltinType>()->getKind() != BuiltinType::Float) {
3991 Res = ImpCastExprToType(E: Res, Type: Context.FloatTy, CK: CK_FloatingCast).get();
3992 }
3993 } else if (getLangOpts().OpenCL && !getOpenCLOptions().isAvailableOption(
3994 Ext: "cl_khr_fp64", LO: getLangOpts())) {
3995 // Impose single-precision float type when cl_khr_fp64 is not enabled.
3996 Diag(Loc: Tok.getLocation(), DiagID: diag::warn_double_const_requires_fp64)
3997 << (getLangOpts().getOpenCLCompatibleVersion() >= 300);
3998 Res = ImpCastExprToType(E: Res, Type: Context.FloatTy, CK: CK_FloatingCast).get();
3999 }
4000 }
4001 } else if (!Literal.isIntegerLiteral()) {
4002 return ExprError();
4003 } else {
4004 QualType Ty;
4005
4006 // 'z/uz' literals are a C++23 feature.
4007 if (Literal.isSizeT)
4008 Diag(Loc: Tok.getLocation(), DiagID: getLangOpts().CPlusPlus
4009 ? getLangOpts().CPlusPlus23
4010 ? diag::warn_cxx20_compat_size_t_suffix
4011 : diag::ext_cxx23_size_t_suffix
4012 : diag::err_cxx23_size_t_suffix);
4013
4014 // 'wb/uwb' literals are a C23 feature. We support _BitInt as a type in C++,
4015 // but we do not currently support the suffix in C++ mode because it's not
4016 // entirely clear whether WG21 will prefer this suffix to return a library
4017 // type such as std::bit_int instead of returning a _BitInt. '__wb/__uwb'
4018 // literals are a C++ extension.
4019 if (Literal.isBitInt)
4020 PP.Diag(Loc: Tok.getLocation(),
4021 DiagID: getLangOpts().CPlusPlus ? diag::ext_cxx_bitint_suffix
4022 : getLangOpts().C23 ? diag::warn_c23_compat_bitint_suffix
4023 : diag::ext_c23_bitint_suffix);
4024
4025 // Get the value in the widest-possible width. What is "widest" depends on
4026 // whether the literal is a bit-precise integer or not. For a bit-precise
4027 // integer type, try to scan the source to determine how many bits are
4028 // needed to represent the value. This may seem a bit expensive, but trying
4029 // to get the integer value from an overly-wide APInt is *extremely*
4030 // expensive, so the naive approach of assuming
4031 // llvm::IntegerType::MAX_INT_BITS is a big performance hit.
4032 unsigned BitsNeeded = Context.getTargetInfo().getIntMaxTWidth();
4033 if (Literal.isBitInt)
4034 BitsNeeded = llvm::APInt::getSufficientBitsNeeded(
4035 Str: Literal.getLiteralDigits(), Radix: Literal.getRadix());
4036 if (Literal.MicrosoftInteger) {
4037 if (Literal.MicrosoftInteger == 128 &&
4038 !Context.getTargetInfo().hasInt128Type())
4039 PP.Diag(Loc: Tok.getLocation(), DiagID: diag::err_integer_literal_too_large)
4040 << Literal.isUnsigned;
4041 BitsNeeded = Literal.MicrosoftInteger;
4042 }
4043
4044 llvm::APInt ResultVal(BitsNeeded, 0);
4045
4046 if (Literal.GetIntegerValue(Val&: ResultVal)) {
4047 // If this value didn't fit into uintmax_t, error and force to ull.
4048 Diag(Loc: Tok.getLocation(), DiagID: diag::err_integer_literal_too_large)
4049 << /* Unsigned */ 1;
4050 Ty = Context.UnsignedLongLongTy;
4051 assert(Context.getTypeSize(Ty) == ResultVal.getBitWidth() &&
4052 "long long is not intmax_t?");
4053 } else {
4054 // If this value fits into a ULL, try to figure out what else it fits into
4055 // according to the rules of C99 6.4.4.1p5.
4056
4057 // Octal, Hexadecimal, and integers with a U suffix are allowed to
4058 // be an unsigned int.
4059 bool AllowUnsigned = Literal.isUnsigned || Literal.getRadix() != 10;
4060
4061 // HLSL doesn't really have `long` or `long long`. We support the `ll`
4062 // suffix for portability of code with C++, but both `l` and `ll` are
4063 // 64-bit integer types, and we want the type of `1l` and `1ll` to be the
4064 // same.
4065 if (getLangOpts().HLSL && !Literal.isLong && Literal.isLongLong) {
4066 Literal.isLong = true;
4067 Literal.isLongLong = false;
4068 }
4069
4070 // Check from smallest to largest, picking the smallest type we can.
4071 unsigned Width = 0;
4072
4073 // Microsoft specific integer suffixes are explicitly sized.
4074 if (Literal.MicrosoftInteger) {
4075 if (Literal.MicrosoftInteger == 8 && !Literal.isUnsigned) {
4076 Width = 8;
4077 Ty = Context.CharTy;
4078 } else {
4079 Width = Literal.MicrosoftInteger;
4080 Ty = Context.getIntTypeForBitwidth(DestWidth: Width,
4081 /*Signed=*/!Literal.isUnsigned);
4082 }
4083 }
4084
4085 // Bit-precise integer literals are automagically-sized based on the
4086 // width required by the literal.
4087 if (Literal.isBitInt) {
4088 // The signed version has one more bit for the sign value. There are no
4089 // zero-width bit-precise integers, even if the literal value is 0.
4090 Width = std::max(a: ResultVal.getActiveBits(), b: 1u) +
4091 (Literal.isUnsigned ? 0u : 1u);
4092
4093 // Diagnose if the width of the constant is larger than BITINT_MAXWIDTH,
4094 // and reset the type to the largest supported width.
4095 unsigned int MaxBitIntWidth =
4096 Context.getTargetInfo().getMaxBitIntWidth();
4097 if (Width > MaxBitIntWidth) {
4098 Diag(Loc: Tok.getLocation(), DiagID: diag::err_integer_literal_too_large)
4099 << Literal.isUnsigned;
4100 Width = MaxBitIntWidth;
4101 }
4102
4103 // Reset the result value to the smaller APInt and select the correct
4104 // type to be used. Note, we zext even for signed values because the
4105 // literal itself is always an unsigned value (a preceeding - is a
4106 // unary operator, not part of the literal).
4107 ResultVal = ResultVal.zextOrTrunc(width: Width);
4108 Ty = Context.getBitIntType(Unsigned: Literal.isUnsigned, NumBits: Width);
4109 }
4110
4111 // Check C++23 size_t literals.
4112 if (Literal.isSizeT) {
4113 assert(!Literal.MicrosoftInteger &&
4114 "size_t literals can't be Microsoft literals");
4115 unsigned SizeTSize = Context.getTargetInfo().getTypeWidth(
4116 T: Context.getTargetInfo().getSizeType());
4117
4118 // Does it fit in size_t?
4119 if (ResultVal.isIntN(N: SizeTSize)) {
4120 // Does it fit in ssize_t?
4121 if (!Literal.isUnsigned && ResultVal[SizeTSize - 1] == 0)
4122 Ty = Context.getSignedSizeType();
4123 else if (AllowUnsigned)
4124 Ty = Context.getSizeType();
4125 Width = SizeTSize;
4126 }
4127 }
4128
4129 if (Ty.isNull() && !Literal.isLong && !Literal.isLongLong &&
4130 !Literal.isSizeT) {
4131 // Are int/unsigned possibilities?
4132 unsigned IntSize = Context.getTargetInfo().getIntWidth();
4133
4134 // Does it fit in a unsigned int?
4135 if (ResultVal.isIntN(N: IntSize)) {
4136 // Does it fit in a signed int?
4137 if (!Literal.isUnsigned && ResultVal[IntSize-1] == 0)
4138 Ty = Context.IntTy;
4139 else if (AllowUnsigned)
4140 Ty = Context.UnsignedIntTy;
4141 Width = IntSize;
4142 }
4143 }
4144
4145 // Are long/unsigned long possibilities?
4146 if (Ty.isNull() && !Literal.isLongLong && !Literal.isSizeT) {
4147 unsigned LongSize = Context.getTargetInfo().getLongWidth();
4148
4149 // Does it fit in a unsigned long?
4150 if (ResultVal.isIntN(N: LongSize)) {
4151 // Does it fit in a signed long?
4152 if (!Literal.isUnsigned && ResultVal[LongSize-1] == 0)
4153 Ty = Context.LongTy;
4154 else if (AllowUnsigned)
4155 Ty = Context.UnsignedLongTy;
4156 // Check according to the rules of C90 6.1.3.2p5. C++03 [lex.icon]p2
4157 // is compatible.
4158 else if (!getLangOpts().C99 && !getLangOpts().CPlusPlus11) {
4159 const unsigned LongLongSize =
4160 Context.getTargetInfo().getLongLongWidth();
4161 Diag(Loc: Tok.getLocation(),
4162 DiagID: getLangOpts().CPlusPlus
4163 ? Literal.isLong
4164 ? diag::warn_old_implicitly_unsigned_long_cxx
4165 : /*C++98 UB*/ diag::
4166 ext_old_implicitly_unsigned_long_cxx
4167 : diag::warn_old_implicitly_unsigned_long)
4168 << (LongLongSize > LongSize ? /*will have type 'long long'*/ 0
4169 : /*will be ill-formed*/ 1);
4170 Ty = Context.UnsignedLongTy;
4171 }
4172 Width = LongSize;
4173 }
4174 }
4175
4176 // Check long long if needed.
4177 if (Ty.isNull() && !Literal.isSizeT) {
4178 unsigned LongLongSize = Context.getTargetInfo().getLongLongWidth();
4179
4180 // Does it fit in a unsigned long long?
4181 if (ResultVal.isIntN(N: LongLongSize)) {
4182 // Does it fit in a signed long long?
4183 // To be compatible with MSVC, hex integer literals ending with the
4184 // LL or i64 suffix are always signed in Microsoft mode.
4185 if (!Literal.isUnsigned && (ResultVal[LongLongSize-1] == 0 ||
4186 (getLangOpts().MSVCCompat && Literal.isLongLong)))
4187 Ty = Context.LongLongTy;
4188 else if (AllowUnsigned)
4189 Ty = Context.UnsignedLongLongTy;
4190 Width = LongLongSize;
4191
4192 // 'long long' is a C99 or C++11 feature, whether the literal
4193 // explicitly specified 'long long' or we needed the extra width.
4194 if (getLangOpts().CPlusPlus)
4195 Diag(Loc: Tok.getLocation(), DiagID: getLangOpts().CPlusPlus11
4196 ? diag::warn_cxx98_compat_longlong
4197 : diag::ext_cxx11_longlong);
4198 else if (!getLangOpts().C99)
4199 Diag(Loc: Tok.getLocation(), DiagID: diag::ext_c99_longlong);
4200 }
4201 }
4202
4203 // If we still couldn't decide a type, we either have 'size_t' literal
4204 // that is out of range, or a decimal literal that does not fit in a
4205 // signed long long and has no U suffix.
4206 if (Ty.isNull()) {
4207 if (Literal.isSizeT)
4208 Diag(Loc: Tok.getLocation(), DiagID: diag::err_size_t_literal_too_large)
4209 << Literal.isUnsigned;
4210 else
4211 Diag(Loc: Tok.getLocation(),
4212 DiagID: diag::ext_integer_literal_too_large_for_signed);
4213 Ty = Context.UnsignedLongLongTy;
4214 Width = Context.getTargetInfo().getLongLongWidth();
4215 }
4216
4217 if (ResultVal.getBitWidth() != Width)
4218 ResultVal = ResultVal.trunc(width: Width);
4219 }
4220 Res = IntegerLiteral::Create(C: Context, V: ResultVal, type: Ty, l: Tok.getLocation());
4221 }
4222
4223 // If this is an imaginary literal, create the ImaginaryLiteral wrapper.
4224 if (Literal.isImaginary) {
4225 Res = new (Context) ImaginaryLiteral(Res,
4226 Context.getComplexType(T: Res->getType()));
4227
4228 // In C++, this is a GNU extension. In C, it's a C2y extension.
4229 unsigned DiagId;
4230 if (getLangOpts().CPlusPlus)
4231 DiagId = diag::ext_gnu_imaginary_constant;
4232 else if (getLangOpts().C2y)
4233 DiagId = diag::warn_c23_compat_imaginary_constant;
4234 else
4235 DiagId = diag::ext_c2y_imaginary_constant;
4236 Diag(Loc: Tok.getLocation(), DiagID: DiagId);
4237 }
4238 return Res;
4239}
4240
4241ExprResult Sema::ActOnParenExpr(SourceLocation L, SourceLocation R, Expr *E) {
4242 assert(E && "ActOnParenExpr() missing expr");
4243 QualType ExprTy = E->getType();
4244 if (getLangOpts().ProtectParens && CurFPFeatures.getAllowFPReassociate() &&
4245 !E->isLValue() && ExprTy->hasFloatingRepresentation())
4246 return BuildBuiltinCallExpr(Loc: R, Id: Builtin::BI__arithmetic_fence, CallArgs: E);
4247 return new (Context) ParenExpr(L, R, E);
4248}
4249
4250static bool CheckVecStepTraitOperandType(Sema &S, QualType T,
4251 SourceLocation Loc,
4252 SourceRange ArgRange) {
4253 // [OpenCL 1.1 6.11.12] "The vec_step built-in function takes a built-in
4254 // scalar or vector data type argument..."
4255 // Every built-in scalar type (OpenCL 1.1 6.1.1) is either an arithmetic
4256 // type (C99 6.2.5p18) or void.
4257 if (!(T->isArithmeticType() || T->isVoidType() || T->isVectorType())) {
4258 S.Diag(Loc, DiagID: diag::err_vecstep_non_scalar_vector_type)
4259 << T << ArgRange;
4260 return true;
4261 }
4262
4263 assert((T->isVoidType() || !T->isIncompleteType()) &&
4264 "Scalar types should always be complete");
4265 return false;
4266}
4267
4268static bool CheckVectorElementsTraitOperandType(Sema &S, QualType T,
4269 SourceLocation Loc,
4270 SourceRange ArgRange) {
4271 // builtin_vectorelements supports both fixed-sized and scalable vectors.
4272 if (!T->isVectorType() && !T->isSizelessVectorType())
4273 return S.Diag(Loc, DiagID: diag::err_builtin_non_vector_type)
4274 << ""
4275 << "__builtin_vectorelements" << T << ArgRange;
4276
4277 if (auto *FD = dyn_cast<FunctionDecl>(Val: S.CurContext)) {
4278 if (T->isSVESizelessBuiltinType()) {
4279 llvm::StringMap<bool> CallerFeatureMap;
4280 S.Context.getFunctionFeatureMap(FeatureMap&: CallerFeatureMap, FD);
4281 return S.ARM().checkSVETypeSupport(Ty: T, Loc, FD, FeatureMap: CallerFeatureMap);
4282 }
4283 }
4284
4285 return false;
4286}
4287
4288static bool checkPtrAuthTypeDiscriminatorOperandType(Sema &S, QualType T,
4289 SourceLocation Loc,
4290 SourceRange ArgRange) {
4291 if (S.checkPointerAuthEnabled(Loc, Range: ArgRange))
4292 return true;
4293
4294 if (!T->isFunctionType() && !T->isFunctionPointerType() &&
4295 !T->isFunctionReferenceType() && !T->isMemberFunctionPointerType()) {
4296 S.Diag(Loc, DiagID: diag::err_ptrauth_type_disc_undiscriminated) << T << ArgRange;
4297 return true;
4298 }
4299
4300 return false;
4301}
4302
4303static bool CheckExtensionTraitOperandType(Sema &S, QualType T,
4304 SourceLocation Loc,
4305 SourceRange ArgRange,
4306 UnaryExprOrTypeTrait TraitKind) {
4307 // Invalid types must be hard errors for SFINAE in C++.
4308 if (S.LangOpts.CPlusPlus)
4309 return true;
4310
4311 // C99 6.5.3.4p1:
4312 if (TraitKind == UETT_SizeOf || TraitKind == UETT_AlignOf ||
4313 TraitKind == UETT_PreferredAlignOf) {
4314
4315 // sizeof(function)/alignof(function) is allowed as an extension.
4316 if (T->isFunctionType()) {
4317 S.Diag(Loc, DiagID: diag::ext_sizeof_alignof_function_type)
4318 << getTraitSpelling(T: TraitKind) << ArgRange;
4319 return false;
4320 }
4321
4322 // Allow sizeof(void)/alignof(void) as an extension, unless in OpenCL where
4323 // this is an error (OpenCL v1.1 s6.3.k)
4324 if (T->isVoidType()) {
4325 unsigned DiagID = S.LangOpts.OpenCL ? diag::err_opencl_sizeof_alignof_type
4326 : diag::ext_sizeof_alignof_void_type;
4327 S.Diag(Loc, DiagID) << getTraitSpelling(T: TraitKind) << ArgRange;
4328 return false;
4329 }
4330 }
4331 return true;
4332}
4333
4334static bool CheckObjCTraitOperandConstraints(Sema &S, QualType T,
4335 SourceLocation Loc,
4336 SourceRange ArgRange,
4337 UnaryExprOrTypeTrait TraitKind) {
4338 // Reject sizeof(interface) and sizeof(interface<proto>) if the
4339 // runtime doesn't allow it.
4340 if (!S.LangOpts.ObjCRuntime.allowsSizeofAlignof() && T->isObjCObjectType()) {
4341 S.Diag(Loc, DiagID: diag::err_sizeof_nonfragile_interface)
4342 << T << (TraitKind == UETT_SizeOf)
4343 << ArgRange;
4344 return true;
4345 }
4346
4347 return false;
4348}
4349
4350/// Check whether E is a pointer from a decayed array type (the decayed
4351/// pointer type is equal to T) and emit a warning if it is.
4352static void warnOnSizeofOnArrayDecay(Sema &S, SourceLocation Loc, QualType T,
4353 const Expr *E) {
4354 // Don't warn if the operation changed the type.
4355 if (T != E->getType())
4356 return;
4357
4358 // Now look for array decays.
4359 const auto *ICE = dyn_cast<ImplicitCastExpr>(Val: E);
4360 if (!ICE || ICE->getCastKind() != CK_ArrayToPointerDecay)
4361 return;
4362
4363 S.Diag(Loc, DiagID: diag::warn_sizeof_array_decay) << ICE->getSourceRange()
4364 << ICE->getType()
4365 << ICE->getSubExpr()->getType();
4366}
4367
4368bool Sema::CheckUnaryExprOrTypeTraitOperand(Expr *E,
4369 UnaryExprOrTypeTrait ExprKind) {
4370 QualType ExprTy = E->getType();
4371 assert(!ExprTy->isReferenceType());
4372
4373 bool IsUnevaluatedOperand =
4374 (ExprKind == UETT_SizeOf || ExprKind == UETT_DataSizeOf ||
4375 ExprKind == UETT_AlignOf || ExprKind == UETT_PreferredAlignOf ||
4376 ExprKind == UETT_VecStep || ExprKind == UETT_CountOf);
4377 if (IsUnevaluatedOperand) {
4378 ExprResult Result = CheckUnevaluatedOperand(E);
4379 if (Result.isInvalid())
4380 return true;
4381 E = Result.get();
4382 }
4383
4384 // The operand for sizeof and alignof is in an unevaluated expression context,
4385 // so side effects could result in unintended consequences.
4386 // Exclude instantiation-dependent expressions, because 'sizeof' is sometimes
4387 // used to build SFINAE gadgets.
4388 // FIXME: Should we consider instantiation-dependent operands to 'alignof'?
4389 if (IsUnevaluatedOperand && !inTemplateInstantiation() &&
4390 !E->isInstantiationDependent() &&
4391 !E->getType()->isVariableArrayType() &&
4392 E->HasSideEffects(Ctx: Context, IncludePossibleEffects: false))
4393 Diag(Loc: E->getExprLoc(), DiagID: diag::warn_side_effects_unevaluated_context);
4394
4395 if (ExprKind == UETT_VecStep)
4396 return CheckVecStepTraitOperandType(S&: *this, T: ExprTy, Loc: E->getExprLoc(),
4397 ArgRange: E->getSourceRange());
4398
4399 if (ExprKind == UETT_VectorElements)
4400 return CheckVectorElementsTraitOperandType(S&: *this, T: ExprTy, Loc: E->getExprLoc(),
4401 ArgRange: E->getSourceRange());
4402
4403 // Explicitly list some types as extensions.
4404 if (!CheckExtensionTraitOperandType(S&: *this, T: ExprTy, Loc: E->getExprLoc(),
4405 ArgRange: E->getSourceRange(), TraitKind: ExprKind))
4406 return false;
4407
4408 // WebAssembly tables are always illegal operands to unary expressions and
4409 // type traits.
4410 if (Context.getTargetInfo().getTriple().isWasm() &&
4411 E->getType()->isWebAssemblyTableType()) {
4412 Diag(Loc: E->getExprLoc(), DiagID: diag::err_wasm_table_invalid_uett_operand)
4413 << getTraitSpelling(T: ExprKind);
4414 return true;
4415 }
4416
4417 // 'alignof' applied to an expression only requires the base element type of
4418 // the expression to be complete. 'sizeof' requires the expression's type to
4419 // be complete (and will attempt to complete it if it's an array of unknown
4420 // bound).
4421 if (ExprKind == UETT_AlignOf || ExprKind == UETT_PreferredAlignOf) {
4422 if (RequireCompleteSizedType(
4423 Loc: E->getExprLoc(), T: Context.getBaseElementType(QT: E->getType()),
4424 DiagID: diag::err_sizeof_alignof_incomplete_or_sizeless_type,
4425 Args: getTraitSpelling(T: ExprKind), Args: E->getSourceRange()))
4426 return true;
4427 } else {
4428 if (RequireCompleteSizedExprType(
4429 E, DiagID: diag::err_sizeof_alignof_incomplete_or_sizeless_type,
4430 Args: getTraitSpelling(T: ExprKind), Args: E->getSourceRange()))
4431 return true;
4432 }
4433
4434 // Completing the expression's type may have changed it.
4435 ExprTy = E->getType();
4436 assert(!ExprTy->isReferenceType());
4437
4438 if (ExprTy->isFunctionType()) {
4439 Diag(Loc: E->getExprLoc(), DiagID: diag::err_sizeof_alignof_function_type)
4440 << getTraitSpelling(T: ExprKind) << E->getSourceRange();
4441 return true;
4442 }
4443
4444 if (CheckObjCTraitOperandConstraints(S&: *this, T: ExprTy, Loc: E->getExprLoc(),
4445 ArgRange: E->getSourceRange(), TraitKind: ExprKind))
4446 return true;
4447
4448 if (ExprKind == UETT_CountOf) {
4449 // The type has to be an array type. We already checked for incomplete
4450 // types above.
4451 QualType ExprType = E->IgnoreParens()->getType();
4452 if (!ExprType->isArrayType()) {
4453 Diag(Loc: E->getExprLoc(), DiagID: diag::err_countof_arg_not_array_type) << ExprType;
4454 return true;
4455 }
4456 // FIXME: warn on _Countof on an array parameter. Not warning on it
4457 // currently because there are papers in WG14 about array types which do
4458 // not decay that could impact this behavior, so we want to see if anything
4459 // changes here before coming up with a warning group for _Countof-related
4460 // diagnostics.
4461 }
4462
4463 if (ExprKind == UETT_SizeOf) {
4464 if (const auto *DeclRef = dyn_cast<DeclRefExpr>(Val: E->IgnoreParens())) {
4465 if (const auto *PVD = dyn_cast<ParmVarDecl>(Val: DeclRef->getFoundDecl())) {
4466 QualType OType = PVD->getOriginalType();
4467 QualType Type = PVD->getType();
4468 if (Type->isPointerType() && OType->isArrayType()) {
4469 Diag(Loc: E->getExprLoc(), DiagID: diag::warn_sizeof_array_param)
4470 << Type << OType;
4471 Diag(Loc: PVD->getLocation(), DiagID: diag::note_declared_at);
4472 }
4473 }
4474 }
4475
4476 // Warn on "sizeof(array op x)" and "sizeof(x op array)", where the array
4477 // decays into a pointer and returns an unintended result. This is most
4478 // likely a typo for "sizeof(array) op x".
4479 if (const auto *BO = dyn_cast<BinaryOperator>(Val: E->IgnoreParens())) {
4480 warnOnSizeofOnArrayDecay(S&: *this, Loc: BO->getOperatorLoc(), T: BO->getType(),
4481 E: BO->getLHS());
4482 warnOnSizeofOnArrayDecay(S&: *this, Loc: BO->getOperatorLoc(), T: BO->getType(),
4483 E: BO->getRHS());
4484 }
4485 }
4486
4487 return false;
4488}
4489
4490static bool CheckAlignOfExpr(Sema &S, Expr *E, UnaryExprOrTypeTrait ExprKind) {
4491 // Cannot know anything else if the expression is dependent.
4492 if (E->isTypeDependent())
4493 return false;
4494
4495 if (E->getObjectKind() == OK_BitField) {
4496 S.Diag(Loc: E->getExprLoc(), DiagID: diag::err_sizeof_alignof_typeof_bitfield)
4497 << 1 << E->getSourceRange();
4498 return true;
4499 }
4500
4501 ValueDecl *D = nullptr;
4502 Expr *Inner = E->IgnoreParens();
4503 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Val: Inner)) {
4504 D = DRE->getDecl();
4505 } else if (MemberExpr *ME = dyn_cast<MemberExpr>(Val: Inner)) {
4506 D = ME->getMemberDecl();
4507 }
4508
4509 // If it's a field, require the containing struct to have a
4510 // complete definition so that we can compute the layout.
4511 //
4512 // This can happen in C++11 onwards, either by naming the member
4513 // in a way that is not transformed into a member access expression
4514 // (in an unevaluated operand, for instance), or by naming the member
4515 // in a trailing-return-type.
4516 //
4517 // For the record, since __alignof__ on expressions is a GCC
4518 // extension, GCC seems to permit this but always gives the
4519 // nonsensical answer 0.
4520 //
4521 // We don't really need the layout here --- we could instead just
4522 // directly check for all the appropriate alignment-lowing
4523 // attributes --- but that would require duplicating a lot of
4524 // logic that just isn't worth duplicating for such a marginal
4525 // use-case.
4526 if (FieldDecl *FD = dyn_cast_or_null<FieldDecl>(Val: D)) {
4527 // Fast path this check, since we at least know the record has a
4528 // definition if we can find a member of it.
4529 if (!FD->getParent()->isCompleteDefinition()) {
4530 S.Diag(Loc: E->getExprLoc(), DiagID: diag::err_alignof_member_of_incomplete_type)
4531 << E->getSourceRange();
4532 return true;
4533 }
4534
4535 // Otherwise, if it's a field, and the field doesn't have
4536 // reference type, then it must have a complete type (or be a
4537 // flexible array member, which we explicitly want to
4538 // white-list anyway), which makes the following checks trivial.
4539 if (!FD->getType()->isReferenceType())
4540 return false;
4541 }
4542
4543 return S.CheckUnaryExprOrTypeTraitOperand(E, ExprKind);
4544}
4545
4546bool Sema::CheckVecStepExpr(Expr *E) {
4547 E = E->IgnoreParens();
4548
4549 // Cannot know anything else if the expression is dependent.
4550 if (E->isTypeDependent())
4551 return false;
4552
4553 return CheckUnaryExprOrTypeTraitOperand(E, ExprKind: UETT_VecStep);
4554}
4555
4556static void captureVariablyModifiedType(ASTContext &Context, QualType T,
4557 CapturingScopeInfo *CSI) {
4558 assert(T->isVariablyModifiedType());
4559 assert(CSI != nullptr);
4560
4561 // We're going to walk down into the type and look for VLA expressions.
4562 do {
4563 const Type *Ty = T.getTypePtr();
4564 switch (Ty->getTypeClass()) {
4565#define TYPE(Class, Base)
4566#define ABSTRACT_TYPE(Class, Base)
4567#define NON_CANONICAL_TYPE(Class, Base)
4568#define DEPENDENT_TYPE(Class, Base) case Type::Class:
4569#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base)
4570#include "clang/AST/TypeNodes.inc"
4571 T = QualType();
4572 break;
4573 // These types are never variably-modified.
4574 case Type::Builtin:
4575 case Type::Complex:
4576 case Type::Vector:
4577 case Type::ExtVector:
4578 case Type::ConstantMatrix:
4579 case Type::Record:
4580 case Type::Enum:
4581 case Type::TemplateSpecialization:
4582 case Type::ObjCObject:
4583 case Type::ObjCInterface:
4584 case Type::ObjCObjectPointer:
4585 case Type::ObjCTypeParam:
4586 case Type::Pipe:
4587 case Type::BitInt:
4588 case Type::HLSLInlineSpirv:
4589 llvm_unreachable("type class is never variably-modified!");
4590 case Type::Adjusted:
4591 T = cast<AdjustedType>(Val: Ty)->getOriginalType();
4592 break;
4593 case Type::Decayed:
4594 T = cast<DecayedType>(Val: Ty)->getPointeeType();
4595 break;
4596 case Type::ArrayParameter:
4597 T = cast<ArrayParameterType>(Val: Ty)->getElementType();
4598 break;
4599 case Type::Pointer:
4600 T = cast<PointerType>(Val: Ty)->getPointeeType();
4601 break;
4602 case Type::BlockPointer:
4603 T = cast<BlockPointerType>(Val: Ty)->getPointeeType();
4604 break;
4605 case Type::LValueReference:
4606 case Type::RValueReference:
4607 T = cast<ReferenceType>(Val: Ty)->getPointeeType();
4608 break;
4609 case Type::MemberPointer:
4610 T = cast<MemberPointerType>(Val: Ty)->getPointeeType();
4611 break;
4612 case Type::ConstantArray:
4613 case Type::IncompleteArray:
4614 // Losing element qualification here is fine.
4615 T = cast<ArrayType>(Val: Ty)->getElementType();
4616 break;
4617 case Type::VariableArray: {
4618 // Losing element qualification here is fine.
4619 const VariableArrayType *VAT = cast<VariableArrayType>(Val: Ty);
4620
4621 // Unknown size indication requires no size computation.
4622 // Otherwise, evaluate and record it.
4623 auto Size = VAT->getSizeExpr();
4624 if (Size && !CSI->isVLATypeCaptured(VAT) &&
4625 (isa<CapturedRegionScopeInfo>(Val: CSI) || isa<LambdaScopeInfo>(Val: CSI)))
4626 CSI->addVLATypeCapture(Loc: Size->getExprLoc(), VLAType: VAT, CaptureType: Context.getSizeType());
4627
4628 T = VAT->getElementType();
4629 break;
4630 }
4631 case Type::FunctionProto:
4632 case Type::FunctionNoProto:
4633 T = cast<FunctionType>(Val: Ty)->getReturnType();
4634 break;
4635 case Type::Paren:
4636 case Type::TypeOf:
4637 case Type::UnaryTransform:
4638 case Type::Attributed:
4639 case Type::BTFTagAttributed:
4640 case Type::OverflowBehavior:
4641 case Type::HLSLAttributedResource:
4642 case Type::SubstTemplateTypeParm:
4643 case Type::MacroQualified:
4644 case Type::CountAttributed:
4645 // Keep walking after single level desugaring.
4646 T = T.getSingleStepDesugaredType(Context);
4647 break;
4648 case Type::Typedef:
4649 T = cast<TypedefType>(Val: Ty)->desugar();
4650 break;
4651 case Type::Decltype:
4652 T = cast<DecltypeType>(Val: Ty)->desugar();
4653 break;
4654 case Type::PackIndexing:
4655 T = cast<PackIndexingType>(Val: Ty)->desugar();
4656 break;
4657 case Type::Using:
4658 T = cast<UsingType>(Val: Ty)->desugar();
4659 break;
4660 case Type::Auto:
4661 case Type::DeducedTemplateSpecialization:
4662 T = cast<DeducedType>(Val: Ty)->getDeducedType();
4663 break;
4664 case Type::TypeOfExpr:
4665 T = cast<TypeOfExprType>(Val: Ty)->getUnderlyingExpr()->getType();
4666 break;
4667 case Type::Atomic:
4668 T = cast<AtomicType>(Val: Ty)->getValueType();
4669 break;
4670 case Type::PredefinedSugar:
4671 T = cast<PredefinedSugarType>(Val: Ty)->desugar();
4672 break;
4673 }
4674 } while (!T.isNull() && T->isVariablyModifiedType());
4675}
4676
4677bool Sema::CheckUnaryExprOrTypeTraitOperand(QualType ExprType,
4678 SourceLocation OpLoc,
4679 SourceRange ExprRange,
4680 UnaryExprOrTypeTrait ExprKind,
4681 StringRef KWName) {
4682 if (ExprType->isDependentType())
4683 return false;
4684
4685 // C++ [expr.sizeof]p2:
4686 // When applied to a reference or a reference type, the result
4687 // is the size of the referenced type.
4688 // C++11 [expr.alignof]p3:
4689 // When alignof is applied to a reference type, the result
4690 // shall be the alignment of the referenced type.
4691 if (const ReferenceType *Ref = ExprType->getAs<ReferenceType>())
4692 ExprType = Ref->getPointeeType();
4693
4694 // C11 6.5.3.4/3, C++11 [expr.alignof]p3:
4695 // When alignof or _Alignof is applied to an array type, the result
4696 // is the alignment of the element type.
4697 if (ExprKind == UETT_AlignOf || ExprKind == UETT_PreferredAlignOf ||
4698 ExprKind == UETT_OpenMPRequiredSimdAlign) {
4699 // If the trait is 'alignof' in C before C2y, the ability to apply the
4700 // trait to an incomplete array is an extension.
4701 if (ExprKind == UETT_AlignOf && !getLangOpts().CPlusPlus &&
4702 ExprType->isIncompleteArrayType())
4703 Diag(Loc: OpLoc, DiagID: getLangOpts().C2y
4704 ? diag::warn_c2y_compat_alignof_incomplete_array
4705 : diag::ext_c2y_alignof_incomplete_array);
4706 ExprType = Context.getBaseElementType(QT: ExprType);
4707 }
4708
4709 if (ExprKind == UETT_VecStep)
4710 return CheckVecStepTraitOperandType(S&: *this, T: ExprType, Loc: OpLoc, ArgRange: ExprRange);
4711
4712 if (ExprKind == UETT_VectorElements)
4713 return CheckVectorElementsTraitOperandType(S&: *this, T: ExprType, Loc: OpLoc,
4714 ArgRange: ExprRange);
4715
4716 if (ExprKind == UETT_PtrAuthTypeDiscriminator)
4717 return checkPtrAuthTypeDiscriminatorOperandType(S&: *this, T: ExprType, Loc: OpLoc,
4718 ArgRange: ExprRange);
4719
4720 // Explicitly list some types as extensions.
4721 if (!CheckExtensionTraitOperandType(S&: *this, T: ExprType, Loc: OpLoc, ArgRange: ExprRange,
4722 TraitKind: ExprKind))
4723 return false;
4724
4725 if (RequireCompleteSizedType(
4726 Loc: OpLoc, T: ExprType, DiagID: diag::err_sizeof_alignof_incomplete_or_sizeless_type,
4727 Args: KWName, Args: ExprRange))
4728 return true;
4729
4730 if (ExprType->isFunctionType()) {
4731 Diag(Loc: OpLoc, DiagID: diag::err_sizeof_alignof_function_type) << KWName << ExprRange;
4732 return true;
4733 }
4734
4735 if (ExprKind == UETT_CountOf) {
4736 // The type has to be an array type. We already checked for incomplete
4737 // types above.
4738 if (!ExprType->isArrayType()) {
4739 Diag(Loc: OpLoc, DiagID: diag::err_countof_arg_not_array_type) << ExprType;
4740 return true;
4741 }
4742 }
4743
4744 // WebAssembly tables are always illegal operands to unary expressions and
4745 // type traits.
4746 if (Context.getTargetInfo().getTriple().isWasm() &&
4747 ExprType->isWebAssemblyTableType()) {
4748 Diag(Loc: OpLoc, DiagID: diag::err_wasm_table_invalid_uett_operand)
4749 << getTraitSpelling(T: ExprKind);
4750 return true;
4751 }
4752
4753 if (CheckObjCTraitOperandConstraints(S&: *this, T: ExprType, Loc: OpLoc, ArgRange: ExprRange,
4754 TraitKind: ExprKind))
4755 return true;
4756
4757 if (ExprType->isVariablyModifiedType() && FunctionScopes.size() > 1) {
4758 if (auto *TT = ExprType->getAs<TypedefType>()) {
4759 for (auto I = FunctionScopes.rbegin(),
4760 E = std::prev(x: FunctionScopes.rend());
4761 I != E; ++I) {
4762 auto *CSI = dyn_cast<CapturingScopeInfo>(Val: *I);
4763 if (CSI == nullptr)
4764 break;
4765 DeclContext *DC = nullptr;
4766 if (auto *LSI = dyn_cast<LambdaScopeInfo>(Val: CSI))
4767 DC = LSI->CallOperator;
4768 else if (auto *CRSI = dyn_cast<CapturedRegionScopeInfo>(Val: CSI))
4769 DC = CRSI->TheCapturedDecl;
4770 else if (auto *BSI = dyn_cast<BlockScopeInfo>(Val: CSI))
4771 DC = BSI->TheDecl;
4772 if (DC) {
4773 if (DC->containsDecl(D: TT->getDecl()))
4774 break;
4775 captureVariablyModifiedType(Context, T: ExprType, CSI);
4776 }
4777 }
4778 }
4779 }
4780
4781 return false;
4782}
4783
4784ExprResult Sema::CreateUnaryExprOrTypeTraitExpr(TypeSourceInfo *TInfo,
4785 SourceLocation OpLoc,
4786 UnaryExprOrTypeTrait ExprKind,
4787 SourceRange R) {
4788 if (!TInfo)
4789 return ExprError();
4790
4791 QualType T = TInfo->getType();
4792
4793 if (!T->isDependentType() &&
4794 CheckUnaryExprOrTypeTraitOperand(ExprType: T, OpLoc, ExprRange: R, ExprKind,
4795 KWName: getTraitSpelling(T: ExprKind)))
4796 return ExprError();
4797
4798 // Adds overload of TransformToPotentiallyEvaluated for TypeSourceInfo to
4799 // properly deal with VLAs in nested calls of sizeof and typeof.
4800 if (currentEvaluationContext().isUnevaluated() &&
4801 currentEvaluationContext().InConditionallyConstantEvaluateContext &&
4802 (ExprKind == UETT_SizeOf || ExprKind == UETT_CountOf) &&
4803 TInfo->getType()->isVariablyModifiedType())
4804 TInfo = TransformToPotentiallyEvaluated(TInfo);
4805
4806 // It's possible that the transformation above failed.
4807 if (!TInfo)
4808 return ExprError();
4809
4810 // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t.
4811 return new (Context) UnaryExprOrTypeTraitExpr(
4812 ExprKind, TInfo, Context.getSizeType(), OpLoc, R.getEnd());
4813}
4814
4815ExprResult
4816Sema::CreateUnaryExprOrTypeTraitExpr(Expr *E, SourceLocation OpLoc,
4817 UnaryExprOrTypeTrait ExprKind) {
4818 ExprResult PE = CheckPlaceholderExpr(E);
4819 if (PE.isInvalid())
4820 return ExprError();
4821
4822 E = PE.get();
4823
4824 // Verify that the operand is valid.
4825 bool isInvalid = false;
4826 if (E->isTypeDependent()) {
4827 // Delay type-checking for type-dependent expressions.
4828 } else if (ExprKind == UETT_AlignOf || ExprKind == UETT_PreferredAlignOf) {
4829 isInvalid = CheckAlignOfExpr(S&: *this, E, ExprKind);
4830 } else if (ExprKind == UETT_VecStep) {
4831 isInvalid = CheckVecStepExpr(E);
4832 } else if (ExprKind == UETT_OpenMPRequiredSimdAlign) {
4833 Diag(Loc: E->getExprLoc(), DiagID: diag::err_openmp_default_simd_align_expr);
4834 isInvalid = true;
4835 } else if (E->refersToBitField()) { // C99 6.5.3.4p1.
4836 Diag(Loc: E->getExprLoc(), DiagID: diag::err_sizeof_alignof_typeof_bitfield) << 0;
4837 isInvalid = true;
4838 } else if (ExprKind == UETT_VectorElements || ExprKind == UETT_SizeOf ||
4839 ExprKind == UETT_CountOf) { // FIXME: __datasizeof?
4840 isInvalid = CheckUnaryExprOrTypeTraitOperand(E, ExprKind);
4841 }
4842
4843 if (isInvalid)
4844 return ExprError();
4845
4846 if ((ExprKind == UETT_SizeOf || ExprKind == UETT_CountOf) &&
4847 E->getType()->isVariableArrayType()) {
4848 PE = TransformToPotentiallyEvaluated(E);
4849 if (PE.isInvalid()) return ExprError();
4850 E = PE.get();
4851 }
4852
4853 // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t.
4854 return new (Context) UnaryExprOrTypeTraitExpr(
4855 ExprKind, E, Context.getSizeType(), OpLoc, E->getSourceRange().getEnd());
4856}
4857
4858ExprResult
4859Sema::ActOnUnaryExprOrTypeTraitExpr(SourceLocation OpLoc,
4860 UnaryExprOrTypeTrait ExprKind, bool IsType,
4861 void *TyOrEx, SourceRange ArgRange) {
4862 // If error parsing type, ignore.
4863 if (!TyOrEx) return ExprError();
4864
4865 if (IsType) {
4866 TypeSourceInfo *TInfo;
4867 (void) GetTypeFromParser(Ty: ParsedType::getFromOpaquePtr(P: TyOrEx), TInfo: &TInfo);
4868 return CreateUnaryExprOrTypeTraitExpr(TInfo, OpLoc, ExprKind, R: ArgRange);
4869 }
4870
4871 Expr *ArgEx = (Expr *)TyOrEx;
4872 ExprResult Result = CreateUnaryExprOrTypeTraitExpr(E: ArgEx, OpLoc, ExprKind);
4873 return Result;
4874}
4875
4876bool Sema::CheckAlignasTypeArgument(StringRef KWName, TypeSourceInfo *TInfo,
4877 SourceLocation OpLoc, SourceRange R) {
4878 if (!TInfo)
4879 return true;
4880 return CheckUnaryExprOrTypeTraitOperand(ExprType: TInfo->getType(), OpLoc, ExprRange: R,
4881 ExprKind: UETT_AlignOf, KWName);
4882}
4883
4884bool Sema::ActOnAlignasTypeArgument(StringRef KWName, ParsedType Ty,
4885 SourceLocation OpLoc, SourceRange R) {
4886 TypeSourceInfo *TInfo;
4887 (void)GetTypeFromParser(Ty: ParsedType::getFromOpaquePtr(P: Ty.getAsOpaquePtr()),
4888 TInfo: &TInfo);
4889 return CheckAlignasTypeArgument(KWName, TInfo, OpLoc, R);
4890}
4891
4892static QualType CheckRealImagOperand(Sema &S, ExprResult &V, SourceLocation Loc,
4893 bool IsReal) {
4894 if (V.get()->isTypeDependent())
4895 return S.Context.DependentTy;
4896
4897 // _Real and _Imag are only l-values for normal l-values.
4898 if (V.get()->getObjectKind() != OK_Ordinary) {
4899 V = S.DefaultLvalueConversion(E: V.get());
4900 if (V.isInvalid())
4901 return QualType();
4902 }
4903
4904 // These operators return the element type of a complex type.
4905 if (const ComplexType *CT = V.get()->getType()->getAs<ComplexType>())
4906 return CT->getElementType();
4907
4908 // Otherwise they pass through real integer and floating point types here.
4909 if (V.get()->getType()->isArithmeticType())
4910 return V.get()->getType();
4911
4912 // Test for placeholders.
4913 ExprResult PR = S.CheckPlaceholderExpr(E: V.get());
4914 if (PR.isInvalid()) return QualType();
4915 if (PR.get() != V.get()) {
4916 V = PR;
4917 return CheckRealImagOperand(S, V, Loc, IsReal);
4918 }
4919
4920 // Reject anything else.
4921 S.Diag(Loc, DiagID: diag::err_realimag_invalid_type) << V.get()->getType()
4922 << (IsReal ? "__real" : "__imag");
4923 return QualType();
4924}
4925
4926
4927
4928ExprResult
4929Sema::ActOnPostfixUnaryOp(Scope *S, SourceLocation OpLoc,
4930 tok::TokenKind Kind, Expr *Input) {
4931 UnaryOperatorKind Opc;
4932 switch (Kind) {
4933 default: llvm_unreachable("Unknown unary op!");
4934 case tok::plusplus: Opc = UO_PostInc; break;
4935 case tok::minusminus: Opc = UO_PostDec; break;
4936 }
4937
4938 // Since this might is a postfix expression, get rid of ParenListExprs.
4939 ExprResult Result = MaybeConvertParenListExprToParenExpr(S, ME: Input);
4940 if (Result.isInvalid()) return ExprError();
4941 Input = Result.get();
4942
4943 return BuildUnaryOp(S, OpLoc, Opc, Input);
4944}
4945
4946/// Diagnose if arithmetic on the given ObjC pointer is illegal.
4947///
4948/// \return true on error
4949static bool checkArithmeticOnObjCPointer(Sema &S,
4950 SourceLocation opLoc,
4951 Expr *op) {
4952 assert(op->getType()->isObjCObjectPointerType());
4953 if (S.LangOpts.ObjCRuntime.allowsPointerArithmetic() &&
4954 !S.LangOpts.ObjCSubscriptingLegacyRuntime)
4955 return false;
4956
4957 S.Diag(Loc: opLoc, DiagID: diag::err_arithmetic_nonfragile_interface)
4958 << op->getType()->castAs<ObjCObjectPointerType>()->getPointeeType()
4959 << op->getSourceRange();
4960 return true;
4961}
4962
4963static bool isMSPropertySubscriptExpr(Sema &S, Expr *Base) {
4964 auto *BaseNoParens = Base->IgnoreParens();
4965 if (auto *MSProp = dyn_cast<MSPropertyRefExpr>(Val: BaseNoParens))
4966 return MSProp->getPropertyDecl()->getType()->isArrayType();
4967 return isa<MSPropertySubscriptExpr>(Val: BaseNoParens);
4968}
4969
4970// Returns the type used for LHS[RHS], given one of LHS, RHS is type-dependent.
4971// Typically this is DependentTy, but can sometimes be more precise.
4972//
4973// There are cases when we could determine a non-dependent type:
4974// - LHS and RHS may have non-dependent types despite being type-dependent
4975// (e.g. unbounded array static members of the current instantiation)
4976// - one may be a dependent-sized array with known element type
4977// - one may be a dependent-typed valid index (enum in current instantiation)
4978//
4979// We *always* return a dependent type, in such cases it is DependentTy.
4980// This avoids creating type-dependent expressions with non-dependent types.
4981// FIXME: is this important to avoid? See https://reviews.llvm.org/D107275
4982static QualType getDependentArraySubscriptType(Expr *LHS, Expr *RHS,
4983 const ASTContext &Ctx) {
4984 assert(LHS->isTypeDependent() || RHS->isTypeDependent());
4985 QualType LTy = LHS->getType(), RTy = RHS->getType();
4986 QualType Result = Ctx.DependentTy;
4987 if (RTy->isIntegralOrUnscopedEnumerationType()) {
4988 if (const PointerType *PT = LTy->getAs<PointerType>())
4989 Result = PT->getPointeeType();
4990 else if (const ArrayType *AT = LTy->getAsArrayTypeUnsafe())
4991 Result = AT->getElementType();
4992 } else if (LTy->isIntegralOrUnscopedEnumerationType()) {
4993 if (const PointerType *PT = RTy->getAs<PointerType>())
4994 Result = PT->getPointeeType();
4995 else if (const ArrayType *AT = RTy->getAsArrayTypeUnsafe())
4996 Result = AT->getElementType();
4997 }
4998 // Ensure we return a dependent type.
4999 return Result->isDependentType() ? Result : Ctx.DependentTy;
5000}
5001
5002ExprResult Sema::ActOnArraySubscriptExpr(Scope *S, Expr *base,
5003 SourceLocation lbLoc,
5004 MultiExprArg ArgExprs,
5005 SourceLocation rbLoc) {
5006
5007 if (base && !base->getType().isNull() &&
5008 base->hasPlaceholderType(K: BuiltinType::ArraySection)) {
5009 auto *AS = cast<ArraySectionExpr>(Val: base);
5010 if (AS->isOMPArraySection())
5011 return OpenMP().ActOnOMPArraySectionExpr(
5012 Base: base, LBLoc: lbLoc, LowerBound: ArgExprs.front(), ColonLocFirst: SourceLocation(), ColonLocSecond: SourceLocation(),
5013 /*Length*/ nullptr,
5014 /*Stride=*/nullptr, RBLoc: rbLoc);
5015
5016 return OpenACC().ActOnArraySectionExpr(Base: base, LBLoc: lbLoc, LowerBound: ArgExprs.front(),
5017 ColonLocFirst: SourceLocation(), /*Length*/ nullptr,
5018 RBLoc: rbLoc);
5019 }
5020
5021 // Since this might be a postfix expression, get rid of ParenListExprs.
5022 if (isa<ParenListExpr>(Val: base)) {
5023 ExprResult result = MaybeConvertParenListExprToParenExpr(S, ME: base);
5024 if (result.isInvalid())
5025 return ExprError();
5026 base = result.get();
5027 }
5028
5029 // Check if base and idx form a MatrixSubscriptExpr.
5030 //
5031 // Helper to check for comma expressions, which are not allowed as indices for
5032 // matrix subscript expressions.
5033 auto CheckAndReportCommaError = [this, base, rbLoc](Expr *E) {
5034 if (isa<BinaryOperator>(Val: E) && cast<BinaryOperator>(Val: E)->isCommaOp()) {
5035 Diag(Loc: E->getExprLoc(), DiagID: diag::err_matrix_subscript_comma)
5036 << SourceRange(base->getBeginLoc(), rbLoc);
5037 return true;
5038 }
5039 return false;
5040 };
5041 // The matrix subscript operator ([][])is considered a single operator.
5042 // Separating the index expressions by parenthesis is not allowed.
5043 if (base && !base->getType().isNull() &&
5044 base->hasPlaceholderType(K: BuiltinType::IncompleteMatrixIdx) &&
5045 !isa<MatrixSubscriptExpr>(Val: base)) {
5046 Diag(Loc: base->getExprLoc(), DiagID: diag::err_matrix_separate_incomplete_index)
5047 << SourceRange(base->getBeginLoc(), rbLoc);
5048 return ExprError();
5049 }
5050 // If the base is a MatrixSubscriptExpr, try to create a new
5051 // MatrixSubscriptExpr.
5052 auto *matSubscriptE = dyn_cast<MatrixSubscriptExpr>(Val: base);
5053 if (matSubscriptE) {
5054 assert(ArgExprs.size() == 1);
5055 if (CheckAndReportCommaError(ArgExprs.front()))
5056 return ExprError();
5057
5058 assert(matSubscriptE->isIncomplete() &&
5059 "base has to be an incomplete matrix subscript");
5060 return CreateBuiltinMatrixSubscriptExpr(Base: matSubscriptE->getBase(),
5061 RowIdx: matSubscriptE->getRowIdx(),
5062 ColumnIdx: ArgExprs.front(), RBLoc: rbLoc);
5063 }
5064 if (base->getType()->isWebAssemblyTableType()) {
5065 Diag(Loc: base->getExprLoc(), DiagID: diag::err_wasm_table_art)
5066 << SourceRange(base->getBeginLoc(), rbLoc) << 3;
5067 return ExprError();
5068 }
5069
5070 CheckInvalidBuiltinCountedByRef(E: base,
5071 K: BuiltinCountedByRefKind::ArraySubscript);
5072
5073 // Handle any non-overload placeholder types in the base and index
5074 // expressions. We can't handle overloads here because the other
5075 // operand might be an overloadable type, in which case the overload
5076 // resolution for the operator overload should get the first crack
5077 // at the overload.
5078 bool IsMSPropertySubscript = false;
5079 if (base->getType()->isNonOverloadPlaceholderType()) {
5080 IsMSPropertySubscript = isMSPropertySubscriptExpr(S&: *this, Base: base);
5081 if (!IsMSPropertySubscript) {
5082 ExprResult result = CheckPlaceholderExpr(E: base);
5083 if (result.isInvalid())
5084 return ExprError();
5085 base = result.get();
5086 }
5087 }
5088
5089 // If the base is a matrix type, try to create a new MatrixSubscriptExpr.
5090 if (base->getType()->isMatrixType()) {
5091 assert(ArgExprs.size() == 1);
5092 if (CheckAndReportCommaError(ArgExprs.front()))
5093 return ExprError();
5094
5095 return CreateBuiltinMatrixSubscriptExpr(Base: base, RowIdx: ArgExprs.front(), ColumnIdx: nullptr,
5096 RBLoc: rbLoc);
5097 }
5098
5099 if (ArgExprs.size() == 1 && getLangOpts().CPlusPlus20) {
5100 Expr *idx = ArgExprs[0];
5101 if ((isa<BinaryOperator>(Val: idx) && cast<BinaryOperator>(Val: idx)->isCommaOp()) ||
5102 (isa<CXXOperatorCallExpr>(Val: idx) &&
5103 cast<CXXOperatorCallExpr>(Val: idx)->getOperator() == OO_Comma)) {
5104 Diag(Loc: idx->getExprLoc(), DiagID: diag::warn_deprecated_comma_subscript)
5105 << SourceRange(base->getBeginLoc(), rbLoc);
5106 }
5107 }
5108
5109 if (ArgExprs.size() == 1 &&
5110 ArgExprs[0]->getType()->isNonOverloadPlaceholderType()) {
5111 ExprResult result = CheckPlaceholderExpr(E: ArgExprs[0]);
5112 if (result.isInvalid())
5113 return ExprError();
5114 ArgExprs[0] = result.get();
5115 } else {
5116 if (CheckArgsForPlaceholders(args: ArgExprs))
5117 return ExprError();
5118 }
5119
5120 // Build an unanalyzed expression if either operand is type-dependent.
5121 if (getLangOpts().CPlusPlus && ArgExprs.size() == 1 &&
5122 (base->isTypeDependent() ||
5123 Expr::hasAnyTypeDependentArguments(Exprs: ArgExprs)) &&
5124 !isa<PackExpansionExpr>(Val: ArgExprs[0])) {
5125 return new (Context) ArraySubscriptExpr(
5126 base, ArgExprs.front(),
5127 getDependentArraySubscriptType(LHS: base, RHS: ArgExprs.front(), Ctx: getASTContext()),
5128 VK_LValue, OK_Ordinary, rbLoc);
5129 }
5130
5131 // MSDN, property (C++)
5132 // https://msdn.microsoft.com/en-us/library/yhfk0thd(v=vs.120).aspx
5133 // This attribute can also be used in the declaration of an empty array in a
5134 // class or structure definition. For example:
5135 // __declspec(property(get=GetX, put=PutX)) int x[];
5136 // The above statement indicates that x[] can be used with one or more array
5137 // indices. In this case, i=p->x[a][b] will be turned into i=p->GetX(a, b),
5138 // and p->x[a][b] = i will be turned into p->PutX(a, b, i);
5139 if (IsMSPropertySubscript) {
5140 assert(ArgExprs.size() == 1);
5141 // Build MS property subscript expression if base is MS property reference
5142 // or MS property subscript.
5143 return new (Context)
5144 MSPropertySubscriptExpr(base, ArgExprs.front(), Context.PseudoObjectTy,
5145 VK_LValue, OK_Ordinary, rbLoc);
5146 }
5147
5148 // Use C++ overloaded-operator rules if either operand has record
5149 // type. The spec says to do this if either type is *overloadable*,
5150 // but enum types can't declare subscript operators or conversion
5151 // operators, so there's nothing interesting for overload resolution
5152 // to do if there aren't any record types involved.
5153 //
5154 // ObjC pointers have their own subscripting logic that is not tied
5155 // to overload resolution and so should not take this path.
5156 if (getLangOpts().CPlusPlus && !base->getType()->isObjCObjectPointerType() &&
5157 ((base->getType()->isRecordType() ||
5158 (ArgExprs.size() != 1 || isa<PackExpansionExpr>(Val: ArgExprs[0]) ||
5159 ArgExprs[0]->getType()->isRecordType())))) {
5160 return CreateOverloadedArraySubscriptExpr(LLoc: lbLoc, RLoc: rbLoc, Base: base, Args: ArgExprs);
5161 }
5162
5163 ExprResult Res =
5164 CreateBuiltinArraySubscriptExpr(Base: base, LLoc: lbLoc, Idx: ArgExprs.front(), RLoc: rbLoc);
5165
5166 if (!Res.isInvalid() && isa<ArraySubscriptExpr>(Val: Res.get()))
5167 CheckSubscriptAccessOfNoDeref(E: cast<ArraySubscriptExpr>(Val: Res.get()));
5168
5169 return Res;
5170}
5171
5172ExprResult Sema::tryConvertExprToType(Expr *E, QualType Ty) {
5173 InitializedEntity Entity = InitializedEntity::InitializeTemporary(Type: Ty);
5174 InitializationKind Kind =
5175 InitializationKind::CreateCopy(InitLoc: E->getBeginLoc(), EqualLoc: SourceLocation());
5176 InitializationSequence InitSeq(*this, Entity, Kind, E);
5177 return InitSeq.Perform(S&: *this, Entity, Kind, Args: E);
5178}
5179
5180ExprResult Sema::CreateBuiltinMatrixSingleSubscriptExpr(Expr *Base,
5181 Expr *RowIdx,
5182 SourceLocation RBLoc) {
5183 ExprResult BaseR = CheckPlaceholderExpr(E: Base);
5184 if (BaseR.isInvalid())
5185 return BaseR;
5186 Base = BaseR.get();
5187
5188 ExprResult RowR = CheckPlaceholderExpr(E: RowIdx);
5189 if (RowR.isInvalid())
5190 return RowR;
5191 RowIdx = RowR.get();
5192
5193 // Build an unanalyzed expression if any of the operands is type-dependent.
5194 if (Base->isTypeDependent() || RowIdx->isTypeDependent())
5195 return new (Context)
5196 MatrixSingleSubscriptExpr(Base, RowIdx, Context.DependentTy, RBLoc);
5197
5198 // Check that IndexExpr is an integer expression. If it is a constant
5199 // expression, check that it is less than Dim (= the number of elements in the
5200 // corresponding dimension).
5201 auto IsIndexValid = [&](Expr *IndexExpr, unsigned Dim,
5202 bool IsColumnIdx) -> Expr * {
5203 if (!IndexExpr->getType()->isIntegerType() &&
5204 !IndexExpr->isTypeDependent()) {
5205 Diag(Loc: IndexExpr->getBeginLoc(), DiagID: diag::err_matrix_index_not_integer)
5206 << IsColumnIdx;
5207 return nullptr;
5208 }
5209
5210 if (std::optional<llvm::APSInt> Idx =
5211 IndexExpr->getIntegerConstantExpr(Ctx: Context)) {
5212 if ((*Idx < 0 || *Idx >= Dim)) {
5213 Diag(Loc: IndexExpr->getBeginLoc(), DiagID: diag::err_matrix_index_outside_range)
5214 << IsColumnIdx << Dim;
5215 return nullptr;
5216 }
5217 }
5218
5219 ExprResult ConvExpr = IndexExpr;
5220 assert(!ConvExpr.isInvalid() &&
5221 "should be able to convert any integer type to size type");
5222 return ConvExpr.get();
5223 };
5224
5225 auto *MTy = Base->getType()->getAs<ConstantMatrixType>();
5226 RowIdx = IsIndexValid(RowIdx, MTy->getNumRows(), false);
5227 if (!RowIdx)
5228 return ExprError();
5229
5230 QualType RowVecQT =
5231 Context.getExtVectorType(VectorType: MTy->getElementType(), NumElts: MTy->getNumColumns());
5232
5233 return new (Context) MatrixSingleSubscriptExpr(Base, RowIdx, RowVecQT, RBLoc);
5234}
5235
5236ExprResult Sema::CreateBuiltinMatrixSubscriptExpr(Expr *Base, Expr *RowIdx,
5237 Expr *ColumnIdx,
5238 SourceLocation RBLoc) {
5239 ExprResult BaseR = CheckPlaceholderExpr(E: Base);
5240 if (BaseR.isInvalid())
5241 return BaseR;
5242 Base = BaseR.get();
5243
5244 ExprResult RowR = CheckPlaceholderExpr(E: RowIdx);
5245 if (RowR.isInvalid())
5246 return RowR;
5247 RowIdx = RowR.get();
5248
5249 if (!ColumnIdx)
5250 return new (Context) MatrixSubscriptExpr(
5251 Base, RowIdx, ColumnIdx, Context.IncompleteMatrixIdxTy, RBLoc);
5252
5253 // Build an unanalyzed expression if any of the operands is type-dependent.
5254 if (Base->isTypeDependent() || RowIdx->isTypeDependent() ||
5255 ColumnIdx->isTypeDependent())
5256 return new (Context) MatrixSubscriptExpr(Base, RowIdx, ColumnIdx,
5257 Context.DependentTy, RBLoc);
5258
5259 ExprResult ColumnR = CheckPlaceholderExpr(E: ColumnIdx);
5260 if (ColumnR.isInvalid())
5261 return ColumnR;
5262 ColumnIdx = ColumnR.get();
5263
5264 // Check that IndexExpr is an integer expression. If it is a constant
5265 // expression, check that it is less than Dim (= the number of elements in the
5266 // corresponding dimension).
5267 auto IsIndexValid = [&](Expr *IndexExpr, unsigned Dim,
5268 bool IsColumnIdx) -> Expr * {
5269 if (!IndexExpr->getType()->isIntegerType() &&
5270 !IndexExpr->isTypeDependent()) {
5271 Diag(Loc: IndexExpr->getBeginLoc(), DiagID: diag::err_matrix_index_not_integer)
5272 << IsColumnIdx;
5273 return nullptr;
5274 }
5275
5276 if (std::optional<llvm::APSInt> Idx =
5277 IndexExpr->getIntegerConstantExpr(Ctx: Context)) {
5278 if ((*Idx < 0 || *Idx >= Dim)) {
5279 Diag(Loc: IndexExpr->getBeginLoc(), DiagID: diag::err_matrix_index_outside_range)
5280 << IsColumnIdx << Dim;
5281 return nullptr;
5282 }
5283 }
5284
5285 ExprResult ConvExpr = IndexExpr;
5286 assert(!ConvExpr.isInvalid() &&
5287 "should be able to convert any integer type to size type");
5288 return ConvExpr.get();
5289 };
5290
5291 auto *MTy = Base->getType()->getAs<ConstantMatrixType>();
5292 RowIdx = IsIndexValid(RowIdx, MTy->getNumRows(), false);
5293 ColumnIdx = IsIndexValid(ColumnIdx, MTy->getNumColumns(), true);
5294 if (!RowIdx || !ColumnIdx)
5295 return ExprError();
5296
5297 return new (Context) MatrixSubscriptExpr(Base, RowIdx, ColumnIdx,
5298 MTy->getElementType(), RBLoc);
5299}
5300
5301void Sema::CheckAddressOfNoDeref(const Expr *E) {
5302 ExpressionEvaluationContextRecord &LastRecord = ExprEvalContexts.back();
5303 const Expr *StrippedExpr = E->IgnoreParenImpCasts();
5304
5305 // For expressions like `&(*s).b`, the base is recorded and what should be
5306 // checked.
5307 const MemberExpr *Member = nullptr;
5308 while ((Member = dyn_cast<MemberExpr>(Val: StrippedExpr)) && !Member->isArrow())
5309 StrippedExpr = Member->getBase()->IgnoreParenImpCasts();
5310
5311 LastRecord.PossibleDerefs.erase(Ptr: StrippedExpr);
5312}
5313
5314void Sema::CheckSubscriptAccessOfNoDeref(const ArraySubscriptExpr *E) {
5315 if (isUnevaluatedContext())
5316 return;
5317
5318 QualType ResultTy = E->getType();
5319 ExpressionEvaluationContextRecord &LastRecord = ExprEvalContexts.back();
5320
5321 // Bail if the element is an array since it is not memory access.
5322 if (isa<ArrayType>(Val: ResultTy))
5323 return;
5324
5325 if (ResultTy->hasAttr(AK: attr::NoDeref)) {
5326 LastRecord.PossibleDerefs.insert(Ptr: E);
5327 return;
5328 }
5329
5330 // Check if the base type is a pointer to a member access of a struct
5331 // marked with noderef.
5332 const Expr *Base = E->getBase();
5333 QualType BaseTy = Base->getType();
5334 if (!(isa<ArrayType>(Val: BaseTy) || isa<PointerType>(Val: BaseTy)))
5335 // Not a pointer access
5336 return;
5337
5338 const MemberExpr *Member = nullptr;
5339 while ((Member = dyn_cast<MemberExpr>(Val: Base->IgnoreParenCasts())) &&
5340 Member->isArrow())
5341 Base = Member->getBase();
5342
5343 if (const auto *Ptr = dyn_cast<PointerType>(Val: Base->getType())) {
5344 if (Ptr->getPointeeType()->hasAttr(AK: attr::NoDeref))
5345 LastRecord.PossibleDerefs.insert(Ptr: E);
5346 }
5347}
5348
5349ExprResult
5350Sema::CreateBuiltinArraySubscriptExpr(Expr *Base, SourceLocation LLoc,
5351 Expr *Idx, SourceLocation RLoc) {
5352 Expr *LHSExp = Base;
5353 Expr *RHSExp = Idx;
5354
5355 ExprValueKind VK = VK_LValue;
5356 ExprObjectKind OK = OK_Ordinary;
5357
5358 // Per C++ core issue 1213, the result is an xvalue if either operand is
5359 // a non-lvalue array, and an lvalue otherwise.
5360 if (getLangOpts().CPlusPlus11) {
5361 for (auto *Op : {LHSExp, RHSExp}) {
5362 Op = Op->IgnoreImplicit();
5363 if (Op->getType()->isArrayType() && !Op->isLValue())
5364 VK = VK_XValue;
5365 }
5366 }
5367
5368 // Perform default conversions.
5369 if (!LHSExp->getType()->isSubscriptableVectorType()) {
5370 ExprResult Result = DefaultFunctionArrayLvalueConversion(E: LHSExp);
5371 if (Result.isInvalid())
5372 return ExprError();
5373 LHSExp = Result.get();
5374 }
5375 ExprResult Result = DefaultFunctionArrayLvalueConversion(E: RHSExp);
5376 if (Result.isInvalid())
5377 return ExprError();
5378 RHSExp = Result.get();
5379
5380 QualType LHSTy = LHSExp->getType(), RHSTy = RHSExp->getType();
5381
5382 // C99 6.5.2.1p2: the expression e1[e2] is by definition precisely equivalent
5383 // to the expression *((e1)+(e2)). This means the array "Base" may actually be
5384 // in the subscript position. As a result, we need to derive the array base
5385 // and index from the expression types.
5386 Expr *BaseExpr, *IndexExpr;
5387 QualType ResultType;
5388 if (LHSTy->isDependentType() || RHSTy->isDependentType()) {
5389 BaseExpr = LHSExp;
5390 IndexExpr = RHSExp;
5391 ResultType =
5392 getDependentArraySubscriptType(LHS: LHSExp, RHS: RHSExp, Ctx: getASTContext());
5393 } else if (const PointerType *PTy = LHSTy->getAs<PointerType>()) {
5394 BaseExpr = LHSExp;
5395 IndexExpr = RHSExp;
5396 ResultType = PTy->getPointeeType();
5397 } else if (const ObjCObjectPointerType *PTy =
5398 LHSTy->getAs<ObjCObjectPointerType>()) {
5399 BaseExpr = LHSExp;
5400 IndexExpr = RHSExp;
5401
5402 // Use custom logic if this should be the pseudo-object subscript
5403 // expression.
5404 if (!LangOpts.isSubscriptPointerArithmetic())
5405 return ObjC().BuildObjCSubscriptExpression(RB: RLoc, BaseExpr, IndexExpr,
5406 getterMethod: nullptr, setterMethod: nullptr);
5407
5408 ResultType = PTy->getPointeeType();
5409 } else if (const PointerType *PTy = RHSTy->getAs<PointerType>()) {
5410 // Handle the uncommon case of "123[Ptr]".
5411 BaseExpr = RHSExp;
5412 IndexExpr = LHSExp;
5413 ResultType = PTy->getPointeeType();
5414 } else if (const ObjCObjectPointerType *PTy =
5415 RHSTy->getAs<ObjCObjectPointerType>()) {
5416 // Handle the uncommon case of "123[Ptr]".
5417 BaseExpr = RHSExp;
5418 IndexExpr = LHSExp;
5419 ResultType = PTy->getPointeeType();
5420 if (!LangOpts.isSubscriptPointerArithmetic()) {
5421 Diag(Loc: LLoc, DiagID: diag::err_subscript_nonfragile_interface)
5422 << ResultType << BaseExpr->getSourceRange();
5423 return ExprError();
5424 }
5425 } else if (LHSTy->isSubscriptableVectorType()) {
5426 if (LHSTy->isBuiltinType() &&
5427 LHSTy->getAs<BuiltinType>()->isSveVLSBuiltinType()) {
5428 const BuiltinType *BTy = LHSTy->getAs<BuiltinType>();
5429 if (BTy->isSVEBool())
5430 return ExprError(Diag(Loc: LLoc, DiagID: diag::err_subscript_svbool_t)
5431 << LHSExp->getSourceRange()
5432 << RHSExp->getSourceRange());
5433 ResultType = BTy->getSveEltType(Ctx: Context);
5434 } else {
5435 const VectorType *VTy = LHSTy->getAs<VectorType>();
5436 ResultType = VTy->getElementType();
5437 }
5438 BaseExpr = LHSExp; // vectors: V[123]
5439 IndexExpr = RHSExp;
5440 // We apply C++ DR1213 to vector subscripting too.
5441 if (getLangOpts().CPlusPlus11 && LHSExp->isPRValue()) {
5442 ExprResult Materialized = TemporaryMaterializationConversion(E: LHSExp);
5443 if (Materialized.isInvalid())
5444 return ExprError();
5445 LHSExp = Materialized.get();
5446 }
5447 VK = LHSExp->getValueKind();
5448 if (VK != VK_PRValue)
5449 OK = OK_VectorComponent;
5450
5451 QualType BaseType = BaseExpr->getType();
5452 Qualifiers BaseQuals = BaseType.getQualifiers();
5453 Qualifiers MemberQuals = ResultType.getQualifiers();
5454 Qualifiers Combined = BaseQuals + MemberQuals;
5455 if (Combined != MemberQuals)
5456 ResultType = Context.getQualifiedType(T: ResultType, Qs: Combined);
5457 } else if (LHSTy->isArrayType()) {
5458 // If we see an array that wasn't promoted by
5459 // DefaultFunctionArrayLvalueConversion, it must be an array that
5460 // wasn't promoted because of the C90 rule that doesn't
5461 // allow promoting non-lvalue arrays. Warn, then
5462 // force the promotion here.
5463 Diag(Loc: LHSExp->getBeginLoc(), DiagID: diag::ext_subscript_non_lvalue)
5464 << LHSExp->getSourceRange();
5465 LHSExp = ImpCastExprToType(E: LHSExp, Type: Context.getArrayDecayedType(T: LHSTy),
5466 CK: CK_ArrayToPointerDecay).get();
5467 LHSTy = LHSExp->getType();
5468
5469 BaseExpr = LHSExp;
5470 IndexExpr = RHSExp;
5471 ResultType = LHSTy->castAs<PointerType>()->getPointeeType();
5472 } else if (RHSTy->isArrayType()) {
5473 // Same as previous, except for 123[f().a] case
5474 Diag(Loc: RHSExp->getBeginLoc(), DiagID: diag::ext_subscript_non_lvalue)
5475 << RHSExp->getSourceRange();
5476 RHSExp = ImpCastExprToType(E: RHSExp, Type: Context.getArrayDecayedType(T: RHSTy),
5477 CK: CK_ArrayToPointerDecay).get();
5478 RHSTy = RHSExp->getType();
5479
5480 BaseExpr = RHSExp;
5481 IndexExpr = LHSExp;
5482 ResultType = RHSTy->castAs<PointerType>()->getPointeeType();
5483 } else {
5484 return ExprError(Diag(Loc: LLoc, DiagID: diag::err_typecheck_subscript_value)
5485 << LHSExp->getSourceRange() << RHSExp->getSourceRange());
5486 }
5487 // C99 6.5.2.1p1
5488 if (!IndexExpr->getType()->isIntegerType() && !IndexExpr->isTypeDependent())
5489 return ExprError(Diag(Loc: LLoc, DiagID: diag::err_typecheck_subscript_not_integer)
5490 << IndexExpr->getSourceRange());
5491
5492 if ((IndexExpr->getType()->isSpecificBuiltinType(K: BuiltinType::Char_S) ||
5493 IndexExpr->getType()->isSpecificBuiltinType(K: BuiltinType::Char_U)) &&
5494 !IndexExpr->isTypeDependent()) {
5495 std::optional<llvm::APSInt> IntegerContantExpr =
5496 IndexExpr->getIntegerConstantExpr(Ctx: getASTContext());
5497 if (!IntegerContantExpr.has_value() ||
5498 IntegerContantExpr.value().isNegative())
5499 Diag(Loc: LLoc, DiagID: diag::warn_subscript_is_char) << IndexExpr->getSourceRange();
5500 }
5501
5502 // C99 6.5.2.1p1: "shall have type "pointer to *object* type". Similarly,
5503 // C++ [expr.sub]p1: The type "T" shall be a completely-defined object
5504 // type. Note that Functions are not objects, and that (in C99 parlance)
5505 // incomplete types are not object types.
5506 if (ResultType->isFunctionType()) {
5507 Diag(Loc: BaseExpr->getBeginLoc(), DiagID: diag::err_subscript_function_type)
5508 << ResultType << BaseExpr->getSourceRange();
5509 return ExprError();
5510 }
5511
5512 if (ResultType->isVoidType() && !getLangOpts().CPlusPlus) {
5513 // GNU extension: subscripting on pointer to void
5514 Diag(Loc: LLoc, DiagID: diag::ext_gnu_subscript_void_type)
5515 << BaseExpr->getSourceRange();
5516
5517 // C forbids expressions of unqualified void type from being l-values.
5518 // See IsCForbiddenLValueType.
5519 if (!ResultType.hasQualifiers())
5520 VK = VK_PRValue;
5521 } else if (!ResultType->isDependentType() &&
5522 !ResultType.isWebAssemblyReferenceType() &&
5523 RequireCompleteSizedType(
5524 Loc: LLoc, T: ResultType,
5525 DiagID: diag::err_subscript_incomplete_or_sizeless_type, Args: BaseExpr))
5526 return ExprError();
5527
5528 assert(VK == VK_PRValue || LangOpts.CPlusPlus ||
5529 !ResultType.isCForbiddenLValueType());
5530
5531 if (LHSExp->IgnoreParenImpCasts()->getType()->isVariablyModifiedType() &&
5532 FunctionScopes.size() > 1) {
5533 if (auto *TT =
5534 LHSExp->IgnoreParenImpCasts()->getType()->getAs<TypedefType>()) {
5535 for (auto I = FunctionScopes.rbegin(),
5536 E = std::prev(x: FunctionScopes.rend());
5537 I != E; ++I) {
5538 auto *CSI = dyn_cast<CapturingScopeInfo>(Val: *I);
5539 if (CSI == nullptr)
5540 break;
5541 DeclContext *DC = nullptr;
5542 if (auto *LSI = dyn_cast<LambdaScopeInfo>(Val: CSI))
5543 DC = LSI->CallOperator;
5544 else if (auto *CRSI = dyn_cast<CapturedRegionScopeInfo>(Val: CSI))
5545 DC = CRSI->TheCapturedDecl;
5546 else if (auto *BSI = dyn_cast<BlockScopeInfo>(Val: CSI))
5547 DC = BSI->TheDecl;
5548 if (DC) {
5549 if (DC->containsDecl(D: TT->getDecl()))
5550 break;
5551 captureVariablyModifiedType(
5552 Context, T: LHSExp->IgnoreParenImpCasts()->getType(), CSI);
5553 }
5554 }
5555 }
5556 }
5557
5558 return new (Context)
5559 ArraySubscriptExpr(LHSExp, RHSExp, ResultType, VK, OK, RLoc);
5560}
5561
5562bool Sema::CheckCXXDefaultArgExpr(SourceLocation CallLoc, FunctionDecl *FD,
5563 ParmVarDecl *Param, Expr *RewrittenInit,
5564 bool SkipImmediateInvocations) {
5565 if (Param->hasUnparsedDefaultArg()) {
5566 assert(!RewrittenInit && "Should not have a rewritten init expression yet");
5567 // If we've already cleared out the location for the default argument,
5568 // that means we're parsing it right now.
5569 if (!UnparsedDefaultArgLocs.count(Val: Param)) {
5570 Diag(Loc: Param->getBeginLoc(), DiagID: diag::err_recursive_default_argument) << FD;
5571 Diag(Loc: CallLoc, DiagID: diag::note_recursive_default_argument_used_here);
5572 Param->setInvalidDecl();
5573 return true;
5574 }
5575
5576 Diag(Loc: CallLoc, DiagID: diag::err_use_of_default_argument_to_function_declared_later)
5577 << FD << cast<CXXRecordDecl>(Val: FD->getDeclContext());
5578 Diag(Loc: UnparsedDefaultArgLocs[Param],
5579 DiagID: diag::note_default_argument_declared_here);
5580 return true;
5581 }
5582
5583 if (Param->hasUninstantiatedDefaultArg()) {
5584 assert(!RewrittenInit && "Should not have a rewitten init expression yet");
5585 if (InstantiateDefaultArgument(CallLoc, FD, Param))
5586 return true;
5587 }
5588
5589 Expr *Init = RewrittenInit ? RewrittenInit : Param->getInit();
5590 assert(Init && "default argument but no initializer?");
5591
5592 // If the default expression creates temporaries, we need to
5593 // push them to the current stack of expression temporaries so they'll
5594 // be properly destroyed.
5595 // FIXME: We should really be rebuilding the default argument with new
5596 // bound temporaries; see the comment in PR5810.
5597 // We don't need to do that with block decls, though, because
5598 // blocks in default argument expression can never capture anything.
5599 if (auto *InitWithCleanup = dyn_cast<ExprWithCleanups>(Val: Init)) {
5600 // Set the "needs cleanups" bit regardless of whether there are
5601 // any explicit objects.
5602 Cleanup.setExprNeedsCleanups(InitWithCleanup->cleanupsHaveSideEffects());
5603 // Append all the objects to the cleanup list. Right now, this
5604 // should always be a no-op, because blocks in default argument
5605 // expressions should never be able to capture anything.
5606 assert(!InitWithCleanup->getNumObjects() &&
5607 "default argument expression has capturing blocks?");
5608 }
5609 // C++ [expr.const]p15.1:
5610 // An expression or conversion is in an immediate function context if it is
5611 // potentially evaluated and [...] its innermost enclosing non-block scope
5612 // is a function parameter scope of an immediate function.
5613 EnterExpressionEvaluationContext EvalContext(
5614 *this,
5615 FD->isImmediateFunction()
5616 ? ExpressionEvaluationContext::ImmediateFunctionContext
5617 : ExpressionEvaluationContext::PotentiallyEvaluated,
5618 Param);
5619 ExprEvalContexts.back().IsCurrentlyCheckingDefaultArgumentOrInitializer =
5620 SkipImmediateInvocations;
5621 runWithSufficientStackSpace(Loc: CallLoc, Fn: [&] {
5622 MarkDeclarationsReferencedInExpr(E: Init, /*SkipLocalVariables=*/true);
5623 });
5624 return false;
5625}
5626
5627struct ImmediateCallVisitor : DynamicRecursiveASTVisitor {
5628 const ASTContext &Context;
5629 ImmediateCallVisitor(const ASTContext &Ctx) : Context(Ctx) {
5630 ShouldVisitImplicitCode = true;
5631 }
5632
5633 bool HasImmediateCalls = false;
5634
5635 bool VisitCallExpr(CallExpr *E) override {
5636 if (const FunctionDecl *FD = E->getDirectCallee())
5637 HasImmediateCalls |= FD->isImmediateFunction();
5638 return DynamicRecursiveASTVisitor::VisitStmt(S: E);
5639 }
5640
5641 bool VisitCXXConstructExpr(CXXConstructExpr *E) override {
5642 if (const FunctionDecl *FD = E->getConstructor())
5643 HasImmediateCalls |= FD->isImmediateFunction();
5644 return DynamicRecursiveASTVisitor::VisitStmt(S: E);
5645 }
5646
5647 // SourceLocExpr are not immediate invocations
5648 // but CXXDefaultInitExpr/CXXDefaultArgExpr containing a SourceLocExpr
5649 // need to be rebuilt so that they refer to the correct SourceLocation and
5650 // DeclContext.
5651 bool VisitSourceLocExpr(SourceLocExpr *E) override {
5652 HasImmediateCalls = true;
5653 return DynamicRecursiveASTVisitor::VisitStmt(S: E);
5654 }
5655
5656 // A nested lambda might have parameters with immediate invocations
5657 // in their default arguments.
5658 // The compound statement is not visited (as it does not constitute a
5659 // subexpression).
5660 // FIXME: We should consider visiting and transforming captures
5661 // with init expressions.
5662 bool VisitLambdaExpr(LambdaExpr *E) override {
5663 return VisitCXXMethodDecl(D: E->getCallOperator());
5664 }
5665
5666 bool VisitCXXDefaultArgExpr(CXXDefaultArgExpr *E) override {
5667 return TraverseStmt(S: E->getExpr());
5668 }
5669
5670 bool VisitCXXDefaultInitExpr(CXXDefaultInitExpr *E) override {
5671 return TraverseStmt(S: E->getExpr());
5672 }
5673};
5674
5675struct EnsureImmediateInvocationInDefaultArgs
5676 : TreeTransform<EnsureImmediateInvocationInDefaultArgs> {
5677 EnsureImmediateInvocationInDefaultArgs(Sema &SemaRef)
5678 : TreeTransform(SemaRef) {}
5679
5680 bool AlwaysRebuild() { return true; }
5681
5682 // Lambda can only have immediate invocations in the default
5683 // args of their parameters, which is transformed upon calling the closure.
5684 // The body is not a subexpression, so we have nothing to do.
5685 // FIXME: Immediate calls in capture initializers should be transformed.
5686 ExprResult TransformLambdaExpr(LambdaExpr *E) { return E; }
5687 ExprResult TransformBlockExpr(BlockExpr *E) { return E; }
5688
5689 // Make sure we don't rebuild the this pointer as it would
5690 // cause it to incorrectly point it to the outermost class
5691 // in the case of nested struct initialization.
5692 ExprResult TransformCXXThisExpr(CXXThisExpr *E) { return E; }
5693
5694 // Rewrite to source location to refer to the context in which they are used.
5695 ExprResult TransformSourceLocExpr(SourceLocExpr *E) {
5696 DeclContext *DC = E->getParentContext();
5697 if (DC == SemaRef.CurContext)
5698 return E;
5699
5700 // FIXME: During instantiation, because the rebuild of defaults arguments
5701 // is not always done in the context of the template instantiator,
5702 // we run the risk of producing a dependent source location
5703 // that would never be rebuilt.
5704 // This usually happens during overload resolution, or in contexts
5705 // where the value of the source location does not matter.
5706 // However, we should find a better way to deal with source location
5707 // of function templates.
5708 if (!SemaRef.CurrentInstantiationScope ||
5709 !SemaRef.CurContext->isDependentContext() || DC->isDependentContext())
5710 DC = SemaRef.CurContext;
5711
5712 return getDerived().RebuildSourceLocExpr(
5713 Kind: E->getIdentKind(), ResultTy: E->getType(), BuiltinLoc: E->getBeginLoc(), RPLoc: E->getEndLoc(), ParentContext: DC);
5714 }
5715};
5716
5717ExprResult Sema::BuildCXXDefaultArgExpr(SourceLocation CallLoc,
5718 FunctionDecl *FD, ParmVarDecl *Param,
5719 Expr *Init) {
5720 assert(Param->hasDefaultArg() && "can't build nonexistent default arg");
5721
5722 bool NestedDefaultChecking = isCheckingDefaultArgumentOrInitializer();
5723 bool NeedRebuild = needsRebuildOfDefaultArgOrInit();
5724 std::optional<ExpressionEvaluationContextRecord::InitializationContext>
5725 InitializationContext =
5726 OutermostDeclarationWithDelayedImmediateInvocations();
5727 if (!InitializationContext.has_value())
5728 InitializationContext.emplace(args&: CallLoc, args&: Param, args&: CurContext);
5729
5730 if (!Init && !Param->hasUnparsedDefaultArg()) {
5731 // Mark that we are replacing a default argument first.
5732 // If we are instantiating a template we won't have to
5733 // retransform immediate calls.
5734 // C++ [expr.const]p15.1:
5735 // An expression or conversion is in an immediate function context if it
5736 // is potentially evaluated and [...] its innermost enclosing non-block
5737 // scope is a function parameter scope of an immediate function.
5738 EnterExpressionEvaluationContext EvalContext(
5739 *this,
5740 FD->isImmediateFunction()
5741 ? ExpressionEvaluationContext::ImmediateFunctionContext
5742 : ExpressionEvaluationContext::PotentiallyEvaluated,
5743 Param);
5744
5745 if (Param->hasUninstantiatedDefaultArg()) {
5746 if (InstantiateDefaultArgument(CallLoc, FD, Param))
5747 return ExprError();
5748 }
5749 // CWG2631
5750 // An immediate invocation that is not evaluated where it appears is
5751 // evaluated and checked for whether it is a constant expression at the
5752 // point where the enclosing initializer is used in a function call.
5753 ImmediateCallVisitor V(getASTContext());
5754 if (!NestedDefaultChecking)
5755 V.TraverseDecl(D: Param);
5756
5757 // Rewrite the call argument that was created from the corresponding
5758 // parameter's default argument.
5759 if (V.HasImmediateCalls ||
5760 (NeedRebuild && isa_and_present<ExprWithCleanups>(Val: Param->getInit()))) {
5761 if (V.HasImmediateCalls)
5762 ExprEvalContexts.back().DelayedDefaultInitializationContext = {
5763 CallLoc, Param, CurContext};
5764 // Pass down lifetime extending flag, and collect temporaries in
5765 // CreateMaterializeTemporaryExpr when we rewrite the call argument.
5766 currentEvaluationContext().InLifetimeExtendingContext =
5767 parentEvaluationContext().InLifetimeExtendingContext;
5768 EnsureImmediateInvocationInDefaultArgs Immediate(*this);
5769 ExprResult Res;
5770 runWithSufficientStackSpace(Loc: CallLoc, Fn: [&] {
5771 Res = Immediate.TransformInitializer(Init: Param->getInit(),
5772 /*NotCopy=*/NotCopyInit: false);
5773 });
5774 if (Res.isInvalid())
5775 return ExprError();
5776 Res = ConvertParamDefaultArgument(Param, DefaultArg: Res.get(),
5777 EqualLoc: Res.get()->getBeginLoc());
5778 if (Res.isInvalid())
5779 return ExprError();
5780 Init = Res.get();
5781 }
5782 }
5783
5784 if (CheckCXXDefaultArgExpr(
5785 CallLoc, FD, Param, RewrittenInit: Init,
5786 /*SkipImmediateInvocations=*/NestedDefaultChecking))
5787 return ExprError();
5788
5789 return CXXDefaultArgExpr::Create(C: Context, Loc: InitializationContext->Loc, Param,
5790 RewrittenExpr: Init, UsedContext: InitializationContext->Context);
5791}
5792
5793static FieldDecl *FindFieldDeclInstantiationPattern(const ASTContext &Ctx,
5794 FieldDecl *Field) {
5795 if (FieldDecl *Pattern = Ctx.getInstantiatedFromUnnamedFieldDecl(Field))
5796 return Pattern;
5797 auto *ParentRD = cast<CXXRecordDecl>(Val: Field->getParent());
5798 CXXRecordDecl *ClassPattern = ParentRD->getTemplateInstantiationPattern();
5799 DeclContext::lookup_result Lookup =
5800 ClassPattern->lookup(Name: Field->getDeclName());
5801 auto Rng = llvm::make_filter_range(
5802 Range&: Lookup, Pred: [](auto &&L) { return isa<FieldDecl>(*L); });
5803 if (Rng.empty())
5804 return nullptr;
5805 // FIXME: this breaks clang/test/Modules/pr28812.cpp
5806 // assert(std::distance(Rng.begin(), Rng.end()) <= 1
5807 // && "Duplicated instantiation pattern for field decl");
5808 return cast<FieldDecl>(Val: *Rng.begin());
5809}
5810
5811ExprResult Sema::BuildCXXDefaultInitExpr(SourceLocation Loc, FieldDecl *Field) {
5812 assert(Field->hasInClassInitializer());
5813
5814 CXXThisScopeRAII This(*this, Field->getParent(), Qualifiers());
5815
5816 auto *ParentRD = cast<CXXRecordDecl>(Val: Field->getParent());
5817
5818 std::optional<ExpressionEvaluationContextRecord::InitializationContext>
5819 InitializationContext =
5820 OutermostDeclarationWithDelayedImmediateInvocations();
5821 if (!InitializationContext.has_value())
5822 InitializationContext.emplace(args&: Loc, args&: Field, args&: CurContext);
5823
5824 Expr *Init = nullptr;
5825
5826 bool NestedDefaultChecking = isCheckingDefaultArgumentOrInitializer();
5827 bool NeedRebuild = needsRebuildOfDefaultArgOrInit();
5828 EnterExpressionEvaluationContext EvalContext(
5829 *this, ExpressionEvaluationContext::PotentiallyEvaluated, Field);
5830
5831 if (!Field->getInClassInitializer()) {
5832 // Maybe we haven't instantiated the in-class initializer. Go check the
5833 // pattern FieldDecl to see if it has one.
5834 if (isTemplateInstantiation(Kind: ParentRD->getTemplateSpecializationKind())) {
5835 FieldDecl *Pattern =
5836 FindFieldDeclInstantiationPattern(Ctx: getASTContext(), Field);
5837 assert(Pattern && "We must have set the Pattern!");
5838 if (!Pattern->hasInClassInitializer() ||
5839 InstantiateInClassInitializer(PointOfInstantiation: Loc, Instantiation: Field, Pattern,
5840 TemplateArgs: getTemplateInstantiationArgs(D: Field))) {
5841 Field->setInvalidDecl();
5842 return ExprError();
5843 }
5844 }
5845 }
5846
5847 // CWG2631
5848 // An immediate invocation that is not evaluated where it appears is
5849 // evaluated and checked for whether it is a constant expression at the
5850 // point where the enclosing initializer is used in a [...] a constructor
5851 // definition, or an aggregate initialization.
5852 ImmediateCallVisitor V(getASTContext());
5853 if (!NestedDefaultChecking)
5854 V.TraverseDecl(D: Field);
5855
5856 // CWG1815
5857 // Support lifetime extension of temporary created by aggregate
5858 // initialization using a default member initializer. We should rebuild
5859 // the initializer in a lifetime extension context if the initializer
5860 // expression is an ExprWithCleanups. Then make sure the normal lifetime
5861 // extension code recurses into the default initializer and does lifetime
5862 // extension when warranted.
5863 bool ContainsAnyTemporaries =
5864 isa_and_present<ExprWithCleanups>(Val: Field->getInClassInitializer());
5865 if (Field->getInClassInitializer() &&
5866 !Field->getInClassInitializer()->containsErrors() &&
5867 (V.HasImmediateCalls || (NeedRebuild && ContainsAnyTemporaries))) {
5868 ExprEvalContexts.back().DelayedDefaultInitializationContext = {Loc, Field,
5869 CurContext};
5870 ExprEvalContexts.back().IsCurrentlyCheckingDefaultArgumentOrInitializer =
5871 NestedDefaultChecking;
5872 // Pass down lifetime extending flag, and collect temporaries in
5873 // CreateMaterializeTemporaryExpr when we rewrite the call argument.
5874 currentEvaluationContext().InLifetimeExtendingContext =
5875 parentEvaluationContext().InLifetimeExtendingContext;
5876 EnsureImmediateInvocationInDefaultArgs Immediate(*this);
5877 ExprResult Res;
5878 runWithSufficientStackSpace(Loc, Fn: [&] {
5879 Res = Immediate.TransformInitializer(Init: Field->getInClassInitializer(),
5880 /*CXXDirectInit=*/NotCopyInit: false);
5881 });
5882 if (!Res.isInvalid())
5883 Res = ConvertMemberDefaultInitExpression(FD: Field, InitExpr: Res.get(), InitLoc: Loc);
5884 if (Res.isInvalid()) {
5885 Field->setInvalidDecl();
5886 return ExprError();
5887 }
5888 Init = Res.get();
5889 }
5890
5891 if (Field->getInClassInitializer()) {
5892 Expr *E = Init ? Init : Field->getInClassInitializer();
5893 if (!NestedDefaultChecking)
5894 runWithSufficientStackSpace(Loc, Fn: [&] {
5895 MarkDeclarationsReferencedInExpr(E, /*SkipLocalVariables=*/false);
5896 });
5897 if (isInLifetimeExtendingContext())
5898 DiscardCleanupsInEvaluationContext();
5899 // C++11 [class.base.init]p7:
5900 // The initialization of each base and member constitutes a
5901 // full-expression.
5902 ExprResult Res = ActOnFinishFullExpr(Expr: E, /*DiscardedValue=*/false);
5903 if (Res.isInvalid()) {
5904 Field->setInvalidDecl();
5905 return ExprError();
5906 }
5907 Init = Res.get();
5908
5909 return CXXDefaultInitExpr::Create(Ctx: Context, Loc: InitializationContext->Loc,
5910 Field, UsedContext: InitializationContext->Context,
5911 RewrittenInitExpr: Init);
5912 }
5913
5914 // DR1351:
5915 // If the brace-or-equal-initializer of a non-static data member
5916 // invokes a defaulted default constructor of its class or of an
5917 // enclosing class in a potentially evaluated subexpression, the
5918 // program is ill-formed.
5919 //
5920 // This resolution is unworkable: the exception specification of the
5921 // default constructor can be needed in an unevaluated context, in
5922 // particular, in the operand of a noexcept-expression, and we can be
5923 // unable to compute an exception specification for an enclosed class.
5924 //
5925 // Any attempt to resolve the exception specification of a defaulted default
5926 // constructor before the initializer is lexically complete will ultimately
5927 // come here at which point we can diagnose it.
5928 RecordDecl *OutermostClass = ParentRD->getOuterLexicalRecordContext();
5929 Diag(Loc, DiagID: diag::err_default_member_initializer_not_yet_parsed)
5930 << OutermostClass << Field;
5931 Diag(Loc: Field->getEndLoc(),
5932 DiagID: diag::note_default_member_initializer_not_yet_parsed);
5933 // Recover by marking the field invalid, unless we're in a SFINAE context.
5934 if (!isSFINAEContext())
5935 Field->setInvalidDecl();
5936 return ExprError();
5937}
5938
5939VariadicCallType Sema::getVariadicCallType(FunctionDecl *FDecl,
5940 const FunctionProtoType *Proto,
5941 Expr *Fn) {
5942 if (Proto && Proto->isVariadic()) {
5943 if (isa_and_nonnull<CXXConstructorDecl>(Val: FDecl))
5944 return VariadicCallType::Constructor;
5945 else if (Fn && Fn->getType()->isBlockPointerType())
5946 return VariadicCallType::Block;
5947 else if (FDecl) {
5948 if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(Val: FDecl))
5949 if (Method->isInstance())
5950 return VariadicCallType::Method;
5951 } else if (Fn && Fn->getType() == Context.BoundMemberTy)
5952 return VariadicCallType::Method;
5953 return VariadicCallType::Function;
5954 }
5955 return VariadicCallType::DoesNotApply;
5956}
5957
5958namespace {
5959class FunctionCallCCC final : public FunctionCallFilterCCC {
5960public:
5961 FunctionCallCCC(Sema &SemaRef, const IdentifierInfo *FuncName,
5962 unsigned NumArgs, MemberExpr *ME)
5963 : FunctionCallFilterCCC(SemaRef, NumArgs, false, ME),
5964 FunctionName(FuncName) {}
5965
5966 bool ValidateCandidate(const TypoCorrection &candidate) override {
5967 if (!candidate.getCorrectionSpecifier() ||
5968 candidate.getCorrectionAsIdentifierInfo() != FunctionName) {
5969 return false;
5970 }
5971
5972 return FunctionCallFilterCCC::ValidateCandidate(candidate);
5973 }
5974
5975 std::unique_ptr<CorrectionCandidateCallback> clone() override {
5976 return std::make_unique<FunctionCallCCC>(args&: *this);
5977 }
5978
5979private:
5980 const IdentifierInfo *const FunctionName;
5981};
5982}
5983
5984static TypoCorrection TryTypoCorrectionForCall(Sema &S, Expr *Fn,
5985 FunctionDecl *FDecl,
5986 ArrayRef<Expr *> Args) {
5987 MemberExpr *ME = dyn_cast<MemberExpr>(Val: Fn);
5988 DeclarationName FuncName = FDecl->getDeclName();
5989 SourceLocation NameLoc = ME ? ME->getMemberLoc() : Fn->getBeginLoc();
5990
5991 FunctionCallCCC CCC(S, FuncName.getAsIdentifierInfo(), Args.size(), ME);
5992 if (TypoCorrection Corrected = S.CorrectTypo(
5993 Typo: DeclarationNameInfo(FuncName, NameLoc), LookupKind: Sema::LookupOrdinaryName,
5994 S: S.getScopeForContext(Ctx: S.CurContext), SS: nullptr, CCC,
5995 Mode: CorrectTypoKind::ErrorRecovery)) {
5996 if (NamedDecl *ND = Corrected.getFoundDecl()) {
5997 if (Corrected.isOverloaded()) {
5998 OverloadCandidateSet OCS(NameLoc, OverloadCandidateSet::CSK_Normal);
5999 OverloadCandidateSet::iterator Best;
6000 for (NamedDecl *CD : Corrected) {
6001 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Val: CD))
6002 S.AddOverloadCandidate(Function: FD, FoundDecl: DeclAccessPair::make(D: FD, AS: AS_none), Args,
6003 CandidateSet&: OCS);
6004 }
6005 switch (OCS.BestViableFunction(S, Loc: NameLoc, Best)) {
6006 case OR_Success:
6007 ND = Best->FoundDecl;
6008 Corrected.setCorrectionDecl(ND);
6009 break;
6010 default:
6011 break;
6012 }
6013 }
6014 ND = ND->getUnderlyingDecl();
6015 if (isa<ValueDecl>(Val: ND) || isa<FunctionTemplateDecl>(Val: ND))
6016 return Corrected;
6017 }
6018 }
6019 return TypoCorrection();
6020}
6021
6022// [C++26][[expr.unary.op]/p4
6023// A pointer to member is only formed when an explicit &
6024// is used and its operand is a qualified-id not enclosed in parentheses.
6025static bool isParenthetizedAndQualifiedAddressOfExpr(Expr *Fn) {
6026 if (!isa<ParenExpr>(Val: Fn))
6027 return false;
6028
6029 Fn = Fn->IgnoreParens();
6030
6031 auto *UO = dyn_cast<UnaryOperator>(Val: Fn);
6032 if (!UO || UO->getOpcode() != clang::UO_AddrOf)
6033 return false;
6034 if (auto *DRE = dyn_cast<DeclRefExpr>(Val: UO->getSubExpr()->IgnoreParens())) {
6035 return DRE->hasQualifier();
6036 }
6037 if (auto *OVL = dyn_cast<OverloadExpr>(Val: UO->getSubExpr()->IgnoreParens()))
6038 return bool(OVL->getQualifier());
6039 return false;
6040}
6041
6042bool
6043Sema::ConvertArgumentsForCall(CallExpr *Call, Expr *Fn,
6044 FunctionDecl *FDecl,
6045 const FunctionProtoType *Proto,
6046 ArrayRef<Expr *> Args,
6047 SourceLocation RParenLoc,
6048 bool IsExecConfig) {
6049 // Bail out early if calling a builtin with custom typechecking.
6050 if (FDecl)
6051 if (unsigned ID = FDecl->getBuiltinID())
6052 if (Context.BuiltinInfo.hasCustomTypechecking(ID))
6053 return false;
6054
6055 // C99 6.5.2.2p7 - the arguments are implicitly converted, as if by
6056 // assignment, to the types of the corresponding parameter, ...
6057
6058 bool AddressOf = isParenthetizedAndQualifiedAddressOfExpr(Fn);
6059 bool HasExplicitObjectParameter =
6060 !AddressOf && FDecl && FDecl->hasCXXExplicitFunctionObjectParameter();
6061 unsigned ExplicitObjectParameterOffset = HasExplicitObjectParameter ? 1 : 0;
6062 unsigned NumParams = Proto->getNumParams();
6063 bool Invalid = false;
6064 unsigned MinArgs = FDecl ? FDecl->getMinRequiredArguments() : NumParams;
6065 unsigned FnKind = Fn->getType()->isBlockPointerType()
6066 ? 1 /* block */
6067 : (IsExecConfig ? 3 /* kernel function (exec config) */
6068 : 0 /* function */);
6069
6070 // If too few arguments are available (and we don't have default
6071 // arguments for the remaining parameters), don't make the call.
6072 if (Args.size() < NumParams) {
6073 if (Args.size() < MinArgs) {
6074 TypoCorrection TC;
6075 if (FDecl && (TC = TryTypoCorrectionForCall(S&: *this, Fn, FDecl, Args))) {
6076 unsigned diag_id =
6077 MinArgs == NumParams && !Proto->isVariadic()
6078 ? diag::err_typecheck_call_too_few_args_suggest
6079 : diag::err_typecheck_call_too_few_args_at_least_suggest;
6080 diagnoseTypo(
6081 Correction: TC, TypoDiag: PDiag(DiagID: diag_id)
6082 << FnKind << MinArgs - ExplicitObjectParameterOffset
6083 << static_cast<unsigned>(Args.size()) -
6084 ExplicitObjectParameterOffset
6085 << HasExplicitObjectParameter << TC.getCorrectionRange());
6086 } else if (MinArgs - ExplicitObjectParameterOffset == 1 && FDecl &&
6087 FDecl->getParamDecl(i: ExplicitObjectParameterOffset)
6088 ->getDeclName())
6089 Diag(Loc: RParenLoc,
6090 DiagID: MinArgs == NumParams && !Proto->isVariadic()
6091 ? diag::err_typecheck_call_too_few_args_one
6092 : diag::err_typecheck_call_too_few_args_at_least_one)
6093 << FnKind << FDecl->getParamDecl(i: ExplicitObjectParameterOffset)
6094 << HasExplicitObjectParameter << Fn->getSourceRange();
6095 else
6096 Diag(Loc: RParenLoc, DiagID: MinArgs == NumParams && !Proto->isVariadic()
6097 ? diag::err_typecheck_call_too_few_args
6098 : diag::err_typecheck_call_too_few_args_at_least)
6099 << FnKind << MinArgs - ExplicitObjectParameterOffset
6100 << static_cast<unsigned>(Args.size()) -
6101 ExplicitObjectParameterOffset
6102 << HasExplicitObjectParameter << Fn->getSourceRange();
6103
6104 // Emit the location of the prototype.
6105 if (!TC && FDecl && !FDecl->getBuiltinID() && !IsExecConfig)
6106 Diag(Loc: FDecl->getLocation(), DiagID: diag::note_callee_decl)
6107 << FDecl << FDecl->getParametersSourceRange();
6108
6109 return true;
6110 }
6111 // We reserve space for the default arguments when we create
6112 // the call expression, before calling ConvertArgumentsForCall.
6113 assert((Call->getNumArgs() == NumParams) &&
6114 "We should have reserved space for the default arguments before!");
6115 }
6116
6117 // If too many are passed and not variadic, error on the extras and drop
6118 // them.
6119 if (Args.size() > NumParams) {
6120 if (!Proto->isVariadic()) {
6121 TypoCorrection TC;
6122 if (FDecl && (TC = TryTypoCorrectionForCall(S&: *this, Fn, FDecl, Args))) {
6123 unsigned diag_id =
6124 MinArgs == NumParams && !Proto->isVariadic()
6125 ? diag::err_typecheck_call_too_many_args_suggest
6126 : diag::err_typecheck_call_too_many_args_at_most_suggest;
6127 diagnoseTypo(
6128 Correction: TC, TypoDiag: PDiag(DiagID: diag_id)
6129 << FnKind << NumParams - ExplicitObjectParameterOffset
6130 << static_cast<unsigned>(Args.size()) -
6131 ExplicitObjectParameterOffset
6132 << HasExplicitObjectParameter << TC.getCorrectionRange());
6133 } else if (NumParams - ExplicitObjectParameterOffset == 1 && FDecl &&
6134 FDecl->getParamDecl(i: ExplicitObjectParameterOffset)
6135 ->getDeclName())
6136 Diag(Loc: Args[NumParams]->getBeginLoc(),
6137 DiagID: MinArgs == NumParams
6138 ? diag::err_typecheck_call_too_many_args_one
6139 : diag::err_typecheck_call_too_many_args_at_most_one)
6140 << FnKind << FDecl->getParamDecl(i: ExplicitObjectParameterOffset)
6141 << static_cast<unsigned>(Args.size()) -
6142 ExplicitObjectParameterOffset
6143 << HasExplicitObjectParameter << Fn->getSourceRange()
6144 << SourceRange(Args[NumParams]->getBeginLoc(),
6145 Args.back()->getEndLoc());
6146 else
6147 Diag(Loc: Args[NumParams]->getBeginLoc(),
6148 DiagID: MinArgs == NumParams
6149 ? diag::err_typecheck_call_too_many_args
6150 : diag::err_typecheck_call_too_many_args_at_most)
6151 << FnKind << NumParams - ExplicitObjectParameterOffset
6152 << static_cast<unsigned>(Args.size()) -
6153 ExplicitObjectParameterOffset
6154 << HasExplicitObjectParameter << Fn->getSourceRange()
6155 << SourceRange(Args[NumParams]->getBeginLoc(),
6156 Args.back()->getEndLoc());
6157
6158 // Emit the location of the prototype.
6159 if (!TC && FDecl && !FDecl->getBuiltinID() && !IsExecConfig)
6160 Diag(Loc: FDecl->getLocation(), DiagID: diag::note_callee_decl)
6161 << FDecl << FDecl->getParametersSourceRange();
6162
6163 // This deletes the extra arguments.
6164 Call->shrinkNumArgs(NewNumArgs: NumParams);
6165 return true;
6166 }
6167 }
6168 SmallVector<Expr *, 8> AllArgs;
6169 VariadicCallType CallType = getVariadicCallType(FDecl, Proto, Fn);
6170
6171 Invalid = GatherArgumentsForCall(CallLoc: Call->getExprLoc(), FDecl, Proto, FirstParam: 0, Args,
6172 AllArgs, CallType);
6173 if (Invalid)
6174 return true;
6175 unsigned TotalNumArgs = AllArgs.size();
6176 for (unsigned i = 0; i < TotalNumArgs; ++i)
6177 Call->setArg(Arg: i, ArgExpr: AllArgs[i]);
6178
6179 Call->computeDependence();
6180 return false;
6181}
6182
6183bool Sema::GatherArgumentsForCall(SourceLocation CallLoc, FunctionDecl *FDecl,
6184 const FunctionProtoType *Proto,
6185 unsigned FirstParam, ArrayRef<Expr *> Args,
6186 SmallVectorImpl<Expr *> &AllArgs,
6187 VariadicCallType CallType, bool AllowExplicit,
6188 bool IsListInitialization) {
6189 unsigned NumParams = Proto->getNumParams();
6190 bool Invalid = false;
6191 size_t ArgIx = 0;
6192 // Continue to check argument types (even if we have too few/many args).
6193 for (unsigned i = FirstParam; i < NumParams; i++) {
6194 QualType ProtoArgType = Proto->getParamType(i);
6195
6196 Expr *Arg;
6197 ParmVarDecl *Param = FDecl ? FDecl->getParamDecl(i) : nullptr;
6198 if (ArgIx < Args.size()) {
6199 Arg = Args[ArgIx++];
6200
6201 if (RequireCompleteType(Loc: Arg->getBeginLoc(), T: ProtoArgType,
6202 DiagID: diag::err_call_incomplete_argument, Args: Arg))
6203 return true;
6204
6205 // Strip the unbridged-cast placeholder expression off, if applicable.
6206 bool CFAudited = false;
6207 if (Arg->getType() == Context.ARCUnbridgedCastTy &&
6208 FDecl && FDecl->hasAttr<CFAuditedTransferAttr>() &&
6209 (!Param || !Param->hasAttr<CFConsumedAttr>()))
6210 Arg = ObjC().stripARCUnbridgedCast(e: Arg);
6211 else if (getLangOpts().ObjCAutoRefCount &&
6212 FDecl && FDecl->hasAttr<CFAuditedTransferAttr>() &&
6213 (!Param || !Param->hasAttr<CFConsumedAttr>()))
6214 CFAudited = true;
6215
6216 if (Proto->getExtParameterInfo(I: i).isNoEscape() &&
6217 ProtoArgType->isBlockPointerType())
6218 if (auto *BE = dyn_cast<BlockExpr>(Val: Arg->IgnoreParenNoopCasts(Ctx: Context)))
6219 BE->getBlockDecl()->setDoesNotEscape();
6220 if ((Proto->getExtParameterInfo(I: i).getABI() == ParameterABI::HLSLOut ||
6221 Proto->getExtParameterInfo(I: i).getABI() == ParameterABI::HLSLInOut)) {
6222 ExprResult ArgExpr = HLSL().ActOnOutParamExpr(Param, Arg);
6223 if (ArgExpr.isInvalid())
6224 return true;
6225 Arg = ArgExpr.getAs<Expr>();
6226 }
6227
6228 InitializedEntity Entity =
6229 Param ? InitializedEntity::InitializeParameter(Context, Parm: Param,
6230 Type: ProtoArgType)
6231 : InitializedEntity::InitializeParameter(
6232 Context, Type: ProtoArgType, Consumed: Proto->isParamConsumed(I: i));
6233
6234 // Remember that parameter belongs to a CF audited API.
6235 if (CFAudited)
6236 Entity.setParameterCFAudited();
6237
6238 // Warn if argument has OBT but parameter doesn't, discarding OBTs at
6239 // function boundaries is a common oversight.
6240 if (const auto *OBT = Arg->getType()->getAs<OverflowBehaviorType>();
6241 OBT && !ProtoArgType->isOverflowBehaviorType()) {
6242 bool isPedantic =
6243 OBT->isUnsignedIntegerOrEnumerationType() && OBT->isWrapKind();
6244 Diag(Loc: Arg->getExprLoc(),
6245 DiagID: isPedantic ? diag::warn_obt_discarded_at_function_boundary_pedantic
6246 : diag::warn_obt_discarded_at_function_boundary)
6247 << Arg->getType() << ProtoArgType;
6248 }
6249
6250 ExprResult ArgE = PerformCopyInitialization(
6251 Entity, EqualLoc: SourceLocation(), Init: Arg, TopLevelOfInitList: IsListInitialization, AllowExplicit);
6252 if (ArgE.isInvalid())
6253 return true;
6254
6255 Arg = ArgE.getAs<Expr>();
6256 } else {
6257 assert(Param && "can't use default arguments without a known callee");
6258
6259 ExprResult ArgExpr = BuildCXXDefaultArgExpr(CallLoc, FD: FDecl, Param);
6260 if (ArgExpr.isInvalid())
6261 return true;
6262
6263 Arg = ArgExpr.getAs<Expr>();
6264 }
6265
6266 // Check for array bounds violations for each argument to the call. This
6267 // check only triggers warnings when the argument isn't a more complex Expr
6268 // with its own checking, such as a BinaryOperator.
6269 CheckArrayAccess(E: Arg);
6270
6271 // Check for violations of C99 static array rules (C99 6.7.5.3p7).
6272 CheckStaticArrayArgument(CallLoc, Param, ArgExpr: Arg);
6273
6274 AllArgs.push_back(Elt: Arg);
6275 }
6276
6277 // If this is a variadic call, handle args passed through "...".
6278 if (CallType != VariadicCallType::DoesNotApply) {
6279 // Assume that extern "C" functions with variadic arguments that
6280 // return __unknown_anytype aren't *really* variadic.
6281 if (Proto->getReturnType() == Context.UnknownAnyTy && FDecl &&
6282 FDecl->isExternC()) {
6283 for (Expr *A : Args.slice(N: ArgIx)) {
6284 QualType paramType; // ignored
6285 ExprResult arg = checkUnknownAnyArg(callLoc: CallLoc, result: A, paramType);
6286 Invalid |= arg.isInvalid();
6287 AllArgs.push_back(Elt: arg.get());
6288 }
6289
6290 // Otherwise do argument promotion, (C99 6.5.2.2p7).
6291 } else {
6292 for (Expr *A : Args.slice(N: ArgIx)) {
6293 ExprResult Arg = DefaultVariadicArgumentPromotion(E: A, CT: CallType, FDecl);
6294 Invalid |= Arg.isInvalid();
6295 AllArgs.push_back(Elt: Arg.get());
6296 }
6297 }
6298
6299 // Check for array bounds violations.
6300 for (Expr *A : Args.slice(N: ArgIx))
6301 CheckArrayAccess(E: A);
6302 }
6303 return Invalid;
6304}
6305
6306static void DiagnoseCalleeStaticArrayParam(Sema &S, ParmVarDecl *PVD) {
6307 TypeLoc TL = PVD->getTypeSourceInfo()->getTypeLoc();
6308 if (DecayedTypeLoc DTL = TL.getAs<DecayedTypeLoc>())
6309 TL = DTL.getOriginalLoc();
6310 if (ArrayTypeLoc ATL = TL.getAs<ArrayTypeLoc>())
6311 S.Diag(Loc: PVD->getLocation(), DiagID: diag::note_callee_static_array)
6312 << ATL.getLocalSourceRange();
6313}
6314
6315void
6316Sema::CheckStaticArrayArgument(SourceLocation CallLoc,
6317 ParmVarDecl *Param,
6318 const Expr *ArgExpr) {
6319 // Static array parameters are not supported in C++.
6320 if (!Param || getLangOpts().CPlusPlus)
6321 return;
6322
6323 QualType OrigTy = Param->getOriginalType();
6324
6325 const ArrayType *AT = Context.getAsArrayType(T: OrigTy);
6326 if (!AT || AT->getSizeModifier() != ArraySizeModifier::Static)
6327 return;
6328
6329 if (ArgExpr->isNullPointerConstant(Ctx&: Context,
6330 NPC: Expr::NPC_NeverValueDependent)) {
6331 Diag(Loc: CallLoc, DiagID: diag::warn_null_arg) << ArgExpr->getSourceRange();
6332 DiagnoseCalleeStaticArrayParam(S&: *this, PVD: Param);
6333 return;
6334 }
6335
6336 const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(Val: AT);
6337 if (!CAT)
6338 return;
6339
6340 const ConstantArrayType *ArgCAT =
6341 Context.getAsConstantArrayType(T: ArgExpr->IgnoreParenCasts()->getType());
6342 if (!ArgCAT)
6343 return;
6344
6345 if (getASTContext().hasSameUnqualifiedType(T1: CAT->getElementType(),
6346 T2: ArgCAT->getElementType())) {
6347 if (ArgCAT->getSize().ult(RHS: CAT->getSize())) {
6348 Diag(Loc: CallLoc, DiagID: diag::warn_static_array_too_small)
6349 << ArgExpr->getSourceRange() << (unsigned)ArgCAT->getZExtSize()
6350 << (unsigned)CAT->getZExtSize() << 0;
6351 DiagnoseCalleeStaticArrayParam(S&: *this, PVD: Param);
6352 }
6353 return;
6354 }
6355
6356 std::optional<CharUnits> ArgSize =
6357 getASTContext().getTypeSizeInCharsIfKnown(Ty: ArgCAT);
6358 std::optional<CharUnits> ParmSize =
6359 getASTContext().getTypeSizeInCharsIfKnown(Ty: CAT);
6360 if (ArgSize && ParmSize && *ArgSize < *ParmSize) {
6361 Diag(Loc: CallLoc, DiagID: diag::warn_static_array_too_small)
6362 << ArgExpr->getSourceRange() << (unsigned)ArgSize->getQuantity()
6363 << (unsigned)ParmSize->getQuantity() << 1;
6364 DiagnoseCalleeStaticArrayParam(S&: *this, PVD: Param);
6365 }
6366}
6367
6368/// Given a function expression of unknown-any type, try to rebuild it
6369/// to have a function type.
6370static ExprResult rebuildUnknownAnyFunction(Sema &S, Expr *fn);
6371
6372/// Is the given type a placeholder that we need to lower out
6373/// immediately during argument processing?
6374static bool isPlaceholderToRemoveAsArg(QualType type) {
6375 // Placeholders are never sugared.
6376 const BuiltinType *placeholder = dyn_cast<BuiltinType>(Val&: type);
6377 if (!placeholder) return false;
6378
6379 switch (placeholder->getKind()) {
6380 // Ignore all the non-placeholder types.
6381#define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
6382 case BuiltinType::Id:
6383#include "clang/Basic/OpenCLImageTypes.def"
6384#define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \
6385 case BuiltinType::Id:
6386#include "clang/Basic/OpenCLExtensionTypes.def"
6387 // In practice we'll never use this, since all SVE types are sugared
6388 // via TypedefTypes rather than exposed directly as BuiltinTypes.
6389#define SVE_TYPE(Name, Id, SingletonId) \
6390 case BuiltinType::Id:
6391#include "clang/Basic/AArch64ACLETypes.def"
6392#define PPC_VECTOR_TYPE(Name, Id, Size) \
6393 case BuiltinType::Id:
6394#include "clang/Basic/PPCTypes.def"
6395#define RVV_TYPE(Name, Id, SingletonId) case BuiltinType::Id:
6396#include "clang/Basic/RISCVVTypes.def"
6397#define WASM_TYPE(Name, Id, SingletonId) case BuiltinType::Id:
6398#include "clang/Basic/WebAssemblyReferenceTypes.def"
6399#define AMDGPU_TYPE(Name, Id, SingletonId, Width, Align) case BuiltinType::Id:
6400#include "clang/Basic/AMDGPUTypes.def"
6401#define HLSL_INTANGIBLE_TYPE(Name, Id, SingletonId) case BuiltinType::Id:
6402#include "clang/Basic/HLSLIntangibleTypes.def"
6403#define PLACEHOLDER_TYPE(ID, SINGLETON_ID)
6404#define BUILTIN_TYPE(ID, SINGLETON_ID) case BuiltinType::ID:
6405#include "clang/AST/BuiltinTypes.def"
6406 return false;
6407
6408 case BuiltinType::UnresolvedTemplate:
6409 // We cannot lower out overload sets; they might validly be resolved
6410 // by the call machinery.
6411 case BuiltinType::Overload:
6412 return false;
6413
6414 // Unbridged casts in ARC can be handled in some call positions and
6415 // should be left in place.
6416 case BuiltinType::ARCUnbridgedCast:
6417 return false;
6418
6419 // Pseudo-objects should be converted as soon as possible.
6420 case BuiltinType::PseudoObject:
6421 return true;
6422
6423 // The debugger mode could theoretically but currently does not try
6424 // to resolve unknown-typed arguments based on known parameter types.
6425 case BuiltinType::UnknownAny:
6426 return true;
6427
6428 // These are always invalid as call arguments and should be reported.
6429 case BuiltinType::BoundMember:
6430 case BuiltinType::BuiltinFn:
6431 case BuiltinType::IncompleteMatrixIdx:
6432 case BuiltinType::ArraySection:
6433 case BuiltinType::OMPArrayShaping:
6434 case BuiltinType::OMPIterator:
6435 return true;
6436
6437 }
6438 llvm_unreachable("bad builtin type kind");
6439}
6440
6441bool Sema::CheckArgsForPlaceholders(MultiExprArg args) {
6442 // Apply this processing to all the arguments at once instead of
6443 // dying at the first failure.
6444 bool hasInvalid = false;
6445 for (size_t i = 0, e = args.size(); i != e; i++) {
6446 if (isPlaceholderToRemoveAsArg(type: args[i]->getType())) {
6447 ExprResult result = CheckPlaceholderExpr(E: args[i]);
6448 if (result.isInvalid()) hasInvalid = true;
6449 else args[i] = result.get();
6450 }
6451 }
6452 return hasInvalid;
6453}
6454
6455/// If a builtin function has a pointer argument with no explicit address
6456/// space, then it should be able to accept a pointer to any address
6457/// space as input. In order to do this, we need to replace the
6458/// standard builtin declaration with one that uses the same address space
6459/// as the call.
6460///
6461/// \returns nullptr If this builtin is not a candidate for a rewrite i.e.
6462/// it does not contain any pointer arguments without
6463/// an address space qualifer. Otherwise the rewritten
6464/// FunctionDecl is returned.
6465/// TODO: Handle pointer return types.
6466static FunctionDecl *rewriteBuiltinFunctionDecl(Sema *Sema, ASTContext &Context,
6467 FunctionDecl *FDecl,
6468 MultiExprArg ArgExprs) {
6469
6470 QualType DeclType = FDecl->getType();
6471 const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(Val&: DeclType);
6472
6473 if (!Context.BuiltinInfo.hasPtrArgsOrResult(ID: FDecl->getBuiltinID()) || !FT ||
6474 ArgExprs.size() < FT->getNumParams())
6475 return nullptr;
6476
6477 bool NeedsNewDecl = false;
6478 unsigned i = 0;
6479 SmallVector<QualType, 8> OverloadParams;
6480
6481 {
6482 // The lvalue conversions in this loop are only for type resolution and
6483 // don't actually occur.
6484 EnterExpressionEvaluationContext Unevaluated(
6485 *Sema, Sema::ExpressionEvaluationContext::Unevaluated);
6486 Sema::SFINAETrap Trap(*Sema, /*ForValidityCheck=*/true);
6487
6488 for (QualType ParamType : FT->param_types()) {
6489
6490 // Convert array arguments to pointer to simplify type lookup.
6491 ExprResult ArgRes =
6492 Sema->DefaultFunctionArrayLvalueConversion(E: ArgExprs[i++]);
6493 if (ArgRes.isInvalid())
6494 return nullptr;
6495 Expr *Arg = ArgRes.get();
6496 QualType ArgType = Arg->getType();
6497 if (!ParamType->isPointerType() ||
6498 ParamType->getPointeeType().hasAddressSpace() ||
6499 !ArgType->isPointerType() ||
6500 !ArgType->getPointeeType().hasAddressSpace() ||
6501 isPtrSizeAddressSpace(AS: ArgType->getPointeeType().getAddressSpace())) {
6502 OverloadParams.push_back(Elt: ParamType);
6503 continue;
6504 }
6505
6506 QualType PointeeType = ParamType->getPointeeType();
6507 NeedsNewDecl = true;
6508 LangAS AS = ArgType->getPointeeType().getAddressSpace();
6509
6510 PointeeType = Context.getAddrSpaceQualType(T: PointeeType, AddressSpace: AS);
6511 OverloadParams.push_back(Elt: Context.getPointerType(T: PointeeType));
6512 }
6513 }
6514
6515 if (!NeedsNewDecl)
6516 return nullptr;
6517
6518 FunctionProtoType::ExtProtoInfo EPI;
6519 EPI.Variadic = FT->isVariadic();
6520 QualType OverloadTy = Context.getFunctionType(ResultTy: FT->getReturnType(),
6521 Args: OverloadParams, EPI);
6522 DeclContext *Parent = FDecl->getParent();
6523 FunctionDecl *OverloadDecl = FunctionDecl::Create(
6524 C&: Context, DC: Parent, StartLoc: FDecl->getLocation(), NLoc: FDecl->getLocation(),
6525 N: FDecl->getIdentifier(), T: OverloadTy,
6526 /*TInfo=*/nullptr, SC: SC_Extern, UsesFPIntrin: Sema->getCurFPFeatures().isFPConstrained(),
6527 isInlineSpecified: false,
6528 /*hasPrototype=*/hasWrittenPrototype: true);
6529 SmallVector<ParmVarDecl*, 16> Params;
6530 FT = cast<FunctionProtoType>(Val&: OverloadTy);
6531 for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i) {
6532 QualType ParamType = FT->getParamType(i);
6533 ParmVarDecl *Parm =
6534 ParmVarDecl::Create(C&: Context, DC: OverloadDecl, StartLoc: SourceLocation(),
6535 IdLoc: SourceLocation(), Id: nullptr, T: ParamType,
6536 /*TInfo=*/nullptr, S: SC_None, DefArg: nullptr);
6537 Parm->setScopeInfo(scopeDepth: 0, parameterIndex: i);
6538 Params.push_back(Elt: Parm);
6539 }
6540 OverloadDecl->setParams(Params);
6541 // We cannot merge host/device attributes of redeclarations. They have to
6542 // be consistent when created.
6543 if (Sema->LangOpts.CUDA) {
6544 if (FDecl->hasAttr<CUDAHostAttr>())
6545 OverloadDecl->addAttr(A: CUDAHostAttr::CreateImplicit(Ctx&: Context));
6546 if (FDecl->hasAttr<CUDADeviceAttr>())
6547 OverloadDecl->addAttr(A: CUDADeviceAttr::CreateImplicit(Ctx&: Context));
6548 }
6549 Sema->mergeDeclAttributes(New: OverloadDecl, Old: FDecl);
6550 return OverloadDecl;
6551}
6552
6553static void checkDirectCallValidity(Sema &S, const Expr *Fn,
6554 FunctionDecl *Callee,
6555 MultiExprArg ArgExprs) {
6556 // `Callee` (when called with ArgExprs) may be ill-formed. enable_if (and
6557 // similar attributes) really don't like it when functions are called with an
6558 // invalid number of args.
6559 if (S.TooManyArguments(NumParams: Callee->getNumParams(), NumArgs: ArgExprs.size(),
6560 /*PartialOverloading=*/false) &&
6561 !Callee->isVariadic())
6562 return;
6563 if (Callee->getMinRequiredArguments() > ArgExprs.size())
6564 return;
6565
6566 if (const EnableIfAttr *Attr =
6567 S.CheckEnableIf(Function: Callee, CallLoc: Fn->getBeginLoc(), Args: ArgExprs, MissingImplicitThis: true)) {
6568 S.Diag(Loc: Fn->getBeginLoc(),
6569 DiagID: isa<CXXMethodDecl>(Val: Callee)
6570 ? diag::err_ovl_no_viable_member_function_in_call
6571 : diag::err_ovl_no_viable_function_in_call)
6572 << Callee << Callee->getSourceRange();
6573 S.Diag(Loc: Callee->getLocation(),
6574 DiagID: diag::note_ovl_candidate_disabled_by_function_cond_attr)
6575 << Attr->getCond()->getSourceRange() << Attr->getMessage();
6576 return;
6577 }
6578}
6579
6580static bool enclosingClassIsRelatedToClassInWhichMembersWereFound(
6581 const UnresolvedMemberExpr *const UME, Sema &S) {
6582
6583 const auto GetFunctionLevelDCIfCXXClass =
6584 [](Sema &S) -> const CXXRecordDecl * {
6585 const DeclContext *const DC = S.getFunctionLevelDeclContext();
6586 if (!DC || !DC->getParent())
6587 return nullptr;
6588
6589 // If the call to some member function was made from within a member
6590 // function body 'M' return return 'M's parent.
6591 if (const auto *MD = dyn_cast<CXXMethodDecl>(Val: DC))
6592 return MD->getParent()->getCanonicalDecl();
6593 // else the call was made from within a default member initializer of a
6594 // class, so return the class.
6595 if (const auto *RD = dyn_cast<CXXRecordDecl>(Val: DC))
6596 return RD->getCanonicalDecl();
6597 return nullptr;
6598 };
6599 // If our DeclContext is neither a member function nor a class (in the
6600 // case of a lambda in a default member initializer), we can't have an
6601 // enclosing 'this'.
6602
6603 const CXXRecordDecl *const CurParentClass = GetFunctionLevelDCIfCXXClass(S);
6604 if (!CurParentClass)
6605 return false;
6606
6607 // The naming class for implicit member functions call is the class in which
6608 // name lookup starts.
6609 const CXXRecordDecl *const NamingClass =
6610 UME->getNamingClass()->getCanonicalDecl();
6611 assert(NamingClass && "Must have naming class even for implicit access");
6612
6613 // If the unresolved member functions were found in a 'naming class' that is
6614 // related (either the same or derived from) to the class that contains the
6615 // member function that itself contained the implicit member access.
6616
6617 return CurParentClass == NamingClass ||
6618 CurParentClass->isDerivedFrom(Base: NamingClass);
6619}
6620
6621static void
6622tryImplicitlyCaptureThisIfImplicitMemberFunctionAccessWithDependentArgs(
6623 Sema &S, const UnresolvedMemberExpr *const UME, SourceLocation CallLoc) {
6624
6625 if (!UME)
6626 return;
6627
6628 LambdaScopeInfo *const CurLSI = S.getCurLambda();
6629 // Only try and implicitly capture 'this' within a C++ Lambda if it hasn't
6630 // already been captured, or if this is an implicit member function call (if
6631 // it isn't, an attempt to capture 'this' should already have been made).
6632 if (!CurLSI || CurLSI->ImpCaptureStyle == CurLSI->ImpCap_None ||
6633 !UME->isImplicitAccess() || CurLSI->isCXXThisCaptured())
6634 return;
6635
6636 // Check if the naming class in which the unresolved members were found is
6637 // related (same as or is a base of) to the enclosing class.
6638
6639 if (!enclosingClassIsRelatedToClassInWhichMembersWereFound(UME, S))
6640 return;
6641
6642
6643 DeclContext *EnclosingFunctionCtx = S.CurContext->getParent()->getParent();
6644 // If the enclosing function is not dependent, then this lambda is
6645 // capture ready, so if we can capture this, do so.
6646 if (!EnclosingFunctionCtx->isDependentContext()) {
6647 // If the current lambda and all enclosing lambdas can capture 'this' -
6648 // then go ahead and capture 'this' (since our unresolved overload set
6649 // contains at least one non-static member function).
6650 if (!S.CheckCXXThisCapture(Loc: CallLoc, /*Explcit*/ Explicit: false, /*Diagnose*/ BuildAndDiagnose: false))
6651 S.CheckCXXThisCapture(Loc: CallLoc);
6652 } else if (S.CurContext->isDependentContext()) {
6653 // ... since this is an implicit member reference, that might potentially
6654 // involve a 'this' capture, mark 'this' for potential capture in
6655 // enclosing lambdas.
6656 if (CurLSI->ImpCaptureStyle != CurLSI->ImpCap_None)
6657 CurLSI->addPotentialThisCapture(Loc: CallLoc);
6658 }
6659}
6660
6661// Once a call is fully resolved, warn for unqualified calls to specific
6662// C++ standard functions, like move and forward.
6663static void DiagnosedUnqualifiedCallsToStdFunctions(Sema &S,
6664 const CallExpr *Call) {
6665 // We are only checking unary move and forward so exit early here.
6666 if (Call->getNumArgs() != 1)
6667 return;
6668
6669 const Expr *E = Call->getCallee()->IgnoreParenImpCasts();
6670 if (!E || isa<UnresolvedLookupExpr>(Val: E))
6671 return;
6672 const DeclRefExpr *DRE = dyn_cast_if_present<DeclRefExpr>(Val: E);
6673 if (!DRE || !DRE->getLocation().isValid())
6674 return;
6675
6676 if (DRE->getQualifier())
6677 return;
6678
6679 const FunctionDecl *FD = Call->getDirectCallee();
6680 if (!FD)
6681 return;
6682
6683 // Only warn for some functions deemed more frequent or problematic.
6684 unsigned BuiltinID = FD->getBuiltinID();
6685 if (BuiltinID != Builtin::BImove && BuiltinID != Builtin::BIforward)
6686 return;
6687
6688 S.Diag(Loc: DRE->getLocation(), DiagID: diag::warn_unqualified_call_to_std_cast_function)
6689 << FD->getQualifiedNameAsString()
6690 << FixItHint::CreateInsertion(InsertionLoc: DRE->getLocation(), Code: "std::");
6691}
6692
6693ExprResult Sema::ActOnCallExpr(Scope *Scope, Expr *Fn, SourceLocation LParenLoc,
6694 MultiExprArg ArgExprs, SourceLocation RParenLoc,
6695 Expr *ExecConfig) {
6696 ExprResult Call =
6697 BuildCallExpr(S: Scope, Fn, LParenLoc, ArgExprs, RParenLoc, ExecConfig,
6698 /*IsExecConfig=*/false, /*AllowRecovery=*/true);
6699 if (Call.isInvalid())
6700 return Call;
6701
6702 // Diagnose uses of the C++20 "ADL-only template-id call" feature in earlier
6703 // language modes.
6704 if (const auto *ULE = dyn_cast<UnresolvedLookupExpr>(Val: Fn);
6705 ULE && ULE->hasExplicitTemplateArgs() && ULE->decls().empty()) {
6706 DiagCompat(Loc: Fn->getExprLoc(), CompatDiagId: diag_compat::adl_only_template_id)
6707 << ULE->getName();
6708 }
6709
6710 if (LangOpts.OpenMP)
6711 Call = OpenMP().ActOnOpenMPCall(Call, Scope, LParenLoc, ArgExprs, RParenLoc,
6712 ExecConfig);
6713 if (LangOpts.CPlusPlus) {
6714 if (const auto *CE = dyn_cast<CallExpr>(Val: Call.get()))
6715 DiagnosedUnqualifiedCallsToStdFunctions(S&: *this, Call: CE);
6716
6717 // If we previously found that the id-expression of this call refers to a
6718 // consteval function but the call is dependent, we should not treat is an
6719 // an invalid immediate call.
6720 if (auto *DRE = dyn_cast<DeclRefExpr>(Val: Fn->IgnoreParens());
6721 DRE && Call.get()->isValueDependent()) {
6722 currentEvaluationContext().ReferenceToConsteval.erase(Ptr: DRE);
6723 }
6724 }
6725 return Call;
6726}
6727
6728// Any type that could be used to form a callable expression
6729static bool MayBeFunctionType(const ASTContext &Context, const Expr *E) {
6730 QualType T = E->getType();
6731 if (T->isDependentType())
6732 return true;
6733
6734 if (T == Context.BoundMemberTy || T == Context.UnknownAnyTy ||
6735 T == Context.BuiltinFnTy || T == Context.OverloadTy ||
6736 T->isFunctionType() || T->isFunctionReferenceType() ||
6737 T->isMemberFunctionPointerType() || T->isFunctionPointerType() ||
6738 T->isBlockPointerType() || T->isRecordType())
6739 return true;
6740
6741 return isa<CallExpr, DeclRefExpr, MemberExpr, CXXPseudoDestructorExpr,
6742 OverloadExpr, UnresolvedMemberExpr, UnaryOperator>(Val: E);
6743}
6744
6745ExprResult Sema::BuildCallExpr(Scope *Scope, Expr *Fn, SourceLocation LParenLoc,
6746 MultiExprArg ArgExprs, SourceLocation RParenLoc,
6747 Expr *ExecConfig, bool IsExecConfig,
6748 bool AllowRecovery) {
6749 // Since this might be a postfix expression, get rid of ParenListExprs.
6750 ExprResult Result = MaybeConvertParenListExprToParenExpr(S: Scope, ME: Fn);
6751 if (Result.isInvalid()) return ExprError();
6752 Fn = Result.get();
6753
6754 if (CheckArgsForPlaceholders(args: ArgExprs))
6755 return ExprError();
6756
6757 // The result of __builtin_counted_by_ref cannot be used as a function
6758 // argument. It allows leaking and modification of bounds safety information.
6759 for (const Expr *Arg : ArgExprs)
6760 if (CheckInvalidBuiltinCountedByRef(E: Arg,
6761 K: BuiltinCountedByRefKind::FunctionArg))
6762 return ExprError();
6763
6764 if (getLangOpts().CPlusPlus) {
6765 // If this is a pseudo-destructor expression, build the call immediately.
6766 if (isa<CXXPseudoDestructorExpr>(Val: Fn)) {
6767 if (!ArgExprs.empty()) {
6768 // Pseudo-destructor calls should not have any arguments.
6769 Diag(Loc: Fn->getBeginLoc(), DiagID: diag::err_pseudo_dtor_call_with_args)
6770 << FixItHint::CreateRemoval(
6771 RemoveRange: SourceRange(ArgExprs.front()->getBeginLoc(),
6772 ArgExprs.back()->getEndLoc()));
6773 }
6774
6775 return CallExpr::Create(Ctx: Context, Fn, /*Args=*/{}, Ty: Context.VoidTy,
6776 VK: VK_PRValue, RParenLoc, FPFeatures: CurFPFeatureOverrides());
6777 }
6778 if (Fn->getType() == Context.PseudoObjectTy) {
6779 ExprResult result = CheckPlaceholderExpr(E: Fn);
6780 if (result.isInvalid()) return ExprError();
6781 Fn = result.get();
6782 }
6783
6784 // Determine whether this is a dependent call inside a C++ template,
6785 // in which case we won't do any semantic analysis now.
6786 if (Fn->isTypeDependent() || Expr::hasAnyTypeDependentArguments(Exprs: ArgExprs)) {
6787 if (ExecConfig) {
6788 return CUDAKernelCallExpr::Create(Ctx: Context, Fn,
6789 Config: cast<CallExpr>(Val: ExecConfig), Args: ArgExprs,
6790 Ty: Context.DependentTy, VK: VK_PRValue,
6791 RP: RParenLoc, FPFeatures: CurFPFeatureOverrides());
6792 } else {
6793
6794 tryImplicitlyCaptureThisIfImplicitMemberFunctionAccessWithDependentArgs(
6795 S&: *this, UME: dyn_cast<UnresolvedMemberExpr>(Val: Fn->IgnoreParens()),
6796 CallLoc: Fn->getBeginLoc());
6797
6798 // If the type of the function itself is not dependent
6799 // check that it is a reasonable as a function, as type deduction
6800 // later assume the CallExpr has a sensible TYPE.
6801 if (!MayBeFunctionType(Context, E: Fn))
6802 return ExprError(
6803 Diag(Loc: LParenLoc, DiagID: diag::err_typecheck_call_not_function)
6804 << Fn->getType() << Fn->getSourceRange());
6805
6806 return CallExpr::Create(Ctx: Context, Fn, Args: ArgExprs, Ty: Context.DependentTy,
6807 VK: VK_PRValue, RParenLoc, FPFeatures: CurFPFeatureOverrides());
6808 }
6809 }
6810
6811 // Determine whether this is a call to an object (C++ [over.call.object]).
6812 if (Fn->getType()->isRecordType())
6813 return BuildCallToObjectOfClassType(S: Scope, Object: Fn, LParenLoc, Args: ArgExprs,
6814 RParenLoc);
6815
6816 if (Fn->getType() == Context.UnknownAnyTy) {
6817 ExprResult result = rebuildUnknownAnyFunction(S&: *this, fn: Fn);
6818 if (result.isInvalid()) return ExprError();
6819 Fn = result.get();
6820 }
6821
6822 if (Fn->getType() == Context.BoundMemberTy) {
6823 return BuildCallToMemberFunction(S: Scope, MemExpr: Fn, LParenLoc, Args: ArgExprs,
6824 RParenLoc, ExecConfig, IsExecConfig,
6825 AllowRecovery);
6826 }
6827 }
6828
6829 // Check for overloaded calls. This can happen even in C due to extensions.
6830 if (Fn->getType() == Context.OverloadTy) {
6831 OverloadExpr::FindResult find = OverloadExpr::find(E: Fn);
6832
6833 // We aren't supposed to apply this logic if there's an '&' involved.
6834 if (!find.HasFormOfMemberPointer || find.IsAddressOfOperandWithParen) {
6835 if (Expr::hasAnyTypeDependentArguments(Exprs: ArgExprs))
6836 return CallExpr::Create(Ctx: Context, Fn, Args: ArgExprs, Ty: Context.DependentTy,
6837 VK: VK_PRValue, RParenLoc, FPFeatures: CurFPFeatureOverrides());
6838 OverloadExpr *ovl = find.Expression;
6839 if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(Val: ovl))
6840 return BuildOverloadedCallExpr(
6841 S: Scope, Fn, ULE, LParenLoc, Args: ArgExprs, RParenLoc, ExecConfig,
6842 /*AllowTypoCorrection=*/true, CalleesAddressIsTaken: find.IsAddressOfOperand);
6843 return BuildCallToMemberFunction(S: Scope, MemExpr: Fn, LParenLoc, Args: ArgExprs,
6844 RParenLoc, ExecConfig, IsExecConfig,
6845 AllowRecovery);
6846 }
6847 }
6848
6849 // If we're directly calling a function, get the appropriate declaration.
6850 if (Fn->getType() == Context.UnknownAnyTy) {
6851 ExprResult result = rebuildUnknownAnyFunction(S&: *this, fn: Fn);
6852 if (result.isInvalid()) return ExprError();
6853 Fn = result.get();
6854 }
6855
6856 Expr *NakedFn = Fn->IgnoreParens();
6857
6858 bool CallingNDeclIndirectly = false;
6859 NamedDecl *NDecl = nullptr;
6860 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(Val: NakedFn)) {
6861 if (UnOp->getOpcode() == UO_AddrOf) {
6862 CallingNDeclIndirectly = true;
6863 NakedFn = UnOp->getSubExpr()->IgnoreParens();
6864 }
6865 }
6866
6867 if (auto *DRE = dyn_cast<DeclRefExpr>(Val: NakedFn)) {
6868 NDecl = DRE->getDecl();
6869
6870 FunctionDecl *FDecl = dyn_cast<FunctionDecl>(Val: NDecl);
6871 if (FDecl && FDecl->getBuiltinID()) {
6872 // Rewrite the function decl for this builtin by replacing parameters
6873 // with no explicit address space with the address space of the arguments
6874 // in ArgExprs.
6875 if ((FDecl =
6876 rewriteBuiltinFunctionDecl(Sema: this, Context, FDecl, ArgExprs))) {
6877 NDecl = FDecl;
6878 Fn = DeclRefExpr::Create(
6879 Context, QualifierLoc: FDecl->getQualifierLoc(), TemplateKWLoc: SourceLocation(), D: FDecl, RefersToEnclosingVariableOrCapture: false,
6880 NameLoc: SourceLocation(), T: FDecl->getType(), VK: Fn->getValueKind(), FoundD: FDecl,
6881 TemplateArgs: nullptr, NOUR: DRE->isNonOdrUse());
6882 }
6883 }
6884 } else if (auto *ME = dyn_cast<MemberExpr>(Val: NakedFn))
6885 NDecl = ME->getMemberDecl();
6886
6887 if (FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(Val: NDecl)) {
6888 if (CallingNDeclIndirectly && !checkAddressOfFunctionIsAvailable(
6889 Function: FD, /*Complain=*/true, Loc: Fn->getBeginLoc()))
6890 return ExprError();
6891
6892 checkDirectCallValidity(S&: *this, Fn, Callee: FD, ArgExprs);
6893
6894 // If this expression is a call to a builtin function in HIP compilation,
6895 // allow a pointer-type argument to default address space to be passed as a
6896 // pointer-type parameter to a non-default address space. If Arg is declared
6897 // in the default address space and Param is declared in a non-default
6898 // address space, perform an implicit address space cast to the parameter
6899 // type.
6900 if (getLangOpts().HIP && FD && FD->getBuiltinID()) {
6901 for (unsigned Idx = 0; Idx < ArgExprs.size() && Idx < FD->param_size();
6902 ++Idx) {
6903 ParmVarDecl *Param = FD->getParamDecl(i: Idx);
6904 if (!ArgExprs[Idx] || !Param || !Param->getType()->isPointerType() ||
6905 !ArgExprs[Idx]->getType()->isPointerType())
6906 continue;
6907
6908 auto ParamAS = Param->getType()->getPointeeType().getAddressSpace();
6909 auto ArgTy = ArgExprs[Idx]->getType();
6910 auto ArgPtTy = ArgTy->getPointeeType();
6911 auto ArgAS = ArgPtTy.getAddressSpace();
6912
6913 // Add address space cast if target address spaces are different
6914 bool NeedImplicitASC =
6915 ParamAS != LangAS::Default && // Pointer params in generic AS don't need special handling.
6916 ( ArgAS == LangAS::Default || // We do allow implicit conversion from generic AS
6917 // or from specific AS which has target AS matching that of Param.
6918 getASTContext().getTargetAddressSpace(AS: ArgAS) == getASTContext().getTargetAddressSpace(AS: ParamAS));
6919 if (!NeedImplicitASC)
6920 continue;
6921
6922 // First, ensure that the Arg is an RValue.
6923 if (ArgExprs[Idx]->isGLValue()) {
6924 ExprResult Res = DefaultLvalueConversion(E: ArgExprs[Idx]);
6925 if (Res.isInvalid())
6926 return ExprError();
6927 ArgExprs[Idx] = Res.get();
6928 }
6929
6930 // Construct a new arg type with address space of Param
6931 Qualifiers ArgPtQuals = ArgPtTy.getQualifiers();
6932 ArgPtQuals.setAddressSpace(ParamAS);
6933 auto NewArgPtTy =
6934 Context.getQualifiedType(T: ArgPtTy.getUnqualifiedType(), Qs: ArgPtQuals);
6935 auto NewArgTy =
6936 Context.getQualifiedType(T: Context.getPointerType(T: NewArgPtTy),
6937 Qs: ArgTy.getQualifiers());
6938
6939 // Finally perform an implicit address space cast
6940 ArgExprs[Idx] = ImpCastExprToType(E: ArgExprs[Idx], Type: NewArgTy,
6941 CK: CK_AddressSpaceConversion)
6942 .get();
6943 }
6944 }
6945 }
6946
6947 if (Context.isDependenceAllowed() &&
6948 (Fn->isTypeDependent() || Expr::hasAnyTypeDependentArguments(Exprs: ArgExprs))) {
6949 assert(!getLangOpts().CPlusPlus);
6950 assert((Fn->containsErrors() ||
6951 llvm::any_of(ArgExprs,
6952 [](clang::Expr *E) { return E->containsErrors(); })) &&
6953 "should only occur in error-recovery path.");
6954 return CallExpr::Create(Ctx: Context, Fn, Args: ArgExprs, Ty: Context.DependentTy,
6955 VK: VK_PRValue, RParenLoc, FPFeatures: CurFPFeatureOverrides());
6956 }
6957 return BuildResolvedCallExpr(Fn, NDecl, LParenLoc, Arg: ArgExprs, RParenLoc,
6958 Config: ExecConfig, IsExecConfig);
6959}
6960
6961Expr *Sema::BuildBuiltinCallExpr(SourceLocation Loc, Builtin::ID Id,
6962 MultiExprArg CallArgs) {
6963 std::string Name = Context.BuiltinInfo.getName(ID: Id);
6964 LookupResult R(*this, &Context.Idents.get(Name), Loc,
6965 Sema::LookupOrdinaryName);
6966 LookupName(R, S: TUScope, /*AllowBuiltinCreation=*/true);
6967
6968 auto *BuiltInDecl = R.getAsSingle<FunctionDecl>();
6969 assert(BuiltInDecl && "failed to find builtin declaration");
6970
6971 ExprResult DeclRef =
6972 BuildDeclRefExpr(D: BuiltInDecl, Ty: BuiltInDecl->getType(), VK: VK_LValue, Loc);
6973 assert(DeclRef.isUsable() && "Builtin reference cannot fail");
6974
6975 ExprResult Call =
6976 BuildCallExpr(/*Scope=*/nullptr, Fn: DeclRef.get(), LParenLoc: Loc, ArgExprs: CallArgs, RParenLoc: Loc);
6977
6978 assert(!Call.isInvalid() && "Call to builtin cannot fail!");
6979 return Call.get();
6980}
6981
6982ExprResult Sema::ActOnAsTypeExpr(Expr *E, ParsedType ParsedDestTy,
6983 SourceLocation BuiltinLoc,
6984 SourceLocation RParenLoc) {
6985 QualType DstTy = GetTypeFromParser(Ty: ParsedDestTy);
6986 return BuildAsTypeExpr(E, DestTy: DstTy, BuiltinLoc, RParenLoc);
6987}
6988
6989ExprResult Sema::BuildAsTypeExpr(Expr *E, QualType DestTy,
6990 SourceLocation BuiltinLoc,
6991 SourceLocation RParenLoc) {
6992 ExprValueKind VK = VK_PRValue;
6993 ExprObjectKind OK = OK_Ordinary;
6994 QualType SrcTy = E->getType();
6995 if (!SrcTy->isDependentType() &&
6996 Context.getTypeSize(T: DestTy) != Context.getTypeSize(T: SrcTy))
6997 return ExprError(
6998 Diag(Loc: BuiltinLoc, DiagID: diag::err_invalid_astype_of_different_size)
6999 << DestTy << SrcTy << E->getSourceRange());
7000 return new (Context) AsTypeExpr(E, DestTy, VK, OK, BuiltinLoc, RParenLoc);
7001}
7002
7003ExprResult Sema::ActOnConvertVectorExpr(Expr *E, ParsedType ParsedDestTy,
7004 SourceLocation BuiltinLoc,
7005 SourceLocation RParenLoc) {
7006 TypeSourceInfo *TInfo;
7007 GetTypeFromParser(Ty: ParsedDestTy, TInfo: &TInfo);
7008 return ConvertVectorExpr(E, TInfo, BuiltinLoc, RParenLoc);
7009}
7010
7011ExprResult Sema::BuildResolvedCallExpr(Expr *Fn, NamedDecl *NDecl,
7012 SourceLocation LParenLoc,
7013 ArrayRef<Expr *> Args,
7014 SourceLocation RParenLoc, Expr *Config,
7015 bool IsExecConfig, ADLCallKind UsesADL) {
7016 FunctionDecl *FDecl = dyn_cast_or_null<FunctionDecl>(Val: NDecl);
7017 unsigned BuiltinID = (FDecl ? FDecl->getBuiltinID() : 0);
7018
7019 auto IsSJLJ = [&] {
7020 switch (BuiltinID) {
7021 case Builtin::BI__builtin_longjmp:
7022 case Builtin::BI__builtin_setjmp:
7023 case Builtin::BI__sigsetjmp:
7024 case Builtin::BI_longjmp:
7025 case Builtin::BI_setjmp:
7026 case Builtin::BIlongjmp:
7027 case Builtin::BIsetjmp:
7028 case Builtin::BIsiglongjmp:
7029 case Builtin::BIsigsetjmp:
7030 return true;
7031 default:
7032 return false;
7033 }
7034 };
7035
7036 // Forbid any call to setjmp/longjmp and friends inside a '_Defer' statement.
7037 if (!CurrentDefer.empty() && IsSJLJ()) {
7038 // Note: If we ever start supporting '_Defer' in C++ we'll have to check
7039 // for more than just blocks (e.g. lambdas, nested classes...).
7040 Scope *DeferParent = CurrentDefer.back().first;
7041 Scope *Block = CurScope->getBlockParent();
7042 if (DeferParent->Contains(rhs: *CurScope) &&
7043 (!Block || !DeferParent->Contains(rhs: *Block)))
7044 Diag(Loc: Fn->getExprLoc(), DiagID: diag::err_defer_invalid_sjlj) << FDecl;
7045 }
7046
7047 // Functions with 'interrupt' attribute cannot be called directly.
7048 if (FDecl) {
7049 if (FDecl->hasAttr<AnyX86InterruptAttr>()) {
7050 Diag(Loc: Fn->getExprLoc(), DiagID: diag::err_anyx86_interrupt_called);
7051 return ExprError();
7052 }
7053 if (FDecl->hasAttr<ARMInterruptAttr>()) {
7054 Diag(Loc: Fn->getExprLoc(), DiagID: diag::err_arm_interrupt_called);
7055 return ExprError();
7056 }
7057 }
7058
7059 // X86 interrupt handlers may only call routines with attribute
7060 // no_caller_saved_registers since there is no efficient way to
7061 // save and restore the non-GPR state.
7062 if (auto *Caller = getCurFunctionDecl()) {
7063 if (Caller->hasAttr<AnyX86InterruptAttr>() ||
7064 Caller->hasAttr<AnyX86NoCallerSavedRegistersAttr>()) {
7065 const TargetInfo &TI = Context.getTargetInfo();
7066 bool HasNonGPRRegisters =
7067 TI.hasFeature(Feature: "sse") || TI.hasFeature(Feature: "x87") || TI.hasFeature(Feature: "mmx");
7068 if (HasNonGPRRegisters &&
7069 (!FDecl || !FDecl->hasAttr<AnyX86NoCallerSavedRegistersAttr>())) {
7070 Diag(Loc: Fn->getExprLoc(), DiagID: diag::warn_anyx86_excessive_regsave)
7071 << (Caller->hasAttr<AnyX86InterruptAttr>() ? 0 : 1);
7072 if (FDecl)
7073 Diag(Loc: FDecl->getLocation(), DiagID: diag::note_callee_decl) << FDecl;
7074 }
7075 }
7076 }
7077
7078 // Promote the function operand.
7079 // We special-case function promotion here because we only allow promoting
7080 // builtin functions to function pointers in the callee of a call.
7081 ExprResult Result;
7082 QualType ResultTy;
7083 if (BuiltinID &&
7084 Fn->getType()->isSpecificBuiltinType(K: BuiltinType::BuiltinFn)) {
7085 // Extract the return type from the (builtin) function pointer type.
7086 // FIXME Several builtins still have setType in
7087 // Sema::CheckBuiltinFunctionCall. One should review their definitions in
7088 // Builtins.td to ensure they are correct before removing setType calls.
7089 QualType FnPtrTy = Context.getPointerType(T: FDecl->getType());
7090 Result = ImpCastExprToType(E: Fn, Type: FnPtrTy, CK: CK_BuiltinFnToFnPtr).get();
7091 ResultTy = FDecl->getCallResultType();
7092 } else {
7093 Result = CallExprUnaryConversions(E: Fn);
7094 ResultTy = Context.BoolTy;
7095 }
7096 if (Result.isInvalid())
7097 return ExprError();
7098 Fn = Result.get();
7099
7100 // Check for a valid function type, but only if it is not a builtin which
7101 // requires custom type checking. These will be handled by
7102 // CheckBuiltinFunctionCall below just after creation of the call expression.
7103 const FunctionType *FuncT = nullptr;
7104 if (!BuiltinID || !Context.BuiltinInfo.hasCustomTypechecking(ID: BuiltinID)) {
7105 retry:
7106 if (const PointerType *PT = Fn->getType()->getAs<PointerType>()) {
7107 // C99 6.5.2.2p1 - "The expression that denotes the called function shall
7108 // have type pointer to function".
7109 FuncT = PT->getPointeeType()->getAs<FunctionType>();
7110 if (!FuncT)
7111 return ExprError(Diag(Loc: LParenLoc, DiagID: diag::err_typecheck_call_not_function)
7112 << Fn->getType() << Fn->getSourceRange());
7113 } else if (const BlockPointerType *BPT =
7114 Fn->getType()->getAs<BlockPointerType>()) {
7115 FuncT = BPT->getPointeeType()->castAs<FunctionType>();
7116 } else {
7117 // Handle calls to expressions of unknown-any type.
7118 if (Fn->getType() == Context.UnknownAnyTy) {
7119 ExprResult rewrite = rebuildUnknownAnyFunction(S&: *this, fn: Fn);
7120 if (rewrite.isInvalid())
7121 return ExprError();
7122 Fn = rewrite.get();
7123 goto retry;
7124 }
7125
7126 return ExprError(Diag(Loc: LParenLoc, DiagID: diag::err_typecheck_call_not_function)
7127 << Fn->getType() << Fn->getSourceRange());
7128 }
7129 }
7130
7131 // Get the number of parameters in the function prototype, if any.
7132 // We will allocate space for max(Args.size(), NumParams) arguments
7133 // in the call expression.
7134 const auto *Proto = dyn_cast_or_null<FunctionProtoType>(Val: FuncT);
7135 unsigned NumParams = Proto ? Proto->getNumParams() : 0;
7136
7137 CallExpr *TheCall;
7138 if (Config) {
7139 assert(UsesADL == ADLCallKind::NotADL &&
7140 "CUDAKernelCallExpr should not use ADL");
7141 TheCall = CUDAKernelCallExpr::Create(Ctx: Context, Fn, Config: cast<CallExpr>(Val: Config),
7142 Args, Ty: ResultTy, VK: VK_PRValue, RP: RParenLoc,
7143 FPFeatures: CurFPFeatureOverrides(), MinNumArgs: NumParams);
7144 } else {
7145 TheCall =
7146 CallExpr::Create(Ctx: Context, Fn, Args, Ty: ResultTy, VK: VK_PRValue, RParenLoc,
7147 FPFeatures: CurFPFeatureOverrides(), MinNumArgs: NumParams, UsesADL);
7148 }
7149
7150 // Bail out early if calling a builtin with custom type checking.
7151 if (BuiltinID && Context.BuiltinInfo.hasCustomTypechecking(ID: BuiltinID)) {
7152 ExprResult E = CheckBuiltinFunctionCall(FDecl, BuiltinID, TheCall);
7153 if (!E.isInvalid() && Context.BuiltinInfo.isImmediate(ID: BuiltinID))
7154 E = CheckForImmediateInvocation(E, Decl: FDecl);
7155 return E;
7156 }
7157
7158 if (getLangOpts().CUDA) {
7159 if (Config) {
7160 // CUDA: Kernel calls must be to global functions
7161 if (FDecl && !FDecl->hasAttr<CUDAGlobalAttr>())
7162 return ExprError(Diag(Loc: LParenLoc,DiagID: diag::err_kern_call_not_global_function)
7163 << FDecl << Fn->getSourceRange());
7164
7165 // CUDA: Kernel function must have 'void' return type
7166 if (!FuncT->getReturnType()->isVoidType() &&
7167 !FuncT->getReturnType()->getAs<AutoType>() &&
7168 !FuncT->getReturnType()->isInstantiationDependentType())
7169 return ExprError(Diag(Loc: LParenLoc, DiagID: diag::err_kern_type_not_void_return)
7170 << Fn->getType() << Fn->getSourceRange());
7171 } else {
7172 // CUDA: Calls to global functions must be configured
7173 if (FDecl && FDecl->hasAttr<CUDAGlobalAttr>())
7174 return ExprError(Diag(Loc: LParenLoc, DiagID: diag::err_global_call_not_config)
7175 << FDecl << Fn->getSourceRange());
7176 }
7177 }
7178
7179 // Check for a valid return type
7180 if (CheckCallReturnType(ReturnType: FuncT->getReturnType(), Loc: Fn->getBeginLoc(), CE: TheCall,
7181 FD: FDecl))
7182 return ExprError();
7183
7184 // We know the result type of the call, set it.
7185 TheCall->setType(FuncT->getCallResultType(Context));
7186 TheCall->setValueKind(Expr::getValueKindForType(T: FuncT->getReturnType()));
7187
7188 // WebAssembly tables can't be used as arguments.
7189 if (Context.getTargetInfo().getTriple().isWasm()) {
7190 for (const Expr *Arg : Args) {
7191 if (Arg && Arg->getType()->isWebAssemblyTableType()) {
7192 return ExprError(Diag(Loc: Arg->getExprLoc(),
7193 DiagID: diag::err_wasm_table_as_function_parameter));
7194 }
7195 }
7196 }
7197
7198 if (Proto) {
7199 if (ConvertArgumentsForCall(Call: TheCall, Fn, FDecl, Proto, Args, RParenLoc,
7200 IsExecConfig))
7201 return ExprError();
7202 } else {
7203 assert(isa<FunctionNoProtoType>(FuncT) && "Unknown FunctionType!");
7204
7205 if (FDecl) {
7206 // Check if we have too few/too many template arguments, based
7207 // on our knowledge of the function definition.
7208 const FunctionDecl *Def = nullptr;
7209 if (FDecl->hasBody(Definition&: Def) && Args.size() != Def->param_size()) {
7210 Proto = Def->getType()->getAs<FunctionProtoType>();
7211 if (!Proto || !(Proto->isVariadic() && Args.size() >= Def->param_size()))
7212 Diag(Loc: RParenLoc, DiagID: diag::warn_call_wrong_number_of_arguments)
7213 << (Args.size() > Def->param_size()) << FDecl << Fn->getSourceRange();
7214 }
7215
7216 // If the function we're calling isn't a function prototype, but we have
7217 // a function prototype from a prior declaratiom, use that prototype.
7218 if (!FDecl->hasPrototype())
7219 Proto = FDecl->getType()->getAs<FunctionProtoType>();
7220 }
7221
7222 // If we still haven't found a prototype to use but there are arguments to
7223 // the call, diagnose this as calling a function without a prototype.
7224 // However, if we found a function declaration, check to see if
7225 // -Wdeprecated-non-prototype was disabled where the function was declared.
7226 // If so, we will silence the diagnostic here on the assumption that this
7227 // interface is intentional and the user knows what they're doing. We will
7228 // also silence the diagnostic if there is a function declaration but it
7229 // was implicitly defined (the user already gets diagnostics about the
7230 // creation of the implicit function declaration, so the additional warning
7231 // is not helpful).
7232 if (!Proto && !Args.empty() &&
7233 (!FDecl || (!FDecl->isImplicit() &&
7234 !Diags.isIgnored(DiagID: diag::warn_strict_uses_without_prototype,
7235 Loc: FDecl->getLocation()))))
7236 Diag(Loc: LParenLoc, DiagID: diag::warn_strict_uses_without_prototype)
7237 << (FDecl != nullptr) << FDecl;
7238
7239 // Promote the arguments (C99 6.5.2.2p6).
7240 for (unsigned i = 0, e = Args.size(); i != e; i++) {
7241 Expr *Arg = Args[i];
7242
7243 if (Proto && i < Proto->getNumParams()) {
7244 InitializedEntity Entity = InitializedEntity::InitializeParameter(
7245 Context, Type: Proto->getParamType(i), Consumed: Proto->isParamConsumed(I: i));
7246 ExprResult ArgE =
7247 PerformCopyInitialization(Entity, EqualLoc: SourceLocation(), Init: Arg);
7248 if (ArgE.isInvalid())
7249 return true;
7250
7251 Arg = ArgE.getAs<Expr>();
7252
7253 } else {
7254 ExprResult ArgE = DefaultArgumentPromotion(E: Arg);
7255
7256 if (ArgE.isInvalid())
7257 return true;
7258
7259 Arg = ArgE.getAs<Expr>();
7260 }
7261
7262 if (RequireCompleteType(Loc: Arg->getBeginLoc(), T: Arg->getType(),
7263 DiagID: diag::err_call_incomplete_argument, Args: Arg))
7264 return ExprError();
7265
7266 TheCall->setArg(Arg: i, ArgExpr: Arg);
7267 }
7268 TheCall->computeDependence();
7269 }
7270
7271 if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(Val: FDecl))
7272 if (Method->isImplicitObjectMemberFunction())
7273 return ExprError(Diag(Loc: LParenLoc, DiagID: diag::err_member_call_without_object)
7274 << Fn->getSourceRange() << 0);
7275
7276 // Check for sentinels
7277 if (NDecl)
7278 DiagnoseSentinelCalls(D: NDecl, Loc: LParenLoc, Args);
7279
7280 // Warn for unions passing across security boundary (CMSE).
7281 if (FuncT != nullptr && FuncT->getCmseNSCallAttr()) {
7282 for (unsigned i = 0, e = Args.size(); i != e; i++) {
7283 if (const auto *RT =
7284 dyn_cast<RecordType>(Val: Args[i]->getType().getCanonicalType())) {
7285 if (RT->getDecl()->isOrContainsUnion())
7286 Diag(Loc: Args[i]->getBeginLoc(), DiagID: diag::warn_cmse_nonsecure_union)
7287 << 0 << i;
7288 }
7289 }
7290 }
7291
7292 // Do special checking on direct calls to functions.
7293 if (FDecl) {
7294 if (CheckFunctionCall(FDecl, TheCall, Proto))
7295 return ExprError();
7296
7297 checkFortifiedBuiltinMemoryFunction(FD: FDecl, TheCall);
7298
7299 if (BuiltinID)
7300 return CheckBuiltinFunctionCall(FDecl, BuiltinID, TheCall);
7301 } else if (NDecl) {
7302 if (CheckPointerCall(NDecl, TheCall, Proto))
7303 return ExprError();
7304 } else {
7305 if (CheckOtherCall(TheCall, Proto))
7306 return ExprError();
7307 }
7308
7309 return CheckForImmediateInvocation(E: MaybeBindToTemporary(E: TheCall), Decl: FDecl);
7310}
7311
7312ExprResult
7313Sema::ActOnCompoundLiteral(SourceLocation LParenLoc, ParsedType Ty,
7314 SourceLocation RParenLoc, Expr *InitExpr) {
7315 assert(Ty && "ActOnCompoundLiteral(): missing type");
7316 assert(InitExpr && "ActOnCompoundLiteral(): missing expression");
7317
7318 TypeSourceInfo *TInfo;
7319 QualType literalType = GetTypeFromParser(Ty, TInfo: &TInfo);
7320 if (!TInfo)
7321 TInfo = Context.getTrivialTypeSourceInfo(T: literalType);
7322
7323 return BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc, LiteralExpr: InitExpr);
7324}
7325
7326ExprResult
7327Sema::BuildCompoundLiteralExpr(SourceLocation LParenLoc, TypeSourceInfo *TInfo,
7328 SourceLocation RParenLoc, Expr *LiteralExpr) {
7329 QualType literalType = TInfo->getType();
7330
7331 if (literalType->isArrayType()) {
7332 if (RequireCompleteSizedType(
7333 Loc: LParenLoc, T: Context.getBaseElementType(QT: literalType),
7334 DiagID: diag::err_array_incomplete_or_sizeless_type,
7335 Args: SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd())))
7336 return ExprError();
7337 if (literalType->isVariableArrayType()) {
7338 // C23 6.7.10p4: An entity of variable length array type shall not be
7339 // initialized except by an empty initializer.
7340 //
7341 // The C extension warnings are issued from ParseBraceInitializer() and
7342 // do not need to be issued here. However, we continue to issue an error
7343 // in the case there are initializers or we are compiling C++. We allow
7344 // use of VLAs in C++, but it's not clear we want to allow {} to zero
7345 // init a VLA in C++ in all cases (such as with non-trivial constructors).
7346 // FIXME: should we allow this construct in C++ when it makes sense to do
7347 // so?
7348 //
7349 // But: C99-C23 6.5.2.5 Compound literals constraint 1: The type name
7350 // shall specify an object type or an array of unknown size, but not a
7351 // variable length array type. This seems odd, as it allows 'int a[size] =
7352 // {}', but forbids 'int *a = (int[size]){}'. As this is what the standard
7353 // says, this is what's implemented here for C (except for the extension
7354 // that permits constant foldable size arrays)
7355
7356 auto diagID = LangOpts.CPlusPlus
7357 ? diag::err_variable_object_no_init
7358 : diag::err_compound_literal_with_vla_type;
7359 if (!tryToFixVariablyModifiedVarType(TInfo, T&: literalType, Loc: LParenLoc,
7360 FailedFoldDiagID: diagID))
7361 return ExprError();
7362 }
7363 } else if (!literalType->isDependentType() &&
7364 RequireCompleteType(Loc: LParenLoc, T: literalType,
7365 DiagID: diag::err_typecheck_decl_incomplete_type,
7366 Args: SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd())))
7367 return ExprError();
7368
7369 InitializedEntity Entity
7370 = InitializedEntity::InitializeCompoundLiteralInit(TSI: TInfo);
7371 InitializationKind Kind
7372 = InitializationKind::CreateCStyleCast(StartLoc: LParenLoc,
7373 TypeRange: SourceRange(LParenLoc, RParenLoc),
7374 /*InitList=*/true);
7375 InitializationSequence InitSeq(*this, Entity, Kind, LiteralExpr);
7376 ExprResult Result = InitSeq.Perform(S&: *this, Entity, Kind, Args: LiteralExpr,
7377 ResultType: &literalType);
7378 if (Result.isInvalid())
7379 return ExprError();
7380 LiteralExpr = Result.get();
7381
7382 // We treat the compound literal as being at file scope if it's not in a
7383 // function or method body, or within the function's prototype scope. This
7384 // means the following compound literal is not at file scope:
7385 // void func(char *para[(int [1]){ 0 }[0]);
7386 const Scope *S = getCurScope();
7387 bool IsFileScope = !CurContext->isFunctionOrMethod() &&
7388 !S->isInCFunctionScope() &&
7389 (!S || !S->isFunctionPrototypeScope());
7390
7391 // In C, compound literals are l-values for some reason.
7392 // For GCC compatibility, in C++, file-scope array compound literals with
7393 // constant initializers are also l-values, and compound literals are
7394 // otherwise prvalues.
7395 //
7396 // (GCC also treats C++ list-initialized file-scope array prvalues with
7397 // constant initializers as l-values, but that's non-conforming, so we don't
7398 // follow it there.)
7399 //
7400 // FIXME: It would be better to handle the lvalue cases as materializing and
7401 // lifetime-extending a temporary object, but our materialized temporaries
7402 // representation only supports lifetime extension from a variable, not "out
7403 // of thin air".
7404 // FIXME: For C++, we might want to instead lifetime-extend only if a pointer
7405 // is bound to the result of applying array-to-pointer decay to the compound
7406 // literal.
7407 // FIXME: GCC supports compound literals of reference type, which should
7408 // obviously have a value kind derived from the kind of reference involved.
7409 ExprValueKind VK =
7410 (getLangOpts().CPlusPlus && !(IsFileScope && literalType->isArrayType()))
7411 ? VK_PRValue
7412 : VK_LValue;
7413
7414 // C99 6.5.2.5
7415 // "If the compound literal occurs outside the body of a function, the
7416 // initializer list shall consist of constant expressions."
7417 if (IsFileScope)
7418 if (auto ILE = dyn_cast<InitListExpr>(Val: LiteralExpr))
7419 for (unsigned i = 0, j = ILE->getNumInits(); i != j; i++) {
7420 Expr *Init = ILE->getInit(Init: i);
7421 if (!Init->isTypeDependent() && !Init->isValueDependent() &&
7422 !Init->isConstantInitializer(Ctx&: Context, /*IsForRef=*/ForRef: false)) {
7423 Diag(Loc: Init->getExprLoc(), DiagID: diag::err_init_element_not_constant)
7424 << Init->getSourceBitField();
7425 return ExprError();
7426 }
7427
7428 ILE->setInit(Init: i, expr: ConstantExpr::Create(Context, E: Init));
7429 }
7430
7431 auto *E = new (Context) CompoundLiteralExpr(LParenLoc, TInfo, literalType, VK,
7432 LiteralExpr, IsFileScope);
7433 if (IsFileScope) {
7434 if (!LiteralExpr->isTypeDependent() &&
7435 !LiteralExpr->isValueDependent() &&
7436 !literalType->isDependentType()) // C99 6.5.2.5p3
7437 if (CheckForConstantInitializer(Init: LiteralExpr))
7438 return ExprError();
7439 } else if (literalType.getAddressSpace() != LangAS::opencl_private &&
7440 literalType.getAddressSpace() != LangAS::Default) {
7441 // Embedded-C extensions to C99 6.5.2.5:
7442 // "If the compound literal occurs inside the body of a function, the
7443 // type name shall not be qualified by an address-space qualifier."
7444 Diag(Loc: LParenLoc, DiagID: diag::err_compound_literal_with_address_space)
7445 << SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd());
7446 return ExprError();
7447 }
7448
7449 if (!IsFileScope && !getLangOpts().CPlusPlus) {
7450 // Compound literals that have automatic storage duration are destroyed at
7451 // the end of the scope in C; in C++, they're just temporaries.
7452
7453 // Emit diagnostics if it is or contains a C union type that is non-trivial
7454 // to destruct.
7455 if (E->getType().hasNonTrivialToPrimitiveDestructCUnion())
7456 checkNonTrivialCUnion(QT: E->getType(), Loc: E->getExprLoc(),
7457 UseContext: NonTrivialCUnionContext::CompoundLiteral,
7458 NonTrivialKind: NTCUK_Destruct);
7459
7460 // Diagnose jumps that enter or exit the lifetime of the compound literal.
7461 if (literalType.isDestructedType()) {
7462 Cleanup.setExprNeedsCleanups(true);
7463 ExprCleanupObjects.push_back(Elt: E);
7464 getCurFunction()->setHasBranchProtectedScope();
7465 }
7466 }
7467
7468 if (E->getType().hasNonTrivialToPrimitiveDefaultInitializeCUnion() ||
7469 E->getType().hasNonTrivialToPrimitiveCopyCUnion())
7470 checkNonTrivialCUnionInInitializer(Init: E->getInitializer(),
7471 Loc: E->getInitializer()->getExprLoc());
7472
7473 return MaybeBindToTemporary(E);
7474}
7475
7476ExprResult
7477Sema::ActOnInitList(SourceLocation LBraceLoc, MultiExprArg InitArgList,
7478 SourceLocation RBraceLoc) {
7479 // Only produce each kind of designated initialization diagnostic once.
7480 SourceLocation FirstDesignator;
7481 bool DiagnosedArrayDesignator = false;
7482 bool DiagnosedNestedDesignator = false;
7483 bool DiagnosedMixedDesignator = false;
7484
7485 // Check that any designated initializers are syntactically valid in the
7486 // current language mode.
7487 for (unsigned I = 0, E = InitArgList.size(); I != E; ++I) {
7488 if (auto *DIE = dyn_cast<DesignatedInitExpr>(Val: InitArgList[I])) {
7489 if (FirstDesignator.isInvalid())
7490 FirstDesignator = DIE->getBeginLoc();
7491
7492 if (!getLangOpts().CPlusPlus)
7493 break;
7494
7495 if (!DiagnosedNestedDesignator && DIE->size() > 1) {
7496 DiagnosedNestedDesignator = true;
7497 Diag(Loc: DIE->getBeginLoc(), DiagID: diag::ext_designated_init_nested)
7498 << DIE->getDesignatorsSourceRange();
7499 }
7500
7501 for (auto &Desig : DIE->designators()) {
7502 if (!Desig.isFieldDesignator() && !DiagnosedArrayDesignator) {
7503 DiagnosedArrayDesignator = true;
7504 Diag(Loc: Desig.getBeginLoc(), DiagID: diag::ext_designated_init_array)
7505 << Desig.getSourceRange();
7506 }
7507 }
7508
7509 if (!DiagnosedMixedDesignator &&
7510 !isa<DesignatedInitExpr>(Val: InitArgList[0])) {
7511 DiagnosedMixedDesignator = true;
7512 Diag(Loc: DIE->getBeginLoc(), DiagID: diag::ext_designated_init_mixed)
7513 << DIE->getSourceRange();
7514 Diag(Loc: InitArgList[0]->getBeginLoc(), DiagID: diag::note_designated_init_mixed)
7515 << InitArgList[0]->getSourceRange();
7516 }
7517 } else if (getLangOpts().CPlusPlus && !DiagnosedMixedDesignator &&
7518 isa<DesignatedInitExpr>(Val: InitArgList[0])) {
7519 DiagnosedMixedDesignator = true;
7520 auto *DIE = cast<DesignatedInitExpr>(Val: InitArgList[0]);
7521 Diag(Loc: DIE->getBeginLoc(), DiagID: diag::ext_designated_init_mixed)
7522 << DIE->getSourceRange();
7523 Diag(Loc: InitArgList[I]->getBeginLoc(), DiagID: diag::note_designated_init_mixed)
7524 << InitArgList[I]->getSourceRange();
7525 }
7526 }
7527
7528 if (FirstDesignator.isValid()) {
7529 // Only diagnose designated initiaization as a C++20 extension if we didn't
7530 // already diagnose use of (non-C++20) C99 designator syntax.
7531 if (getLangOpts().CPlusPlus && !DiagnosedArrayDesignator &&
7532 !DiagnosedNestedDesignator && !DiagnosedMixedDesignator) {
7533 Diag(Loc: FirstDesignator, DiagID: getLangOpts().CPlusPlus20
7534 ? diag::warn_cxx17_compat_designated_init
7535 : diag::ext_cxx_designated_init);
7536 } else if (!getLangOpts().CPlusPlus && !getLangOpts().C99) {
7537 Diag(Loc: FirstDesignator, DiagID: diag::ext_designated_init);
7538 }
7539 }
7540
7541 return BuildInitList(LBraceLoc, InitArgList, RBraceLoc);
7542}
7543
7544ExprResult
7545Sema::BuildInitList(SourceLocation LBraceLoc, MultiExprArg InitArgList,
7546 SourceLocation RBraceLoc) {
7547 // Semantic analysis for initializers is done by ActOnDeclarator() and
7548 // CheckInitializer() - it requires knowledge of the object being initialized.
7549
7550 // Immediately handle non-overload placeholders. Overloads can be
7551 // resolved contextually, but everything else here can't.
7552 for (unsigned I = 0, E = InitArgList.size(); I != E; ++I) {
7553 if (InitArgList[I]->getType()->isNonOverloadPlaceholderType()) {
7554 ExprResult result = CheckPlaceholderExpr(E: InitArgList[I]);
7555
7556 // Ignore failures; dropping the entire initializer list because
7557 // of one failure would be terrible for indexing/etc.
7558 if (result.isInvalid()) continue;
7559
7560 InitArgList[I] = result.get();
7561 }
7562 }
7563
7564 InitListExpr *E =
7565 new (Context) InitListExpr(Context, LBraceLoc, InitArgList, RBraceLoc);
7566 E->setType(Context.VoidTy); // FIXME: just a place holder for now.
7567 return E;
7568}
7569
7570void Sema::maybeExtendBlockObject(ExprResult &E) {
7571 assert(E.get()->getType()->isBlockPointerType());
7572 assert(E.get()->isPRValue());
7573
7574 // Only do this in an r-value context.
7575 if (!getLangOpts().ObjCAutoRefCount) return;
7576
7577 E = ImplicitCastExpr::Create(
7578 Context, T: E.get()->getType(), Kind: CK_ARCExtendBlockObject, Operand: E.get(),
7579 /*base path*/ BasePath: nullptr, Cat: VK_PRValue, FPO: FPOptionsOverride());
7580 Cleanup.setExprNeedsCleanups(true);
7581}
7582
7583CastKind Sema::PrepareScalarCast(ExprResult &Src, QualType DestTy) {
7584 // Both Src and Dest are scalar types, i.e. arithmetic or pointer.
7585 // Also, callers should have filtered out the invalid cases with
7586 // pointers. Everything else should be possible.
7587
7588 QualType SrcTy = Src.get()->getType();
7589 if (Context.hasSameUnqualifiedType(T1: SrcTy, T2: DestTy))
7590 return CK_NoOp;
7591
7592 switch (Type::ScalarTypeKind SrcKind = SrcTy->getScalarTypeKind()) {
7593 case Type::STK_MemberPointer:
7594 llvm_unreachable("member pointer type in C");
7595
7596 case Type::STK_CPointer:
7597 case Type::STK_BlockPointer:
7598 case Type::STK_ObjCObjectPointer:
7599 switch (DestTy->getScalarTypeKind()) {
7600 case Type::STK_CPointer: {
7601 LangAS SrcAS = SrcTy->getPointeeType().getAddressSpace();
7602 LangAS DestAS = DestTy->getPointeeType().getAddressSpace();
7603 if (SrcAS != DestAS)
7604 return CK_AddressSpaceConversion;
7605 if (Context.hasCvrSimilarType(T1: SrcTy, T2: DestTy))
7606 return CK_NoOp;
7607 return CK_BitCast;
7608 }
7609 case Type::STK_BlockPointer:
7610 return (SrcKind == Type::STK_BlockPointer
7611 ? CK_BitCast : CK_AnyPointerToBlockPointerCast);
7612 case Type::STK_ObjCObjectPointer:
7613 if (SrcKind == Type::STK_ObjCObjectPointer)
7614 return CK_BitCast;
7615 if (SrcKind == Type::STK_CPointer)
7616 return CK_CPointerToObjCPointerCast;
7617 maybeExtendBlockObject(E&: Src);
7618 return CK_BlockPointerToObjCPointerCast;
7619 case Type::STK_Bool:
7620 return CK_PointerToBoolean;
7621 case Type::STK_Integral:
7622 return CK_PointerToIntegral;
7623 case Type::STK_Floating:
7624 case Type::STK_FloatingComplex:
7625 case Type::STK_IntegralComplex:
7626 case Type::STK_MemberPointer:
7627 case Type::STK_FixedPoint:
7628 llvm_unreachable("illegal cast from pointer");
7629 }
7630 llvm_unreachable("Should have returned before this");
7631
7632 case Type::STK_FixedPoint:
7633 switch (DestTy->getScalarTypeKind()) {
7634 case Type::STK_FixedPoint:
7635 return CK_FixedPointCast;
7636 case Type::STK_Bool:
7637 return CK_FixedPointToBoolean;
7638 case Type::STK_Integral:
7639 return CK_FixedPointToIntegral;
7640 case Type::STK_Floating:
7641 return CK_FixedPointToFloating;
7642 case Type::STK_IntegralComplex:
7643 case Type::STK_FloatingComplex:
7644 Diag(Loc: Src.get()->getExprLoc(),
7645 DiagID: diag::err_unimplemented_conversion_with_fixed_point_type)
7646 << DestTy;
7647 return CK_IntegralCast;
7648 case Type::STK_CPointer:
7649 case Type::STK_ObjCObjectPointer:
7650 case Type::STK_BlockPointer:
7651 case Type::STK_MemberPointer:
7652 llvm_unreachable("illegal cast to pointer type");
7653 }
7654 llvm_unreachable("Should have returned before this");
7655
7656 case Type::STK_Bool: // casting from bool is like casting from an integer
7657 case Type::STK_Integral:
7658 switch (DestTy->getScalarTypeKind()) {
7659 case Type::STK_CPointer:
7660 case Type::STK_ObjCObjectPointer:
7661 case Type::STK_BlockPointer:
7662 if (Src.get()->isNullPointerConstant(Ctx&: Context,
7663 NPC: Expr::NPC_ValueDependentIsNull))
7664 return CK_NullToPointer;
7665 return CK_IntegralToPointer;
7666 case Type::STK_Bool:
7667 return CK_IntegralToBoolean;
7668 case Type::STK_Integral:
7669 return CK_IntegralCast;
7670 case Type::STK_Floating:
7671 return CK_IntegralToFloating;
7672 case Type::STK_IntegralComplex:
7673 Src = ImpCastExprToType(E: Src.get(),
7674 Type: DestTy->castAs<ComplexType>()->getElementType(),
7675 CK: CK_IntegralCast);
7676 return CK_IntegralRealToComplex;
7677 case Type::STK_FloatingComplex:
7678 Src = ImpCastExprToType(E: Src.get(),
7679 Type: DestTy->castAs<ComplexType>()->getElementType(),
7680 CK: CK_IntegralToFloating);
7681 return CK_FloatingRealToComplex;
7682 case Type::STK_MemberPointer:
7683 llvm_unreachable("member pointer type in C");
7684 case Type::STK_FixedPoint:
7685 return CK_IntegralToFixedPoint;
7686 }
7687 llvm_unreachable("Should have returned before this");
7688
7689 case Type::STK_Floating:
7690 switch (DestTy->getScalarTypeKind()) {
7691 case Type::STK_Floating:
7692 return CK_FloatingCast;
7693 case Type::STK_Bool:
7694 return CK_FloatingToBoolean;
7695 case Type::STK_Integral:
7696 return CK_FloatingToIntegral;
7697 case Type::STK_FloatingComplex:
7698 Src = ImpCastExprToType(E: Src.get(),
7699 Type: DestTy->castAs<ComplexType>()->getElementType(),
7700 CK: CK_FloatingCast);
7701 return CK_FloatingRealToComplex;
7702 case Type::STK_IntegralComplex:
7703 Src = ImpCastExprToType(E: Src.get(),
7704 Type: DestTy->castAs<ComplexType>()->getElementType(),
7705 CK: CK_FloatingToIntegral);
7706 return CK_IntegralRealToComplex;
7707 case Type::STK_CPointer:
7708 case Type::STK_ObjCObjectPointer:
7709 case Type::STK_BlockPointer:
7710 llvm_unreachable("valid float->pointer cast?");
7711 case Type::STK_MemberPointer:
7712 llvm_unreachable("member pointer type in C");
7713 case Type::STK_FixedPoint:
7714 return CK_FloatingToFixedPoint;
7715 }
7716 llvm_unreachable("Should have returned before this");
7717
7718 case Type::STK_FloatingComplex:
7719 switch (DestTy->getScalarTypeKind()) {
7720 case Type::STK_FloatingComplex:
7721 return CK_FloatingComplexCast;
7722 case Type::STK_IntegralComplex:
7723 return CK_FloatingComplexToIntegralComplex;
7724 case Type::STK_Floating: {
7725 QualType ET = SrcTy->castAs<ComplexType>()->getElementType();
7726 if (Context.hasSameType(T1: ET, T2: DestTy))
7727 return CK_FloatingComplexToReal;
7728 Src = ImpCastExprToType(E: Src.get(), Type: ET, CK: CK_FloatingComplexToReal);
7729 return CK_FloatingCast;
7730 }
7731 case Type::STK_Bool:
7732 return CK_FloatingComplexToBoolean;
7733 case Type::STK_Integral:
7734 Src = ImpCastExprToType(E: Src.get(),
7735 Type: SrcTy->castAs<ComplexType>()->getElementType(),
7736 CK: CK_FloatingComplexToReal);
7737 return CK_FloatingToIntegral;
7738 case Type::STK_CPointer:
7739 case Type::STK_ObjCObjectPointer:
7740 case Type::STK_BlockPointer:
7741 llvm_unreachable("valid complex float->pointer cast?");
7742 case Type::STK_MemberPointer:
7743 llvm_unreachable("member pointer type in C");
7744 case Type::STK_FixedPoint:
7745 Diag(Loc: Src.get()->getExprLoc(),
7746 DiagID: diag::err_unimplemented_conversion_with_fixed_point_type)
7747 << SrcTy;
7748 return CK_IntegralCast;
7749 }
7750 llvm_unreachable("Should have returned before this");
7751
7752 case Type::STK_IntegralComplex:
7753 switch (DestTy->getScalarTypeKind()) {
7754 case Type::STK_FloatingComplex:
7755 return CK_IntegralComplexToFloatingComplex;
7756 case Type::STK_IntegralComplex:
7757 return CK_IntegralComplexCast;
7758 case Type::STK_Integral: {
7759 QualType ET = SrcTy->castAs<ComplexType>()->getElementType();
7760 if (Context.hasSameType(T1: ET, T2: DestTy))
7761 return CK_IntegralComplexToReal;
7762 Src = ImpCastExprToType(E: Src.get(), Type: ET, CK: CK_IntegralComplexToReal);
7763 return CK_IntegralCast;
7764 }
7765 case Type::STK_Bool:
7766 return CK_IntegralComplexToBoolean;
7767 case Type::STK_Floating:
7768 Src = ImpCastExprToType(E: Src.get(),
7769 Type: SrcTy->castAs<ComplexType>()->getElementType(),
7770 CK: CK_IntegralComplexToReal);
7771 return CK_IntegralToFloating;
7772 case Type::STK_CPointer:
7773 case Type::STK_ObjCObjectPointer:
7774 case Type::STK_BlockPointer:
7775 llvm_unreachable("valid complex int->pointer cast?");
7776 case Type::STK_MemberPointer:
7777 llvm_unreachable("member pointer type in C");
7778 case Type::STK_FixedPoint:
7779 Diag(Loc: Src.get()->getExprLoc(),
7780 DiagID: diag::err_unimplemented_conversion_with_fixed_point_type)
7781 << SrcTy;
7782 return CK_IntegralCast;
7783 }
7784 llvm_unreachable("Should have returned before this");
7785 }
7786
7787 llvm_unreachable("Unhandled scalar cast");
7788}
7789
7790static bool breakDownVectorType(QualType type, uint64_t &len,
7791 QualType &eltType) {
7792 // Vectors are simple.
7793 if (const VectorType *vecType = type->getAs<VectorType>()) {
7794 len = vecType->getNumElements();
7795 eltType = vecType->getElementType();
7796 assert(eltType->isScalarType() || eltType->isMFloat8Type());
7797 return true;
7798 }
7799
7800 // We allow lax conversion to and from non-vector types, but only if
7801 // they're real types (i.e. non-complex, non-pointer scalar types).
7802 if (!type->isRealType()) return false;
7803
7804 len = 1;
7805 eltType = type;
7806 return true;
7807}
7808
7809bool Sema::isValidSveBitcast(QualType srcTy, QualType destTy) {
7810 assert(srcTy->isVectorType() || destTy->isVectorType());
7811
7812 auto ValidScalableConversion = [](QualType FirstType, QualType SecondType) {
7813 if (!FirstType->isSVESizelessBuiltinType())
7814 return false;
7815
7816 const auto *VecTy = SecondType->getAs<VectorType>();
7817 return VecTy && VecTy->getVectorKind() == VectorKind::SveFixedLengthData;
7818 };
7819
7820 return ValidScalableConversion(srcTy, destTy) ||
7821 ValidScalableConversion(destTy, srcTy);
7822}
7823
7824bool Sema::areMatrixTypesOfTheSameDimension(QualType srcTy, QualType destTy) {
7825 if (!destTy->isMatrixType() || !srcTy->isMatrixType())
7826 return false;
7827
7828 const ConstantMatrixType *matSrcType = srcTy->getAs<ConstantMatrixType>();
7829 const ConstantMatrixType *matDestType = destTy->getAs<ConstantMatrixType>();
7830
7831 return matSrcType->getNumRows() == matDestType->getNumRows() &&
7832 matSrcType->getNumColumns() == matDestType->getNumColumns();
7833}
7834
7835bool Sema::areVectorTypesSameSize(QualType SrcTy, QualType DestTy) {
7836 assert(DestTy->isVectorType() || SrcTy->isVectorType());
7837
7838 uint64_t SrcLen, DestLen;
7839 QualType SrcEltTy, DestEltTy;
7840 if (!breakDownVectorType(type: SrcTy, len&: SrcLen, eltType&: SrcEltTy))
7841 return false;
7842 if (!breakDownVectorType(type: DestTy, len&: DestLen, eltType&: DestEltTy))
7843 return false;
7844
7845 // ASTContext::getTypeSize will return the size rounded up to a
7846 // power of 2, so instead of using that, we need to use the raw
7847 // element size multiplied by the element count.
7848 uint64_t SrcEltSize = Context.getTypeSize(T: SrcEltTy);
7849 uint64_t DestEltSize = Context.getTypeSize(T: DestEltTy);
7850
7851 return (SrcLen * SrcEltSize == DestLen * DestEltSize);
7852}
7853
7854bool Sema::anyAltivecTypes(QualType SrcTy, QualType DestTy) {
7855 assert((DestTy->isVectorType() || SrcTy->isVectorType()) &&
7856 "expected at least one type to be a vector here");
7857
7858 bool IsSrcTyAltivec =
7859 SrcTy->isVectorType() && ((SrcTy->castAs<VectorType>()->getVectorKind() ==
7860 VectorKind::AltiVecVector) ||
7861 (SrcTy->castAs<VectorType>()->getVectorKind() ==
7862 VectorKind::AltiVecBool) ||
7863 (SrcTy->castAs<VectorType>()->getVectorKind() ==
7864 VectorKind::AltiVecPixel));
7865
7866 bool IsDestTyAltivec = DestTy->isVectorType() &&
7867 ((DestTy->castAs<VectorType>()->getVectorKind() ==
7868 VectorKind::AltiVecVector) ||
7869 (DestTy->castAs<VectorType>()->getVectorKind() ==
7870 VectorKind::AltiVecBool) ||
7871 (DestTy->castAs<VectorType>()->getVectorKind() ==
7872 VectorKind::AltiVecPixel));
7873
7874 return (IsSrcTyAltivec || IsDestTyAltivec);
7875}
7876
7877bool Sema::areLaxCompatibleVectorTypes(QualType srcTy, QualType destTy) {
7878 assert(destTy->isVectorType() || srcTy->isVectorType());
7879
7880 // Disallow lax conversions between scalars and ExtVectors (these
7881 // conversions are allowed for other vector types because common headers
7882 // depend on them). Most scalar OP ExtVector cases are handled by the
7883 // splat path anyway, which does what we want (convert, not bitcast).
7884 // What this rules out for ExtVectors is crazy things like char4*float.
7885 if (srcTy->isScalarType() && destTy->isExtVectorType()) return false;
7886 if (destTy->isScalarType() && srcTy->isExtVectorType()) return false;
7887
7888 return areVectorTypesSameSize(SrcTy: srcTy, DestTy: destTy);
7889}
7890
7891bool Sema::isLaxVectorConversion(QualType srcTy, QualType destTy) {
7892 assert(destTy->isVectorType() || srcTy->isVectorType());
7893
7894 switch (Context.getLangOpts().getLaxVectorConversions()) {
7895 case LangOptions::LaxVectorConversionKind::None:
7896 return false;
7897
7898 case LangOptions::LaxVectorConversionKind::Integer:
7899 if (!srcTy->isIntegralOrEnumerationType()) {
7900 auto *Vec = srcTy->getAs<VectorType>();
7901 if (!Vec || !Vec->getElementType()->isIntegralOrEnumerationType())
7902 return false;
7903 }
7904 if (!destTy->isIntegralOrEnumerationType()) {
7905 auto *Vec = destTy->getAs<VectorType>();
7906 if (!Vec || !Vec->getElementType()->isIntegralOrEnumerationType())
7907 return false;
7908 }
7909 // OK, integer (vector) -> integer (vector) bitcast.
7910 break;
7911
7912 case LangOptions::LaxVectorConversionKind::All:
7913 break;
7914 }
7915
7916 return areLaxCompatibleVectorTypes(srcTy, destTy);
7917}
7918
7919bool Sema::CheckMatrixCast(SourceRange R, QualType DestTy, QualType SrcTy,
7920 CastKind &Kind) {
7921 if (SrcTy->isMatrixType() && DestTy->isMatrixType()) {
7922 if (!areMatrixTypesOfTheSameDimension(srcTy: SrcTy, destTy: DestTy)) {
7923 return Diag(Loc: R.getBegin(), DiagID: diag::err_invalid_conversion_between_matrixes)
7924 << DestTy << SrcTy << R;
7925 }
7926 } else if (SrcTy->isMatrixType()) {
7927 return Diag(Loc: R.getBegin(),
7928 DiagID: diag::err_invalid_conversion_between_matrix_and_type)
7929 << SrcTy << DestTy << R;
7930 } else if (DestTy->isMatrixType()) {
7931 return Diag(Loc: R.getBegin(),
7932 DiagID: diag::err_invalid_conversion_between_matrix_and_type)
7933 << DestTy << SrcTy << R;
7934 }
7935
7936 Kind = CK_MatrixCast;
7937 return false;
7938}
7939
7940bool Sema::CheckVectorCast(SourceRange R, QualType VectorTy, QualType Ty,
7941 CastKind &Kind) {
7942 assert(VectorTy->isVectorType() && "Not a vector type!");
7943
7944 if (Ty->isVectorType() || Ty->isIntegralType(Ctx: Context)) {
7945 if (!areLaxCompatibleVectorTypes(srcTy: Ty, destTy: VectorTy))
7946 return Diag(Loc: R.getBegin(),
7947 DiagID: Ty->isVectorType() ?
7948 diag::err_invalid_conversion_between_vectors :
7949 diag::err_invalid_conversion_between_vector_and_integer)
7950 << VectorTy << Ty << R;
7951 } else
7952 return Diag(Loc: R.getBegin(),
7953 DiagID: diag::err_invalid_conversion_between_vector_and_scalar)
7954 << VectorTy << Ty << R;
7955
7956 Kind = CK_BitCast;
7957 return false;
7958}
7959
7960ExprResult Sema::prepareVectorSplat(QualType VectorTy, Expr *SplattedExpr) {
7961 QualType DestElemTy = VectorTy->castAs<VectorType>()->getElementType();
7962
7963 if (DestElemTy == SplattedExpr->getType())
7964 return SplattedExpr;
7965
7966 assert(DestElemTy->isFloatingType() ||
7967 DestElemTy->isIntegralOrEnumerationType());
7968
7969 CastKind CK;
7970 if (VectorTy->isExtVectorType() && SplattedExpr->getType()->isBooleanType()) {
7971 // OpenCL requires that we convert `true` boolean expressions to -1, but
7972 // only when splatting vectors.
7973 if (DestElemTy->isFloatingType()) {
7974 // To avoid having to have a CK_BooleanToSignedFloating cast kind, we cast
7975 // in two steps: boolean to signed integral, then to floating.
7976 ExprResult CastExprRes = ImpCastExprToType(E: SplattedExpr, Type: Context.IntTy,
7977 CK: CK_BooleanToSignedIntegral);
7978 SplattedExpr = CastExprRes.get();
7979 CK = CK_IntegralToFloating;
7980 } else {
7981 CK = CK_BooleanToSignedIntegral;
7982 }
7983 } else {
7984 ExprResult CastExprRes = SplattedExpr;
7985 CK = PrepareScalarCast(Src&: CastExprRes, DestTy: DestElemTy);
7986 if (CastExprRes.isInvalid())
7987 return ExprError();
7988 SplattedExpr = CastExprRes.get();
7989 }
7990 return ImpCastExprToType(E: SplattedExpr, Type: DestElemTy, CK);
7991}
7992
7993ExprResult Sema::prepareMatrixSplat(QualType MatrixTy, Expr *SplattedExpr) {
7994 QualType DestElemTy = MatrixTy->castAs<MatrixType>()->getElementType();
7995
7996 if (DestElemTy == SplattedExpr->getType())
7997 return SplattedExpr;
7998
7999 assert(DestElemTy->isFloatingType() ||
8000 DestElemTy->isIntegralOrEnumerationType());
8001
8002 ExprResult CastExprRes = SplattedExpr;
8003 CastKind CK = PrepareScalarCast(Src&: CastExprRes, DestTy: DestElemTy);
8004 if (CastExprRes.isInvalid())
8005 return ExprError();
8006 SplattedExpr = CastExprRes.get();
8007
8008 return ImpCastExprToType(E: SplattedExpr, Type: DestElemTy, CK);
8009}
8010
8011ExprResult Sema::CheckExtVectorCast(SourceRange R, QualType DestTy,
8012 Expr *CastExpr, CastKind &Kind) {
8013 assert(DestTy->isExtVectorType() && "Not an extended vector type!");
8014
8015 QualType SrcTy = CastExpr->getType();
8016
8017 // If SrcTy is a VectorType, the total size must match to explicitly cast to
8018 // an ExtVectorType.
8019 // In OpenCL, casts between vectors of different types are not allowed.
8020 // (See OpenCL 6.2).
8021 if (SrcTy->isVectorType()) {
8022 if (!areLaxCompatibleVectorTypes(srcTy: SrcTy, destTy: DestTy) ||
8023 (getLangOpts().OpenCL &&
8024 !Context.hasSameUnqualifiedType(T1: DestTy, T2: SrcTy) &&
8025 !Context.areCompatibleVectorTypes(FirstVec: DestTy, SecondVec: SrcTy))) {
8026 Diag(Loc: R.getBegin(),DiagID: diag::err_invalid_conversion_between_ext_vectors)
8027 << DestTy << SrcTy << R;
8028 return ExprError();
8029 }
8030 Kind = CK_BitCast;
8031 return CastExpr;
8032 }
8033
8034 // All non-pointer scalars can be cast to ExtVector type. The appropriate
8035 // conversion will take place first from scalar to elt type, and then
8036 // splat from elt type to vector.
8037 if (SrcTy->isPointerType())
8038 return Diag(Loc: R.getBegin(),
8039 DiagID: diag::err_invalid_conversion_between_vector_and_scalar)
8040 << DestTy << SrcTy << R;
8041
8042 Kind = CK_VectorSplat;
8043 return prepareVectorSplat(VectorTy: DestTy, SplattedExpr: CastExpr);
8044}
8045
8046/// Check that a call to alloc_size function specifies sufficient space for the
8047/// destination type.
8048static void CheckSufficientAllocSize(Sema &S, QualType DestType,
8049 const Expr *E) {
8050 QualType SourceType = E->getType();
8051 if (!DestType->isPointerType() || !SourceType->isPointerType() ||
8052 DestType == SourceType)
8053 return;
8054
8055 const auto *CE = dyn_cast<CallExpr>(Val: E->IgnoreParenCasts());
8056 if (!CE)
8057 return;
8058
8059 // Find the total size allocated by the function call.
8060 if (!CE->getCalleeAllocSizeAttr())
8061 return;
8062 std::optional<llvm::APInt> AllocSize =
8063 CE->evaluateBytesReturnedByAllocSizeCall(Ctx: S.Context);
8064 // Allocations of size zero are permitted as a special case. They are usually
8065 // done intentionally.
8066 if (!AllocSize || AllocSize->isZero())
8067 return;
8068 auto Size = CharUnits::fromQuantity(Quantity: AllocSize->getZExtValue());
8069
8070 QualType TargetType = DestType->getPointeeType();
8071 // Find the destination size. As a special case function types have size of
8072 // one byte to match the sizeof operator behavior.
8073 auto LhsSize = TargetType->isFunctionType()
8074 ? CharUnits::One()
8075 : S.Context.getTypeSizeInCharsIfKnown(Ty: TargetType);
8076 if (LhsSize && Size < LhsSize)
8077 S.Diag(Loc: E->getExprLoc(), DiagID: diag::warn_alloc_size)
8078 << Size.getQuantity() << TargetType << LhsSize->getQuantity();
8079}
8080
8081ExprResult
8082Sema::ActOnCastExpr(Scope *S, SourceLocation LParenLoc,
8083 Declarator &D, ParsedType &Ty,
8084 SourceLocation RParenLoc, Expr *CastExpr) {
8085 assert(!D.isInvalidType() && (CastExpr != nullptr) &&
8086 "ActOnCastExpr(): missing type or expr");
8087
8088 TypeSourceInfo *castTInfo = GetTypeForDeclaratorCast(D, FromTy: CastExpr->getType());
8089 if (D.isInvalidType())
8090 return ExprError();
8091
8092 if (getLangOpts().CPlusPlus) {
8093 // Check that there are no default arguments (C++ only).
8094 CheckExtraCXXDefaultArguments(D);
8095 }
8096
8097 checkUnusedDeclAttributes(D);
8098
8099 QualType castType = castTInfo->getType();
8100 Ty = CreateParsedType(T: castType, TInfo: castTInfo);
8101
8102 bool isVectorLiteral = false;
8103
8104 // Check for an altivec or OpenCL literal,
8105 // i.e. all the elements are integer constants.
8106 ParenExpr *PE = dyn_cast<ParenExpr>(Val: CastExpr);
8107 ParenListExpr *PLE = dyn_cast<ParenListExpr>(Val: CastExpr);
8108 if ((getLangOpts().AltiVec || getLangOpts().ZVector || getLangOpts().OpenCL)
8109 && castType->isVectorType() && (PE || PLE)) {
8110 if (PLE && PLE->getNumExprs() == 0) {
8111 Diag(Loc: PLE->getExprLoc(), DiagID: diag::err_altivec_empty_initializer);
8112 return ExprError();
8113 }
8114 if (PE || PLE->getNumExprs() == 1) {
8115 Expr *E = (PE ? PE->getSubExpr() : PLE->getExpr(Init: 0));
8116 if (!E->isTypeDependent() && !E->getType()->isVectorType())
8117 isVectorLiteral = true;
8118 }
8119 else
8120 isVectorLiteral = true;
8121 }
8122
8123 // If this is a vector initializer, '(' type ')' '(' init, ..., init ')'
8124 // then handle it as such.
8125 if (isVectorLiteral)
8126 return BuildVectorLiteral(LParenLoc, RParenLoc, E: CastExpr, TInfo: castTInfo);
8127
8128 // If the Expr being casted is a ParenListExpr, handle it specially.
8129 // This is not an AltiVec-style cast, so turn the ParenListExpr into a
8130 // sequence of BinOp comma operators.
8131 if (isa<ParenListExpr>(Val: CastExpr)) {
8132 ExprResult Result = MaybeConvertParenListExprToParenExpr(S, ME: CastExpr);
8133 if (Result.isInvalid()) return ExprError();
8134 CastExpr = Result.get();
8135 }
8136
8137 if (getLangOpts().CPlusPlus && !castType->isVoidType())
8138 Diag(Loc: LParenLoc, DiagID: diag::warn_old_style_cast) << CastExpr->getSourceRange();
8139
8140 ObjC().CheckTollFreeBridgeCast(castType, castExpr: CastExpr);
8141
8142 ObjC().CheckObjCBridgeRelatedCast(castType, castExpr: CastExpr);
8143
8144 DiscardMisalignedMemberAddress(T: castType.getTypePtr(), E: CastExpr);
8145
8146 CheckSufficientAllocSize(S&: *this, DestType: castType, E: CastExpr);
8147
8148 return BuildCStyleCastExpr(LParenLoc, Ty: castTInfo, RParenLoc, Op: CastExpr);
8149}
8150
8151ExprResult Sema::BuildVectorLiteral(SourceLocation LParenLoc,
8152 SourceLocation RParenLoc, Expr *E,
8153 TypeSourceInfo *TInfo) {
8154 assert((isa<ParenListExpr>(E) || isa<ParenExpr>(E)) &&
8155 "Expected paren or paren list expression");
8156
8157 Expr **exprs;
8158 unsigned numExprs;
8159 Expr *subExpr;
8160 SourceLocation LiteralLParenLoc, LiteralRParenLoc;
8161 if (ParenListExpr *PE = dyn_cast<ParenListExpr>(Val: E)) {
8162 LiteralLParenLoc = PE->getLParenLoc();
8163 LiteralRParenLoc = PE->getRParenLoc();
8164 exprs = PE->getExprs();
8165 numExprs = PE->getNumExprs();
8166 } else { // isa<ParenExpr> by assertion at function entrance
8167 LiteralLParenLoc = cast<ParenExpr>(Val: E)->getLParen();
8168 LiteralRParenLoc = cast<ParenExpr>(Val: E)->getRParen();
8169 subExpr = cast<ParenExpr>(Val: E)->getSubExpr();
8170 exprs = &subExpr;
8171 numExprs = 1;
8172 }
8173
8174 QualType Ty = TInfo->getType();
8175 assert(Ty->isVectorType() && "Expected vector type");
8176
8177 SmallVector<Expr *, 8> initExprs;
8178 const VectorType *VTy = Ty->castAs<VectorType>();
8179 unsigned numElems = VTy->getNumElements();
8180
8181 // '(...)' form of vector initialization in AltiVec: the number of
8182 // initializers must be one or must match the size of the vector.
8183 // If a single value is specified in the initializer then it will be
8184 // replicated to all the components of the vector
8185 if (CheckAltivecInitFromScalar(R: E->getSourceRange(), VecTy: Ty,
8186 SrcTy: VTy->getElementType()))
8187 return ExprError();
8188 if (ShouldSplatAltivecScalarInCast(VecTy: VTy)) {
8189 // The number of initializers must be one or must match the size of the
8190 // vector. If a single value is specified in the initializer then it will
8191 // be replicated to all the components of the vector
8192 if (numExprs == 1) {
8193 QualType ElemTy = VTy->getElementType();
8194 ExprResult Literal = DefaultLvalueConversion(E: exprs[0]);
8195 if (Literal.isInvalid())
8196 return ExprError();
8197 Literal = ImpCastExprToType(E: Literal.get(), Type: ElemTy,
8198 CK: PrepareScalarCast(Src&: Literal, DestTy: ElemTy));
8199 return BuildCStyleCastExpr(LParenLoc, Ty: TInfo, RParenLoc, Op: Literal.get());
8200 }
8201 else if (numExprs < numElems) {
8202 Diag(Loc: E->getExprLoc(),
8203 DiagID: diag::err_incorrect_number_of_vector_initializers);
8204 return ExprError();
8205 }
8206 else
8207 initExprs.append(in_start: exprs, in_end: exprs + numExprs);
8208 }
8209 else {
8210 // For OpenCL, when the number of initializers is a single value,
8211 // it will be replicated to all components of the vector.
8212 if (getLangOpts().OpenCL && VTy->getVectorKind() == VectorKind::Generic &&
8213 numExprs == 1) {
8214 QualType SrcTy = exprs[0]->getType();
8215 if (!SrcTy->isArithmeticType()) {
8216 Diag(Loc: exprs[0]->getBeginLoc(), DiagID: diag::err_typecheck_convert_incompatible)
8217 << Ty << SrcTy << AssignmentAction::Initializing << /*elidable=*/0
8218 << /*c_style=*/0 << /*cast_kind=*/"" << exprs[0]->getSourceRange();
8219 return ExprError();
8220 }
8221 QualType ElemTy = VTy->getElementType();
8222 ExprResult Literal = DefaultLvalueConversion(E: exprs[0]);
8223 if (Literal.isInvalid())
8224 return ExprError();
8225 Literal = ImpCastExprToType(E: Literal.get(), Type: ElemTy,
8226 CK: PrepareScalarCast(Src&: Literal, DestTy: ElemTy));
8227 return BuildCStyleCastExpr(LParenLoc, Ty: TInfo, RParenLoc, Op: Literal.get());
8228 }
8229
8230 initExprs.append(in_start: exprs, in_end: exprs + numExprs);
8231 }
8232 // FIXME: This means that pretty-printing the final AST will produce curly
8233 // braces instead of the original commas.
8234 InitListExpr *initE = new (Context) InitListExpr(Context, LiteralLParenLoc,
8235 initExprs, LiteralRParenLoc);
8236 initE->setType(Ty);
8237 return BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc, LiteralExpr: initE);
8238}
8239
8240ExprResult
8241Sema::MaybeConvertParenListExprToParenExpr(Scope *S, Expr *OrigExpr) {
8242 ParenListExpr *E = dyn_cast<ParenListExpr>(Val: OrigExpr);
8243 if (!E)
8244 return OrigExpr;
8245
8246 ExprResult Result(E->getExpr(Init: 0));
8247
8248 for (unsigned i = 1, e = E->getNumExprs(); i != e && !Result.isInvalid(); ++i)
8249 Result = ActOnBinOp(S, TokLoc: E->getExprLoc(), Kind: tok::comma, LHSExpr: Result.get(),
8250 RHSExpr: E->getExpr(Init: i));
8251
8252 if (Result.isInvalid()) return ExprError();
8253
8254 return ActOnParenExpr(L: E->getLParenLoc(), R: E->getRParenLoc(), E: Result.get());
8255}
8256
8257ExprResult Sema::ActOnParenListExpr(SourceLocation L,
8258 SourceLocation R,
8259 MultiExprArg Val) {
8260 return ParenListExpr::Create(Ctx: Context, LParenLoc: L, Exprs: Val, RParenLoc: R);
8261}
8262
8263ExprResult Sema::ActOnCXXParenListInitExpr(ArrayRef<Expr *> Args, QualType T,
8264 unsigned NumUserSpecifiedExprs,
8265 SourceLocation InitLoc,
8266 SourceLocation LParenLoc,
8267 SourceLocation RParenLoc) {
8268 return CXXParenListInitExpr::Create(C&: Context, Args, T, NumUserSpecifiedExprs,
8269 InitLoc, LParenLoc, RParenLoc);
8270}
8271
8272bool Sema::DiagnoseConditionalForNull(const Expr *LHSExpr, const Expr *RHSExpr,
8273 SourceLocation QuestionLoc) {
8274 const Expr *NullExpr = LHSExpr;
8275 const Expr *NonPointerExpr = RHSExpr;
8276 Expr::NullPointerConstantKind NullKind =
8277 NullExpr->isNullPointerConstant(Ctx&: Context,
8278 NPC: Expr::NPC_ValueDependentIsNotNull);
8279
8280 if (NullKind == Expr::NPCK_NotNull) {
8281 NullExpr = RHSExpr;
8282 NonPointerExpr = LHSExpr;
8283 NullKind =
8284 NullExpr->isNullPointerConstant(Ctx&: Context,
8285 NPC: Expr::NPC_ValueDependentIsNotNull);
8286 }
8287
8288 if (NullKind == Expr::NPCK_NotNull)
8289 return false;
8290
8291 if (NullKind == Expr::NPCK_ZeroExpression)
8292 return false;
8293
8294 if (NullKind == Expr::NPCK_ZeroLiteral) {
8295 // In this case, check to make sure that we got here from a "NULL"
8296 // string in the source code.
8297 NullExpr = NullExpr->IgnoreParenImpCasts();
8298 SourceLocation loc = NullExpr->getExprLoc();
8299 if (!findMacroSpelling(loc, name: "NULL"))
8300 return false;
8301 }
8302
8303 int DiagType = (NullKind == Expr::NPCK_CXX11_nullptr);
8304 Diag(Loc: QuestionLoc, DiagID: diag::err_typecheck_cond_incompatible_operands_null)
8305 << NonPointerExpr->getType() << DiagType
8306 << NonPointerExpr->getSourceRange();
8307 return true;
8308}
8309
8310/// Return false if the condition expression is valid, true otherwise.
8311static bool checkCondition(Sema &S, const Expr *Cond,
8312 SourceLocation QuestionLoc) {
8313 QualType CondTy = Cond->getType();
8314
8315 // OpenCL v1.1 s6.3.i says the condition cannot be a floating point type.
8316 if (S.getLangOpts().OpenCL && CondTy->isFloatingType()) {
8317 S.Diag(Loc: QuestionLoc, DiagID: diag::err_typecheck_cond_expect_nonfloat)
8318 << CondTy << Cond->getSourceRange();
8319 return true;
8320 }
8321
8322 // C99 6.5.15p2
8323 if (CondTy->isScalarType()) return false;
8324
8325 S.Diag(Loc: QuestionLoc, DiagID: diag::err_typecheck_cond_expect_scalar)
8326 << CondTy << Cond->getSourceRange();
8327 return true;
8328}
8329
8330/// Return false if the NullExpr can be promoted to PointerTy,
8331/// true otherwise.
8332static bool checkConditionalNullPointer(Sema &S, ExprResult &NullExpr,
8333 QualType PointerTy) {
8334 if ((!PointerTy->isAnyPointerType() && !PointerTy->isBlockPointerType()) ||
8335 !NullExpr.get()->isNullPointerConstant(Ctx&: S.Context,
8336 NPC: Expr::NPC_ValueDependentIsNull))
8337 return true;
8338
8339 NullExpr = S.ImpCastExprToType(E: NullExpr.get(), Type: PointerTy, CK: CK_NullToPointer);
8340 return false;
8341}
8342
8343/// Checks compatibility between two pointers and return the resulting
8344/// type.
8345static QualType checkConditionalPointerCompatibility(Sema &S, ExprResult &LHS,
8346 ExprResult &RHS,
8347 SourceLocation Loc) {
8348 QualType LHSTy = LHS.get()->getType();
8349 QualType RHSTy = RHS.get()->getType();
8350
8351 if (S.Context.hasSameType(T1: LHSTy, T2: RHSTy)) {
8352 // Two identical pointers types are always compatible.
8353 return S.Context.getCommonSugaredType(X: LHSTy, Y: RHSTy);
8354 }
8355
8356 QualType lhptee, rhptee;
8357
8358 // Get the pointee types.
8359 bool IsBlockPointer = false;
8360 if (const BlockPointerType *LHSBTy = LHSTy->getAs<BlockPointerType>()) {
8361 lhptee = LHSBTy->getPointeeType();
8362 rhptee = RHSTy->castAs<BlockPointerType>()->getPointeeType();
8363 IsBlockPointer = true;
8364 } else {
8365 lhptee = LHSTy->castAs<PointerType>()->getPointeeType();
8366 rhptee = RHSTy->castAs<PointerType>()->getPointeeType();
8367 }
8368
8369 // C99 6.5.15p6: If both operands are pointers to compatible types or to
8370 // differently qualified versions of compatible types, the result type is
8371 // a pointer to an appropriately qualified version of the composite
8372 // type.
8373
8374 // Only CVR-qualifiers exist in the standard, and the differently-qualified
8375 // clause doesn't make sense for our extensions. E.g. address space 2 should
8376 // be incompatible with address space 3: they may live on different devices or
8377 // anything.
8378 Qualifiers lhQual = lhptee.getQualifiers();
8379 Qualifiers rhQual = rhptee.getQualifiers();
8380
8381 LangAS ResultAddrSpace = LangAS::Default;
8382 LangAS LAddrSpace = lhQual.getAddressSpace();
8383 LangAS RAddrSpace = rhQual.getAddressSpace();
8384
8385 // OpenCL v1.1 s6.5 - Conversion between pointers to distinct address
8386 // spaces is disallowed.
8387 if (lhQual.isAddressSpaceSupersetOf(other: rhQual, Ctx: S.getASTContext()))
8388 ResultAddrSpace = LAddrSpace;
8389 else if (rhQual.isAddressSpaceSupersetOf(other: lhQual, Ctx: S.getASTContext()))
8390 ResultAddrSpace = RAddrSpace;
8391 else {
8392 S.Diag(Loc, DiagID: diag::err_typecheck_op_on_nonoverlapping_address_space_pointers)
8393 << LHSTy << RHSTy << 2 << LHS.get()->getSourceRange()
8394 << RHS.get()->getSourceRange();
8395 return QualType();
8396 }
8397
8398 unsigned MergedCVRQual = lhQual.getCVRQualifiers() | rhQual.getCVRQualifiers();
8399 auto LHSCastKind = CK_BitCast, RHSCastKind = CK_BitCast;
8400 lhQual.removeCVRQualifiers();
8401 rhQual.removeCVRQualifiers();
8402
8403 if (!lhQual.getPointerAuth().isEquivalent(Other: rhQual.getPointerAuth())) {
8404 S.Diag(Loc, DiagID: diag::err_typecheck_cond_incompatible_ptrauth)
8405 << LHSTy << RHSTy << LHS.get()->getSourceRange()
8406 << RHS.get()->getSourceRange();
8407 return QualType();
8408 }
8409
8410 // OpenCL v2.0 specification doesn't extend compatibility of type qualifiers
8411 // (C99 6.7.3) for address spaces. We assume that the check should behave in
8412 // the same manner as it's defined for CVR qualifiers, so for OpenCL two
8413 // qual types are compatible iff
8414 // * corresponded types are compatible
8415 // * CVR qualifiers are equal
8416 // * address spaces are equal
8417 // Thus for conditional operator we merge CVR and address space unqualified
8418 // pointees and if there is a composite type we return a pointer to it with
8419 // merged qualifiers.
8420 LHSCastKind =
8421 LAddrSpace == ResultAddrSpace ? CK_BitCast : CK_AddressSpaceConversion;
8422 RHSCastKind =
8423 RAddrSpace == ResultAddrSpace ? CK_BitCast : CK_AddressSpaceConversion;
8424 lhQual.removeAddressSpace();
8425 rhQual.removeAddressSpace();
8426
8427 lhptee = S.Context.getQualifiedType(T: lhptee.getUnqualifiedType(), Qs: lhQual);
8428 rhptee = S.Context.getQualifiedType(T: rhptee.getUnqualifiedType(), Qs: rhQual);
8429
8430 QualType CompositeTy = S.Context.mergeTypes(
8431 lhptee, rhptee, /*OfBlockPointer=*/false, /*Unqualified=*/false,
8432 /*BlockReturnType=*/false, /*IsConditionalOperator=*/true);
8433
8434 if (CompositeTy.isNull()) {
8435 // In this situation, we assume void* type. No especially good
8436 // reason, but this is what gcc does, and we do have to pick
8437 // to get a consistent AST.
8438 QualType incompatTy;
8439 incompatTy = S.Context.getPointerType(
8440 T: S.Context.getAddrSpaceQualType(T: S.Context.VoidTy, AddressSpace: ResultAddrSpace));
8441 LHS = S.ImpCastExprToType(E: LHS.get(), Type: incompatTy, CK: LHSCastKind);
8442 RHS = S.ImpCastExprToType(E: RHS.get(), Type: incompatTy, CK: RHSCastKind);
8443
8444 // FIXME: For OpenCL the warning emission and cast to void* leaves a room
8445 // for casts between types with incompatible address space qualifiers.
8446 // For the following code the compiler produces casts between global and
8447 // local address spaces of the corresponded innermost pointees:
8448 // local int *global *a;
8449 // global int *global *b;
8450 // a = (0 ? a : b); // see C99 6.5.16.1.p1.
8451 S.Diag(Loc, DiagID: diag::ext_typecheck_cond_incompatible_pointers)
8452 << LHSTy << RHSTy << LHS.get()->getSourceRange()
8453 << RHS.get()->getSourceRange();
8454
8455 return incompatTy;
8456 }
8457
8458 // The pointer types are compatible.
8459 // In case of OpenCL ResultTy should have the address space qualifier
8460 // which is a superset of address spaces of both the 2nd and the 3rd
8461 // operands of the conditional operator.
8462 QualType ResultTy = [&, ResultAddrSpace]() {
8463 if (S.getLangOpts().OpenCL) {
8464 Qualifiers CompositeQuals = CompositeTy.getQualifiers();
8465 CompositeQuals.setAddressSpace(ResultAddrSpace);
8466 return S.Context
8467 .getQualifiedType(T: CompositeTy.getUnqualifiedType(), Qs: CompositeQuals)
8468 .withCVRQualifiers(CVR: MergedCVRQual);
8469 }
8470 return CompositeTy.withCVRQualifiers(CVR: MergedCVRQual);
8471 }();
8472 if (IsBlockPointer)
8473 ResultTy = S.Context.getBlockPointerType(T: ResultTy);
8474 else
8475 ResultTy = S.Context.getPointerType(T: ResultTy);
8476
8477 LHS = S.ImpCastExprToType(E: LHS.get(), Type: ResultTy, CK: LHSCastKind);
8478 RHS = S.ImpCastExprToType(E: RHS.get(), Type: ResultTy, CK: RHSCastKind);
8479 return ResultTy;
8480}
8481
8482/// Return the resulting type when the operands are both block pointers.
8483static QualType checkConditionalBlockPointerCompatibility(Sema &S,
8484 ExprResult &LHS,
8485 ExprResult &RHS,
8486 SourceLocation Loc) {
8487 QualType LHSTy = LHS.get()->getType();
8488 QualType RHSTy = RHS.get()->getType();
8489
8490 if (!LHSTy->isBlockPointerType() || !RHSTy->isBlockPointerType()) {
8491 if (LHSTy->isVoidPointerType() || RHSTy->isVoidPointerType()) {
8492 QualType destType = S.Context.getPointerType(T: S.Context.VoidTy);
8493 LHS = S.ImpCastExprToType(E: LHS.get(), Type: destType, CK: CK_BitCast);
8494 RHS = S.ImpCastExprToType(E: RHS.get(), Type: destType, CK: CK_BitCast);
8495 return destType;
8496 }
8497 S.Diag(Loc, DiagID: diag::err_typecheck_cond_incompatible_operands)
8498 << LHSTy << RHSTy << LHS.get()->getSourceRange()
8499 << RHS.get()->getSourceRange();
8500 return QualType();
8501 }
8502
8503 // We have 2 block pointer types.
8504 return checkConditionalPointerCompatibility(S, LHS, RHS, Loc);
8505}
8506
8507/// Return the resulting type when the operands are both pointers.
8508static QualType
8509checkConditionalObjectPointersCompatibility(Sema &S, ExprResult &LHS,
8510 ExprResult &RHS,
8511 SourceLocation Loc) {
8512 // get the pointer types
8513 QualType LHSTy = LHS.get()->getType();
8514 QualType RHSTy = RHS.get()->getType();
8515
8516 // get the "pointed to" types
8517 QualType lhptee = LHSTy->castAs<PointerType>()->getPointeeType();
8518 QualType rhptee = RHSTy->castAs<PointerType>()->getPointeeType();
8519
8520 // ignore qualifiers on void (C99 6.5.15p3, clause 6)
8521 if (lhptee->isVoidType() && rhptee->isIncompleteOrObjectType()) {
8522 // Figure out necessary qualifiers (C99 6.5.15p6)
8523 QualType destPointee
8524 = S.Context.getQualifiedType(T: lhptee, Qs: rhptee.getQualifiers());
8525 QualType destType = S.Context.getPointerType(T: destPointee);
8526 // Add qualifiers if necessary.
8527 LHS = S.ImpCastExprToType(E: LHS.get(), Type: destType, CK: CK_NoOp);
8528 // Promote to void*.
8529 RHS = S.ImpCastExprToType(E: RHS.get(), Type: destType, CK: CK_BitCast);
8530 return destType;
8531 }
8532 if (rhptee->isVoidType() && lhptee->isIncompleteOrObjectType()) {
8533 QualType destPointee
8534 = S.Context.getQualifiedType(T: rhptee, Qs: lhptee.getQualifiers());
8535 QualType destType = S.Context.getPointerType(T: destPointee);
8536 // Add qualifiers if necessary.
8537 RHS = S.ImpCastExprToType(E: RHS.get(), Type: destType, CK: CK_NoOp);
8538 // Promote to void*.
8539 LHS = S.ImpCastExprToType(E: LHS.get(), Type: destType, CK: CK_BitCast);
8540 return destType;
8541 }
8542
8543 return checkConditionalPointerCompatibility(S, LHS, RHS, Loc);
8544}
8545
8546/// Return false if the first expression is not an integer and the second
8547/// expression is not a pointer, true otherwise.
8548static bool checkPointerIntegerMismatch(Sema &S, ExprResult &Int,
8549 Expr* PointerExpr, SourceLocation Loc,
8550 bool IsIntFirstExpr) {
8551 if (!PointerExpr->getType()->isPointerType() ||
8552 !Int.get()->getType()->isIntegerType())
8553 return false;
8554
8555 Expr *Expr1 = IsIntFirstExpr ? Int.get() : PointerExpr;
8556 Expr *Expr2 = IsIntFirstExpr ? PointerExpr : Int.get();
8557
8558 S.Diag(Loc, DiagID: diag::ext_typecheck_cond_pointer_integer_mismatch)
8559 << Expr1->getType() << Expr2->getType()
8560 << Expr1->getSourceRange() << Expr2->getSourceRange();
8561 Int = S.ImpCastExprToType(E: Int.get(), Type: PointerExpr->getType(),
8562 CK: CK_IntegralToPointer);
8563 return true;
8564}
8565
8566/// Simple conversion between integer and floating point types.
8567///
8568/// Used when handling the OpenCL conditional operator where the
8569/// condition is a vector while the other operands are scalar.
8570///
8571/// OpenCL v1.1 s6.3.i and s6.11.6 together require that the scalar
8572/// types are either integer or floating type. Between the two
8573/// operands, the type with the higher rank is defined as the "result
8574/// type". The other operand needs to be promoted to the same type. No
8575/// other type promotion is allowed. We cannot use
8576/// UsualArithmeticConversions() for this purpose, since it always
8577/// promotes promotable types.
8578static QualType OpenCLArithmeticConversions(Sema &S, ExprResult &LHS,
8579 ExprResult &RHS,
8580 SourceLocation QuestionLoc) {
8581 LHS = S.DefaultFunctionArrayLvalueConversion(E: LHS.get());
8582 if (LHS.isInvalid())
8583 return QualType();
8584 RHS = S.DefaultFunctionArrayLvalueConversion(E: RHS.get());
8585 if (RHS.isInvalid())
8586 return QualType();
8587
8588 // For conversion purposes, we ignore any qualifiers.
8589 // For example, "const float" and "float" are equivalent.
8590 QualType LHSType =
8591 S.Context.getCanonicalType(T: LHS.get()->getType()).getUnqualifiedType();
8592 QualType RHSType =
8593 S.Context.getCanonicalType(T: RHS.get()->getType()).getUnqualifiedType();
8594
8595 if (!LHSType->isIntegerType() && !LHSType->isRealFloatingType()) {
8596 S.Diag(Loc: QuestionLoc, DiagID: diag::err_typecheck_cond_expect_int_float)
8597 << LHSType << LHS.get()->getSourceRange();
8598 return QualType();
8599 }
8600
8601 if (!RHSType->isIntegerType() && !RHSType->isRealFloatingType()) {
8602 S.Diag(Loc: QuestionLoc, DiagID: diag::err_typecheck_cond_expect_int_float)
8603 << RHSType << RHS.get()->getSourceRange();
8604 return QualType();
8605 }
8606
8607 // If both types are identical, no conversion is needed.
8608 if (LHSType == RHSType)
8609 return LHSType;
8610
8611 // Now handle "real" floating types (i.e. float, double, long double).
8612 if (LHSType->isRealFloatingType() || RHSType->isRealFloatingType())
8613 return handleFloatConversion(S, LHS, RHS, LHSType, RHSType,
8614 /*IsCompAssign = */ false);
8615
8616 // Finally, we have two differing integer types.
8617 return handleIntegerConversion<doIntegralCast, doIntegralCast>
8618 (S, LHS, RHS, LHSType, RHSType, /*IsCompAssign = */ false);
8619}
8620
8621/// Convert scalar operands to a vector that matches the
8622/// condition in length.
8623///
8624/// Used when handling the OpenCL conditional operator where the
8625/// condition is a vector while the other operands are scalar.
8626///
8627/// We first compute the "result type" for the scalar operands
8628/// according to OpenCL v1.1 s6.3.i. Both operands are then converted
8629/// into a vector of that type where the length matches the condition
8630/// vector type. s6.11.6 requires that the element types of the result
8631/// and the condition must have the same number of bits.
8632static QualType
8633OpenCLConvertScalarsToVectors(Sema &S, ExprResult &LHS, ExprResult &RHS,
8634 QualType CondTy, SourceLocation QuestionLoc) {
8635 QualType ResTy = OpenCLArithmeticConversions(S, LHS, RHS, QuestionLoc);
8636 if (ResTy.isNull()) return QualType();
8637
8638 const VectorType *CV = CondTy->getAs<VectorType>();
8639 assert(CV);
8640
8641 // Determine the vector result type
8642 unsigned NumElements = CV->getNumElements();
8643 QualType VectorTy = S.Context.getExtVectorType(VectorType: ResTy, NumElts: NumElements);
8644
8645 // Ensure that all types have the same number of bits
8646 if (S.Context.getTypeSize(T: CV->getElementType())
8647 != S.Context.getTypeSize(T: ResTy)) {
8648 // Since VectorTy is created internally, it does not pretty print
8649 // with an OpenCL name. Instead, we just print a description.
8650 std::string EleTyName = ResTy.getUnqualifiedType().getAsString();
8651 SmallString<64> Str;
8652 llvm::raw_svector_ostream OS(Str);
8653 OS << "(vector of " << NumElements << " '" << EleTyName << "' values)";
8654 S.Diag(Loc: QuestionLoc, DiagID: diag::err_conditional_vector_element_size)
8655 << CondTy << OS.str();
8656 return QualType();
8657 }
8658
8659 // Convert operands to the vector result type
8660 LHS = S.ImpCastExprToType(E: LHS.get(), Type: VectorTy, CK: CK_VectorSplat);
8661 RHS = S.ImpCastExprToType(E: RHS.get(), Type: VectorTy, CK: CK_VectorSplat);
8662
8663 return VectorTy;
8664}
8665
8666/// Return false if this is a valid OpenCL condition vector
8667static bool checkOpenCLConditionVector(Sema &S, Expr *Cond,
8668 SourceLocation QuestionLoc) {
8669 // OpenCL v1.1 s6.11.6 says the elements of the vector must be of
8670 // integral type.
8671 const VectorType *CondTy = Cond->getType()->getAs<VectorType>();
8672 assert(CondTy);
8673 QualType EleTy = CondTy->getElementType();
8674 if (EleTy->isIntegerType()) return false;
8675
8676 S.Diag(Loc: QuestionLoc, DiagID: diag::err_typecheck_cond_expect_nonfloat)
8677 << Cond->getType() << Cond->getSourceRange();
8678 return true;
8679}
8680
8681/// Return false if the vector condition type and the vector
8682/// result type are compatible.
8683///
8684/// OpenCL v1.1 s6.11.6 requires that both vector types have the same
8685/// number of elements, and their element types have the same number
8686/// of bits.
8687static bool checkVectorResult(Sema &S, QualType CondTy, QualType VecResTy,
8688 SourceLocation QuestionLoc) {
8689 const VectorType *CV = CondTy->getAs<VectorType>();
8690 const VectorType *RV = VecResTy->getAs<VectorType>();
8691 assert(CV && RV);
8692
8693 if (CV->getNumElements() != RV->getNumElements()) {
8694 S.Diag(Loc: QuestionLoc, DiagID: diag::err_conditional_vector_size)
8695 << CondTy << VecResTy;
8696 return true;
8697 }
8698
8699 QualType CVE = CV->getElementType();
8700 QualType RVE = RV->getElementType();
8701
8702 // Boolean vectors are permitted outside of OpenCL mode.
8703 if (S.Context.getTypeSize(T: CVE) != S.Context.getTypeSize(T: RVE) &&
8704 (!CVE->isBooleanType() || S.LangOpts.OpenCL)) {
8705 S.Diag(Loc: QuestionLoc, DiagID: diag::err_conditional_vector_element_size)
8706 << CondTy << VecResTy;
8707 return true;
8708 }
8709
8710 return false;
8711}
8712
8713/// Return the resulting type for the conditional operator in
8714/// OpenCL (aka "ternary selection operator", OpenCL v1.1
8715/// s6.3.i) when the condition is a vector type.
8716static QualType
8717OpenCLCheckVectorConditional(Sema &S, ExprResult &Cond,
8718 ExprResult &LHS, ExprResult &RHS,
8719 SourceLocation QuestionLoc) {
8720 Cond = S.DefaultFunctionArrayLvalueConversion(E: Cond.get());
8721 if (Cond.isInvalid())
8722 return QualType();
8723 QualType CondTy = Cond.get()->getType();
8724
8725 if (checkOpenCLConditionVector(S, Cond: Cond.get(), QuestionLoc))
8726 return QualType();
8727
8728 // If either operand is a vector then find the vector type of the
8729 // result as specified in OpenCL v1.1 s6.3.i.
8730 if (LHS.get()->getType()->isVectorType() ||
8731 RHS.get()->getType()->isVectorType()) {
8732 bool IsBoolVecLang =
8733 !S.getLangOpts().OpenCL && !S.getLangOpts().OpenCLCPlusPlus;
8734 QualType VecResTy =
8735 S.CheckVectorOperands(LHS, RHS, Loc: QuestionLoc,
8736 /*isCompAssign*/ IsCompAssign: false,
8737 /*AllowBothBool*/ true,
8738 /*AllowBoolConversions*/ AllowBoolConversion: false,
8739 /*AllowBooleanOperation*/ AllowBoolOperation: IsBoolVecLang,
8740 /*ReportInvalid*/ true);
8741 if (VecResTy.isNull())
8742 return QualType();
8743 // The result type must match the condition type as specified in
8744 // OpenCL v1.1 s6.11.6.
8745 if (checkVectorResult(S, CondTy, VecResTy, QuestionLoc))
8746 return QualType();
8747 return VecResTy;
8748 }
8749
8750 // Both operands are scalar.
8751 return OpenCLConvertScalarsToVectors(S, LHS, RHS, CondTy, QuestionLoc);
8752}
8753
8754/// Return true if the Expr is block type
8755static bool checkBlockType(Sema &S, const Expr *E) {
8756 if (E->getType()->isBlockPointerType()) {
8757 S.Diag(Loc: E->getExprLoc(), DiagID: diag::err_opencl_ternary_with_block);
8758 return true;
8759 }
8760
8761 if (const CallExpr *CE = dyn_cast<CallExpr>(Val: E)) {
8762 QualType Ty = CE->getCallee()->getType();
8763 if (Ty->isBlockPointerType()) {
8764 S.Diag(Loc: E->getExprLoc(), DiagID: diag::err_opencl_ternary_with_block);
8765 return true;
8766 }
8767 }
8768 return false;
8769}
8770
8771/// Note that LHS is not null here, even if this is the gnu "x ?: y" extension.
8772/// In that case, LHS = cond.
8773/// C99 6.5.15
8774QualType Sema::CheckConditionalOperands(ExprResult &Cond, ExprResult &LHS,
8775 ExprResult &RHS, ExprValueKind &VK,
8776 ExprObjectKind &OK,
8777 SourceLocation QuestionLoc) {
8778
8779 ExprResult LHSResult = CheckPlaceholderExpr(E: LHS.get());
8780 if (!LHSResult.isUsable()) return QualType();
8781 LHS = LHSResult;
8782
8783 ExprResult RHSResult = CheckPlaceholderExpr(E: RHS.get());
8784 if (!RHSResult.isUsable()) return QualType();
8785 RHS = RHSResult;
8786
8787 // C++ is sufficiently different to merit its own checker.
8788 if (getLangOpts().CPlusPlus)
8789 return CXXCheckConditionalOperands(cond&: Cond, lhs&: LHS, rhs&: RHS, VK, OK, questionLoc: QuestionLoc);
8790
8791 VK = VK_PRValue;
8792 OK = OK_Ordinary;
8793
8794 if (Context.isDependenceAllowed() &&
8795 (Cond.get()->isTypeDependent() || LHS.get()->isTypeDependent() ||
8796 RHS.get()->isTypeDependent())) {
8797 assert(!getLangOpts().CPlusPlus);
8798 assert((Cond.get()->containsErrors() || LHS.get()->containsErrors() ||
8799 RHS.get()->containsErrors()) &&
8800 "should only occur in error-recovery path.");
8801 return Context.DependentTy;
8802 }
8803
8804 // The OpenCL operator with a vector condition is sufficiently
8805 // different to merit its own checker.
8806 if ((getLangOpts().OpenCL && Cond.get()->getType()->isVectorType()) ||
8807 Cond.get()->getType()->isExtVectorType())
8808 return OpenCLCheckVectorConditional(S&: *this, Cond, LHS, RHS, QuestionLoc);
8809
8810 // First, check the condition.
8811 Cond = UsualUnaryConversions(E: Cond.get());
8812 if (Cond.isInvalid())
8813 return QualType();
8814 if (checkCondition(S&: *this, Cond: Cond.get(), QuestionLoc))
8815 return QualType();
8816
8817 // Handle vectors.
8818 if (LHS.get()->getType()->isVectorType() ||
8819 RHS.get()->getType()->isVectorType())
8820 return CheckVectorOperands(LHS, RHS, Loc: QuestionLoc, /*isCompAssign*/ IsCompAssign: false,
8821 /*AllowBothBool*/ true,
8822 /*AllowBoolConversions*/ AllowBoolConversion: false,
8823 /*AllowBooleanOperation*/ AllowBoolOperation: false,
8824 /*ReportInvalid*/ true);
8825
8826 QualType ResTy = UsualArithmeticConversions(LHS, RHS, Loc: QuestionLoc,
8827 ACK: ArithConvKind::Conditional);
8828 if (LHS.isInvalid() || RHS.isInvalid())
8829 return QualType();
8830
8831 // WebAssembly tables are not allowed as conditional LHS or RHS.
8832 QualType LHSTy = LHS.get()->getType();
8833 QualType RHSTy = RHS.get()->getType();
8834 if (LHSTy->isWebAssemblyTableType() || RHSTy->isWebAssemblyTableType()) {
8835 Diag(Loc: QuestionLoc, DiagID: diag::err_wasm_table_conditional_expression)
8836 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
8837 return QualType();
8838 }
8839
8840 // Diagnose attempts to convert between __ibm128, __float128 and long double
8841 // where such conversions currently can't be handled.
8842 if (unsupportedTypeConversion(S: *this, LHSType: LHSTy, RHSType: RHSTy)) {
8843 Diag(Loc: QuestionLoc,
8844 DiagID: diag::err_typecheck_cond_incompatible_operands) << LHSTy << RHSTy
8845 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
8846 return QualType();
8847 }
8848
8849 // OpenCL v2.0 s6.12.5 - Blocks cannot be used as expressions of the ternary
8850 // selection operator (?:).
8851 if (getLangOpts().OpenCL &&
8852 ((int)checkBlockType(S&: *this, E: LHS.get()) | (int)checkBlockType(S&: *this, E: RHS.get()))) {
8853 return QualType();
8854 }
8855
8856 // If both operands have arithmetic type, do the usual arithmetic conversions
8857 // to find a common type: C99 6.5.15p3,5.
8858 if (LHSTy->isArithmeticType() && RHSTy->isArithmeticType()) {
8859 // Disallow invalid arithmetic conversions, such as those between bit-
8860 // precise integers types of different sizes, or between a bit-precise
8861 // integer and another type.
8862 if (ResTy.isNull() && (LHSTy->isBitIntType() || RHSTy->isBitIntType())) {
8863 Diag(Loc: QuestionLoc, DiagID: diag::err_typecheck_cond_incompatible_operands)
8864 << LHSTy << RHSTy << LHS.get()->getSourceRange()
8865 << RHS.get()->getSourceRange();
8866 return QualType();
8867 }
8868
8869 LHS = ImpCastExprToType(E: LHS.get(), Type: ResTy, CK: PrepareScalarCast(Src&: LHS, DestTy: ResTy));
8870 RHS = ImpCastExprToType(E: RHS.get(), Type: ResTy, CK: PrepareScalarCast(Src&: RHS, DestTy: ResTy));
8871
8872 return ResTy;
8873 }
8874
8875 // If both operands are the same structure or union type, the result is that
8876 // type.
8877 // FIXME: Type of conditional expression must be complete in C mode.
8878 if (LHSTy->isRecordType() &&
8879 Context.hasSameUnqualifiedType(T1: LHSTy, T2: RHSTy)) // C99 6.5.15p3
8880 return Context.getCommonSugaredType(X: LHSTy.getUnqualifiedType(),
8881 Y: RHSTy.getUnqualifiedType());
8882
8883 // C99 6.5.15p5: "If both operands have void type, the result has void type."
8884 // The following || allows only one side to be void (a GCC-ism).
8885 if (LHSTy->isVoidType() || RHSTy->isVoidType()) {
8886 QualType ResTy;
8887 if (LHSTy->isVoidType() && RHSTy->isVoidType()) {
8888 ResTy = Context.getCommonSugaredType(X: LHSTy, Y: RHSTy);
8889 } else if (RHSTy->isVoidType()) {
8890 ResTy = RHSTy;
8891 Diag(Loc: RHS.get()->getBeginLoc(), DiagID: diag::ext_typecheck_cond_one_void)
8892 << RHS.get()->getSourceRange();
8893 } else {
8894 ResTy = LHSTy;
8895 Diag(Loc: LHS.get()->getBeginLoc(), DiagID: diag::ext_typecheck_cond_one_void)
8896 << LHS.get()->getSourceRange();
8897 }
8898 LHS = ImpCastExprToType(E: LHS.get(), Type: ResTy, CK: CK_ToVoid);
8899 RHS = ImpCastExprToType(E: RHS.get(), Type: ResTy, CK: CK_ToVoid);
8900 return ResTy;
8901 }
8902
8903 // C23 6.5.15p7:
8904 // ... if both the second and third operands have nullptr_t type, the
8905 // result also has that type.
8906 if (LHSTy->isNullPtrType() && Context.hasSameType(T1: LHSTy, T2: RHSTy))
8907 return ResTy;
8908
8909 // C99 6.5.15p6 - "if one operand is a null pointer constant, the result has
8910 // the type of the other operand."
8911 if (!checkConditionalNullPointer(S&: *this, NullExpr&: RHS, PointerTy: LHSTy)) return LHSTy;
8912 if (!checkConditionalNullPointer(S&: *this, NullExpr&: LHS, PointerTy: RHSTy)) return RHSTy;
8913
8914 // All objective-c pointer type analysis is done here.
8915 QualType compositeType =
8916 ObjC().FindCompositeObjCPointerType(LHS, RHS, QuestionLoc);
8917 if (LHS.isInvalid() || RHS.isInvalid())
8918 return QualType();
8919 if (!compositeType.isNull())
8920 return compositeType;
8921
8922
8923 // Handle block pointer types.
8924 if (LHSTy->isBlockPointerType() || RHSTy->isBlockPointerType())
8925 return checkConditionalBlockPointerCompatibility(S&: *this, LHS, RHS,
8926 Loc: QuestionLoc);
8927
8928 // Check constraints for C object pointers types (C99 6.5.15p3,6).
8929 if (LHSTy->isPointerType() && RHSTy->isPointerType())
8930 return checkConditionalObjectPointersCompatibility(S&: *this, LHS, RHS,
8931 Loc: QuestionLoc);
8932
8933 // GCC compatibility: soften pointer/integer mismatch. Note that
8934 // null pointers have been filtered out by this point.
8935 if (checkPointerIntegerMismatch(S&: *this, Int&: LHS, PointerExpr: RHS.get(), Loc: QuestionLoc,
8936 /*IsIntFirstExpr=*/true))
8937 return RHSTy;
8938 if (checkPointerIntegerMismatch(S&: *this, Int&: RHS, PointerExpr: LHS.get(), Loc: QuestionLoc,
8939 /*IsIntFirstExpr=*/false))
8940 return LHSTy;
8941
8942 // Emit a better diagnostic if one of the expressions is a null pointer
8943 // constant and the other is not a pointer type. In this case, the user most
8944 // likely forgot to take the address of the other expression.
8945 if (DiagnoseConditionalForNull(LHSExpr: LHS.get(), RHSExpr: RHS.get(), QuestionLoc))
8946 return QualType();
8947
8948 // Finally, if the LHS and RHS types are canonically the same type, we can
8949 // use the common sugared type.
8950 if (Context.hasSameType(T1: LHSTy, T2: RHSTy))
8951 return Context.getCommonSugaredType(X: LHSTy, Y: RHSTy);
8952
8953 // Otherwise, the operands are not compatible.
8954 Diag(Loc: QuestionLoc, DiagID: diag::err_typecheck_cond_incompatible_operands)
8955 << LHSTy << RHSTy << LHS.get()->getSourceRange()
8956 << RHS.get()->getSourceRange();
8957 return QualType();
8958}
8959
8960/// SuggestParentheses - Emit a note with a fixit hint that wraps
8961/// ParenRange in parentheses.
8962static void SuggestParentheses(Sema &Self, SourceLocation Loc,
8963 const PartialDiagnostic &Note,
8964 SourceRange ParenRange) {
8965 SourceLocation EndLoc = Self.getLocForEndOfToken(Loc: ParenRange.getEnd());
8966 if (ParenRange.getBegin().isFileID() && ParenRange.getEnd().isFileID() &&
8967 EndLoc.isValid()) {
8968 Self.Diag(Loc, PD: Note)
8969 << FixItHint::CreateInsertion(InsertionLoc: ParenRange.getBegin(), Code: "(")
8970 << FixItHint::CreateInsertion(InsertionLoc: EndLoc, Code: ")");
8971 } else {
8972 // We can't display the parentheses, so just show the bare note.
8973 Self.Diag(Loc, PD: Note) << ParenRange;
8974 }
8975}
8976
8977static bool IsArithmeticOp(BinaryOperatorKind Opc) {
8978 return BinaryOperator::isAdditiveOp(Opc) ||
8979 BinaryOperator::isMultiplicativeOp(Opc) ||
8980 BinaryOperator::isShiftOp(Opc) || Opc == BO_And || Opc == BO_Or;
8981 // This only checks for bitwise-or and bitwise-and, but not bitwise-xor and
8982 // not any of the logical operators. Bitwise-xor is commonly used as a
8983 // logical-xor because there is no logical-xor operator. The logical
8984 // operators, including uses of xor, have a high false positive rate for
8985 // precedence warnings.
8986}
8987
8988/// IsArithmeticBinaryExpr - Returns true if E is an arithmetic binary
8989/// expression, either using a built-in or overloaded operator,
8990/// and sets *OpCode to the opcode and *RHSExprs to the right-hand side
8991/// expression.
8992static bool IsArithmeticBinaryExpr(const Expr *E, BinaryOperatorKind *Opcode,
8993 const Expr **RHSExprs) {
8994 // Don't strip parenthesis: we should not warn if E is in parenthesis.
8995 E = E->IgnoreImpCasts();
8996 E = E->IgnoreConversionOperatorSingleStep();
8997 E = E->IgnoreImpCasts();
8998 if (const auto *MTE = dyn_cast<MaterializeTemporaryExpr>(Val: E)) {
8999 E = MTE->getSubExpr();
9000 E = E->IgnoreImpCasts();
9001 }
9002
9003 // Built-in binary operator.
9004 if (const auto *OP = dyn_cast<BinaryOperator>(Val: E);
9005 OP && IsArithmeticOp(Opc: OP->getOpcode())) {
9006 *Opcode = OP->getOpcode();
9007 *RHSExprs = OP->getRHS();
9008 return true;
9009 }
9010
9011 // Overloaded operator.
9012 if (const auto *Call = dyn_cast<CXXOperatorCallExpr>(Val: E)) {
9013 if (Call->getNumArgs() != 2)
9014 return false;
9015
9016 // Make sure this is really a binary operator that is safe to pass into
9017 // BinaryOperator::getOverloadedOpcode(), e.g. it's not a subscript op.
9018 OverloadedOperatorKind OO = Call->getOperator();
9019 if (OO < OO_Plus || OO > OO_Arrow ||
9020 OO == OO_PlusPlus || OO == OO_MinusMinus)
9021 return false;
9022
9023 BinaryOperatorKind OpKind = BinaryOperator::getOverloadedOpcode(OO);
9024 if (IsArithmeticOp(Opc: OpKind)) {
9025 *Opcode = OpKind;
9026 *RHSExprs = Call->getArg(Arg: 1);
9027 return true;
9028 }
9029 }
9030
9031 return false;
9032}
9033
9034/// ExprLooksBoolean - Returns true if E looks boolean, i.e. it has boolean type
9035/// or is a logical expression such as (x==y) which has int type, but is
9036/// commonly interpreted as boolean.
9037static bool ExprLooksBoolean(const Expr *E) {
9038 E = E->IgnoreParenImpCasts();
9039
9040 if (E->getType()->isBooleanType())
9041 return true;
9042 if (const auto *OP = dyn_cast<BinaryOperator>(Val: E))
9043 return OP->isComparisonOp() || OP->isLogicalOp();
9044 if (const auto *OP = dyn_cast<UnaryOperator>(Val: E))
9045 return OP->getOpcode() == UO_LNot;
9046 if (E->getType()->isPointerType())
9047 return true;
9048 // FIXME: What about overloaded operator calls returning "unspecified boolean
9049 // type"s (commonly pointer-to-members)?
9050
9051 return false;
9052}
9053
9054/// DiagnoseConditionalPrecedence - Emit a warning when a conditional operator
9055/// and binary operator are mixed in a way that suggests the programmer assumed
9056/// the conditional operator has higher precedence, for example:
9057/// "int x = a + someBinaryCondition ? 1 : 2".
9058static void DiagnoseConditionalPrecedence(Sema &Self, SourceLocation OpLoc,
9059 Expr *Condition, const Expr *LHSExpr,
9060 const Expr *RHSExpr) {
9061 BinaryOperatorKind CondOpcode;
9062 const Expr *CondRHS;
9063
9064 if (!IsArithmeticBinaryExpr(E: Condition, Opcode: &CondOpcode, RHSExprs: &CondRHS))
9065 return;
9066 if (!ExprLooksBoolean(E: CondRHS))
9067 return;
9068
9069 // The condition is an arithmetic binary expression, with a right-
9070 // hand side that looks boolean, so warn.
9071
9072 unsigned DiagID = BinaryOperator::isBitwiseOp(Opc: CondOpcode)
9073 ? diag::warn_precedence_bitwise_conditional
9074 : diag::warn_precedence_conditional;
9075
9076 Self.Diag(Loc: OpLoc, DiagID)
9077 << Condition->getSourceRange()
9078 << BinaryOperator::getOpcodeStr(Op: CondOpcode);
9079
9080 SuggestParentheses(
9081 Self, Loc: OpLoc,
9082 Note: Self.PDiag(DiagID: diag::note_precedence_silence)
9083 << BinaryOperator::getOpcodeStr(Op: CondOpcode),
9084 ParenRange: SourceRange(Condition->getBeginLoc(), Condition->getEndLoc()));
9085
9086 SuggestParentheses(Self, Loc: OpLoc,
9087 Note: Self.PDiag(DiagID: diag::note_precedence_conditional_first),
9088 ParenRange: SourceRange(CondRHS->getBeginLoc(), RHSExpr->getEndLoc()));
9089}
9090
9091/// Compute the nullability of a conditional expression.
9092static QualType computeConditionalNullability(QualType ResTy, bool IsBin,
9093 QualType LHSTy, QualType RHSTy,
9094 ASTContext &Ctx) {
9095 if (!ResTy->isAnyPointerType())
9096 return ResTy;
9097
9098 auto GetNullability = [](QualType Ty) {
9099 std::optional<NullabilityKind> Kind = Ty->getNullability();
9100 if (Kind) {
9101 // For our purposes, treat _Nullable_result as _Nullable.
9102 if (*Kind == NullabilityKind::NullableResult)
9103 return NullabilityKind::Nullable;
9104 return *Kind;
9105 }
9106 return NullabilityKind::Unspecified;
9107 };
9108
9109 auto LHSKind = GetNullability(LHSTy), RHSKind = GetNullability(RHSTy);
9110 NullabilityKind MergedKind;
9111
9112 // Compute nullability of a binary conditional expression.
9113 if (IsBin) {
9114 if (LHSKind == NullabilityKind::NonNull)
9115 MergedKind = NullabilityKind::NonNull;
9116 else
9117 MergedKind = RHSKind;
9118 // Compute nullability of a normal conditional expression.
9119 } else {
9120 if (LHSKind == NullabilityKind::Nullable ||
9121 RHSKind == NullabilityKind::Nullable)
9122 MergedKind = NullabilityKind::Nullable;
9123 else if (LHSKind == NullabilityKind::NonNull)
9124 MergedKind = RHSKind;
9125 else if (RHSKind == NullabilityKind::NonNull)
9126 MergedKind = LHSKind;
9127 else
9128 MergedKind = NullabilityKind::Unspecified;
9129 }
9130
9131 // Return if ResTy already has the correct nullability.
9132 if (GetNullability(ResTy) == MergedKind)
9133 return ResTy;
9134
9135 // Strip all nullability from ResTy.
9136 while (ResTy->getNullability())
9137 ResTy = ResTy.getSingleStepDesugaredType(Context: Ctx);
9138
9139 // Create a new AttributedType with the new nullability kind.
9140 return Ctx.getAttributedType(nullability: MergedKind, modifiedType: ResTy, equivalentType: ResTy);
9141}
9142
9143ExprResult Sema::ActOnConditionalOp(SourceLocation QuestionLoc,
9144 SourceLocation ColonLoc,
9145 Expr *CondExpr, Expr *LHSExpr,
9146 Expr *RHSExpr) {
9147 // If this is the gnu "x ?: y" extension, analyze the types as though the LHS
9148 // was the condition.
9149 OpaqueValueExpr *opaqueValue = nullptr;
9150 Expr *commonExpr = nullptr;
9151 if (!LHSExpr) {
9152 commonExpr = CondExpr;
9153 // Lower out placeholder types first. This is important so that we don't
9154 // try to capture a placeholder. This happens in few cases in C++; such
9155 // as Objective-C++'s dictionary subscripting syntax.
9156 if (commonExpr->hasPlaceholderType()) {
9157 ExprResult result = CheckPlaceholderExpr(E: commonExpr);
9158 if (!result.isUsable()) return ExprError();
9159 commonExpr = result.get();
9160 }
9161 // We usually want to apply unary conversions *before* saving, except
9162 // in the special case of a C++ l-value conditional.
9163 if (!(getLangOpts().CPlusPlus
9164 && !commonExpr->isTypeDependent()
9165 && commonExpr->getValueKind() == RHSExpr->getValueKind()
9166 && commonExpr->isGLValue()
9167 && commonExpr->isOrdinaryOrBitFieldObject()
9168 && RHSExpr->isOrdinaryOrBitFieldObject()
9169 && Context.hasSameType(T1: commonExpr->getType(), T2: RHSExpr->getType()))) {
9170 ExprResult commonRes = UsualUnaryConversions(E: commonExpr);
9171 if (commonRes.isInvalid())
9172 return ExprError();
9173 commonExpr = commonRes.get();
9174 }
9175
9176 // If the common expression is a class or array prvalue, materialize it
9177 // so that we can safely refer to it multiple times.
9178 if (commonExpr->isPRValue() && (commonExpr->getType()->isRecordType() ||
9179 commonExpr->getType()->isArrayType())) {
9180 ExprResult MatExpr = TemporaryMaterializationConversion(E: commonExpr);
9181 if (MatExpr.isInvalid())
9182 return ExprError();
9183 commonExpr = MatExpr.get();
9184 }
9185
9186 opaqueValue = new (Context) OpaqueValueExpr(commonExpr->getExprLoc(),
9187 commonExpr->getType(),
9188 commonExpr->getValueKind(),
9189 commonExpr->getObjectKind(),
9190 commonExpr);
9191 LHSExpr = CondExpr = opaqueValue;
9192 }
9193
9194 QualType LHSTy = LHSExpr->getType(), RHSTy = RHSExpr->getType();
9195 ExprValueKind VK = VK_PRValue;
9196 ExprObjectKind OK = OK_Ordinary;
9197 ExprResult Cond = CondExpr, LHS = LHSExpr, RHS = RHSExpr;
9198 QualType result = CheckConditionalOperands(Cond, LHS, RHS,
9199 VK, OK, QuestionLoc);
9200 if (result.isNull() || Cond.isInvalid() || LHS.isInvalid() ||
9201 RHS.isInvalid())
9202 return ExprError();
9203
9204 DiagnoseConditionalPrecedence(Self&: *this, OpLoc: QuestionLoc, Condition: Cond.get(), LHSExpr: LHS.get(),
9205 RHSExpr: RHS.get());
9206
9207 CheckBoolLikeConversion(E: Cond.get(), CC: QuestionLoc);
9208
9209 result = computeConditionalNullability(ResTy: result, IsBin: commonExpr, LHSTy, RHSTy,
9210 Ctx&: Context);
9211
9212 if (!commonExpr)
9213 return new (Context)
9214 ConditionalOperator(Cond.get(), QuestionLoc, LHS.get(), ColonLoc,
9215 RHS.get(), result, VK, OK);
9216
9217 return new (Context) BinaryConditionalOperator(
9218 commonExpr, opaqueValue, Cond.get(), LHS.get(), RHS.get(), QuestionLoc,
9219 ColonLoc, result, VK, OK);
9220}
9221
9222bool Sema::IsInvalidSMECallConversion(QualType FromType, QualType ToType) {
9223 unsigned FromAttributes = 0, ToAttributes = 0;
9224 if (const auto *FromFn =
9225 dyn_cast<FunctionProtoType>(Val: Context.getCanonicalType(T: FromType)))
9226 FromAttributes =
9227 FromFn->getAArch64SMEAttributes() & FunctionType::SME_AttributeMask;
9228 if (const auto *ToFn =
9229 dyn_cast<FunctionProtoType>(Val: Context.getCanonicalType(T: ToType)))
9230 ToAttributes =
9231 ToFn->getAArch64SMEAttributes() & FunctionType::SME_AttributeMask;
9232
9233 return FromAttributes != ToAttributes;
9234}
9235
9236// checkPointerTypesForAssignment - This is a very tricky routine (despite
9237// being closely modeled after the C99 spec:-). The odd characteristic of this
9238// routine is it effectively iqnores the qualifiers on the top level pointee.
9239// This circumvents the usual type rules specified in 6.2.7p1 & 6.7.5.[1-3].
9240// FIXME: add a couple examples in this comment.
9241static AssignConvertType checkPointerTypesForAssignment(Sema &S,
9242 QualType LHSType,
9243 QualType RHSType,
9244 SourceLocation Loc) {
9245 assert(LHSType.isCanonical() && "LHS not canonicalized!");
9246 assert(RHSType.isCanonical() && "RHS not canonicalized!");
9247
9248 // get the "pointed to" type (ignoring qualifiers at the top level)
9249 const Type *lhptee, *rhptee;
9250 Qualifiers lhq, rhq;
9251 std::tie(args&: lhptee, args&: lhq) =
9252 cast<PointerType>(Val&: LHSType)->getPointeeType().split().asPair();
9253 std::tie(args&: rhptee, args&: rhq) =
9254 cast<PointerType>(Val&: RHSType)->getPointeeType().split().asPair();
9255
9256 AssignConvertType ConvTy = AssignConvertType::Compatible;
9257
9258 // C99 6.5.16.1p1: This following citation is common to constraints
9259 // 3 & 4 (below). ...and the type *pointed to* by the left has all the
9260 // qualifiers of the type *pointed to* by the right;
9261
9262 // As a special case, 'non-__weak A *' -> 'non-__weak const *' is okay.
9263 if (lhq.getObjCLifetime() != rhq.getObjCLifetime() &&
9264 lhq.compatiblyIncludesObjCLifetime(other: rhq)) {
9265 // Ignore lifetime for further calculation.
9266 lhq.removeObjCLifetime();
9267 rhq.removeObjCLifetime();
9268 }
9269
9270 if (!lhq.compatiblyIncludes(other: rhq, Ctx: S.getASTContext())) {
9271 // Treat address-space mismatches as fatal.
9272 if (!lhq.isAddressSpaceSupersetOf(other: rhq, Ctx: S.getASTContext()))
9273 return AssignConvertType::IncompatiblePointerDiscardsQualifiers;
9274
9275 // It's okay to add or remove GC or lifetime qualifiers when converting to
9276 // and from void*.
9277 else if (lhq.withoutObjCGCAttr().withoutObjCLifetime().compatiblyIncludes(
9278 other: rhq.withoutObjCGCAttr().withoutObjCLifetime(),
9279 Ctx: S.getASTContext()) &&
9280 (lhptee->isVoidType() || rhptee->isVoidType()))
9281 ; // keep old
9282
9283 // Treat lifetime mismatches as fatal.
9284 else if (lhq.getObjCLifetime() != rhq.getObjCLifetime())
9285 ConvTy = AssignConvertType::IncompatiblePointerDiscardsQualifiers;
9286
9287 // Treat pointer-auth mismatches as fatal.
9288 else if (!lhq.getPointerAuth().isEquivalent(Other: rhq.getPointerAuth()))
9289 ConvTy = AssignConvertType::IncompatiblePointerDiscardsQualifiers;
9290
9291 // For GCC/MS compatibility, other qualifier mismatches are treated
9292 // as still compatible in C.
9293 else
9294 ConvTy = AssignConvertType::CompatiblePointerDiscardsQualifiers;
9295 }
9296
9297 // C99 6.5.16.1p1 (constraint 4): If one operand is a pointer to an object or
9298 // incomplete type and the other is a pointer to a qualified or unqualified
9299 // version of void...
9300 if (lhptee->isVoidType()) {
9301 if (rhptee->isIncompleteOrObjectType())
9302 return ConvTy;
9303
9304 // As an extension, we allow cast to/from void* to function pointer.
9305 assert(rhptee->isFunctionType());
9306 return AssignConvertType::FunctionVoidPointer;
9307 }
9308
9309 if (rhptee->isVoidType()) {
9310 // In C, void * to another pointer type is compatible, but we want to note
9311 // that there will be an implicit conversion happening here.
9312 if (lhptee->isIncompleteOrObjectType())
9313 return ConvTy == AssignConvertType::Compatible &&
9314 !S.getLangOpts().CPlusPlus
9315 ? AssignConvertType::CompatibleVoidPtrToNonVoidPtr
9316 : ConvTy;
9317
9318 // As an extension, we allow cast to/from void* to function pointer.
9319 assert(lhptee->isFunctionType());
9320 return AssignConvertType::FunctionVoidPointer;
9321 }
9322
9323 if (!S.Diags.isIgnored(
9324 DiagID: diag::warn_typecheck_convert_incompatible_function_pointer_strict,
9325 Loc) &&
9326 RHSType->isFunctionPointerType() && LHSType->isFunctionPointerType() &&
9327 !S.TryFunctionConversion(FromType: RHSType, ToType: LHSType, ResultTy&: RHSType))
9328 return AssignConvertType::IncompatibleFunctionPointerStrict;
9329
9330 // C99 6.5.16.1p1 (constraint 3): both operands are pointers to qualified or
9331 // unqualified versions of compatible types, ...
9332 QualType ltrans = QualType(lhptee, 0), rtrans = QualType(rhptee, 0);
9333
9334 if (ltrans->isOverflowBehaviorType() || rtrans->isOverflowBehaviorType()) {
9335 if (!S.Context.hasSameType(T1: ltrans, T2: rtrans)) {
9336 QualType LUnderlying =
9337 ltrans->isOverflowBehaviorType()
9338 ? ltrans->castAs<OverflowBehaviorType>()->getUnderlyingType()
9339 : ltrans;
9340 QualType RUnderlying =
9341 rtrans->isOverflowBehaviorType()
9342 ? rtrans->castAs<OverflowBehaviorType>()->getUnderlyingType()
9343 : rtrans;
9344
9345 if (S.Context.hasSameType(T1: LUnderlying, T2: RUnderlying))
9346 return AssignConvertType::IncompatiblePointerDiscardsOverflowBehavior;
9347
9348 ltrans = LUnderlying;
9349 rtrans = RUnderlying;
9350 }
9351 }
9352
9353 if (!S.Context.typesAreCompatible(T1: ltrans, T2: rtrans)) {
9354 // Check if the pointee types are compatible ignoring the sign.
9355 // We explicitly check for char so that we catch "char" vs
9356 // "unsigned char" on systems where "char" is unsigned.
9357 if (lhptee->isCharType())
9358 ltrans = S.Context.UnsignedCharTy;
9359 else if (lhptee->hasSignedIntegerRepresentation())
9360 ltrans = S.Context.getCorrespondingUnsignedType(T: ltrans);
9361
9362 if (rhptee->isCharType())
9363 rtrans = S.Context.UnsignedCharTy;
9364 else if (rhptee->hasSignedIntegerRepresentation())
9365 rtrans = S.Context.getCorrespondingUnsignedType(T: rtrans);
9366
9367 if (ltrans == rtrans) {
9368 // Types are compatible ignoring the sign. Qualifier incompatibility
9369 // takes priority over sign incompatibility because the sign
9370 // warning can be disabled.
9371 if (!S.IsAssignConvertCompatible(ConvTy))
9372 return ConvTy;
9373
9374 return AssignConvertType::IncompatiblePointerSign;
9375 }
9376
9377 // If we are a multi-level pointer, it's possible that our issue is simply
9378 // one of qualification - e.g. char ** -> const char ** is not allowed. If
9379 // the eventual target type is the same and the pointers have the same
9380 // level of indirection, this must be the issue.
9381 if (isa<PointerType>(Val: lhptee) && isa<PointerType>(Val: rhptee)) {
9382 do {
9383 std::tie(args&: lhptee, args&: lhq) =
9384 cast<PointerType>(Val: lhptee)->getPointeeType().split().asPair();
9385 std::tie(args&: rhptee, args&: rhq) =
9386 cast<PointerType>(Val: rhptee)->getPointeeType().split().asPair();
9387
9388 // Inconsistent address spaces at this point is invalid, even if the
9389 // address spaces would be compatible.
9390 // FIXME: This doesn't catch address space mismatches for pointers of
9391 // different nesting levels, like:
9392 // __local int *** a;
9393 // int ** b = a;
9394 // It's not clear how to actually determine when such pointers are
9395 // invalidly incompatible.
9396 if (lhq.getAddressSpace() != rhq.getAddressSpace())
9397 return AssignConvertType::
9398 IncompatibleNestedPointerAddressSpaceMismatch;
9399
9400 } while (isa<PointerType>(Val: lhptee) && isa<PointerType>(Val: rhptee));
9401
9402 if (lhptee == rhptee)
9403 return AssignConvertType::IncompatibleNestedPointerQualifiers;
9404 }
9405
9406 // General pointer incompatibility takes priority over qualifiers.
9407 if (RHSType->isFunctionPointerType() && LHSType->isFunctionPointerType())
9408 return AssignConvertType::IncompatibleFunctionPointer;
9409 return AssignConvertType::IncompatiblePointer;
9410 }
9411 // Note: in C++, typesAreCompatible(ltrans, rtrans) will have guaranteed
9412 // hasSameType, so we can skip further checks.
9413 const auto *LFT = ltrans->getAs<FunctionType>();
9414 const auto *RFT = rtrans->getAs<FunctionType>();
9415 if (!S.getLangOpts().CPlusPlus && LFT && RFT) {
9416 // The invocation of IsFunctionConversion below will try to transform rtrans
9417 // to obtain an exact match for ltrans. This should not fail because of
9418 // mismatches in result type and parameter types, they were already checked
9419 // by typesAreCompatible above. So we will recreate rtrans (or where
9420 // appropriate ltrans) using the result type and parameter types from ltrans
9421 // (respectively rtrans), but keeping its ExtInfo/ExtProtoInfo.
9422 const auto *LFPT = dyn_cast<FunctionProtoType>(Val: LFT);
9423 const auto *RFPT = dyn_cast<FunctionProtoType>(Val: RFT);
9424 if (LFPT && RFPT) {
9425 rtrans = S.Context.getFunctionType(ResultTy: LFPT->getReturnType(),
9426 Args: LFPT->getParamTypes(),
9427 EPI: RFPT->getExtProtoInfo());
9428 } else if (LFPT) {
9429 FunctionProtoType::ExtProtoInfo EPI;
9430 EPI.ExtInfo = RFT->getExtInfo();
9431 rtrans = S.Context.getFunctionType(ResultTy: LFPT->getReturnType(),
9432 Args: LFPT->getParamTypes(), EPI);
9433 } else if (RFPT) {
9434 // In this case, we want to retain rtrans as a FunctionProtoType, to keep
9435 // all of its ExtProtoInfo. Transform ltrans instead.
9436 FunctionProtoType::ExtProtoInfo EPI;
9437 EPI.ExtInfo = LFT->getExtInfo();
9438 ltrans = S.Context.getFunctionType(ResultTy: RFPT->getReturnType(),
9439 Args: RFPT->getParamTypes(), EPI);
9440 } else {
9441 rtrans = S.Context.getFunctionNoProtoType(ResultTy: LFT->getReturnType(),
9442 Info: RFT->getExtInfo());
9443 }
9444 if (!S.Context.hasSameUnqualifiedType(T1: rtrans, T2: ltrans) &&
9445 !S.IsFunctionConversion(FromType: rtrans, ToType: ltrans))
9446 return AssignConvertType::IncompatibleFunctionPointer;
9447 }
9448 return ConvTy;
9449}
9450
9451/// checkBlockPointerTypesForAssignment - This routine determines whether two
9452/// block pointer types are compatible or whether a block and normal pointer
9453/// are compatible. It is more restrict than comparing two function pointer
9454// types.
9455static AssignConvertType checkBlockPointerTypesForAssignment(Sema &S,
9456 QualType LHSType,
9457 QualType RHSType) {
9458 assert(LHSType.isCanonical() && "LHS not canonicalized!");
9459 assert(RHSType.isCanonical() && "RHS not canonicalized!");
9460
9461 QualType lhptee, rhptee;
9462
9463 // get the "pointed to" type (ignoring qualifiers at the top level)
9464 lhptee = cast<BlockPointerType>(Val&: LHSType)->getPointeeType();
9465 rhptee = cast<BlockPointerType>(Val&: RHSType)->getPointeeType();
9466
9467 // In C++, the types have to match exactly.
9468 if (S.getLangOpts().CPlusPlus)
9469 return AssignConvertType::IncompatibleBlockPointer;
9470
9471 AssignConvertType ConvTy = AssignConvertType::Compatible;
9472
9473 // For blocks we enforce that qualifiers are identical.
9474 Qualifiers LQuals = lhptee.getLocalQualifiers();
9475 Qualifiers RQuals = rhptee.getLocalQualifiers();
9476 if (S.getLangOpts().OpenCL) {
9477 LQuals.removeAddressSpace();
9478 RQuals.removeAddressSpace();
9479 }
9480 if (LQuals != RQuals)
9481 ConvTy = AssignConvertType::CompatiblePointerDiscardsQualifiers;
9482
9483 // FIXME: OpenCL doesn't define the exact compile time semantics for a block
9484 // assignment.
9485 // The current behavior is similar to C++ lambdas. A block might be
9486 // assigned to a variable iff its return type and parameters are compatible
9487 // (C99 6.2.7) with the corresponding return type and parameters of the LHS of
9488 // an assignment. Presumably it should behave in way that a function pointer
9489 // assignment does in C, so for each parameter and return type:
9490 // * CVR and address space of LHS should be a superset of CVR and address
9491 // space of RHS.
9492 // * unqualified types should be compatible.
9493 if (S.getLangOpts().OpenCL) {
9494 if (!S.Context.typesAreBlockPointerCompatible(
9495 S.Context.getQualifiedType(T: LHSType.getUnqualifiedType(), Qs: LQuals),
9496 S.Context.getQualifiedType(T: RHSType.getUnqualifiedType(), Qs: RQuals)))
9497 return AssignConvertType::IncompatibleBlockPointer;
9498 } else if (!S.Context.typesAreBlockPointerCompatible(LHSType, RHSType))
9499 return AssignConvertType::IncompatibleBlockPointer;
9500
9501 return ConvTy;
9502}
9503
9504/// checkObjCPointerTypesForAssignment - Compares two objective-c pointer types
9505/// for assignment compatibility.
9506static AssignConvertType checkObjCPointerTypesForAssignment(Sema &S,
9507 QualType LHSType,
9508 QualType RHSType) {
9509 assert(LHSType.isCanonical() && "LHS was not canonicalized!");
9510 assert(RHSType.isCanonical() && "RHS was not canonicalized!");
9511
9512 if (LHSType->isObjCBuiltinType()) {
9513 // Class is not compatible with ObjC object pointers.
9514 if (LHSType->isObjCClassType() && !RHSType->isObjCBuiltinType() &&
9515 !RHSType->isObjCQualifiedClassType())
9516 return AssignConvertType::IncompatiblePointer;
9517 return AssignConvertType::Compatible;
9518 }
9519 if (RHSType->isObjCBuiltinType()) {
9520 if (RHSType->isObjCClassType() && !LHSType->isObjCBuiltinType() &&
9521 !LHSType->isObjCQualifiedClassType())
9522 return AssignConvertType::IncompatiblePointer;
9523 return AssignConvertType::Compatible;
9524 }
9525 QualType lhptee = LHSType->castAs<ObjCObjectPointerType>()->getPointeeType();
9526 QualType rhptee = RHSType->castAs<ObjCObjectPointerType>()->getPointeeType();
9527
9528 if (!lhptee.isAtLeastAsQualifiedAs(other: rhptee, Ctx: S.getASTContext()) &&
9529 // make an exception for id<P>
9530 !LHSType->isObjCQualifiedIdType())
9531 return AssignConvertType::CompatiblePointerDiscardsQualifiers;
9532
9533 if (S.Context.typesAreCompatible(T1: LHSType, T2: RHSType))
9534 return AssignConvertType::Compatible;
9535 if (LHSType->isObjCQualifiedIdType() || RHSType->isObjCQualifiedIdType())
9536 return AssignConvertType::IncompatibleObjCQualifiedId;
9537 return AssignConvertType::IncompatiblePointer;
9538}
9539
9540AssignConvertType Sema::CheckAssignmentConstraints(SourceLocation Loc,
9541 QualType LHSType,
9542 QualType RHSType) {
9543 // Fake up an opaque expression. We don't actually care about what
9544 // cast operations are required, so if CheckAssignmentConstraints
9545 // adds casts to this they'll be wasted, but fortunately that doesn't
9546 // usually happen on valid code.
9547 OpaqueValueExpr RHSExpr(Loc, RHSType, VK_PRValue);
9548 ExprResult RHSPtr = &RHSExpr;
9549 CastKind K;
9550
9551 return CheckAssignmentConstraints(LHSType, RHS&: RHSPtr, Kind&: K, /*ConvertRHS=*/false);
9552}
9553
9554/// This helper function returns true if QT is a vector type that has element
9555/// type ElementType.
9556static bool isVector(QualType QT, QualType ElementType) {
9557 if (const VectorType *VT = QT->getAs<VectorType>())
9558 return VT->getElementType().getCanonicalType() == ElementType;
9559 return false;
9560}
9561
9562/// CheckAssignmentConstraints (C99 6.5.16) - This routine currently
9563/// has code to accommodate several GCC extensions when type checking
9564/// pointers. Here are some objectionable examples that GCC considers warnings:
9565///
9566/// int a, *pint;
9567/// short *pshort;
9568/// struct foo *pfoo;
9569///
9570/// pint = pshort; // warning: assignment from incompatible pointer type
9571/// a = pint; // warning: assignment makes integer from pointer without a cast
9572/// pint = a; // warning: assignment makes pointer from integer without a cast
9573/// pint = pfoo; // warning: assignment from incompatible pointer type
9574///
9575/// As a result, the code for dealing with pointers is more complex than the
9576/// C99 spec dictates.
9577///
9578/// Sets 'Kind' for any result kind except Incompatible.
9579AssignConvertType Sema::CheckAssignmentConstraints(QualType LHSType,
9580 ExprResult &RHS,
9581 CastKind &Kind,
9582 bool ConvertRHS) {
9583 QualType RHSType = RHS.get()->getType();
9584 QualType OrigLHSType = LHSType;
9585
9586 // Get canonical types. We're not formatting these types, just comparing
9587 // them.
9588 LHSType = Context.getCanonicalType(T: LHSType).getUnqualifiedType();
9589 RHSType = Context.getCanonicalType(T: RHSType).getUnqualifiedType();
9590
9591 // Common case: no conversion required.
9592 if (LHSType == RHSType) {
9593 Kind = CK_NoOp;
9594 return AssignConvertType::Compatible;
9595 }
9596
9597 // If the LHS has an __auto_type, there are no additional type constraints
9598 // to be worried about.
9599 if (const auto *AT = dyn_cast<AutoType>(Val&: LHSType)) {
9600 if (AT->isGNUAutoType()) {
9601 Kind = CK_NoOp;
9602 return AssignConvertType::Compatible;
9603 }
9604 }
9605
9606 auto OBTResult = Context.checkOBTAssignmentCompatibility(LHS: LHSType, RHS: RHSType);
9607 switch (OBTResult) {
9608 case ASTContext::OBTAssignResult::IncompatibleKinds:
9609 Kind = CK_NoOp;
9610 return AssignConvertType::IncompatibleOBTKinds;
9611 case ASTContext::OBTAssignResult::Discards:
9612 Kind = LHSType->isBooleanType() ? CK_IntegralToBoolean : CK_IntegralCast;
9613 return AssignConvertType::CompatibleOBTDiscards;
9614 case ASTContext::OBTAssignResult::Compatible:
9615 case ASTContext::OBTAssignResult::NotApplicable:
9616 break;
9617 }
9618
9619 // Check for incompatible OBT types in pointer pointee types
9620 if (LHSType->isPointerType() && RHSType->isPointerType()) {
9621 QualType LHSPointee = LHSType->getPointeeType();
9622 QualType RHSPointee = RHSType->getPointeeType();
9623 if ((LHSPointee->isOverflowBehaviorType() ||
9624 RHSPointee->isOverflowBehaviorType()) &&
9625 !Context.areCompatibleOverflowBehaviorTypes(LHS: LHSPointee, RHS: RHSPointee)) {
9626 Kind = CK_NoOp;
9627 return AssignConvertType::IncompatibleOBTKinds;
9628 }
9629 }
9630
9631 // If we have an atomic type, try a non-atomic assignment, then just add an
9632 // atomic qualification step.
9633 if (const AtomicType *AtomicTy = dyn_cast<AtomicType>(Val&: LHSType)) {
9634 AssignConvertType Result =
9635 CheckAssignmentConstraints(LHSType: AtomicTy->getValueType(), RHS, Kind);
9636 if (!IsAssignConvertCompatible(ConvTy: Result))
9637 return Result;
9638 if (Kind != CK_NoOp && ConvertRHS)
9639 RHS = ImpCastExprToType(E: RHS.get(), Type: AtomicTy->getValueType(), CK: Kind);
9640 Kind = CK_NonAtomicToAtomic;
9641 return Result;
9642 }
9643
9644 // If the left-hand side is a reference type, then we are in a
9645 // (rare!) case where we've allowed the use of references in C,
9646 // e.g., as a parameter type in a built-in function. In this case,
9647 // just make sure that the type referenced is compatible with the
9648 // right-hand side type. The caller is responsible for adjusting
9649 // LHSType so that the resulting expression does not have reference
9650 // type.
9651 if (const ReferenceType *LHSTypeRef = LHSType->getAs<ReferenceType>()) {
9652 if (Context.typesAreCompatible(T1: LHSTypeRef->getPointeeType(), T2: RHSType)) {
9653 Kind = CK_LValueBitCast;
9654 return AssignConvertType::Compatible;
9655 }
9656 return AssignConvertType::Incompatible;
9657 }
9658
9659 // Allow scalar to ExtVector assignments, assignment to bool, and assignments
9660 // of an ExtVector type to the same ExtVector type.
9661 if (auto *LHSExtType = LHSType->getAs<ExtVectorType>()) {
9662 if (auto *RHSExtType = RHSType->getAs<ExtVectorType>()) {
9663 // Implicit conversions require the same number of elements.
9664 if (LHSExtType->getNumElements() != RHSExtType->getNumElements())
9665 return AssignConvertType::Incompatible;
9666
9667 if (LHSType->isExtVectorBoolType() &&
9668 RHSExtType->getElementType()->isIntegerType()) {
9669 Kind = CK_IntegralToBoolean;
9670 return AssignConvertType::Compatible;
9671 }
9672 // In OpenCL, allow compatible vector types (e.g. half to _Float16)
9673 if (Context.getLangOpts().OpenCL &&
9674 Context.areCompatibleVectorTypes(FirstVec: LHSType, SecondVec: RHSType)) {
9675 Kind = CK_BitCast;
9676 return AssignConvertType::Compatible;
9677 }
9678 return AssignConvertType::Incompatible;
9679 }
9680 if (RHSType->isArithmeticType()) {
9681 // CK_VectorSplat does T -> vector T, so first cast to the element type.
9682 if (ConvertRHS)
9683 RHS = prepareVectorSplat(VectorTy: LHSType, SplattedExpr: RHS.get());
9684 Kind = CK_VectorSplat;
9685 return AssignConvertType::Compatible;
9686 }
9687 }
9688
9689 // Conversions to or from vector type.
9690 if (LHSType->isVectorType() || RHSType->isVectorType()) {
9691 if (LHSType->isVectorType() && RHSType->isVectorType()) {
9692 // Allow assignments of an AltiVec vector type to an equivalent GCC
9693 // vector type and vice versa
9694 if (Context.areCompatibleVectorTypes(FirstVec: LHSType, SecondVec: RHSType)) {
9695 Kind = CK_BitCast;
9696 return AssignConvertType::Compatible;
9697 }
9698
9699 // If we are allowing lax vector conversions, and LHS and RHS are both
9700 // vectors, the total size only needs to be the same. This is a bitcast;
9701 // no bits are changed but the result type is different.
9702 if (isLaxVectorConversion(srcTy: RHSType, destTy: LHSType)) {
9703 // The default for lax vector conversions with Altivec vectors will
9704 // change, so if we are converting between vector types where
9705 // at least one is an Altivec vector, emit a warning.
9706 if (Context.getTargetInfo().getTriple().isPPC() &&
9707 anyAltivecTypes(SrcTy: RHSType, DestTy: LHSType) &&
9708 !Context.areCompatibleVectorTypes(FirstVec: RHSType, SecondVec: LHSType))
9709 Diag(Loc: RHS.get()->getExprLoc(), DiagID: diag::warn_deprecated_lax_vec_conv_all)
9710 << RHSType << LHSType;
9711 Kind = CK_BitCast;
9712 return AssignConvertType::IncompatibleVectors;
9713 }
9714 }
9715
9716 // When the RHS comes from another lax conversion (e.g. binops between
9717 // scalars and vectors) the result is canonicalized as a vector. When the
9718 // LHS is also a vector, the lax is allowed by the condition above. Handle
9719 // the case where LHS is a scalar.
9720 if (LHSType->isScalarType()) {
9721 const VectorType *VecType = RHSType->getAs<VectorType>();
9722 if (VecType && VecType->getNumElements() == 1 &&
9723 isLaxVectorConversion(srcTy: RHSType, destTy: LHSType)) {
9724 if (Context.getTargetInfo().getTriple().isPPC() &&
9725 (VecType->getVectorKind() == VectorKind::AltiVecVector ||
9726 VecType->getVectorKind() == VectorKind::AltiVecBool ||
9727 VecType->getVectorKind() == VectorKind::AltiVecPixel))
9728 Diag(Loc: RHS.get()->getExprLoc(), DiagID: diag::warn_deprecated_lax_vec_conv_all)
9729 << RHSType << LHSType;
9730 ExprResult *VecExpr = &RHS;
9731 *VecExpr = ImpCastExprToType(E: VecExpr->get(), Type: LHSType, CK: CK_BitCast);
9732 Kind = CK_BitCast;
9733 return AssignConvertType::Compatible;
9734 }
9735 }
9736
9737 // Allow assignments between fixed-length and sizeless SVE vectors.
9738 if ((LHSType->isSVESizelessBuiltinType() && RHSType->isVectorType()) ||
9739 (LHSType->isVectorType() && RHSType->isSVESizelessBuiltinType()))
9740 if (ARM().areCompatibleSveTypes(FirstType: LHSType, SecondType: RHSType) ||
9741 ARM().areLaxCompatibleSveTypes(FirstType: LHSType, SecondType: RHSType)) {
9742 Kind = CK_BitCast;
9743 return AssignConvertType::Compatible;
9744 }
9745
9746 // Allow assignments between fixed-length and sizeless RVV vectors.
9747 if ((LHSType->isRVVSizelessBuiltinType() && RHSType->isVectorType()) ||
9748 (LHSType->isVectorType() && RHSType->isRVVSizelessBuiltinType())) {
9749 if (Context.areCompatibleRVVTypes(FirstType: LHSType, SecondType: RHSType) ||
9750 Context.areLaxCompatibleRVVTypes(FirstType: LHSType, SecondType: RHSType)) {
9751 Kind = CK_BitCast;
9752 return AssignConvertType::Compatible;
9753 }
9754 }
9755
9756 return AssignConvertType::Incompatible;
9757 }
9758
9759 // Diagnose attempts to convert between __ibm128, __float128 and long double
9760 // where such conversions currently can't be handled.
9761 if (unsupportedTypeConversion(S: *this, LHSType, RHSType))
9762 return AssignConvertType::Incompatible;
9763
9764 // Disallow assigning a _Complex to a real type in C++ mode since it simply
9765 // discards the imaginary part.
9766 if (getLangOpts().CPlusPlus && RHSType->getAs<ComplexType>() &&
9767 !LHSType->getAs<ComplexType>())
9768 return AssignConvertType::Incompatible;
9769
9770 // Arithmetic conversions.
9771 if (LHSType->isArithmeticType() && RHSType->isArithmeticType() &&
9772 !(getLangOpts().CPlusPlus && LHSType->isEnumeralType())) {
9773 if (ConvertRHS)
9774 Kind = PrepareScalarCast(Src&: RHS, DestTy: LHSType);
9775 return AssignConvertType::Compatible;
9776 }
9777
9778 // Conversions to normal pointers.
9779 if (const PointerType *LHSPointer = dyn_cast<PointerType>(Val&: LHSType)) {
9780 // U* -> T*
9781 if (isa<PointerType>(Val: RHSType)) {
9782 LangAS AddrSpaceL = LHSPointer->getPointeeType().getAddressSpace();
9783 LangAS AddrSpaceR = RHSType->getPointeeType().getAddressSpace();
9784 if (AddrSpaceL != AddrSpaceR)
9785 Kind = CK_AddressSpaceConversion;
9786 else if (Context.hasCvrSimilarType(T1: RHSType, T2: LHSType))
9787 Kind = CK_NoOp;
9788 else
9789 Kind = CK_BitCast;
9790 return checkPointerTypesForAssignment(S&: *this, LHSType, RHSType,
9791 Loc: RHS.get()->getBeginLoc());
9792 }
9793
9794 // int -> T*
9795 if (RHSType->isIntegerType()) {
9796 Kind = CK_IntegralToPointer; // FIXME: null?
9797 return AssignConvertType::IntToPointer;
9798 }
9799
9800 // C pointers are not compatible with ObjC object pointers,
9801 // with two exceptions:
9802 if (isa<ObjCObjectPointerType>(Val: RHSType)) {
9803 // - conversions to void*
9804 if (LHSPointer->getPointeeType()->isVoidType()) {
9805 Kind = CK_BitCast;
9806 return AssignConvertType::Compatible;
9807 }
9808
9809 // - conversions from 'Class' to the redefinition type
9810 if (RHSType->isObjCClassType() &&
9811 Context.hasSameType(T1: LHSType,
9812 T2: Context.getObjCClassRedefinitionType())) {
9813 Kind = CK_BitCast;
9814 return AssignConvertType::Compatible;
9815 }
9816
9817 Kind = CK_BitCast;
9818 return AssignConvertType::IncompatiblePointer;
9819 }
9820
9821 // U^ -> void*
9822 if (RHSType->getAs<BlockPointerType>()) {
9823 if (LHSPointer->getPointeeType()->isVoidType()) {
9824 LangAS AddrSpaceL = LHSPointer->getPointeeType().getAddressSpace();
9825 LangAS AddrSpaceR = RHSType->getAs<BlockPointerType>()
9826 ->getPointeeType()
9827 .getAddressSpace();
9828 Kind =
9829 AddrSpaceL != AddrSpaceR ? CK_AddressSpaceConversion : CK_BitCast;
9830 return AssignConvertType::Compatible;
9831 }
9832 }
9833
9834 return AssignConvertType::Incompatible;
9835 }
9836
9837 // Conversions to block pointers.
9838 if (isa<BlockPointerType>(Val: LHSType)) {
9839 // U^ -> T^
9840 if (RHSType->isBlockPointerType()) {
9841 LangAS AddrSpaceL = LHSType->getAs<BlockPointerType>()
9842 ->getPointeeType()
9843 .getAddressSpace();
9844 LangAS AddrSpaceR = RHSType->getAs<BlockPointerType>()
9845 ->getPointeeType()
9846 .getAddressSpace();
9847 Kind = AddrSpaceL != AddrSpaceR ? CK_AddressSpaceConversion : CK_BitCast;
9848 return checkBlockPointerTypesForAssignment(S&: *this, LHSType, RHSType);
9849 }
9850
9851 // int or null -> T^
9852 if (RHSType->isIntegerType()) {
9853 Kind = CK_IntegralToPointer; // FIXME: null
9854 return AssignConvertType::IntToBlockPointer;
9855 }
9856
9857 // id -> T^
9858 if (getLangOpts().ObjC && RHSType->isObjCIdType()) {
9859 Kind = CK_AnyPointerToBlockPointerCast;
9860 return AssignConvertType::Compatible;
9861 }
9862
9863 // void* -> T^
9864 if (const PointerType *RHSPT = RHSType->getAs<PointerType>())
9865 if (RHSPT->getPointeeType()->isVoidType()) {
9866 Kind = CK_AnyPointerToBlockPointerCast;
9867 return AssignConvertType::Compatible;
9868 }
9869
9870 return AssignConvertType::Incompatible;
9871 }
9872
9873 // Conversions to Objective-C pointers.
9874 if (isa<ObjCObjectPointerType>(Val: LHSType)) {
9875 // A* -> B*
9876 if (RHSType->isObjCObjectPointerType()) {
9877 Kind = CK_BitCast;
9878 AssignConvertType result =
9879 checkObjCPointerTypesForAssignment(S&: *this, LHSType, RHSType);
9880 if (getLangOpts().allowsNonTrivialObjCLifetimeQualifiers() &&
9881 result == AssignConvertType::Compatible &&
9882 !ObjC().CheckObjCARCUnavailableWeakConversion(castType: OrigLHSType, ExprType: RHSType))
9883 result = AssignConvertType::IncompatibleObjCWeakRef;
9884 return result;
9885 }
9886
9887 // int or null -> A*
9888 if (RHSType->isIntegerType()) {
9889 Kind = CK_IntegralToPointer; // FIXME: null
9890 return AssignConvertType::IntToPointer;
9891 }
9892
9893 // In general, C pointers are not compatible with ObjC object pointers,
9894 // with two exceptions:
9895 if (isa<PointerType>(Val: RHSType)) {
9896 Kind = CK_CPointerToObjCPointerCast;
9897
9898 // - conversions from 'void*'
9899 if (RHSType->isVoidPointerType()) {
9900 return AssignConvertType::Compatible;
9901 }
9902
9903 // - conversions to 'Class' from its redefinition type
9904 if (LHSType->isObjCClassType() &&
9905 Context.hasSameType(T1: RHSType,
9906 T2: Context.getObjCClassRedefinitionType())) {
9907 return AssignConvertType::Compatible;
9908 }
9909
9910 return AssignConvertType::IncompatiblePointer;
9911 }
9912
9913 // Only under strict condition T^ is compatible with an Objective-C pointer.
9914 if (RHSType->isBlockPointerType() &&
9915 LHSType->isBlockCompatibleObjCPointerType(ctx&: Context)) {
9916 if (ConvertRHS)
9917 maybeExtendBlockObject(E&: RHS);
9918 Kind = CK_BlockPointerToObjCPointerCast;
9919 return AssignConvertType::Compatible;
9920 }
9921
9922 return AssignConvertType::Incompatible;
9923 }
9924
9925 // Conversion to nullptr_t (C23 only)
9926 if (getLangOpts().C23 && LHSType->isNullPtrType() &&
9927 RHS.get()->isNullPointerConstant(Ctx&: Context,
9928 NPC: Expr::NPC_ValueDependentIsNull)) {
9929 // null -> nullptr_t
9930 Kind = CK_NullToPointer;
9931 return AssignConvertType::Compatible;
9932 }
9933
9934 // Conversions from pointers that are not covered by the above.
9935 if (isa<PointerType>(Val: RHSType)) {
9936 // T* -> _Bool
9937 if (LHSType == Context.BoolTy) {
9938 Kind = CK_PointerToBoolean;
9939 return AssignConvertType::Compatible;
9940 }
9941
9942 // T* -> int
9943 if (LHSType->isIntegerType()) {
9944 Kind = CK_PointerToIntegral;
9945 return AssignConvertType::PointerToInt;
9946 }
9947
9948 return AssignConvertType::Incompatible;
9949 }
9950
9951 // Conversions from Objective-C pointers that are not covered by the above.
9952 if (isa<ObjCObjectPointerType>(Val: RHSType)) {
9953 // T* -> _Bool
9954 if (LHSType == Context.BoolTy) {
9955 Kind = CK_PointerToBoolean;
9956 return AssignConvertType::Compatible;
9957 }
9958
9959 // T* -> int
9960 if (LHSType->isIntegerType()) {
9961 Kind = CK_PointerToIntegral;
9962 return AssignConvertType::PointerToInt;
9963 }
9964
9965 return AssignConvertType::Incompatible;
9966 }
9967
9968 // struct A -> struct B
9969 if (isa<TagType>(Val: LHSType) && isa<TagType>(Val: RHSType)) {
9970 if (Context.typesAreCompatible(T1: LHSType, T2: RHSType)) {
9971 Kind = CK_NoOp;
9972 return AssignConvertType::Compatible;
9973 }
9974 }
9975
9976 if (LHSType->isSamplerT() && RHSType->isIntegerType()) {
9977 Kind = CK_IntToOCLSampler;
9978 return AssignConvertType::Compatible;
9979 }
9980
9981 return AssignConvertType::Incompatible;
9982}
9983
9984/// Constructs a transparent union from an expression that is
9985/// used to initialize the transparent union.
9986static void ConstructTransparentUnion(Sema &S, ASTContext &C,
9987 ExprResult &EResult, QualType UnionType,
9988 FieldDecl *Field) {
9989 // Build an initializer list that designates the appropriate member
9990 // of the transparent union.
9991 Expr *E = EResult.get();
9992 InitListExpr *Initializer = new (C) InitListExpr(C, SourceLocation(),
9993 E, SourceLocation());
9994 Initializer->setType(UnionType);
9995 Initializer->setInitializedFieldInUnion(Field);
9996
9997 // Build a compound literal constructing a value of the transparent
9998 // union type from this initializer list.
9999 TypeSourceInfo *unionTInfo = C.getTrivialTypeSourceInfo(T: UnionType);
10000 EResult = new (C) CompoundLiteralExpr(SourceLocation(), unionTInfo, UnionType,
10001 VK_PRValue, Initializer, false);
10002}
10003
10004AssignConvertType
10005Sema::CheckTransparentUnionArgumentConstraints(QualType ArgType,
10006 ExprResult &RHS) {
10007 QualType RHSType = RHS.get()->getType();
10008
10009 // If the ArgType is a Union type, we want to handle a potential
10010 // transparent_union GCC extension.
10011 const RecordType *UT = ArgType->getAsUnionType();
10012 if (!UT)
10013 return AssignConvertType::Incompatible;
10014
10015 RecordDecl *UD = UT->getDecl()->getDefinitionOrSelf();
10016 if (!UD->hasAttr<TransparentUnionAttr>())
10017 return AssignConvertType::Incompatible;
10018
10019 // The field to initialize within the transparent union.
10020 FieldDecl *InitField = nullptr;
10021 // It's compatible if the expression matches any of the fields.
10022 for (auto *it : UD->fields()) {
10023 if (it->getType()->isPointerType()) {
10024 // If the transparent union contains a pointer type, we allow:
10025 // 1) void pointer
10026 // 2) null pointer constant
10027 if (RHSType->isPointerType())
10028 if (RHSType->castAs<PointerType>()->getPointeeType()->isVoidType()) {
10029 RHS = ImpCastExprToType(E: RHS.get(), Type: it->getType(), CK: CK_BitCast);
10030 InitField = it;
10031 break;
10032 }
10033
10034 if (RHS.get()->isNullPointerConstant(Ctx&: Context,
10035 NPC: Expr::NPC_ValueDependentIsNull)) {
10036 RHS = ImpCastExprToType(E: RHS.get(), Type: it->getType(),
10037 CK: CK_NullToPointer);
10038 InitField = it;
10039 break;
10040 }
10041 }
10042
10043 CastKind Kind;
10044 if (CheckAssignmentConstraints(LHSType: it->getType(), RHS, Kind) ==
10045 AssignConvertType::Compatible) {
10046 RHS = ImpCastExprToType(E: RHS.get(), Type: it->getType(), CK: Kind);
10047 InitField = it;
10048 break;
10049 }
10050 }
10051
10052 if (!InitField)
10053 return AssignConvertType::Incompatible;
10054
10055 ConstructTransparentUnion(S&: *this, C&: Context, EResult&: RHS, UnionType: ArgType, Field: InitField);
10056 return AssignConvertType::Compatible;
10057}
10058
10059AssignConvertType Sema::CheckSingleAssignmentConstraints(QualType LHSType,
10060 ExprResult &CallerRHS,
10061 bool Diagnose,
10062 bool DiagnoseCFAudited,
10063 bool ConvertRHS) {
10064 // We need to be able to tell the caller whether we diagnosed a problem, if
10065 // they ask us to issue diagnostics.
10066 assert((ConvertRHS || !Diagnose) && "can't indicate whether we diagnosed");
10067
10068 // If ConvertRHS is false, we want to leave the caller's RHS untouched. Sadly,
10069 // we can't avoid *all* modifications at the moment, so we need some somewhere
10070 // to put the updated value.
10071 ExprResult LocalRHS = CallerRHS;
10072 ExprResult &RHS = ConvertRHS ? CallerRHS : LocalRHS;
10073
10074 if (const auto *LHSPtrType = LHSType->getAs<PointerType>()) {
10075 if (const auto *RHSPtrType = RHS.get()->getType()->getAs<PointerType>()) {
10076 if (RHSPtrType->getPointeeType()->hasAttr(AK: attr::NoDeref) &&
10077 !LHSPtrType->getPointeeType()->hasAttr(AK: attr::NoDeref)) {
10078 Diag(Loc: RHS.get()->getExprLoc(),
10079 DiagID: diag::warn_noderef_to_dereferenceable_pointer)
10080 << RHS.get()->getSourceRange();
10081 }
10082 }
10083 }
10084
10085 if (getLangOpts().CPlusPlus) {
10086 if (!LHSType->isRecordType() && !LHSType->isAtomicType()) {
10087 // C++ 5.17p3: If the left operand is not of class type, the
10088 // expression is implicitly converted (C++ 4) to the
10089 // cv-unqualified type of the left operand.
10090 QualType RHSType = RHS.get()->getType();
10091 if (Diagnose) {
10092 RHS = PerformImplicitConversion(From: RHS.get(), ToType: LHSType.getUnqualifiedType(),
10093 Action: AssignmentAction::Assigning);
10094 } else {
10095 ImplicitConversionSequence ICS =
10096 TryImplicitConversion(From: RHS.get(), ToType: LHSType.getUnqualifiedType(),
10097 /*SuppressUserConversions=*/false,
10098 AllowExplicit: AllowedExplicit::None,
10099 /*InOverloadResolution=*/false,
10100 /*CStyle=*/false,
10101 /*AllowObjCWritebackConversion=*/false);
10102 if (ICS.isFailure())
10103 return AssignConvertType::Incompatible;
10104 RHS = PerformImplicitConversion(From: RHS.get(), ToType: LHSType.getUnqualifiedType(),
10105 ICS, Action: AssignmentAction::Assigning);
10106 }
10107 if (RHS.isInvalid())
10108 return AssignConvertType::Incompatible;
10109 AssignConvertType result = AssignConvertType::Compatible;
10110 if (getLangOpts().allowsNonTrivialObjCLifetimeQualifiers() &&
10111 !ObjC().CheckObjCARCUnavailableWeakConversion(castType: LHSType, ExprType: RHSType))
10112 result = AssignConvertType::IncompatibleObjCWeakRef;
10113
10114 // Check if OBT is being discarded during assignment
10115 // The RHS may have propagated OBT, but if LHS doesn't have it, warn
10116 if (RHSType->isOverflowBehaviorType() &&
10117 !LHSType->isOverflowBehaviorType()) {
10118 result = AssignConvertType::CompatibleOBTDiscards;
10119 }
10120
10121 return result;
10122 }
10123
10124 // FIXME: Currently, we fall through and treat C++ classes like C
10125 // structures.
10126 // FIXME: We also fall through for atomics; not sure what should
10127 // happen there, though.
10128 } else if (RHS.get()->getType() == Context.OverloadTy) {
10129 // As a set of extensions to C, we support overloading on functions. These
10130 // functions need to be resolved here.
10131 DeclAccessPair DAP;
10132 if (FunctionDecl *FD = ResolveAddressOfOverloadedFunction(
10133 AddressOfExpr: RHS.get(), TargetType: LHSType, /*Complain=*/false, Found&: DAP))
10134 RHS = FixOverloadedFunctionReference(E: RHS.get(), FoundDecl: DAP, Fn: FD);
10135 else
10136 return AssignConvertType::Incompatible;
10137 }
10138
10139 // This check seems unnatural, however it is necessary to ensure the proper
10140 // conversion of functions/arrays. If the conversion were done for all
10141 // DeclExpr's (created by ActOnIdExpression), it would mess up the unary
10142 // expressions that suppress this implicit conversion (&, sizeof). This needs
10143 // to happen before we check for null pointer conversions because C does not
10144 // undergo the same implicit conversions as C++ does above (by the calls to
10145 // TryImplicitConversion() and PerformImplicitConversion()) which insert the
10146 // lvalue to rvalue cast before checking for null pointer constraints. This
10147 // addresses code like: nullptr_t val; int *ptr; ptr = val;
10148 //
10149 // Suppress this for references: C++ 8.5.3p5.
10150 if (!LHSType->isReferenceType()) {
10151 // FIXME: We potentially allocate here even if ConvertRHS is false.
10152 RHS = DefaultFunctionArrayLvalueConversion(E: RHS.get(), Diagnose);
10153 if (RHS.isInvalid())
10154 return AssignConvertType::Incompatible;
10155 }
10156
10157 // The constraints are expressed in terms of the atomic, qualified, or
10158 // unqualified type of the LHS.
10159 QualType LHSTypeAfterConversion = LHSType.getAtomicUnqualifiedType();
10160
10161 // C99 6.5.16.1p1: the left operand is a pointer and the right is
10162 // a null pointer constant <C23>or its type is nullptr_t;</C23>.
10163 if ((LHSTypeAfterConversion->isPointerType() ||
10164 LHSTypeAfterConversion->isObjCObjectPointerType() ||
10165 LHSTypeAfterConversion->isBlockPointerType()) &&
10166 ((getLangOpts().C23 && RHS.get()->getType()->isNullPtrType()) ||
10167 RHS.get()->isNullPointerConstant(Ctx&: Context,
10168 NPC: Expr::NPC_ValueDependentIsNull))) {
10169 AssignConvertType Ret = AssignConvertType::Compatible;
10170 if (Diagnose || ConvertRHS) {
10171 CastKind Kind;
10172 CXXCastPath Path;
10173 CheckPointerConversion(From: RHS.get(), ToType: LHSType, Kind, BasePath&: Path,
10174 /*IgnoreBaseAccess=*/false, Diagnose);
10175
10176 // If there is a conversion of some kind, check to see what kind of
10177 // pointer conversion happened so we can diagnose a C++ compatibility
10178 // diagnostic if the conversion is invalid. This only matters if the RHS
10179 // is some kind of void pointer. We have a carve-out when the RHS is from
10180 // a macro expansion because the use of a macro may indicate different
10181 // code between C and C++. Consider: char *s = NULL; where NULL is
10182 // defined as (void *)0 in C (which would be invalid in C++), but 0 in
10183 // C++, which is valid in C++.
10184 if (Kind != CK_NoOp && !getLangOpts().CPlusPlus &&
10185 !RHS.get()->getBeginLoc().isMacroID()) {
10186 QualType CanRHS =
10187 RHS.get()->getType().getCanonicalType().getUnqualifiedType();
10188 QualType CanLHS = LHSType.getCanonicalType().getUnqualifiedType();
10189 if (CanRHS->isVoidPointerType() && CanLHS->isPointerType()) {
10190 Ret = checkPointerTypesForAssignment(S&: *this, LHSType: CanLHS, RHSType: CanRHS,
10191 Loc: RHS.get()->getExprLoc());
10192 // Anything that's not considered perfectly compatible would be
10193 // incompatible in C++.
10194 if (Ret != AssignConvertType::Compatible)
10195 Ret = AssignConvertType::CompatibleVoidPtrToNonVoidPtr;
10196 }
10197 }
10198
10199 if (ConvertRHS)
10200 RHS = ImpCastExprToType(E: RHS.get(), Type: LHSType, CK: Kind, VK: VK_PRValue, BasePath: &Path);
10201 }
10202 return Ret;
10203 }
10204 // C23 6.5.16.1p1: the left operand has type atomic, qualified, or
10205 // unqualified bool, and the right operand is a pointer or its type is
10206 // nullptr_t.
10207 if (getLangOpts().C23 && LHSType->isBooleanType() &&
10208 RHS.get()->getType()->isNullPtrType()) {
10209 // NB: T* -> _Bool is handled in CheckAssignmentConstraints, this only
10210 // only handles nullptr -> _Bool due to needing an extra conversion
10211 // step.
10212 // We model this by converting from nullptr -> void * and then let the
10213 // conversion from void * -> _Bool happen naturally.
10214 if (Diagnose || ConvertRHS) {
10215 CastKind Kind;
10216 CXXCastPath Path;
10217 CheckPointerConversion(From: RHS.get(), ToType: Context.VoidPtrTy, Kind, BasePath&: Path,
10218 /*IgnoreBaseAccess=*/false, Diagnose);
10219 if (ConvertRHS)
10220 RHS = ImpCastExprToType(E: RHS.get(), Type: Context.VoidPtrTy, CK: Kind, VK: VK_PRValue,
10221 BasePath: &Path);
10222 }
10223 }
10224
10225 // OpenCL queue_t type assignment.
10226 if (LHSType->isQueueT() && RHS.get()->isNullPointerConstant(
10227 Ctx&: Context, NPC: Expr::NPC_ValueDependentIsNull)) {
10228 RHS = ImpCastExprToType(E: RHS.get(), Type: LHSType, CK: CK_NullToPointer);
10229 return AssignConvertType::Compatible;
10230 }
10231
10232 CastKind Kind;
10233 AssignConvertType result =
10234 CheckAssignmentConstraints(LHSType, RHS, Kind, ConvertRHS);
10235
10236 // If assigning a void * created by an allocation function call to some other
10237 // type, check that the allocated size is sufficient for that type.
10238 if (result != AssignConvertType::Incompatible &&
10239 RHS.get()->getType()->isVoidPointerType())
10240 CheckSufficientAllocSize(S&: *this, DestType: LHSType, E: RHS.get());
10241
10242 // C99 6.5.16.1p2: The value of the right operand is converted to the
10243 // type of the assignment expression.
10244 // CheckAssignmentConstraints allows the left-hand side to be a reference,
10245 // so that we can use references in built-in functions even in C.
10246 // The getNonReferenceType() call makes sure that the resulting expression
10247 // does not have reference type.
10248 if (result != AssignConvertType::Incompatible &&
10249 RHS.get()->getType() != LHSType) {
10250 QualType Ty = LHSType.getNonLValueExprType(Context);
10251 Expr *E = RHS.get();
10252
10253 // Check for various Objective-C errors. If we are not reporting
10254 // diagnostics and just checking for errors, e.g., during overload
10255 // resolution, return Incompatible to indicate the failure.
10256 if (getLangOpts().allowsNonTrivialObjCLifetimeQualifiers() &&
10257 ObjC().CheckObjCConversion(castRange: SourceRange(), castType: Ty, op&: E,
10258 CCK: CheckedConversionKind::Implicit, Diagnose,
10259 DiagnoseCFAudited) != SemaObjC::ACR_okay) {
10260 if (!Diagnose)
10261 return AssignConvertType::Incompatible;
10262 }
10263 if (getLangOpts().ObjC &&
10264 (ObjC().CheckObjCBridgeRelatedConversions(Loc: E->getBeginLoc(), DestType: LHSType,
10265 SrcType: E->getType(), SrcExpr&: E, Diagnose) ||
10266 ObjC().CheckConversionToObjCLiteral(DstType: LHSType, SrcExpr&: E, Diagnose))) {
10267 if (!Diagnose)
10268 return AssignConvertType::Incompatible;
10269 // Replace the expression with a corrected version and continue so we
10270 // can find further errors.
10271 RHS = E;
10272 return AssignConvertType::Compatible;
10273 }
10274
10275 if (ConvertRHS)
10276 RHS = ImpCastExprToType(E, Type: Ty, CK: Kind);
10277 }
10278
10279 return result;
10280}
10281
10282namespace {
10283/// The original operand to an operator, prior to the application of the usual
10284/// arithmetic conversions and converting the arguments of a builtin operator
10285/// candidate.
10286struct OriginalOperand {
10287 explicit OriginalOperand(Expr *Op) : Orig(Op), Conversion(nullptr) {
10288 if (auto *MTE = dyn_cast<MaterializeTemporaryExpr>(Val: Op))
10289 Op = MTE->getSubExpr();
10290 if (auto *BTE = dyn_cast<CXXBindTemporaryExpr>(Val: Op))
10291 Op = BTE->getSubExpr();
10292 if (auto *ICE = dyn_cast<ImplicitCastExpr>(Val: Op)) {
10293 Orig = ICE->getSubExprAsWritten();
10294 Conversion = ICE->getConversionFunction();
10295 }
10296 }
10297
10298 QualType getType() const { return Orig->getType(); }
10299
10300 Expr *Orig;
10301 NamedDecl *Conversion;
10302};
10303}
10304
10305QualType Sema::InvalidOperands(SourceLocation Loc, ExprResult &LHS,
10306 ExprResult &RHS) {
10307 OriginalOperand OrigLHS(LHS.get()), OrigRHS(RHS.get());
10308
10309 Diag(Loc, DiagID: diag::err_typecheck_invalid_operands)
10310 << OrigLHS.getType() << OrigRHS.getType()
10311 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
10312
10313 // If a user-defined conversion was applied to either of the operands prior
10314 // to applying the built-in operator rules, tell the user about it.
10315 if (OrigLHS.Conversion) {
10316 Diag(Loc: OrigLHS.Conversion->getLocation(),
10317 DiagID: diag::note_typecheck_invalid_operands_converted)
10318 << 0 << LHS.get()->getType();
10319 }
10320 if (OrigRHS.Conversion) {
10321 Diag(Loc: OrigRHS.Conversion->getLocation(),
10322 DiagID: diag::note_typecheck_invalid_operands_converted)
10323 << 1 << RHS.get()->getType();
10324 }
10325
10326 return QualType();
10327}
10328
10329QualType Sema::InvalidLogicalVectorOperands(SourceLocation Loc, ExprResult &LHS,
10330 ExprResult &RHS) {
10331 QualType LHSType = LHS.get()->IgnoreImpCasts()->getType();
10332 QualType RHSType = RHS.get()->IgnoreImpCasts()->getType();
10333
10334 bool LHSNatVec = LHSType->isVectorType();
10335 bool RHSNatVec = RHSType->isVectorType();
10336
10337 if (!(LHSNatVec && RHSNatVec)) {
10338 Expr *Vector = LHSNatVec ? LHS.get() : RHS.get();
10339 Expr *NonVector = !LHSNatVec ? LHS.get() : RHS.get();
10340 Diag(Loc, DiagID: diag::err_typecheck_logical_vector_expr_gnu_cpp_restrict)
10341 << 0 << Vector->getType() << NonVector->IgnoreImpCasts()->getType()
10342 << Vector->getSourceRange();
10343 return QualType();
10344 }
10345
10346 Diag(Loc, DiagID: diag::err_typecheck_logical_vector_expr_gnu_cpp_restrict)
10347 << 1 << LHSType << RHSType << LHS.get()->getSourceRange()
10348 << RHS.get()->getSourceRange();
10349
10350 return QualType();
10351}
10352
10353/// Try to convert a value of non-vector type to a vector type by converting
10354/// the type to the element type of the vector and then performing a splat.
10355/// If the language is OpenCL, we only use conversions that promote scalar
10356/// rank; for C, Obj-C, and C++ we allow any real scalar conversion except
10357/// for float->int.
10358///
10359/// OpenCL V2.0 6.2.6.p2:
10360/// An error shall occur if any scalar operand type has greater rank
10361/// than the type of the vector element.
10362///
10363/// \param scalar - if non-null, actually perform the conversions
10364/// \return true if the operation fails (but without diagnosing the failure)
10365static bool tryVectorConvertAndSplat(Sema &S, ExprResult *scalar,
10366 QualType scalarTy,
10367 QualType vectorEltTy,
10368 QualType vectorTy,
10369 unsigned &DiagID) {
10370 // The conversion to apply to the scalar before splatting it,
10371 // if necessary.
10372 CastKind scalarCast = CK_NoOp;
10373
10374 if (vectorEltTy->isBooleanType() && scalarTy->isIntegralType(Ctx: S.Context)) {
10375 scalarCast = CK_IntegralToBoolean;
10376 } else if (vectorEltTy->isIntegralType(Ctx: S.Context)) {
10377 if (S.getLangOpts().OpenCL && (scalarTy->isRealFloatingType() ||
10378 (scalarTy->isIntegerType() &&
10379 S.Context.getIntegerTypeOrder(LHS: vectorEltTy, RHS: scalarTy) < 0))) {
10380 DiagID = diag::err_opencl_scalar_type_rank_greater_than_vector_type;
10381 return true;
10382 }
10383 if (!scalarTy->isIntegralType(Ctx: S.Context))
10384 return true;
10385 scalarCast = CK_IntegralCast;
10386 } else if (vectorEltTy->isRealFloatingType()) {
10387 if (scalarTy->isRealFloatingType()) {
10388 if (S.getLangOpts().OpenCL &&
10389 S.Context.getFloatingTypeOrder(LHS: vectorEltTy, RHS: scalarTy) < 0) {
10390 DiagID = diag::err_opencl_scalar_type_rank_greater_than_vector_type;
10391 return true;
10392 }
10393 scalarCast = CK_FloatingCast;
10394 }
10395 else if (scalarTy->isIntegralType(Ctx: S.Context))
10396 scalarCast = CK_IntegralToFloating;
10397 else
10398 return true;
10399 } else {
10400 return true;
10401 }
10402
10403 // Adjust scalar if desired.
10404 if (scalar) {
10405 if (scalarCast != CK_NoOp)
10406 *scalar = S.ImpCastExprToType(E: scalar->get(), Type: vectorEltTy, CK: scalarCast);
10407 *scalar = S.ImpCastExprToType(E: scalar->get(), Type: vectorTy, CK: CK_VectorSplat);
10408 }
10409 return false;
10410}
10411
10412/// Convert vector E to a vector with the same number of elements but different
10413/// element type.
10414static ExprResult convertVector(Expr *E, QualType ElementType, Sema &S) {
10415 const auto *VecTy = E->getType()->getAs<VectorType>();
10416 assert(VecTy && "Expression E must be a vector");
10417 QualType NewVecTy =
10418 VecTy->isExtVectorType()
10419 ? S.Context.getExtVectorType(VectorType: ElementType, NumElts: VecTy->getNumElements())
10420 : S.Context.getVectorType(VectorType: ElementType, NumElts: VecTy->getNumElements(),
10421 VecKind: VecTy->getVectorKind());
10422
10423 // Look through the implicit cast. Return the subexpression if its type is
10424 // NewVecTy.
10425 if (auto *ICE = dyn_cast<ImplicitCastExpr>(Val: E))
10426 if (ICE->getSubExpr()->getType() == NewVecTy)
10427 return ICE->getSubExpr();
10428
10429 auto Cast = ElementType->isIntegerType() ? CK_IntegralCast : CK_FloatingCast;
10430 return S.ImpCastExprToType(E, Type: NewVecTy, CK: Cast);
10431}
10432
10433/// Test if a (constant) integer Int can be casted to another integer type
10434/// IntTy without losing precision.
10435static bool canConvertIntToOtherIntTy(Sema &S, ExprResult *Int,
10436 QualType OtherIntTy) {
10437 Expr *E = Int->get();
10438 if (E->containsErrors() || E->isInstantiationDependent())
10439 return false;
10440
10441 QualType IntTy = Int->get()->getType().getUnqualifiedType();
10442
10443 // Reject cases where the value of the Int is unknown as that would
10444 // possibly cause truncation, but accept cases where the scalar can be
10445 // demoted without loss of precision.
10446 Expr::EvalResult EVResult;
10447 bool CstInt = Int->get()->EvaluateAsInt(Result&: EVResult, Ctx: S.Context);
10448 int Order = S.Context.getIntegerTypeOrder(LHS: OtherIntTy, RHS: IntTy);
10449 bool IntSigned = IntTy->hasSignedIntegerRepresentation();
10450 bool OtherIntSigned = OtherIntTy->hasSignedIntegerRepresentation();
10451
10452 if (CstInt) {
10453 // If the scalar is constant and is of a higher order and has more active
10454 // bits that the vector element type, reject it.
10455 llvm::APSInt Result = EVResult.Val.getInt();
10456 unsigned NumBits = IntSigned
10457 ? (Result.isNegative() ? Result.getSignificantBits()
10458 : Result.getActiveBits())
10459 : Result.getActiveBits();
10460 if (Order < 0 && S.Context.getIntWidth(T: OtherIntTy) < NumBits)
10461 return true;
10462
10463 // If the signedness of the scalar type and the vector element type
10464 // differs and the number of bits is greater than that of the vector
10465 // element reject it.
10466 return (IntSigned != OtherIntSigned &&
10467 NumBits > S.Context.getIntWidth(T: OtherIntTy));
10468 }
10469
10470 // Reject cases where the value of the scalar is not constant and it's
10471 // order is greater than that of the vector element type.
10472 return (Order < 0);
10473}
10474
10475/// Test if a (constant) integer Int can be casted to floating point type
10476/// FloatTy without losing precision.
10477static bool canConvertIntTyToFloatTy(Sema &S, ExprResult *Int,
10478 QualType FloatTy) {
10479 if (Int->get()->containsErrors())
10480 return false;
10481
10482 QualType IntTy = Int->get()->getType().getUnqualifiedType();
10483
10484 // Determine if the integer constant can be expressed as a floating point
10485 // number of the appropriate type.
10486 Expr::EvalResult EVResult;
10487 bool CstInt = Int->get()->EvaluateAsInt(Result&: EVResult, Ctx: S.Context);
10488
10489 uint64_t Bits = 0;
10490 if (CstInt) {
10491 // Reject constants that would be truncated if they were converted to
10492 // the floating point type. Test by simple to/from conversion.
10493 // FIXME: Ideally the conversion to an APFloat and from an APFloat
10494 // could be avoided if there was a convertFromAPInt method
10495 // which could signal back if implicit truncation occurred.
10496 llvm::APSInt Result = EVResult.Val.getInt();
10497 llvm::APFloat Float(S.Context.getFloatTypeSemantics(T: FloatTy));
10498 Float.convertFromAPInt(Input: Result, IsSigned: IntTy->hasSignedIntegerRepresentation(),
10499 RM: llvm::APFloat::rmTowardZero);
10500 llvm::APSInt ConvertBack(S.Context.getIntWidth(T: IntTy),
10501 !IntTy->hasSignedIntegerRepresentation());
10502 bool Ignored = false;
10503 Float.convertToInteger(Result&: ConvertBack, RM: llvm::APFloat::rmNearestTiesToEven,
10504 IsExact: &Ignored);
10505 if (Result != ConvertBack)
10506 return true;
10507 } else {
10508 // Reject types that cannot be fully encoded into the mantissa of
10509 // the float.
10510 Bits = S.Context.getTypeSize(T: IntTy);
10511 unsigned FloatPrec = llvm::APFloat::semanticsPrecision(
10512 S.Context.getFloatTypeSemantics(T: FloatTy));
10513 if (Bits > FloatPrec)
10514 return true;
10515 }
10516
10517 return false;
10518}
10519
10520/// Attempt to convert and splat Scalar into a vector whose types matches
10521/// Vector following GCC conversion rules. The rule is that implicit
10522/// conversion can occur when Scalar can be casted to match Vector's element
10523/// type without causing truncation of Scalar.
10524static bool tryGCCVectorConvertAndSplat(Sema &S, ExprResult *Scalar,
10525 ExprResult *Vector) {
10526 QualType ScalarTy = Scalar->get()->getType().getUnqualifiedType();
10527 QualType VectorTy = Vector->get()->getType().getUnqualifiedType();
10528 QualType VectorEltTy;
10529
10530 if (const auto *VT = VectorTy->getAs<VectorType>()) {
10531 assert(!isa<ExtVectorType>(VT) &&
10532 "ExtVectorTypes should not be handled here!");
10533 VectorEltTy = VT->getElementType();
10534 } else if (VectorTy->isSveVLSBuiltinType()) {
10535 VectorEltTy =
10536 VectorTy->castAs<BuiltinType>()->getSveEltType(Ctx: S.getASTContext());
10537 } else {
10538 llvm_unreachable("Only Fixed-Length and SVE Vector types are handled here");
10539 }
10540
10541 // Reject cases where the vector element type or the scalar element type are
10542 // not integral or floating point types.
10543 if (!VectorEltTy->isArithmeticType() || !ScalarTy->isArithmeticType())
10544 return true;
10545
10546 // The conversion to apply to the scalar before splatting it,
10547 // if necessary.
10548 CastKind ScalarCast = CK_NoOp;
10549
10550 // Accept cases where the vector elements are integers and the scalar is
10551 // an integer.
10552 // FIXME: Notionally if the scalar was a floating point value with a precise
10553 // integral representation, we could cast it to an appropriate integer
10554 // type and then perform the rest of the checks here. GCC will perform
10555 // this conversion in some cases as determined by the input language.
10556 // We should accept it on a language independent basis.
10557 if (VectorEltTy->isIntegralType(Ctx: S.Context) &&
10558 ScalarTy->isIntegralType(Ctx: S.Context) &&
10559 S.Context.getIntegerTypeOrder(LHS: VectorEltTy, RHS: ScalarTy)) {
10560
10561 if (canConvertIntToOtherIntTy(S, Int: Scalar, OtherIntTy: VectorEltTy))
10562 return true;
10563
10564 ScalarCast = CK_IntegralCast;
10565 } else if (VectorEltTy->isIntegralType(Ctx: S.Context) &&
10566 ScalarTy->isRealFloatingType()) {
10567 if (S.Context.getTypeSize(T: VectorEltTy) == S.Context.getTypeSize(T: ScalarTy))
10568 ScalarCast = CK_FloatingToIntegral;
10569 else
10570 return true;
10571 } else if (VectorEltTy->isRealFloatingType()) {
10572 if (ScalarTy->isRealFloatingType()) {
10573
10574 // Reject cases where the scalar type is not a constant and has a higher
10575 // Order than the vector element type.
10576 llvm::APFloat Result(0.0);
10577
10578 // Determine whether this is a constant scalar. In the event that the
10579 // value is dependent (and thus cannot be evaluated by the constant
10580 // evaluator), skip the evaluation. This will then diagnose once the
10581 // expression is instantiated.
10582 bool CstScalar = Scalar->get()->isValueDependent() ||
10583 Scalar->get()->EvaluateAsFloat(Result, Ctx: S.Context);
10584 int Order = S.Context.getFloatingTypeOrder(LHS: VectorEltTy, RHS: ScalarTy);
10585 if (!CstScalar && Order < 0)
10586 return true;
10587
10588 // If the scalar cannot be safely casted to the vector element type,
10589 // reject it.
10590 if (CstScalar) {
10591 bool Truncated = false;
10592 Result.convert(ToSemantics: S.Context.getFloatTypeSemantics(T: VectorEltTy),
10593 RM: llvm::APFloat::rmNearestTiesToEven, losesInfo: &Truncated);
10594 if (Truncated)
10595 return true;
10596 }
10597
10598 ScalarCast = CK_FloatingCast;
10599 } else if (ScalarTy->isIntegralType(Ctx: S.Context)) {
10600 if (canConvertIntTyToFloatTy(S, Int: Scalar, FloatTy: VectorEltTy))
10601 return true;
10602
10603 ScalarCast = CK_IntegralToFloating;
10604 } else
10605 return true;
10606 } else if (ScalarTy->isEnumeralType())
10607 return true;
10608
10609 // Adjust scalar if desired.
10610 if (ScalarCast != CK_NoOp)
10611 *Scalar = S.ImpCastExprToType(E: Scalar->get(), Type: VectorEltTy, CK: ScalarCast);
10612 *Scalar = S.ImpCastExprToType(E: Scalar->get(), Type: VectorTy, CK: CK_VectorSplat);
10613 return false;
10614}
10615
10616QualType Sema::CheckVectorOperands(ExprResult &LHS, ExprResult &RHS,
10617 SourceLocation Loc, bool IsCompAssign,
10618 bool AllowBothBool,
10619 bool AllowBoolConversions,
10620 bool AllowBoolOperation,
10621 bool ReportInvalid) {
10622 if (!IsCompAssign) {
10623 LHS = DefaultFunctionArrayLvalueConversion(E: LHS.get());
10624 if (LHS.isInvalid())
10625 return QualType();
10626 }
10627 RHS = DefaultFunctionArrayLvalueConversion(E: RHS.get());
10628 if (RHS.isInvalid())
10629 return QualType();
10630
10631 // For conversion purposes, we ignore any qualifiers.
10632 // For example, "const float" and "float" are equivalent.
10633 QualType LHSType = LHS.get()->getType().getUnqualifiedType();
10634 QualType RHSType = RHS.get()->getType().getUnqualifiedType();
10635
10636 const VectorType *LHSVecType = LHSType->getAs<VectorType>();
10637 const VectorType *RHSVecType = RHSType->getAs<VectorType>();
10638 assert(LHSVecType || RHSVecType);
10639
10640 if (getLangOpts().HLSL)
10641 return HLSL().handleVectorBinOpConversion(LHS, RHS, LHSType, RHSType,
10642 IsCompAssign);
10643
10644 // Any operation with MFloat8 type is only possible with C intrinsics
10645 if ((LHSVecType && LHSVecType->getElementType()->isMFloat8Type()) ||
10646 (RHSVecType && RHSVecType->getElementType()->isMFloat8Type()))
10647 return InvalidOperands(Loc, LHS, RHS);
10648
10649 // AltiVec-style "vector bool op vector bool" combinations are allowed
10650 // for some operators but not others.
10651 if (!AllowBothBool && LHSVecType &&
10652 LHSVecType->getVectorKind() == VectorKind::AltiVecBool && RHSVecType &&
10653 RHSVecType->getVectorKind() == VectorKind::AltiVecBool)
10654 return ReportInvalid ? InvalidOperands(Loc, LHS, RHS) : QualType();
10655
10656 // This operation may not be performed on boolean vectors.
10657 if (!AllowBoolOperation &&
10658 (LHSType->isExtVectorBoolType() || RHSType->isExtVectorBoolType()))
10659 return ReportInvalid ? InvalidOperands(Loc, LHS, RHS) : QualType();
10660
10661 // If the vector types are identical, return.
10662 if (Context.hasSameType(T1: LHSType, T2: RHSType))
10663 return Context.getCommonSugaredType(X: LHSType, Y: RHSType);
10664
10665 // If we have compatible AltiVec and GCC vector types, use the AltiVec type.
10666 if (LHSVecType && RHSVecType &&
10667 Context.areCompatibleVectorTypes(FirstVec: LHSType, SecondVec: RHSType)) {
10668 if (isa<ExtVectorType>(Val: LHSVecType)) {
10669 RHS = ImpCastExprToType(E: RHS.get(), Type: LHSType, CK: CK_BitCast);
10670 return LHSType;
10671 }
10672
10673 if (!IsCompAssign)
10674 LHS = ImpCastExprToType(E: LHS.get(), Type: RHSType, CK: CK_BitCast);
10675 return RHSType;
10676 }
10677
10678 // AllowBoolConversions says that bool and non-bool AltiVec vectors
10679 // can be mixed, with the result being the non-bool type. The non-bool
10680 // operand must have integer element type.
10681 if (AllowBoolConversions && LHSVecType && RHSVecType &&
10682 LHSVecType->getNumElements() == RHSVecType->getNumElements() &&
10683 (Context.getTypeSize(T: LHSVecType->getElementType()) ==
10684 Context.getTypeSize(T: RHSVecType->getElementType()))) {
10685 if (LHSVecType->getVectorKind() == VectorKind::AltiVecVector &&
10686 LHSVecType->getElementType()->isIntegerType() &&
10687 RHSVecType->getVectorKind() == VectorKind::AltiVecBool) {
10688 RHS = ImpCastExprToType(E: RHS.get(), Type: LHSType, CK: CK_BitCast);
10689 return LHSType;
10690 }
10691 if (!IsCompAssign &&
10692 LHSVecType->getVectorKind() == VectorKind::AltiVecBool &&
10693 RHSVecType->getVectorKind() == VectorKind::AltiVecVector &&
10694 RHSVecType->getElementType()->isIntegerType()) {
10695 LHS = ImpCastExprToType(E: LHS.get(), Type: RHSType, CK: CK_BitCast);
10696 return RHSType;
10697 }
10698 }
10699
10700 // Expressions containing fixed-length and sizeless SVE/RVV vectors are
10701 // invalid since the ambiguity can affect the ABI.
10702 auto IsSveRVVConversion = [](QualType FirstType, QualType SecondType,
10703 unsigned &SVEorRVV) {
10704 const VectorType *VecType = SecondType->getAs<VectorType>();
10705 SVEorRVV = 0;
10706 if (FirstType->isSizelessBuiltinType() && VecType) {
10707 if (VecType->getVectorKind() == VectorKind::SveFixedLengthData ||
10708 VecType->getVectorKind() == VectorKind::SveFixedLengthPredicate)
10709 return true;
10710 if (VecType->getVectorKind() == VectorKind::RVVFixedLengthData ||
10711 VecType->getVectorKind() == VectorKind::RVVFixedLengthMask ||
10712 VecType->getVectorKind() == VectorKind::RVVFixedLengthMask_1 ||
10713 VecType->getVectorKind() == VectorKind::RVVFixedLengthMask_2 ||
10714 VecType->getVectorKind() == VectorKind::RVVFixedLengthMask_4) {
10715 SVEorRVV = 1;
10716 return true;
10717 }
10718 }
10719
10720 return false;
10721 };
10722
10723 unsigned SVEorRVV;
10724 if (IsSveRVVConversion(LHSType, RHSType, SVEorRVV) ||
10725 IsSveRVVConversion(RHSType, LHSType, SVEorRVV)) {
10726 Diag(Loc, DiagID: diag::err_typecheck_sve_rvv_ambiguous)
10727 << SVEorRVV << LHSType << RHSType;
10728 return QualType();
10729 }
10730
10731 // Expressions containing GNU and SVE or RVV (fixed or sizeless) vectors are
10732 // invalid since the ambiguity can affect the ABI.
10733 auto IsSveRVVGnuConversion = [](QualType FirstType, QualType SecondType,
10734 unsigned &SVEorRVV) {
10735 const VectorType *FirstVecType = FirstType->getAs<VectorType>();
10736 const VectorType *SecondVecType = SecondType->getAs<VectorType>();
10737
10738 SVEorRVV = 0;
10739 if (FirstVecType && SecondVecType) {
10740 if (FirstVecType->getVectorKind() == VectorKind::Generic) {
10741 if (SecondVecType->getVectorKind() == VectorKind::SveFixedLengthData ||
10742 SecondVecType->getVectorKind() ==
10743 VectorKind::SveFixedLengthPredicate)
10744 return true;
10745 if (SecondVecType->getVectorKind() == VectorKind::RVVFixedLengthData ||
10746 SecondVecType->getVectorKind() == VectorKind::RVVFixedLengthMask ||
10747 SecondVecType->getVectorKind() ==
10748 VectorKind::RVVFixedLengthMask_1 ||
10749 SecondVecType->getVectorKind() ==
10750 VectorKind::RVVFixedLengthMask_2 ||
10751 SecondVecType->getVectorKind() ==
10752 VectorKind::RVVFixedLengthMask_4) {
10753 SVEorRVV = 1;
10754 return true;
10755 }
10756 }
10757 return false;
10758 }
10759
10760 if (SecondVecType &&
10761 SecondVecType->getVectorKind() == VectorKind::Generic) {
10762 if (FirstType->isSVESizelessBuiltinType())
10763 return true;
10764 if (FirstType->isRVVSizelessBuiltinType()) {
10765 SVEorRVV = 1;
10766 return true;
10767 }
10768 }
10769
10770 return false;
10771 };
10772
10773 if (IsSveRVVGnuConversion(LHSType, RHSType, SVEorRVV) ||
10774 IsSveRVVGnuConversion(RHSType, LHSType, SVEorRVV)) {
10775 Diag(Loc, DiagID: diag::err_typecheck_sve_rvv_gnu_ambiguous)
10776 << SVEorRVV << LHSType << RHSType;
10777 return QualType();
10778 }
10779
10780 // If there's a vector type and a scalar, try to convert the scalar to
10781 // the vector element type and splat.
10782 unsigned DiagID = diag::err_typecheck_vector_not_convertable;
10783 if (!RHSVecType) {
10784 if (isa<ExtVectorType>(Val: LHSVecType)) {
10785 if (!tryVectorConvertAndSplat(S&: *this, scalar: &RHS, scalarTy: RHSType,
10786 vectorEltTy: LHSVecType->getElementType(), vectorTy: LHSType,
10787 DiagID))
10788 return LHSType;
10789 } else {
10790 if (!tryGCCVectorConvertAndSplat(S&: *this, Scalar: &RHS, Vector: &LHS))
10791 return LHSType;
10792 }
10793 }
10794 if (!LHSVecType) {
10795 if (isa<ExtVectorType>(Val: RHSVecType)) {
10796 if (!tryVectorConvertAndSplat(S&: *this, scalar: (IsCompAssign ? nullptr : &LHS),
10797 scalarTy: LHSType, vectorEltTy: RHSVecType->getElementType(),
10798 vectorTy: RHSType, DiagID))
10799 return RHSType;
10800 } else {
10801 if (LHS.get()->isLValue() ||
10802 !tryGCCVectorConvertAndSplat(S&: *this, Scalar: &LHS, Vector: &RHS))
10803 return RHSType;
10804 }
10805 }
10806
10807 // FIXME: The code below also handles conversion between vectors and
10808 // non-scalars, we should break this down into fine grained specific checks
10809 // and emit proper diagnostics.
10810 QualType VecType = LHSVecType ? LHSType : RHSType;
10811 const VectorType *VT = LHSVecType ? LHSVecType : RHSVecType;
10812 QualType OtherType = LHSVecType ? RHSType : LHSType;
10813 ExprResult *OtherExpr = LHSVecType ? &RHS : &LHS;
10814 if (isLaxVectorConversion(srcTy: OtherType, destTy: VecType)) {
10815 if (Context.getTargetInfo().getTriple().isPPC() &&
10816 anyAltivecTypes(SrcTy: RHSType, DestTy: LHSType) &&
10817 !Context.areCompatibleVectorTypes(FirstVec: RHSType, SecondVec: LHSType))
10818 Diag(Loc, DiagID: diag::warn_deprecated_lax_vec_conv_all) << RHSType << LHSType;
10819 // If we're allowing lax vector conversions, only the total (data) size
10820 // needs to be the same. For non compound assignment, if one of the types is
10821 // scalar, the result is always the vector type.
10822 if (!IsCompAssign) {
10823 *OtherExpr = ImpCastExprToType(E: OtherExpr->get(), Type: VecType, CK: CK_BitCast);
10824 return VecType;
10825 // In a compound assignment, lhs += rhs, 'lhs' is a lvalue src, forbidding
10826 // any implicit cast. Here, the 'rhs' should be implicit casted to 'lhs'
10827 // type. Note that this is already done by non-compound assignments in
10828 // CheckAssignmentConstraints. If it's a scalar type, only bitcast for
10829 // <1 x T> -> T. The result is also a vector type.
10830 } else if (OtherType->isExtVectorType() || OtherType->isVectorType() ||
10831 (OtherType->isScalarType() && VT->getNumElements() == 1)) {
10832 ExprResult *RHSExpr = &RHS;
10833 *RHSExpr = ImpCastExprToType(E: RHSExpr->get(), Type: LHSType, CK: CK_BitCast);
10834 return VecType;
10835 }
10836 }
10837
10838 // Okay, the expression is invalid.
10839
10840 // If there's a non-vector, non-real operand, diagnose that.
10841 if ((!RHSVecType && !RHSType->isRealType()) ||
10842 (!LHSVecType && !LHSType->isRealType())) {
10843 Diag(Loc, DiagID: diag::err_typecheck_vector_not_convertable_non_scalar)
10844 << LHSType << RHSType
10845 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
10846 return QualType();
10847 }
10848
10849 // OpenCL V1.1 6.2.6.p1:
10850 // If the operands are of more than one vector type, then an error shall
10851 // occur. Implicit conversions between vector types are not permitted, per
10852 // section 6.2.1.
10853 if (getLangOpts().OpenCL &&
10854 RHSVecType && isa<ExtVectorType>(Val: RHSVecType) &&
10855 LHSVecType && isa<ExtVectorType>(Val: LHSVecType)) {
10856 Diag(Loc, DiagID: diag::err_opencl_implicit_vector_conversion) << LHSType
10857 << RHSType;
10858 return QualType();
10859 }
10860
10861
10862 // If there is a vector type that is not a ExtVector and a scalar, we reach
10863 // this point if scalar could not be converted to the vector's element type
10864 // without truncation.
10865 if ((RHSVecType && !isa<ExtVectorType>(Val: RHSVecType)) ||
10866 (LHSVecType && !isa<ExtVectorType>(Val: LHSVecType))) {
10867 QualType Scalar = LHSVecType ? RHSType : LHSType;
10868 QualType Vector = LHSVecType ? LHSType : RHSType;
10869 unsigned ScalarOrVector = LHSVecType && RHSVecType ? 1 : 0;
10870 Diag(Loc,
10871 DiagID: diag::err_typecheck_vector_not_convertable_implict_truncation)
10872 << ScalarOrVector << Scalar << Vector;
10873
10874 return QualType();
10875 }
10876
10877 // Otherwise, use the generic diagnostic.
10878 Diag(Loc, DiagID)
10879 << LHSType << RHSType
10880 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
10881 return QualType();
10882}
10883
10884QualType Sema::CheckSizelessVectorOperands(ExprResult &LHS, ExprResult &RHS,
10885 SourceLocation Loc,
10886 bool IsCompAssign,
10887 ArithConvKind OperationKind) {
10888 if (!IsCompAssign) {
10889 LHS = DefaultFunctionArrayLvalueConversion(E: LHS.get());
10890 if (LHS.isInvalid())
10891 return QualType();
10892 }
10893 RHS = DefaultFunctionArrayLvalueConversion(E: RHS.get());
10894 if (RHS.isInvalid())
10895 return QualType();
10896
10897 QualType LHSType = LHS.get()->getType().getUnqualifiedType();
10898 QualType RHSType = RHS.get()->getType().getUnqualifiedType();
10899
10900 const BuiltinType *LHSBuiltinTy = LHSType->getAs<BuiltinType>();
10901 const BuiltinType *RHSBuiltinTy = RHSType->getAs<BuiltinType>();
10902
10903 unsigned DiagID = diag::err_typecheck_invalid_operands;
10904 if ((OperationKind == ArithConvKind::Arithmetic) &&
10905 ((LHSBuiltinTy && LHSBuiltinTy->isSVEBool()) ||
10906 (RHSBuiltinTy && RHSBuiltinTy->isSVEBool()))) {
10907 Diag(Loc, DiagID) << LHSType << RHSType << LHS.get()->getSourceRange()
10908 << RHS.get()->getSourceRange();
10909 return QualType();
10910 }
10911
10912 if (Context.hasSameType(T1: LHSType, T2: RHSType))
10913 return LHSType;
10914
10915 if (LHSType->isSveVLSBuiltinType() && !RHSType->isSveVLSBuiltinType()) {
10916 if (!tryGCCVectorConvertAndSplat(S&: *this, Scalar: &RHS, Vector: &LHS))
10917 return LHSType;
10918 }
10919 if (RHSType->isSveVLSBuiltinType() && !LHSType->isSveVLSBuiltinType()) {
10920 if (LHS.get()->isLValue() ||
10921 !tryGCCVectorConvertAndSplat(S&: *this, Scalar: &LHS, Vector: &RHS))
10922 return RHSType;
10923 }
10924
10925 if ((!LHSType->isSveVLSBuiltinType() && !LHSType->isRealType()) ||
10926 (!RHSType->isSveVLSBuiltinType() && !RHSType->isRealType())) {
10927 Diag(Loc, DiagID: diag::err_typecheck_vector_not_convertable_non_scalar)
10928 << LHSType << RHSType << LHS.get()->getSourceRange()
10929 << RHS.get()->getSourceRange();
10930 return QualType();
10931 }
10932
10933 if (LHSType->isSveVLSBuiltinType() && RHSType->isSveVLSBuiltinType() &&
10934 Context.getBuiltinVectorTypeInfo(VecTy: LHSBuiltinTy).EC !=
10935 Context.getBuiltinVectorTypeInfo(VecTy: RHSBuiltinTy).EC) {
10936 Diag(Loc, DiagID: diag::err_typecheck_vector_lengths_not_equal)
10937 << LHSType << RHSType << LHS.get()->getSourceRange()
10938 << RHS.get()->getSourceRange();
10939 return QualType();
10940 }
10941
10942 if (LHSType->isSveVLSBuiltinType() || RHSType->isSveVLSBuiltinType()) {
10943 QualType Scalar = LHSType->isSveVLSBuiltinType() ? RHSType : LHSType;
10944 QualType Vector = LHSType->isSveVLSBuiltinType() ? LHSType : RHSType;
10945 bool ScalarOrVector =
10946 LHSType->isSveVLSBuiltinType() && RHSType->isSveVLSBuiltinType();
10947
10948 Diag(Loc, DiagID: diag::err_typecheck_vector_not_convertable_implict_truncation)
10949 << ScalarOrVector << Scalar << Vector;
10950
10951 return QualType();
10952 }
10953
10954 Diag(Loc, DiagID) << LHSType << RHSType << LHS.get()->getSourceRange()
10955 << RHS.get()->getSourceRange();
10956 return QualType();
10957}
10958
10959// checkArithmeticNull - Detect when a NULL constant is used improperly in an
10960// expression. These are mainly cases where the null pointer is used as an
10961// integer instead of a pointer.
10962static void checkArithmeticNull(Sema &S, ExprResult &LHS, ExprResult &RHS,
10963 SourceLocation Loc, bool IsCompare) {
10964 // The canonical way to check for a GNU null is with isNullPointerConstant,
10965 // but we use a bit of a hack here for speed; this is a relatively
10966 // hot path, and isNullPointerConstant is slow.
10967 bool LHSNull = isa<GNUNullExpr>(Val: LHS.get()->IgnoreParenImpCasts());
10968 bool RHSNull = isa<GNUNullExpr>(Val: RHS.get()->IgnoreParenImpCasts());
10969
10970 QualType NonNullType = LHSNull ? RHS.get()->getType() : LHS.get()->getType();
10971
10972 // Avoid analyzing cases where the result will either be invalid (and
10973 // diagnosed as such) or entirely valid and not something to warn about.
10974 if ((!LHSNull && !RHSNull) || NonNullType->isBlockPointerType() ||
10975 NonNullType->isMemberPointerType() || NonNullType->isFunctionType())
10976 return;
10977
10978 // Comparison operations would not make sense with a null pointer no matter
10979 // what the other expression is.
10980 if (!IsCompare) {
10981 S.Diag(Loc, DiagID: diag::warn_null_in_arithmetic_operation)
10982 << (LHSNull ? LHS.get()->getSourceRange() : SourceRange())
10983 << (RHSNull ? RHS.get()->getSourceRange() : SourceRange());
10984 return;
10985 }
10986
10987 // The rest of the operations only make sense with a null pointer
10988 // if the other expression is a pointer.
10989 if (LHSNull == RHSNull || NonNullType->isAnyPointerType() ||
10990 NonNullType->canDecayToPointerType())
10991 return;
10992
10993 S.Diag(Loc, DiagID: diag::warn_null_in_comparison_operation)
10994 << LHSNull /* LHS is NULL */ << NonNullType
10995 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
10996}
10997
10998static void DetectPrecisionLossInComplexDivision(Sema &S, QualType DivisorTy,
10999 SourceLocation OpLoc) {
11000 // If the divisor is real, then this is real/real or complex/real division.
11001 // Either way there can be no precision loss.
11002 auto *CT = DivisorTy->getAs<ComplexType>();
11003 if (!CT)
11004 return;
11005
11006 QualType ElementType = CT->getElementType().getCanonicalType();
11007 bool IsComplexRangePromoted = S.getLangOpts().getComplexRange() ==
11008 LangOptions::ComplexRangeKind::CX_Promoted;
11009 if (!ElementType->isFloatingType() || !IsComplexRangePromoted)
11010 return;
11011
11012 ASTContext &Ctx = S.getASTContext();
11013 QualType HigherElementType = Ctx.GetHigherPrecisionFPType(ElementType);
11014 const llvm::fltSemantics &ElementTypeSemantics =
11015 Ctx.getFloatTypeSemantics(T: ElementType);
11016 const llvm::fltSemantics &HigherElementTypeSemantics =
11017 Ctx.getFloatTypeSemantics(T: HigherElementType);
11018
11019 if ((llvm::APFloat::semanticsMaxExponent(ElementTypeSemantics) * 2 + 1 >
11020 llvm::APFloat::semanticsMaxExponent(HigherElementTypeSemantics)) ||
11021 (HigherElementType == Ctx.LongDoubleTy &&
11022 !Ctx.getTargetInfo().hasLongDoubleType())) {
11023 // Retain the location of the first use of higher precision type.
11024 if (!S.LocationOfExcessPrecisionNotSatisfied.isValid())
11025 S.LocationOfExcessPrecisionNotSatisfied = OpLoc;
11026 for (auto &[Type, Num] : S.ExcessPrecisionNotSatisfied) {
11027 if (Type == HigherElementType) {
11028 Num++;
11029 return;
11030 }
11031 }
11032 S.ExcessPrecisionNotSatisfied.push_back(x: std::make_pair(
11033 x&: HigherElementType, y: S.ExcessPrecisionNotSatisfied.size()));
11034 }
11035}
11036
11037static void DiagnoseDivisionSizeofPointerOrArray(Sema &S, Expr *LHS, Expr *RHS,
11038 SourceLocation Loc) {
11039 const auto *LUE = dyn_cast<UnaryExprOrTypeTraitExpr>(Val: LHS);
11040 const auto *RUE = dyn_cast<UnaryExprOrTypeTraitExpr>(Val: RHS);
11041 if (!LUE || !RUE)
11042 return;
11043 if (LUE->getKind() != UETT_SizeOf || LUE->isArgumentType() ||
11044 RUE->getKind() != UETT_SizeOf)
11045 return;
11046
11047 const Expr *LHSArg = LUE->getArgumentExpr()->IgnoreParens();
11048 QualType LHSTy = LHSArg->getType();
11049 QualType RHSTy;
11050
11051 if (RUE->isArgumentType())
11052 RHSTy = RUE->getArgumentType().getNonReferenceType();
11053 else
11054 RHSTy = RUE->getArgumentExpr()->IgnoreParens()->getType();
11055
11056 if (LHSTy->isPointerType() && !RHSTy->isPointerType()) {
11057 if (!S.Context.hasSameUnqualifiedType(T1: LHSTy->getPointeeType(), T2: RHSTy))
11058 return;
11059
11060 S.Diag(Loc, DiagID: diag::warn_division_sizeof_ptr) << LHS << LHS->getSourceRange();
11061 if (const auto *DRE = dyn_cast<DeclRefExpr>(Val: LHSArg)) {
11062 if (const ValueDecl *LHSArgDecl = DRE->getDecl())
11063 S.Diag(Loc: LHSArgDecl->getLocation(), DiagID: diag::note_pointer_declared_here)
11064 << LHSArgDecl;
11065 }
11066 } else if (const auto *ArrayTy = S.Context.getAsArrayType(T: LHSTy)) {
11067 QualType ArrayElemTy = ArrayTy->getElementType();
11068 if (ArrayElemTy != S.Context.getBaseElementType(VAT: ArrayTy) ||
11069 ArrayElemTy->isDependentType() || RHSTy->isDependentType() ||
11070 RHSTy->isReferenceType() || ArrayElemTy->isCharType() ||
11071 S.Context.getTypeSize(T: ArrayElemTy) == S.Context.getTypeSize(T: RHSTy))
11072 return;
11073 S.Diag(Loc, DiagID: diag::warn_division_sizeof_array)
11074 << LHSArg->getSourceRange() << ArrayElemTy << RHSTy;
11075 if (const auto *DRE = dyn_cast<DeclRefExpr>(Val: LHSArg)) {
11076 if (const ValueDecl *LHSArgDecl = DRE->getDecl())
11077 S.Diag(Loc: LHSArgDecl->getLocation(), DiagID: diag::note_array_declared_here)
11078 << LHSArgDecl;
11079 }
11080
11081 S.Diag(Loc, DiagID: diag::note_precedence_silence) << RHS;
11082 }
11083}
11084
11085static void DiagnoseBadDivideOrRemainderValues(Sema& S, ExprResult &LHS,
11086 ExprResult &RHS,
11087 SourceLocation Loc, bool IsDiv) {
11088 // Check for division/remainder by zero.
11089 Expr::EvalResult RHSValue;
11090 if (!RHS.get()->isValueDependent() &&
11091 RHS.get()->EvaluateAsInt(Result&: RHSValue, Ctx: S.Context) &&
11092 RHSValue.Val.getInt() == 0)
11093 S.DiagRuntimeBehavior(Loc, Statement: RHS.get(),
11094 PD: S.PDiag(DiagID: diag::warn_remainder_division_by_zero)
11095 << IsDiv << RHS.get()->getSourceRange());
11096}
11097
11098static void diagnoseScopedEnums(Sema &S, const SourceLocation Loc,
11099 const ExprResult &LHS, const ExprResult &RHS,
11100 BinaryOperatorKind Opc) {
11101 if (!LHS.isUsable() || !RHS.isUsable())
11102 return;
11103 const Expr *LHSExpr = LHS.get();
11104 const Expr *RHSExpr = RHS.get();
11105 const QualType LHSType = LHSExpr->getType();
11106 const QualType RHSType = RHSExpr->getType();
11107 const bool LHSIsScoped = LHSType->isScopedEnumeralType();
11108 const bool RHSIsScoped = RHSType->isScopedEnumeralType();
11109 if (!LHSIsScoped && !RHSIsScoped)
11110 return;
11111 if (BinaryOperator::isAssignmentOp(Opc) && LHSIsScoped)
11112 return;
11113 if (!LHSIsScoped && !LHSType->isIntegralOrUnscopedEnumerationType())
11114 return;
11115 if (!RHSIsScoped && !RHSType->isIntegralOrUnscopedEnumerationType())
11116 return;
11117 auto DiagnosticHelper = [&S](const Expr *expr, const QualType type) {
11118 SourceLocation BeginLoc = expr->getBeginLoc();
11119 QualType IntType = type->castAs<EnumType>()
11120 ->getDecl()
11121 ->getDefinitionOrSelf()
11122 ->getIntegerType();
11123 std::string InsertionString = "static_cast<" + IntType.getAsString() + ">(";
11124 S.Diag(Loc: BeginLoc, DiagID: diag::note_no_implicit_conversion_for_scoped_enum)
11125 << FixItHint::CreateInsertion(InsertionLoc: BeginLoc, Code: InsertionString)
11126 << FixItHint::CreateInsertion(InsertionLoc: expr->getEndLoc(), Code: ")");
11127 };
11128 if (LHSIsScoped) {
11129 DiagnosticHelper(LHSExpr, LHSType);
11130 }
11131 if (RHSIsScoped) {
11132 DiagnosticHelper(RHSExpr, RHSType);
11133 }
11134}
11135
11136QualType Sema::CheckMultiplyDivideOperands(ExprResult &LHS, ExprResult &RHS,
11137 SourceLocation Loc,
11138 BinaryOperatorKind Opc) {
11139 bool IsCompAssign = Opc == BO_MulAssign || Opc == BO_DivAssign;
11140 bool IsDiv = Opc == BO_Div || Opc == BO_DivAssign;
11141
11142 checkArithmeticNull(S&: *this, LHS, RHS, Loc, /*IsCompare=*/false);
11143
11144 QualType LHSTy = LHS.get()->getType();
11145 QualType RHSTy = RHS.get()->getType();
11146 if (LHSTy->isVectorType() || RHSTy->isVectorType())
11147 return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign,
11148 /*AllowBothBool*/ getLangOpts().AltiVec,
11149 /*AllowBoolConversions*/ false,
11150 /*AllowBooleanOperation*/ AllowBoolOperation: false,
11151 /*ReportInvalid*/ true);
11152 if (LHSTy->isSveVLSBuiltinType() || RHSTy->isSveVLSBuiltinType())
11153 return CheckSizelessVectorOperands(LHS, RHS, Loc, IsCompAssign,
11154 OperationKind: ArithConvKind::Arithmetic);
11155 if (!IsDiv &&
11156 (LHSTy->isConstantMatrixType() || RHSTy->isConstantMatrixType()))
11157 return CheckMatrixMultiplyOperands(LHS, RHS, Loc, IsCompAssign);
11158 // For division, only matrix-by-scalar is supported. Other combinations with
11159 // matrix types are invalid.
11160 if (IsDiv && LHSTy->isConstantMatrixType() && RHSTy->isArithmeticType())
11161 return CheckMatrixElementwiseOperands(LHS, RHS, Loc, IsCompAssign);
11162
11163 QualType compType = UsualArithmeticConversions(
11164 LHS, RHS, Loc,
11165 ACK: IsCompAssign ? ArithConvKind::CompAssign : ArithConvKind::Arithmetic);
11166 if (LHS.isInvalid() || RHS.isInvalid())
11167 return QualType();
11168
11169 if (compType.isNull() || !compType->isArithmeticType()) {
11170 QualType ResultTy = InvalidOperands(Loc, LHS, RHS);
11171 diagnoseScopedEnums(S&: *this, Loc, LHS, RHS, Opc);
11172 return ResultTy;
11173 }
11174 if (IsDiv) {
11175 DetectPrecisionLossInComplexDivision(S&: *this, DivisorTy: RHS.get()->getType(), OpLoc: Loc);
11176 DiagnoseBadDivideOrRemainderValues(S&: *this, LHS, RHS, Loc, IsDiv);
11177 DiagnoseDivisionSizeofPointerOrArray(S&: *this, LHS: LHS.get(), RHS: RHS.get(), Loc);
11178 }
11179 return compType;
11180}
11181
11182QualType Sema::CheckRemainderOperands(
11183 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, bool IsCompAssign) {
11184 checkArithmeticNull(S&: *this, LHS, RHS, Loc, /*IsCompare=*/false);
11185
11186 // Note: This check is here to simplify the double exclusions of
11187 // scalar and vector HLSL checks. No getLangOpts().HLSL
11188 // is needed since all languages exlcude doubles.
11189 if (LHS.get()->getType()->isDoubleType() ||
11190 RHS.get()->getType()->isDoubleType() ||
11191 (LHS.get()->getType()->isVectorType() && LHS.get()
11192 ->getType()
11193 ->getAs<VectorType>()
11194 ->getElementType()
11195 ->isDoubleType()) ||
11196 (RHS.get()->getType()->isVectorType() && RHS.get()
11197 ->getType()
11198 ->getAs<VectorType>()
11199 ->getElementType()
11200 ->isDoubleType()))
11201 return InvalidOperands(Loc, LHS, RHS);
11202
11203 if (LHS.get()->getType()->isVectorType() ||
11204 RHS.get()->getType()->isVectorType()) {
11205 if ((LHS.get()->getType()->hasIntegerRepresentation() &&
11206 RHS.get()->getType()->hasIntegerRepresentation()) ||
11207 (getLangOpts().HLSL &&
11208 (LHS.get()->getType()->hasFloatingRepresentation() ||
11209 RHS.get()->getType()->hasFloatingRepresentation())))
11210 return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign,
11211 /*AllowBothBool*/ getLangOpts().AltiVec,
11212 /*AllowBoolConversions*/ false,
11213 /*AllowBooleanOperation*/ AllowBoolOperation: false,
11214 /*ReportInvalid*/ true);
11215 return InvalidOperands(Loc, LHS, RHS);
11216 }
11217
11218 if (LHS.get()->getType()->isSveVLSBuiltinType() ||
11219 RHS.get()->getType()->isSveVLSBuiltinType()) {
11220 if (LHS.get()->getType()->hasIntegerRepresentation() &&
11221 RHS.get()->getType()->hasIntegerRepresentation())
11222 return CheckSizelessVectorOperands(LHS, RHS, Loc, IsCompAssign,
11223 OperationKind: ArithConvKind::Arithmetic);
11224
11225 return InvalidOperands(Loc, LHS, RHS);
11226 }
11227
11228 QualType compType = UsualArithmeticConversions(
11229 LHS, RHS, Loc,
11230 ACK: IsCompAssign ? ArithConvKind::CompAssign : ArithConvKind::Arithmetic);
11231 if (LHS.isInvalid() || RHS.isInvalid())
11232 return QualType();
11233
11234 if (compType.isNull() ||
11235 (!compType->isIntegerType() &&
11236 !(getLangOpts().HLSL && compType->isFloatingType()))) {
11237 QualType ResultTy = InvalidOperands(Loc, LHS, RHS);
11238 diagnoseScopedEnums(S&: *this, Loc, LHS, RHS,
11239 Opc: IsCompAssign ? BO_RemAssign : BO_Rem);
11240 return ResultTy;
11241 }
11242 DiagnoseBadDivideOrRemainderValues(S&: *this, LHS, RHS, Loc, IsDiv: false /* IsDiv */);
11243 return compType;
11244}
11245
11246/// Diagnose invalid arithmetic on two void pointers.
11247static void diagnoseArithmeticOnTwoVoidPointers(Sema &S, SourceLocation Loc,
11248 Expr *LHSExpr, Expr *RHSExpr) {
11249 S.Diag(Loc, DiagID: S.getLangOpts().CPlusPlus
11250 ? diag::err_typecheck_pointer_arith_void_type
11251 : diag::ext_gnu_void_ptr)
11252 << 1 /* two pointers */ << LHSExpr->getSourceRange()
11253 << RHSExpr->getSourceRange();
11254}
11255
11256/// Diagnose invalid arithmetic on a void pointer.
11257static void diagnoseArithmeticOnVoidPointer(Sema &S, SourceLocation Loc,
11258 Expr *Pointer) {
11259 S.Diag(Loc, DiagID: S.getLangOpts().CPlusPlus
11260 ? diag::err_typecheck_pointer_arith_void_type
11261 : diag::ext_gnu_void_ptr)
11262 << 0 /* one pointer */ << Pointer->getSourceRange();
11263}
11264
11265/// Diagnose invalid arithmetic on a null pointer.
11266///
11267/// If \p IsGNUIdiom is true, the operation is using the 'p = (i8*)nullptr + n'
11268/// idiom, which we recognize as a GNU extension.
11269///
11270static void diagnoseArithmeticOnNullPointer(Sema &S, SourceLocation Loc,
11271 Expr *Pointer, bool IsGNUIdiom) {
11272 if (IsGNUIdiom)
11273 S.Diag(Loc, DiagID: diag::warn_gnu_null_ptr_arith)
11274 << Pointer->getSourceRange();
11275 else
11276 S.Diag(Loc, DiagID: diag::warn_pointer_arith_null_ptr)
11277 << S.getLangOpts().CPlusPlus << Pointer->getSourceRange();
11278}
11279
11280/// Diagnose invalid subraction on a null pointer.
11281///
11282static void diagnoseSubtractionOnNullPointer(Sema &S, SourceLocation Loc,
11283 Expr *Pointer, bool BothNull) {
11284 // Null - null is valid in C++ [expr.add]p7
11285 if (BothNull && S.getLangOpts().CPlusPlus)
11286 return;
11287
11288 // Is this s a macro from a system header?
11289 if (S.Diags.getSuppressSystemWarnings() && S.SourceMgr.isInSystemMacro(loc: Loc))
11290 return;
11291
11292 S.DiagRuntimeBehavior(Loc, Statement: Pointer,
11293 PD: S.PDiag(DiagID: diag::warn_pointer_sub_null_ptr)
11294 << S.getLangOpts().CPlusPlus
11295 << Pointer->getSourceRange());
11296}
11297
11298/// Diagnose invalid arithmetic on two function pointers.
11299static void diagnoseArithmeticOnTwoFunctionPointers(Sema &S, SourceLocation Loc,
11300 Expr *LHS, Expr *RHS) {
11301 assert(LHS->getType()->isAnyPointerType());
11302 assert(RHS->getType()->isAnyPointerType());
11303 S.Diag(Loc, DiagID: S.getLangOpts().CPlusPlus
11304 ? diag::err_typecheck_pointer_arith_function_type
11305 : diag::ext_gnu_ptr_func_arith)
11306 << 1 /* two pointers */ << LHS->getType()->getPointeeType()
11307 // We only show the second type if it differs from the first.
11308 << (unsigned)!S.Context.hasSameUnqualifiedType(T1: LHS->getType(),
11309 T2: RHS->getType())
11310 << RHS->getType()->getPointeeType()
11311 << LHS->getSourceRange() << RHS->getSourceRange();
11312}
11313
11314/// Diagnose invalid arithmetic on a function pointer.
11315static void diagnoseArithmeticOnFunctionPointer(Sema &S, SourceLocation Loc,
11316 Expr *Pointer) {
11317 assert(Pointer->getType()->isAnyPointerType());
11318 S.Diag(Loc, DiagID: S.getLangOpts().CPlusPlus
11319 ? diag::err_typecheck_pointer_arith_function_type
11320 : diag::ext_gnu_ptr_func_arith)
11321 << 0 /* one pointer */ << Pointer->getType()->getPointeeType()
11322 << 0 /* one pointer, so only one type */
11323 << Pointer->getSourceRange();
11324}
11325
11326/// Emit error if Operand is incomplete pointer type
11327///
11328/// \returns True if pointer has incomplete type
11329static bool checkArithmeticIncompletePointerType(Sema &S, SourceLocation Loc,
11330 Expr *Operand) {
11331 QualType ResType = Operand->getType();
11332 if (const AtomicType *ResAtomicType = ResType->getAs<AtomicType>())
11333 ResType = ResAtomicType->getValueType();
11334
11335 assert(ResType->isAnyPointerType());
11336 QualType PointeeTy = ResType->getPointeeType();
11337 return S.RequireCompleteSizedType(
11338 Loc, T: PointeeTy,
11339 DiagID: diag::err_typecheck_arithmetic_incomplete_or_sizeless_type,
11340 Args: Operand->getSourceRange());
11341}
11342
11343/// Check the validity of an arithmetic pointer operand.
11344///
11345/// If the operand has pointer type, this code will check for pointer types
11346/// which are invalid in arithmetic operations. These will be diagnosed
11347/// appropriately, including whether or not the use is supported as an
11348/// extension.
11349///
11350/// \returns True when the operand is valid to use (even if as an extension).
11351static bool checkArithmeticOpPointerOperand(Sema &S, SourceLocation Loc,
11352 Expr *Operand) {
11353 QualType ResType = Operand->getType();
11354 if (const AtomicType *ResAtomicType = ResType->getAs<AtomicType>())
11355 ResType = ResAtomicType->getValueType();
11356
11357 if (!ResType->isAnyPointerType()) return true;
11358
11359 QualType PointeeTy = ResType->getPointeeType();
11360 if (PointeeTy->isVoidType()) {
11361 diagnoseArithmeticOnVoidPointer(S, Loc, Pointer: Operand);
11362 return !S.getLangOpts().CPlusPlus;
11363 }
11364 if (PointeeTy->isFunctionType()) {
11365 diagnoseArithmeticOnFunctionPointer(S, Loc, Pointer: Operand);
11366 return !S.getLangOpts().CPlusPlus;
11367 }
11368
11369 if (checkArithmeticIncompletePointerType(S, Loc, Operand)) return false;
11370
11371 return true;
11372}
11373
11374/// Check the validity of a binary arithmetic operation w.r.t. pointer
11375/// operands.
11376///
11377/// This routine will diagnose any invalid arithmetic on pointer operands much
11378/// like \see checkArithmeticOpPointerOperand. However, it has special logic
11379/// for emitting a single diagnostic even for operations where both LHS and RHS
11380/// are (potentially problematic) pointers.
11381///
11382/// \returns True when the operand is valid to use (even if as an extension).
11383static bool checkArithmeticBinOpPointerOperands(Sema &S, SourceLocation Loc,
11384 Expr *LHSExpr, Expr *RHSExpr) {
11385 bool isLHSPointer = LHSExpr->getType()->isAnyPointerType();
11386 bool isRHSPointer = RHSExpr->getType()->isAnyPointerType();
11387 if (!isLHSPointer && !isRHSPointer) return true;
11388
11389 QualType LHSPointeeTy, RHSPointeeTy;
11390 if (isLHSPointer) LHSPointeeTy = LHSExpr->getType()->getPointeeType();
11391 if (isRHSPointer) RHSPointeeTy = RHSExpr->getType()->getPointeeType();
11392
11393 // if both are pointers check if operation is valid wrt address spaces
11394 if (isLHSPointer && isRHSPointer) {
11395 if (!LHSPointeeTy.isAddressSpaceOverlapping(T: RHSPointeeTy,
11396 Ctx: S.getASTContext())) {
11397 S.Diag(Loc,
11398 DiagID: diag::err_typecheck_op_on_nonoverlapping_address_space_pointers)
11399 << LHSExpr->getType() << RHSExpr->getType() << 1 /*arithmetic op*/
11400 << LHSExpr->getSourceRange() << RHSExpr->getSourceRange();
11401 return false;
11402 }
11403 }
11404
11405 // Check for arithmetic on pointers to incomplete types.
11406 bool isLHSVoidPtr = isLHSPointer && LHSPointeeTy->isVoidType();
11407 bool isRHSVoidPtr = isRHSPointer && RHSPointeeTy->isVoidType();
11408 if (isLHSVoidPtr || isRHSVoidPtr) {
11409 if (!isRHSVoidPtr) diagnoseArithmeticOnVoidPointer(S, Loc, Pointer: LHSExpr);
11410 else if (!isLHSVoidPtr) diagnoseArithmeticOnVoidPointer(S, Loc, Pointer: RHSExpr);
11411 else diagnoseArithmeticOnTwoVoidPointers(S, Loc, LHSExpr, RHSExpr);
11412
11413 return !S.getLangOpts().CPlusPlus;
11414 }
11415
11416 bool isLHSFuncPtr = isLHSPointer && LHSPointeeTy->isFunctionType();
11417 bool isRHSFuncPtr = isRHSPointer && RHSPointeeTy->isFunctionType();
11418 if (isLHSFuncPtr || isRHSFuncPtr) {
11419 if (!isRHSFuncPtr) diagnoseArithmeticOnFunctionPointer(S, Loc, Pointer: LHSExpr);
11420 else if (!isLHSFuncPtr) diagnoseArithmeticOnFunctionPointer(S, Loc,
11421 Pointer: RHSExpr);
11422 else diagnoseArithmeticOnTwoFunctionPointers(S, Loc, LHS: LHSExpr, RHS: RHSExpr);
11423
11424 return !S.getLangOpts().CPlusPlus;
11425 }
11426
11427 if (isLHSPointer && checkArithmeticIncompletePointerType(S, Loc, Operand: LHSExpr))
11428 return false;
11429 if (isRHSPointer && checkArithmeticIncompletePointerType(S, Loc, Operand: RHSExpr))
11430 return false;
11431
11432 return true;
11433}
11434
11435/// diagnoseStringPlusInt - Emit a warning when adding an integer to a string
11436/// literal.
11437static void diagnoseStringPlusInt(Sema &Self, SourceLocation OpLoc,
11438 Expr *LHSExpr, Expr *RHSExpr) {
11439 StringLiteral* StrExpr = dyn_cast<StringLiteral>(Val: LHSExpr->IgnoreImpCasts());
11440 Expr* IndexExpr = RHSExpr;
11441 if (!StrExpr) {
11442 StrExpr = dyn_cast<StringLiteral>(Val: RHSExpr->IgnoreImpCasts());
11443 IndexExpr = LHSExpr;
11444 }
11445
11446 bool IsStringPlusInt = StrExpr &&
11447 IndexExpr->getType()->isIntegralOrUnscopedEnumerationType();
11448 if (!IsStringPlusInt || IndexExpr->isValueDependent())
11449 return;
11450
11451 SourceRange DiagRange(LHSExpr->getBeginLoc(), RHSExpr->getEndLoc());
11452 Self.Diag(Loc: OpLoc, DiagID: diag::warn_string_plus_int)
11453 << DiagRange << IndexExpr->IgnoreImpCasts()->getType();
11454
11455 // Only print a fixit for "str" + int, not for int + "str".
11456 if (IndexExpr == RHSExpr) {
11457 SourceLocation EndLoc = Self.getLocForEndOfToken(Loc: RHSExpr->getEndLoc());
11458 Self.Diag(Loc: OpLoc, DiagID: diag::note_string_plus_scalar_silence)
11459 << FixItHint::CreateInsertion(InsertionLoc: LHSExpr->getBeginLoc(), Code: "&")
11460 << FixItHint::CreateReplacement(RemoveRange: SourceRange(OpLoc), Code: "[")
11461 << FixItHint::CreateInsertion(InsertionLoc: EndLoc, Code: "]");
11462 } else
11463 Self.Diag(Loc: OpLoc, DiagID: diag::note_string_plus_scalar_silence);
11464}
11465
11466/// Emit a warning when adding a char literal to a string.
11467static void diagnoseStringPlusChar(Sema &Self, SourceLocation OpLoc,
11468 Expr *LHSExpr, Expr *RHSExpr) {
11469 const Expr *StringRefExpr = LHSExpr;
11470 const CharacterLiteral *CharExpr =
11471 dyn_cast<CharacterLiteral>(Val: RHSExpr->IgnoreImpCasts());
11472
11473 if (!CharExpr) {
11474 CharExpr = dyn_cast<CharacterLiteral>(Val: LHSExpr->IgnoreImpCasts());
11475 StringRefExpr = RHSExpr;
11476 }
11477
11478 if (!CharExpr || !StringRefExpr)
11479 return;
11480
11481 const QualType StringType = StringRefExpr->getType();
11482
11483 // Return if not a PointerType.
11484 if (!StringType->isAnyPointerType())
11485 return;
11486
11487 // Return if not a CharacterType.
11488 if (!StringType->getPointeeType()->isAnyCharacterType())
11489 return;
11490
11491 ASTContext &Ctx = Self.getASTContext();
11492 SourceRange DiagRange(LHSExpr->getBeginLoc(), RHSExpr->getEndLoc());
11493
11494 const QualType CharType = CharExpr->getType();
11495 if (!CharType->isAnyCharacterType() &&
11496 CharType->isIntegerType() &&
11497 llvm::isUIntN(N: Ctx.getCharWidth(), x: CharExpr->getValue())) {
11498 Self.Diag(Loc: OpLoc, DiagID: diag::warn_string_plus_char)
11499 << DiagRange << Ctx.CharTy;
11500 } else {
11501 Self.Diag(Loc: OpLoc, DiagID: diag::warn_string_plus_char)
11502 << DiagRange << CharExpr->getType();
11503 }
11504
11505 // Only print a fixit for str + char, not for char + str.
11506 if (isa<CharacterLiteral>(Val: RHSExpr->IgnoreImpCasts())) {
11507 SourceLocation EndLoc = Self.getLocForEndOfToken(Loc: RHSExpr->getEndLoc());
11508 Self.Diag(Loc: OpLoc, DiagID: diag::note_string_plus_scalar_silence)
11509 << FixItHint::CreateInsertion(InsertionLoc: LHSExpr->getBeginLoc(), Code: "&")
11510 << FixItHint::CreateReplacement(RemoveRange: SourceRange(OpLoc), Code: "[")
11511 << FixItHint::CreateInsertion(InsertionLoc: EndLoc, Code: "]");
11512 } else {
11513 Self.Diag(Loc: OpLoc, DiagID: diag::note_string_plus_scalar_silence);
11514 }
11515}
11516
11517/// Emit error when two pointers are incompatible.
11518static void diagnosePointerIncompatibility(Sema &S, SourceLocation Loc,
11519 Expr *LHSExpr, Expr *RHSExpr) {
11520 assert(LHSExpr->getType()->isAnyPointerType());
11521 assert(RHSExpr->getType()->isAnyPointerType());
11522 S.Diag(Loc, DiagID: diag::err_typecheck_sub_ptr_compatible)
11523 << LHSExpr->getType() << RHSExpr->getType() << LHSExpr->getSourceRange()
11524 << RHSExpr->getSourceRange();
11525}
11526
11527// C99 6.5.6
11528QualType Sema::CheckAdditionOperands(ExprResult &LHS, ExprResult &RHS,
11529 SourceLocation Loc, BinaryOperatorKind Opc,
11530 QualType* CompLHSTy) {
11531 checkArithmeticNull(S&: *this, LHS, RHS, Loc, /*IsCompare=*/false);
11532
11533 if (LHS.get()->getType()->isVectorType() ||
11534 RHS.get()->getType()->isVectorType()) {
11535 QualType compType =
11536 CheckVectorOperands(LHS, RHS, Loc, IsCompAssign: CompLHSTy,
11537 /*AllowBothBool*/ getLangOpts().AltiVec,
11538 /*AllowBoolConversions*/ getLangOpts().ZVector,
11539 /*AllowBooleanOperation*/ AllowBoolOperation: false,
11540 /*ReportInvalid*/ true);
11541 if (CompLHSTy) *CompLHSTy = compType;
11542 return compType;
11543 }
11544
11545 if (LHS.get()->getType()->isSveVLSBuiltinType() ||
11546 RHS.get()->getType()->isSveVLSBuiltinType()) {
11547 QualType compType = CheckSizelessVectorOperands(LHS, RHS, Loc, IsCompAssign: CompLHSTy,
11548 OperationKind: ArithConvKind::Arithmetic);
11549 if (CompLHSTy)
11550 *CompLHSTy = compType;
11551 return compType;
11552 }
11553
11554 if (LHS.get()->getType()->isConstantMatrixType() ||
11555 RHS.get()->getType()->isConstantMatrixType()) {
11556 QualType compType =
11557 CheckMatrixElementwiseOperands(LHS, RHS, Loc, IsCompAssign: CompLHSTy);
11558 if (CompLHSTy)
11559 *CompLHSTy = compType;
11560 return compType;
11561 }
11562
11563 QualType compType = UsualArithmeticConversions(
11564 LHS, RHS, Loc,
11565 ACK: CompLHSTy ? ArithConvKind::CompAssign : ArithConvKind::Arithmetic);
11566 if (LHS.isInvalid() || RHS.isInvalid())
11567 return QualType();
11568
11569 // Diagnose "string literal" '+' int and string '+' "char literal".
11570 if (Opc == BO_Add) {
11571 diagnoseStringPlusInt(Self&: *this, OpLoc: Loc, LHSExpr: LHS.get(), RHSExpr: RHS.get());
11572 diagnoseStringPlusChar(Self&: *this, OpLoc: Loc, LHSExpr: LHS.get(), RHSExpr: RHS.get());
11573 }
11574
11575 // handle the common case first (both operands are arithmetic).
11576 if (!compType.isNull() && compType->isArithmeticType()) {
11577 if (CompLHSTy) *CompLHSTy = compType;
11578 return compType;
11579 }
11580
11581 // Type-checking. Ultimately the pointer's going to be in PExp;
11582 // note that we bias towards the LHS being the pointer.
11583 Expr *PExp = LHS.get(), *IExp = RHS.get();
11584
11585 bool isObjCPointer;
11586 if (PExp->getType()->isPointerType()) {
11587 isObjCPointer = false;
11588 } else if (PExp->getType()->isObjCObjectPointerType()) {
11589 isObjCPointer = true;
11590 } else {
11591 std::swap(a&: PExp, b&: IExp);
11592 if (PExp->getType()->isPointerType()) {
11593 isObjCPointer = false;
11594 } else if (PExp->getType()->isObjCObjectPointerType()) {
11595 isObjCPointer = true;
11596 } else {
11597 QualType ResultTy = InvalidOperands(Loc, LHS, RHS);
11598 diagnoseScopedEnums(S&: *this, Loc, LHS, RHS, Opc);
11599 return ResultTy;
11600 }
11601 }
11602 assert(PExp->getType()->isAnyPointerType());
11603
11604 if (!IExp->getType()->isIntegerType())
11605 return InvalidOperands(Loc, LHS, RHS);
11606
11607 // Adding to a null pointer results in undefined behavior.
11608 if (PExp->IgnoreParenCasts()->isNullPointerConstant(
11609 Ctx&: Context, NPC: Expr::NPC_ValueDependentIsNotNull)) {
11610 // In C++ adding zero to a null pointer is defined.
11611 Expr::EvalResult KnownVal;
11612 if (!getLangOpts().CPlusPlus ||
11613 (!IExp->isValueDependent() &&
11614 (!IExp->EvaluateAsInt(Result&: KnownVal, Ctx: Context) ||
11615 KnownVal.Val.getInt() != 0))) {
11616 // Check the conditions to see if this is the 'p = nullptr + n' idiom.
11617 bool IsGNUIdiom = BinaryOperator::isNullPointerArithmeticExtension(
11618 Ctx&: Context, Opc: BO_Add, LHS: PExp, RHS: IExp);
11619 diagnoseArithmeticOnNullPointer(S&: *this, Loc, Pointer: PExp, IsGNUIdiom);
11620 }
11621 }
11622
11623 if (!checkArithmeticOpPointerOperand(S&: *this, Loc, Operand: PExp))
11624 return QualType();
11625
11626 if (isObjCPointer && checkArithmeticOnObjCPointer(S&: *this, opLoc: Loc, op: PExp))
11627 return QualType();
11628
11629 // Arithmetic on label addresses is normally allowed, except when we add
11630 // a ptrauth signature to the addresses.
11631 if (isa<AddrLabelExpr>(Val: PExp) && getLangOpts().PointerAuthIndirectGotos) {
11632 Diag(Loc, DiagID: diag::err_ptrauth_indirect_goto_addrlabel_arithmetic)
11633 << /*addition*/ 1;
11634 return QualType();
11635 }
11636
11637 // Check array bounds for pointer arithemtic
11638 CheckArrayAccess(BaseExpr: PExp, IndexExpr: IExp);
11639
11640 if (CompLHSTy) {
11641 QualType LHSTy = Context.isPromotableBitField(E: LHS.get());
11642 if (LHSTy.isNull()) {
11643 LHSTy = LHS.get()->getType();
11644 if (Context.isPromotableIntegerType(T: LHSTy))
11645 LHSTy = Context.getPromotedIntegerType(PromotableType: LHSTy);
11646 }
11647 *CompLHSTy = LHSTy;
11648 }
11649
11650 return PExp->getType();
11651}
11652
11653// C99 6.5.6
11654QualType Sema::CheckSubtractionOperands(ExprResult &LHS, ExprResult &RHS,
11655 SourceLocation Loc,
11656 BinaryOperatorKind Opc,
11657 QualType *CompLHSTy) {
11658 checkArithmeticNull(S&: *this, LHS, RHS, Loc, /*IsCompare=*/false);
11659
11660 if (LHS.get()->getType()->isVectorType() ||
11661 RHS.get()->getType()->isVectorType()) {
11662 QualType compType =
11663 CheckVectorOperands(LHS, RHS, Loc, IsCompAssign: CompLHSTy,
11664 /*AllowBothBool*/ getLangOpts().AltiVec,
11665 /*AllowBoolConversions*/ getLangOpts().ZVector,
11666 /*AllowBooleanOperation*/ AllowBoolOperation: false,
11667 /*ReportInvalid*/ true);
11668 if (CompLHSTy) *CompLHSTy = compType;
11669 return compType;
11670 }
11671
11672 if (LHS.get()->getType()->isSveVLSBuiltinType() ||
11673 RHS.get()->getType()->isSveVLSBuiltinType()) {
11674 QualType compType = CheckSizelessVectorOperands(LHS, RHS, Loc, IsCompAssign: CompLHSTy,
11675 OperationKind: ArithConvKind::Arithmetic);
11676 if (CompLHSTy)
11677 *CompLHSTy = compType;
11678 return compType;
11679 }
11680
11681 if (LHS.get()->getType()->isConstantMatrixType() ||
11682 RHS.get()->getType()->isConstantMatrixType()) {
11683 QualType compType =
11684 CheckMatrixElementwiseOperands(LHS, RHS, Loc, IsCompAssign: CompLHSTy);
11685 if (CompLHSTy)
11686 *CompLHSTy = compType;
11687 return compType;
11688 }
11689
11690 QualType compType = UsualArithmeticConversions(
11691 LHS, RHS, Loc,
11692 ACK: CompLHSTy ? ArithConvKind::CompAssign : ArithConvKind::Arithmetic);
11693 if (LHS.isInvalid() || RHS.isInvalid())
11694 return QualType();
11695
11696 // Enforce type constraints: C99 6.5.6p3.
11697
11698 // Handle the common case first (both operands are arithmetic).
11699 if (!compType.isNull() && compType->isArithmeticType()) {
11700 if (CompLHSTy) *CompLHSTy = compType;
11701 return compType;
11702 }
11703
11704 // Either ptr - int or ptr - ptr.
11705 if (LHS.get()->getType()->isAnyPointerType()) {
11706 QualType lpointee = LHS.get()->getType()->getPointeeType();
11707
11708 // Diagnose bad cases where we step over interface counts.
11709 if (LHS.get()->getType()->isObjCObjectPointerType() &&
11710 checkArithmeticOnObjCPointer(S&: *this, opLoc: Loc, op: LHS.get()))
11711 return QualType();
11712
11713 // Arithmetic on label addresses is normally allowed, except when we add
11714 // a ptrauth signature to the addresses.
11715 if (isa<AddrLabelExpr>(Val: LHS.get()) &&
11716 getLangOpts().PointerAuthIndirectGotos) {
11717 Diag(Loc, DiagID: diag::err_ptrauth_indirect_goto_addrlabel_arithmetic)
11718 << /*subtraction*/ 0;
11719 return QualType();
11720 }
11721
11722 // The result type of a pointer-int computation is the pointer type.
11723 if (RHS.get()->getType()->isIntegerType()) {
11724 // Subtracting from a null pointer should produce a warning.
11725 // The last argument to the diagnose call says this doesn't match the
11726 // GNU int-to-pointer idiom.
11727 if (LHS.get()->IgnoreParenCasts()->isNullPointerConstant(Ctx&: Context,
11728 NPC: Expr::NPC_ValueDependentIsNotNull)) {
11729 // In C++ adding zero to a null pointer is defined.
11730 Expr::EvalResult KnownVal;
11731 if (!getLangOpts().CPlusPlus ||
11732 (!RHS.get()->isValueDependent() &&
11733 (!RHS.get()->EvaluateAsInt(Result&: KnownVal, Ctx: Context) ||
11734 KnownVal.Val.getInt() != 0))) {
11735 diagnoseArithmeticOnNullPointer(S&: *this, Loc, Pointer: LHS.get(), IsGNUIdiom: false);
11736 }
11737 }
11738
11739 if (!checkArithmeticOpPointerOperand(S&: *this, Loc, Operand: LHS.get()))
11740 return QualType();
11741
11742 // Check array bounds for pointer arithemtic
11743 CheckArrayAccess(BaseExpr: LHS.get(), IndexExpr: RHS.get(), /*ArraySubscriptExpr*/ASE: nullptr,
11744 /*AllowOnePastEnd*/true, /*IndexNegated*/true);
11745
11746 if (CompLHSTy) *CompLHSTy = LHS.get()->getType();
11747 return LHS.get()->getType();
11748 }
11749
11750 // Handle pointer-pointer subtractions.
11751 if (const PointerType *RHSPTy
11752 = RHS.get()->getType()->getAs<PointerType>()) {
11753 QualType rpointee = RHSPTy->getPointeeType();
11754
11755 if (getLangOpts().CPlusPlus) {
11756 // Pointee types must be the same: C++ [expr.add]
11757 if (!Context.hasSameUnqualifiedType(T1: lpointee, T2: rpointee)) {
11758 diagnosePointerIncompatibility(S&: *this, Loc, LHSExpr: LHS.get(), RHSExpr: RHS.get());
11759 }
11760 } else {
11761 // Pointee types must be compatible C99 6.5.6p3
11762 if (!Context.typesAreCompatible(
11763 T1: Context.getCanonicalType(T: lpointee).getUnqualifiedType(),
11764 T2: Context.getCanonicalType(T: rpointee).getUnqualifiedType())) {
11765 diagnosePointerIncompatibility(S&: *this, Loc, LHSExpr: LHS.get(), RHSExpr: RHS.get());
11766 return QualType();
11767 }
11768 }
11769
11770 if (!checkArithmeticBinOpPointerOperands(S&: *this, Loc,
11771 LHSExpr: LHS.get(), RHSExpr: RHS.get()))
11772 return QualType();
11773
11774 bool LHSIsNullPtr = LHS.get()->IgnoreParenCasts()->isNullPointerConstant(
11775 Ctx&: Context, NPC: Expr::NPC_ValueDependentIsNotNull);
11776 bool RHSIsNullPtr = RHS.get()->IgnoreParenCasts()->isNullPointerConstant(
11777 Ctx&: Context, NPC: Expr::NPC_ValueDependentIsNotNull);
11778
11779 // Subtracting nullptr or from nullptr is suspect
11780 if (LHSIsNullPtr)
11781 diagnoseSubtractionOnNullPointer(S&: *this, Loc, Pointer: LHS.get(), BothNull: RHSIsNullPtr);
11782 if (RHSIsNullPtr)
11783 diagnoseSubtractionOnNullPointer(S&: *this, Loc, Pointer: RHS.get(), BothNull: LHSIsNullPtr);
11784
11785 // The pointee type may have zero size. As an extension, a structure or
11786 // union may have zero size or an array may have zero length. In this
11787 // case subtraction does not make sense.
11788 if (!rpointee->isVoidType() && !rpointee->isFunctionType()) {
11789 CharUnits ElementSize = Context.getTypeSizeInChars(T: rpointee);
11790 if (ElementSize.isZero()) {
11791 Diag(Loc,DiagID: diag::warn_sub_ptr_zero_size_types)
11792 << rpointee.getUnqualifiedType()
11793 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
11794 }
11795 }
11796
11797 if (CompLHSTy) *CompLHSTy = LHS.get()->getType();
11798 return Context.getPointerDiffType();
11799 }
11800 }
11801
11802 QualType ResultTy = InvalidOperands(Loc, LHS, RHS);
11803 diagnoseScopedEnums(S&: *this, Loc, LHS, RHS, Opc);
11804 return ResultTy;
11805}
11806
11807static bool isScopedEnumerationType(QualType T) {
11808 if (const EnumType *ET = T->getAsCanonical<EnumType>())
11809 return ET->getDecl()->isScoped();
11810 return false;
11811}
11812
11813static void DiagnoseBadShiftValues(Sema& S, ExprResult &LHS, ExprResult &RHS,
11814 SourceLocation Loc, BinaryOperatorKind Opc,
11815 QualType LHSType) {
11816 // OpenCL 6.3j: shift values are effectively % word size of LHS (more defined),
11817 // so skip remaining warnings as we don't want to modify values within Sema.
11818 if (S.getLangOpts().OpenCL)
11819 return;
11820
11821 if (Opc == BO_Shr &&
11822 LHS.get()->IgnoreParenImpCasts()->getType()->isBooleanType())
11823 S.Diag(Loc, DiagID: diag::warn_shift_bool) << LHS.get()->getSourceRange();
11824
11825 // Check right/shifter operand
11826 Expr::EvalResult RHSResult;
11827 if (RHS.get()->isValueDependent() ||
11828 !RHS.get()->EvaluateAsInt(Result&: RHSResult, Ctx: S.Context))
11829 return;
11830 llvm::APSInt Right = RHSResult.Val.getInt();
11831
11832 if (Right.isNegative()) {
11833 S.DiagRuntimeBehavior(Loc, Statement: RHS.get(),
11834 PD: S.PDiag(DiagID: diag::warn_shift_negative)
11835 << RHS.get()->getSourceRange());
11836 return;
11837 }
11838
11839 QualType LHSExprType = LHS.get()->getType();
11840 uint64_t LeftSize = S.Context.getTypeSize(T: LHSExprType);
11841 if (LHSExprType->isBitIntType())
11842 LeftSize = S.Context.getIntWidth(T: LHSExprType);
11843 else if (LHSExprType->isFixedPointType()) {
11844 auto FXSema = S.Context.getFixedPointSemantics(Ty: LHSExprType);
11845 LeftSize = FXSema.getWidth() - (unsigned)FXSema.hasUnsignedPadding();
11846 }
11847 if (Right.uge(RHS: LeftSize)) {
11848 S.DiagRuntimeBehavior(Loc, Statement: RHS.get(),
11849 PD: S.PDiag(DiagID: diag::warn_shift_gt_typewidth)
11850 << RHS.get()->getSourceRange());
11851 return;
11852 }
11853
11854 // FIXME: We probably need to handle fixed point types specially here.
11855 if (Opc != BO_Shl || LHSExprType->isFixedPointType())
11856 return;
11857
11858 // When left shifting an ICE which is signed, we can check for overflow which
11859 // according to C++ standards prior to C++2a has undefined behavior
11860 // ([expr.shift] 5.8/2). Unsigned integers have defined behavior modulo one
11861 // more than the maximum value representable in the result type, so never
11862 // warn for those. (FIXME: Unsigned left-shift overflow in a constant
11863 // expression is still probably a bug.)
11864 Expr::EvalResult LHSResult;
11865 if (LHS.get()->isValueDependent() ||
11866 LHSType->hasUnsignedIntegerRepresentation() ||
11867 !LHS.get()->EvaluateAsInt(Result&: LHSResult, Ctx: S.Context))
11868 return;
11869 llvm::APSInt Left = LHSResult.Val.getInt();
11870
11871 // Don't warn if signed overflow is defined, then all the rest of the
11872 // diagnostics will not be triggered because the behavior is defined.
11873 // Also don't warn in C++20 mode (and newer), as signed left shifts
11874 // always wrap and never overflow.
11875 if (S.getLangOpts().isSignedOverflowDefined() || S.getLangOpts().CPlusPlus20)
11876 return;
11877
11878 // If LHS does not have a non-negative value then, the
11879 // behavior is undefined before C++2a. Warn about it.
11880 if (Left.isNegative()) {
11881 S.DiagRuntimeBehavior(Loc, Statement: LHS.get(),
11882 PD: S.PDiag(DiagID: diag::warn_shift_lhs_negative)
11883 << LHS.get()->getSourceRange());
11884 return;
11885 }
11886
11887 llvm::APInt ResultBits =
11888 static_cast<llvm::APInt &>(Right) + Left.getSignificantBits();
11889 if (ResultBits.ule(RHS: LeftSize))
11890 return;
11891 llvm::APSInt Result = Left.extend(width: ResultBits.getLimitedValue());
11892 Result = Result.shl(ShiftAmt: Right);
11893
11894 // Print the bit representation of the signed integer as an unsigned
11895 // hexadecimal number.
11896 SmallString<40> HexResult;
11897 Result.toString(Str&: HexResult, Radix: 16, /*Signed =*/false, /*Literal =*/formatAsCLiteral: true);
11898
11899 // If we are only missing a sign bit, this is less likely to result in actual
11900 // bugs -- if the result is cast back to an unsigned type, it will have the
11901 // expected value. Thus we place this behind a different warning that can be
11902 // turned off separately if needed.
11903 if (ResultBits - 1 == LeftSize) {
11904 S.Diag(Loc, DiagID: diag::warn_shift_result_sets_sign_bit)
11905 << HexResult << LHSType
11906 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
11907 return;
11908 }
11909
11910 S.Diag(Loc, DiagID: diag::warn_shift_result_gt_typewidth)
11911 << HexResult.str() << Result.getSignificantBits() << LHSType
11912 << Left.getBitWidth() << LHS.get()->getSourceRange()
11913 << RHS.get()->getSourceRange();
11914}
11915
11916/// Return the resulting type when a vector is shifted
11917/// by a scalar or vector shift amount.
11918static QualType checkVectorShift(Sema &S, ExprResult &LHS, ExprResult &RHS,
11919 SourceLocation Loc, bool IsCompAssign) {
11920 // OpenCL v1.1 s6.3.j says RHS can be a vector only if LHS is a vector.
11921 if ((S.LangOpts.OpenCL || S.LangOpts.ZVector) &&
11922 !LHS.get()->getType()->isVectorType()) {
11923 S.Diag(Loc, DiagID: diag::err_shift_rhs_only_vector)
11924 << RHS.get()->getType() << LHS.get()->getType()
11925 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
11926 return QualType();
11927 }
11928
11929 if (!IsCompAssign) {
11930 LHS = S.UsualUnaryConversions(E: LHS.get());
11931 if (LHS.isInvalid()) return QualType();
11932 }
11933
11934 RHS = S.UsualUnaryConversions(E: RHS.get());
11935 if (RHS.isInvalid()) return QualType();
11936
11937 QualType LHSType = LHS.get()->getType();
11938 // Note that LHS might be a scalar because the routine calls not only in
11939 // OpenCL case.
11940 const VectorType *LHSVecTy = LHSType->getAs<VectorType>();
11941 QualType LHSEleType = LHSVecTy ? LHSVecTy->getElementType() : LHSType;
11942
11943 // Note that RHS might not be a vector.
11944 QualType RHSType = RHS.get()->getType();
11945 const VectorType *RHSVecTy = RHSType->getAs<VectorType>();
11946 QualType RHSEleType = RHSVecTy ? RHSVecTy->getElementType() : RHSType;
11947
11948 // Do not allow shifts for boolean vectors.
11949 if ((LHSVecTy && LHSVecTy->isExtVectorBoolType()) ||
11950 (RHSVecTy && RHSVecTy->isExtVectorBoolType())) {
11951 S.Diag(Loc, DiagID: diag::err_typecheck_invalid_operands)
11952 << LHS.get()->getType() << RHS.get()->getType()
11953 << LHS.get()->getSourceRange();
11954 return QualType();
11955 }
11956
11957 // The operands need to be integers.
11958 if (!LHSEleType->isIntegerType()) {
11959 S.Diag(Loc, DiagID: diag::err_typecheck_expect_int)
11960 << LHS.get()->getType() << LHS.get()->getSourceRange();
11961 return QualType();
11962 }
11963
11964 if (!RHSEleType->isIntegerType()) {
11965 S.Diag(Loc, DiagID: diag::err_typecheck_expect_int)
11966 << RHS.get()->getType() << RHS.get()->getSourceRange();
11967 return QualType();
11968 }
11969
11970 if (!LHSVecTy) {
11971 assert(RHSVecTy);
11972 if (IsCompAssign)
11973 return RHSType;
11974 if (LHSEleType != RHSEleType) {
11975 LHS = S.ImpCastExprToType(E: LHS.get(),Type: RHSEleType, CK: CK_IntegralCast);
11976 LHSEleType = RHSEleType;
11977 }
11978 QualType VecTy =
11979 S.Context.getExtVectorType(VectorType: LHSEleType, NumElts: RHSVecTy->getNumElements());
11980 LHS = S.ImpCastExprToType(E: LHS.get(), Type: VecTy, CK: CK_VectorSplat);
11981 LHSType = VecTy;
11982 } else if (RHSVecTy) {
11983 // OpenCL v1.1 s6.3.j says that for vector types, the operators
11984 // are applied component-wise. So if RHS is a vector, then ensure
11985 // that the number of elements is the same as LHS...
11986 if (RHSVecTy->getNumElements() != LHSVecTy->getNumElements()) {
11987 S.Diag(Loc, DiagID: diag::err_typecheck_vector_lengths_not_equal)
11988 << LHS.get()->getType() << RHS.get()->getType()
11989 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
11990 return QualType();
11991 }
11992 if (!S.LangOpts.OpenCL && !S.LangOpts.ZVector) {
11993 const BuiltinType *LHSBT = LHSEleType->getAs<clang::BuiltinType>();
11994 const BuiltinType *RHSBT = RHSEleType->getAs<clang::BuiltinType>();
11995 if (LHSBT != RHSBT &&
11996 S.Context.getTypeSize(T: LHSBT) != S.Context.getTypeSize(T: RHSBT)) {
11997 S.Diag(Loc, DiagID: diag::warn_typecheck_vector_element_sizes_not_equal)
11998 << LHS.get()->getType() << RHS.get()->getType()
11999 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
12000 }
12001 }
12002 } else {
12003 // ...else expand RHS to match the number of elements in LHS.
12004 QualType VecTy =
12005 S.Context.getExtVectorType(VectorType: RHSEleType, NumElts: LHSVecTy->getNumElements());
12006 RHS = S.ImpCastExprToType(E: RHS.get(), Type: VecTy, CK: CK_VectorSplat);
12007 }
12008
12009 return LHSType;
12010}
12011
12012static QualType checkSizelessVectorShift(Sema &S, ExprResult &LHS,
12013 ExprResult &RHS, SourceLocation Loc,
12014 bool IsCompAssign) {
12015 if (!IsCompAssign) {
12016 LHS = S.UsualUnaryConversions(E: LHS.get());
12017 if (LHS.isInvalid())
12018 return QualType();
12019 }
12020
12021 RHS = S.UsualUnaryConversions(E: RHS.get());
12022 if (RHS.isInvalid())
12023 return QualType();
12024
12025 QualType LHSType = LHS.get()->getType();
12026 const BuiltinType *LHSBuiltinTy = LHSType->castAs<BuiltinType>();
12027 QualType LHSEleType = LHSType->isSveVLSBuiltinType()
12028 ? LHSBuiltinTy->getSveEltType(Ctx: S.getASTContext())
12029 : LHSType;
12030
12031 // Note that RHS might not be a vector
12032 QualType RHSType = RHS.get()->getType();
12033 const BuiltinType *RHSBuiltinTy = RHSType->castAs<BuiltinType>();
12034 QualType RHSEleType = RHSType->isSveVLSBuiltinType()
12035 ? RHSBuiltinTy->getSveEltType(Ctx: S.getASTContext())
12036 : RHSType;
12037
12038 if ((LHSBuiltinTy && LHSBuiltinTy->isSVEBool()) ||
12039 (RHSBuiltinTy && RHSBuiltinTy->isSVEBool())) {
12040 S.Diag(Loc, DiagID: diag::err_typecheck_invalid_operands)
12041 << LHSType << RHSType << LHS.get()->getSourceRange();
12042 return QualType();
12043 }
12044
12045 if (!LHSEleType->isIntegerType()) {
12046 S.Diag(Loc, DiagID: diag::err_typecheck_expect_int)
12047 << LHS.get()->getType() << LHS.get()->getSourceRange();
12048 return QualType();
12049 }
12050
12051 if (!RHSEleType->isIntegerType()) {
12052 S.Diag(Loc, DiagID: diag::err_typecheck_expect_int)
12053 << RHS.get()->getType() << RHS.get()->getSourceRange();
12054 return QualType();
12055 }
12056
12057 if (LHSType->isSveVLSBuiltinType() && RHSType->isSveVLSBuiltinType() &&
12058 (S.Context.getBuiltinVectorTypeInfo(VecTy: LHSBuiltinTy).EC !=
12059 S.Context.getBuiltinVectorTypeInfo(VecTy: RHSBuiltinTy).EC)) {
12060 S.Diag(Loc, DiagID: diag::err_typecheck_invalid_operands)
12061 << LHSType << RHSType << LHS.get()->getSourceRange()
12062 << RHS.get()->getSourceRange();
12063 return QualType();
12064 }
12065
12066 if (!LHSType->isSveVLSBuiltinType()) {
12067 assert(RHSType->isSveVLSBuiltinType());
12068 if (IsCompAssign)
12069 return RHSType;
12070 if (LHSEleType != RHSEleType) {
12071 LHS = S.ImpCastExprToType(E: LHS.get(), Type: RHSEleType, CK: clang::CK_IntegralCast);
12072 LHSEleType = RHSEleType;
12073 }
12074 const llvm::ElementCount VecSize =
12075 S.Context.getBuiltinVectorTypeInfo(VecTy: RHSBuiltinTy).EC;
12076 QualType VecTy =
12077 S.Context.getScalableVectorType(EltTy: LHSEleType, NumElts: VecSize.getKnownMinValue());
12078 LHS = S.ImpCastExprToType(E: LHS.get(), Type: VecTy, CK: clang::CK_VectorSplat);
12079 LHSType = VecTy;
12080 } else if (RHSBuiltinTy && RHSBuiltinTy->isSveVLSBuiltinType()) {
12081 if (S.Context.getTypeSize(T: RHSBuiltinTy) !=
12082 S.Context.getTypeSize(T: LHSBuiltinTy)) {
12083 S.Diag(Loc, DiagID: diag::err_typecheck_vector_lengths_not_equal)
12084 << LHSType << RHSType << LHS.get()->getSourceRange()
12085 << RHS.get()->getSourceRange();
12086 return QualType();
12087 }
12088 } else {
12089 const llvm::ElementCount VecSize =
12090 S.Context.getBuiltinVectorTypeInfo(VecTy: LHSBuiltinTy).EC;
12091 if (LHSEleType != RHSEleType) {
12092 RHS = S.ImpCastExprToType(E: RHS.get(), Type: LHSEleType, CK: clang::CK_IntegralCast);
12093 RHSEleType = LHSEleType;
12094 }
12095 QualType VecTy =
12096 S.Context.getScalableVectorType(EltTy: RHSEleType, NumElts: VecSize.getKnownMinValue());
12097 RHS = S.ImpCastExprToType(E: RHS.get(), Type: VecTy, CK: CK_VectorSplat);
12098 }
12099
12100 return LHSType;
12101}
12102
12103// C99 6.5.7
12104QualType Sema::CheckShiftOperands(ExprResult &LHS, ExprResult &RHS,
12105 SourceLocation Loc, BinaryOperatorKind Opc,
12106 bool IsCompAssign) {
12107 checkArithmeticNull(S&: *this, LHS, RHS, Loc, /*IsCompare=*/false);
12108
12109 // Vector shifts promote their scalar inputs to vector type.
12110 if (LHS.get()->getType()->isVectorType() ||
12111 RHS.get()->getType()->isVectorType()) {
12112 if (LangOpts.ZVector) {
12113 // The shift operators for the z vector extensions work basically
12114 // like general shifts, except that neither the LHS nor the RHS is
12115 // allowed to be a "vector bool".
12116 if (auto LHSVecType = LHS.get()->getType()->getAs<VectorType>())
12117 if (LHSVecType->getVectorKind() == VectorKind::AltiVecBool)
12118 return InvalidOperands(Loc, LHS, RHS);
12119 if (auto RHSVecType = RHS.get()->getType()->getAs<VectorType>())
12120 if (RHSVecType->getVectorKind() == VectorKind::AltiVecBool)
12121 return InvalidOperands(Loc, LHS, RHS);
12122 }
12123 return checkVectorShift(S&: *this, LHS, RHS, Loc, IsCompAssign);
12124 }
12125
12126 if (LHS.get()->getType()->isSveVLSBuiltinType() ||
12127 RHS.get()->getType()->isSveVLSBuiltinType())
12128 return checkSizelessVectorShift(S&: *this, LHS, RHS, Loc, IsCompAssign);
12129
12130 // Shifts don't perform usual arithmetic conversions, they just do integer
12131 // promotions on each operand. C99 6.5.7p3
12132
12133 // For the LHS, do usual unary conversions, but then reset them away
12134 // if this is a compound assignment.
12135 ExprResult OldLHS = LHS;
12136 LHS = UsualUnaryConversions(E: LHS.get());
12137 if (LHS.isInvalid())
12138 return QualType();
12139 QualType LHSType = LHS.get()->getType();
12140 if (IsCompAssign) LHS = OldLHS;
12141
12142 // The RHS is simpler.
12143 RHS = UsualUnaryConversions(E: RHS.get());
12144 if (RHS.isInvalid())
12145 return QualType();
12146 QualType RHSType = RHS.get()->getType();
12147
12148 // C99 6.5.7p2: Each of the operands shall have integer type.
12149 // Embedded-C 4.1.6.2.2: The LHS may also be fixed-point.
12150 if ((!LHSType->isFixedPointOrIntegerType() &&
12151 !LHSType->hasIntegerRepresentation()) ||
12152 !RHSType->hasIntegerRepresentation()) {
12153 QualType ResultTy = InvalidOperands(Loc, LHS, RHS);
12154 diagnoseScopedEnums(S&: *this, Loc, LHS, RHS, Opc);
12155 return ResultTy;
12156 }
12157
12158 DiagnoseBadShiftValues(S&: *this, LHS, RHS, Loc, Opc, LHSType);
12159
12160 // "The type of the result is that of the promoted left operand."
12161 return LHSType;
12162}
12163
12164/// Diagnose bad pointer comparisons.
12165static void diagnoseDistinctPointerComparison(Sema &S, SourceLocation Loc,
12166 ExprResult &LHS, ExprResult &RHS,
12167 bool IsError) {
12168 S.Diag(Loc, DiagID: IsError ? diag::err_typecheck_comparison_of_distinct_pointers
12169 : diag::ext_typecheck_comparison_of_distinct_pointers)
12170 << LHS.get()->getType() << RHS.get()->getType()
12171 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
12172}
12173
12174/// Returns false if the pointers are converted to a composite type,
12175/// true otherwise.
12176static bool convertPointersToCompositeType(Sema &S, SourceLocation Loc,
12177 ExprResult &LHS, ExprResult &RHS) {
12178 // C++ [expr.rel]p2:
12179 // [...] Pointer conversions (4.10) and qualification
12180 // conversions (4.4) are performed on pointer operands (or on
12181 // a pointer operand and a null pointer constant) to bring
12182 // them to their composite pointer type. [...]
12183 //
12184 // C++ [expr.eq]p1 uses the same notion for (in)equality
12185 // comparisons of pointers.
12186
12187 QualType LHSType = LHS.get()->getType();
12188 QualType RHSType = RHS.get()->getType();
12189 assert(LHSType->isPointerType() || RHSType->isPointerType() ||
12190 LHSType->isMemberPointerType() || RHSType->isMemberPointerType());
12191
12192 QualType T = S.FindCompositePointerType(Loc, E1&: LHS, E2&: RHS);
12193 if (T.isNull()) {
12194 if ((LHSType->isAnyPointerType() || LHSType->isMemberPointerType()) &&
12195 (RHSType->isAnyPointerType() || RHSType->isMemberPointerType()))
12196 diagnoseDistinctPointerComparison(S, Loc, LHS, RHS, /*isError*/IsError: true);
12197 else
12198 S.InvalidOperands(Loc, LHS, RHS);
12199 return true;
12200 }
12201
12202 return false;
12203}
12204
12205static void diagnoseFunctionPointerToVoidComparison(Sema &S, SourceLocation Loc,
12206 ExprResult &LHS,
12207 ExprResult &RHS,
12208 bool IsError) {
12209 S.Diag(Loc, DiagID: IsError ? diag::err_typecheck_comparison_of_fptr_to_void
12210 : diag::ext_typecheck_comparison_of_fptr_to_void)
12211 << LHS.get()->getType() << RHS.get()->getType()
12212 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
12213}
12214
12215static bool isObjCObjectLiteral(ExprResult &E) {
12216 switch (E.get()->IgnoreParenImpCasts()->getStmtClass()) {
12217 case Stmt::ObjCArrayLiteralClass:
12218 case Stmt::ObjCDictionaryLiteralClass:
12219 case Stmt::ObjCStringLiteralClass:
12220 case Stmt::ObjCBoxedExprClass:
12221 return true;
12222 default:
12223 // Note that ObjCBoolLiteral is NOT an object literal!
12224 return false;
12225 }
12226}
12227
12228static bool hasIsEqualMethod(Sema &S, const Expr *LHS, const Expr *RHS) {
12229 const ObjCObjectPointerType *Type =
12230 LHS->getType()->getAs<ObjCObjectPointerType>();
12231
12232 // If this is not actually an Objective-C object, bail out.
12233 if (!Type)
12234 return false;
12235
12236 // Get the LHS object's interface type.
12237 QualType InterfaceType = Type->getPointeeType();
12238
12239 // If the RHS isn't an Objective-C object, bail out.
12240 if (!RHS->getType()->isObjCObjectPointerType())
12241 return false;
12242
12243 // Try to find the -isEqual: method.
12244 Selector IsEqualSel = S.ObjC().NSAPIObj->getIsEqualSelector();
12245 ObjCMethodDecl *Method =
12246 S.ObjC().LookupMethodInObjectType(Sel: IsEqualSel, Ty: InterfaceType,
12247 /*IsInstance=*/true);
12248 if (!Method) {
12249 if (Type->isObjCIdType()) {
12250 // For 'id', just check the global pool.
12251 Method =
12252 S.ObjC().LookupInstanceMethodInGlobalPool(Sel: IsEqualSel, R: SourceRange(),
12253 /*receiverId=*/receiverIdOrClass: true);
12254 } else {
12255 // Check protocols.
12256 Method = S.ObjC().LookupMethodInQualifiedType(Sel: IsEqualSel, OPT: Type,
12257 /*IsInstance=*/true);
12258 }
12259 }
12260
12261 if (!Method)
12262 return false;
12263
12264 QualType T = Method->parameters()[0]->getType();
12265 if (!T->isObjCObjectPointerType())
12266 return false;
12267
12268 QualType R = Method->getReturnType();
12269 if (!R->isScalarType())
12270 return false;
12271
12272 return true;
12273}
12274
12275static void diagnoseObjCLiteralComparison(Sema &S, SourceLocation Loc,
12276 ExprResult &LHS, ExprResult &RHS,
12277 BinaryOperator::Opcode Opc){
12278 Expr *Literal;
12279 Expr *Other;
12280 if (isObjCObjectLiteral(E&: LHS)) {
12281 Literal = LHS.get();
12282 Other = RHS.get();
12283 } else {
12284 Literal = RHS.get();
12285 Other = LHS.get();
12286 }
12287
12288 // Don't warn on comparisons against nil.
12289 Other = Other->IgnoreParenCasts();
12290 if (Other->isNullPointerConstant(Ctx&: S.getASTContext(),
12291 NPC: Expr::NPC_ValueDependentIsNotNull))
12292 return;
12293
12294 // This should be kept in sync with warn_objc_literal_comparison.
12295 // LK_String should always be after the other literals, since it has its own
12296 // warning flag.
12297 SemaObjC::ObjCLiteralKind LiteralKind = S.ObjC().CheckLiteralKind(FromE: Literal);
12298 assert(LiteralKind != SemaObjC::LK_Block);
12299 if (LiteralKind == SemaObjC::LK_None) {
12300 llvm_unreachable("Unknown Objective-C object literal kind");
12301 }
12302
12303 if (LiteralKind == SemaObjC::LK_String)
12304 S.Diag(Loc, DiagID: diag::warn_objc_string_literal_comparison)
12305 << Literal->getSourceRange();
12306 else
12307 S.Diag(Loc, DiagID: diag::warn_objc_literal_comparison)
12308 << LiteralKind << Literal->getSourceRange();
12309
12310 if (BinaryOperator::isEqualityOp(Opc) &&
12311 hasIsEqualMethod(S, LHS: LHS.get(), RHS: RHS.get())) {
12312 SourceLocation Start = LHS.get()->getBeginLoc();
12313 SourceLocation End = S.getLocForEndOfToken(Loc: RHS.get()->getEndLoc());
12314 CharSourceRange OpRange =
12315 CharSourceRange::getCharRange(B: Loc, E: S.getLocForEndOfToken(Loc));
12316
12317 S.Diag(Loc, DiagID: diag::note_objc_literal_comparison_isequal)
12318 << FixItHint::CreateInsertion(InsertionLoc: Start, Code: Opc == BO_EQ ? "[" : "![")
12319 << FixItHint::CreateReplacement(RemoveRange: OpRange, Code: " isEqual:")
12320 << FixItHint::CreateInsertion(InsertionLoc: End, Code: "]");
12321 }
12322}
12323
12324/// Warns on !x < y, !x & y where !(x < y), !(x & y) was probably intended.
12325static void diagnoseLogicalNotOnLHSofCheck(Sema &S, ExprResult &LHS,
12326 ExprResult &RHS, SourceLocation Loc,
12327 BinaryOperatorKind Opc) {
12328 // Check that left hand side is !something.
12329 UnaryOperator *UO = dyn_cast<UnaryOperator>(Val: LHS.get()->IgnoreImpCasts());
12330 if (!UO || UO->getOpcode() != UO_LNot) return;
12331
12332 // Only check if the right hand side is non-bool arithmetic type.
12333 if (RHS.get()->isKnownToHaveBooleanValue()) return;
12334
12335 // Make sure that the something in !something is not bool.
12336 Expr *SubExpr = UO->getSubExpr()->IgnoreImpCasts();
12337 if (SubExpr->isKnownToHaveBooleanValue()) return;
12338
12339 // Emit warning.
12340 bool IsBitwiseOp = Opc == BO_And || Opc == BO_Or || Opc == BO_Xor;
12341 S.Diag(Loc: UO->getOperatorLoc(), DiagID: diag::warn_logical_not_on_lhs_of_check)
12342 << Loc << IsBitwiseOp;
12343
12344 // First note suggest !(x < y)
12345 SourceLocation FirstOpen = SubExpr->getBeginLoc();
12346 SourceLocation FirstClose = RHS.get()->getEndLoc();
12347 FirstClose = S.getLocForEndOfToken(Loc: FirstClose);
12348 if (FirstClose.isInvalid())
12349 FirstOpen = SourceLocation();
12350 S.Diag(Loc: UO->getOperatorLoc(), DiagID: diag::note_logical_not_fix)
12351 << IsBitwiseOp
12352 << FixItHint::CreateInsertion(InsertionLoc: FirstOpen, Code: "(")
12353 << FixItHint::CreateInsertion(InsertionLoc: FirstClose, Code: ")");
12354
12355 // Second note suggests (!x) < y
12356 SourceLocation SecondOpen = LHS.get()->getBeginLoc();
12357 SourceLocation SecondClose = LHS.get()->getEndLoc();
12358 SecondClose = S.getLocForEndOfToken(Loc: SecondClose);
12359 if (SecondClose.isInvalid())
12360 SecondOpen = SourceLocation();
12361 S.Diag(Loc: UO->getOperatorLoc(), DiagID: diag::note_logical_not_silence_with_parens)
12362 << FixItHint::CreateInsertion(InsertionLoc: SecondOpen, Code: "(")
12363 << FixItHint::CreateInsertion(InsertionLoc: SecondClose, Code: ")");
12364}
12365
12366// Returns true if E refers to a non-weak array.
12367static bool checkForArray(const Expr *E) {
12368 const ValueDecl *D = nullptr;
12369 if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Val: E)) {
12370 D = DR->getDecl();
12371 } else if (const MemberExpr *Mem = dyn_cast<MemberExpr>(Val: E)) {
12372 if (Mem->isImplicitAccess())
12373 D = Mem->getMemberDecl();
12374 }
12375 if (!D)
12376 return false;
12377 return D->getType()->isArrayType() && !D->isWeak();
12378}
12379
12380/// Detect patterns ptr + size >= ptr and ptr + size < ptr, where ptr is a
12381/// pointer and size is an unsigned integer. Return whether the result is
12382/// always true/false.
12383static std::optional<bool> isTautologicalBoundsCheck(Sema &S, const Expr *LHS,
12384 const Expr *RHS,
12385 BinaryOperatorKind Opc) {
12386 if (!LHS->getType()->isPointerType() ||
12387 S.getLangOpts().PointerOverflowDefined)
12388 return std::nullopt;
12389
12390 // Canonicalize to >= or < predicate.
12391 switch (Opc) {
12392 case BO_GE:
12393 case BO_LT:
12394 break;
12395 case BO_GT:
12396 std::swap(a&: LHS, b&: RHS);
12397 Opc = BO_LT;
12398 break;
12399 case BO_LE:
12400 std::swap(a&: LHS, b&: RHS);
12401 Opc = BO_GE;
12402 break;
12403 default:
12404 return std::nullopt;
12405 }
12406
12407 auto *BO = dyn_cast<BinaryOperator>(Val: LHS);
12408 if (!BO || BO->getOpcode() != BO_Add)
12409 return std::nullopt;
12410
12411 Expr *Other;
12412 if (Expr::isSameComparisonOperand(E1: BO->getLHS(), E2: RHS))
12413 Other = BO->getRHS();
12414 else if (Expr::isSameComparisonOperand(E1: BO->getRHS(), E2: RHS))
12415 Other = BO->getLHS();
12416 else
12417 return std::nullopt;
12418
12419 if (!Other->getType()->isUnsignedIntegerType())
12420 return std::nullopt;
12421
12422 return Opc == BO_GE;
12423}
12424
12425/// Diagnose some forms of syntactically-obvious tautological comparison.
12426static void diagnoseTautologicalComparison(Sema &S, SourceLocation Loc,
12427 Expr *LHS, Expr *RHS,
12428 BinaryOperatorKind Opc) {
12429 Expr *LHSStripped = LHS->IgnoreParenImpCasts();
12430 Expr *RHSStripped = RHS->IgnoreParenImpCasts();
12431
12432 QualType LHSType = LHS->getType();
12433 QualType RHSType = RHS->getType();
12434 if (LHSType->hasFloatingRepresentation() ||
12435 (LHSType->isBlockPointerType() && !BinaryOperator::isEqualityOp(Opc)) ||
12436 S.inTemplateInstantiation())
12437 return;
12438
12439 // WebAssembly Tables cannot be compared, therefore shouldn't emit
12440 // Tautological diagnostics.
12441 if (LHSType->isWebAssemblyTableType() || RHSType->isWebAssemblyTableType())
12442 return;
12443
12444 // Comparisons between two array types are ill-formed for operator<=>, so
12445 // we shouldn't emit any additional warnings about it.
12446 if (Opc == BO_Cmp && LHSType->isArrayType() && RHSType->isArrayType())
12447 return;
12448
12449 // For non-floating point types, check for self-comparisons of the form
12450 // x == x, x != x, x < x, etc. These always evaluate to a constant, and
12451 // often indicate logic errors in the program.
12452 //
12453 // NOTE: Don't warn about comparison expressions resulting from macro
12454 // expansion. Also don't warn about comparisons which are only self
12455 // comparisons within a template instantiation. The warnings should catch
12456 // obvious cases in the definition of the template anyways. The idea is to
12457 // warn when the typed comparison operator will always evaluate to the same
12458 // result.
12459
12460 // Used for indexing into %select in warn_comparison_always
12461 enum {
12462 AlwaysConstant,
12463 AlwaysTrue,
12464 AlwaysFalse,
12465 AlwaysEqual, // std::strong_ordering::equal from operator<=>
12466 };
12467
12468 // C++1a [array.comp]:
12469 // Equality and relational comparisons ([expr.eq], [expr.rel]) between two
12470 // operands of array type.
12471 // C++2a [depr.array.comp]:
12472 // Equality and relational comparisons ([expr.eq], [expr.rel]) between two
12473 // operands of array type are deprecated.
12474 if (S.getLangOpts().CPlusPlus && LHSStripped->getType()->isArrayType() &&
12475 RHSStripped->getType()->isArrayType()) {
12476 auto IsDeprArrayComparionIgnored =
12477 S.getDiagnostics().isIgnored(DiagID: diag::warn_depr_array_comparison, Loc);
12478 auto DiagID = S.getLangOpts().CPlusPlus26
12479 ? diag::warn_array_comparison_cxx26
12480 : !S.getLangOpts().CPlusPlus20 || IsDeprArrayComparionIgnored
12481 ? diag::warn_array_comparison
12482 : diag::warn_depr_array_comparison;
12483 S.Diag(Loc, DiagID) << LHS->getSourceRange() << RHS->getSourceRange()
12484 << LHSStripped->getType() << RHSStripped->getType();
12485 // Carry on to produce the tautological comparison warning, if this
12486 // expression is potentially-evaluated, we can resolve the array to a
12487 // non-weak declaration, and so on.
12488 }
12489
12490 if (!LHS->getBeginLoc().isMacroID() && !RHS->getBeginLoc().isMacroID()) {
12491 if (Expr::isSameComparisonOperand(E1: LHS, E2: RHS)) {
12492 unsigned Result;
12493 switch (Opc) {
12494 case BO_EQ:
12495 case BO_LE:
12496 case BO_GE:
12497 Result = AlwaysTrue;
12498 break;
12499 case BO_NE:
12500 case BO_LT:
12501 case BO_GT:
12502 Result = AlwaysFalse;
12503 break;
12504 case BO_Cmp:
12505 Result = AlwaysEqual;
12506 break;
12507 default:
12508 Result = AlwaysConstant;
12509 break;
12510 }
12511 S.DiagRuntimeBehavior(Loc, Statement: nullptr,
12512 PD: S.PDiag(DiagID: diag::warn_comparison_always)
12513 << 0 /*self-comparison*/
12514 << Result);
12515 } else if (checkForArray(E: LHSStripped) && checkForArray(E: RHSStripped)) {
12516 // What is it always going to evaluate to?
12517 unsigned Result;
12518 switch (Opc) {
12519 case BO_EQ: // e.g. array1 == array2
12520 Result = AlwaysFalse;
12521 break;
12522 case BO_NE: // e.g. array1 != array2
12523 Result = AlwaysTrue;
12524 break;
12525 default: // e.g. array1 <= array2
12526 // The best we can say is 'a constant'
12527 Result = AlwaysConstant;
12528 break;
12529 }
12530 S.DiagRuntimeBehavior(Loc, Statement: nullptr,
12531 PD: S.PDiag(DiagID: diag::warn_comparison_always)
12532 << 1 /*array comparison*/
12533 << Result);
12534 } else if (std::optional<bool> Res =
12535 isTautologicalBoundsCheck(S, LHS, RHS, Opc)) {
12536 S.DiagRuntimeBehavior(Loc, Statement: nullptr,
12537 PD: S.PDiag(DiagID: diag::warn_comparison_always)
12538 << 2 /*pointer comparison*/
12539 << (*Res ? AlwaysTrue : AlwaysFalse));
12540 }
12541 }
12542
12543 if (isa<CastExpr>(Val: LHSStripped))
12544 LHSStripped = LHSStripped->IgnoreParenCasts();
12545 if (isa<CastExpr>(Val: RHSStripped))
12546 RHSStripped = RHSStripped->IgnoreParenCasts();
12547
12548 // Warn about comparisons against a string constant (unless the other
12549 // operand is null); the user probably wants string comparison function.
12550 Expr *LiteralString = nullptr;
12551 Expr *LiteralStringStripped = nullptr;
12552 if ((isa<StringLiteral>(Val: LHSStripped) || isa<ObjCEncodeExpr>(Val: LHSStripped)) &&
12553 !RHSStripped->isNullPointerConstant(Ctx&: S.Context,
12554 NPC: Expr::NPC_ValueDependentIsNull)) {
12555 LiteralString = LHS;
12556 LiteralStringStripped = LHSStripped;
12557 } else if ((isa<StringLiteral>(Val: RHSStripped) ||
12558 isa<ObjCEncodeExpr>(Val: RHSStripped)) &&
12559 !LHSStripped->isNullPointerConstant(Ctx&: S.Context,
12560 NPC: Expr::NPC_ValueDependentIsNull)) {
12561 LiteralString = RHS;
12562 LiteralStringStripped = RHSStripped;
12563 }
12564
12565 if (LiteralString) {
12566 S.DiagRuntimeBehavior(Loc, Statement: nullptr,
12567 PD: S.PDiag(DiagID: diag::warn_stringcompare)
12568 << isa<ObjCEncodeExpr>(Val: LiteralStringStripped)
12569 << LiteralString->getSourceRange());
12570 }
12571}
12572
12573static ImplicitConversionKind castKindToImplicitConversionKind(CastKind CK) {
12574 switch (CK) {
12575 default: {
12576#ifndef NDEBUG
12577 llvm::errs() << "unhandled cast kind: " << CastExpr::getCastKindName(CK)
12578 << "\n";
12579#endif
12580 llvm_unreachable("unhandled cast kind");
12581 }
12582 case CK_UserDefinedConversion:
12583 return ICK_Identity;
12584 case CK_LValueToRValue:
12585 return ICK_Lvalue_To_Rvalue;
12586 case CK_ArrayToPointerDecay:
12587 return ICK_Array_To_Pointer;
12588 case CK_FunctionToPointerDecay:
12589 return ICK_Function_To_Pointer;
12590 case CK_IntegralCast:
12591 return ICK_Integral_Conversion;
12592 case CK_FloatingCast:
12593 return ICK_Floating_Conversion;
12594 case CK_IntegralToFloating:
12595 case CK_FloatingToIntegral:
12596 return ICK_Floating_Integral;
12597 case CK_IntegralComplexCast:
12598 case CK_FloatingComplexCast:
12599 case CK_FloatingComplexToIntegralComplex:
12600 case CK_IntegralComplexToFloatingComplex:
12601 return ICK_Complex_Conversion;
12602 case CK_FloatingComplexToReal:
12603 case CK_FloatingRealToComplex:
12604 case CK_IntegralComplexToReal:
12605 case CK_IntegralRealToComplex:
12606 return ICK_Complex_Real;
12607 case CK_HLSLArrayRValue:
12608 return ICK_HLSL_Array_RValue;
12609 }
12610}
12611
12612static bool checkThreeWayNarrowingConversion(Sema &S, QualType ToType, Expr *E,
12613 QualType FromType,
12614 SourceLocation Loc) {
12615 // Check for a narrowing implicit conversion.
12616 StandardConversionSequence SCS;
12617 SCS.setAsIdentityConversion();
12618 SCS.setToType(Idx: 0, T: FromType);
12619 SCS.setToType(Idx: 1, T: ToType);
12620 if (const auto *ICE = dyn_cast<ImplicitCastExpr>(Val: E))
12621 SCS.Second = castKindToImplicitConversionKind(CK: ICE->getCastKind());
12622
12623 APValue PreNarrowingValue;
12624 QualType PreNarrowingType;
12625 switch (SCS.getNarrowingKind(Context&: S.Context, Converted: E, ConstantValue&: PreNarrowingValue,
12626 ConstantType&: PreNarrowingType,
12627 /*IgnoreFloatToIntegralConversion*/ true)) {
12628 case NK_Dependent_Narrowing:
12629 // Implicit conversion to a narrower type, but the expression is
12630 // value-dependent so we can't tell whether it's actually narrowing.
12631 case NK_Not_Narrowing:
12632 return false;
12633
12634 case NK_Constant_Narrowing:
12635 // Implicit conversion to a narrower type, and the value is not a constant
12636 // expression.
12637 S.Diag(Loc: E->getBeginLoc(), DiagID: diag::err_spaceship_argument_narrowing)
12638 << /*Constant*/ 1
12639 << PreNarrowingValue.getAsString(Ctx: S.Context, Ty: PreNarrowingType) << ToType;
12640 return true;
12641
12642 case NK_Variable_Narrowing:
12643 // Implicit conversion to a narrower type, and the value is not a constant
12644 // expression.
12645 case NK_Type_Narrowing:
12646 S.Diag(Loc: E->getBeginLoc(), DiagID: diag::err_spaceship_argument_narrowing)
12647 << /*Constant*/ 0 << FromType << ToType;
12648 // TODO: It's not a constant expression, but what if the user intended it
12649 // to be? Can we produce notes to help them figure out why it isn't?
12650 return true;
12651 }
12652 llvm_unreachable("unhandled case in switch");
12653}
12654
12655static QualType checkArithmeticOrEnumeralThreeWayCompare(Sema &S,
12656 ExprResult &LHS,
12657 ExprResult &RHS,
12658 SourceLocation Loc) {
12659 QualType LHSType = LHS.get()->getType();
12660 QualType RHSType = RHS.get()->getType();
12661 // Dig out the original argument type and expression before implicit casts
12662 // were applied. These are the types/expressions we need to check the
12663 // [expr.spaceship] requirements against.
12664 ExprResult LHSStripped = LHS.get()->IgnoreParenImpCasts();
12665 ExprResult RHSStripped = RHS.get()->IgnoreParenImpCasts();
12666 QualType LHSStrippedType = LHSStripped.get()->getType();
12667 QualType RHSStrippedType = RHSStripped.get()->getType();
12668
12669 // C++2a [expr.spaceship]p3: If one of the operands is of type bool and the
12670 // other is not, the program is ill-formed.
12671 if (LHSStrippedType->isBooleanType() != RHSStrippedType->isBooleanType()) {
12672 S.InvalidOperands(Loc, LHS&: LHSStripped, RHS&: RHSStripped);
12673 return QualType();
12674 }
12675
12676 // FIXME: Consider combining this with checkEnumArithmeticConversions.
12677 int NumEnumArgs = (int)LHSStrippedType->isEnumeralType() +
12678 RHSStrippedType->isEnumeralType();
12679 if (NumEnumArgs == 1) {
12680 bool LHSIsEnum = LHSStrippedType->isEnumeralType();
12681 QualType OtherTy = LHSIsEnum ? RHSStrippedType : LHSStrippedType;
12682 if (OtherTy->hasFloatingRepresentation()) {
12683 S.InvalidOperands(Loc, LHS&: LHSStripped, RHS&: RHSStripped);
12684 return QualType();
12685 }
12686 }
12687 if (NumEnumArgs == 2) {
12688 // C++2a [expr.spaceship]p5: If both operands have the same enumeration
12689 // type E, the operator yields the result of converting the operands
12690 // to the underlying type of E and applying <=> to the converted operands.
12691 if (!S.Context.hasSameUnqualifiedType(T1: LHSStrippedType, T2: RHSStrippedType)) {
12692 S.InvalidOperands(Loc, LHS, RHS);
12693 return QualType();
12694 }
12695 QualType IntType = LHSStrippedType->castAsEnumDecl()->getIntegerType();
12696 assert(IntType->isArithmeticType());
12697
12698 // We can't use `CK_IntegralCast` when the underlying type is 'bool', so we
12699 // promote the boolean type, and all other promotable integer types, to
12700 // avoid this.
12701 if (S.Context.isPromotableIntegerType(T: IntType))
12702 IntType = S.Context.getPromotedIntegerType(PromotableType: IntType);
12703
12704 LHS = S.ImpCastExprToType(E: LHS.get(), Type: IntType, CK: CK_IntegralCast);
12705 RHS = S.ImpCastExprToType(E: RHS.get(), Type: IntType, CK: CK_IntegralCast);
12706 LHSType = RHSType = IntType;
12707 }
12708
12709 // C++2a [expr.spaceship]p4: If both operands have arithmetic types, the
12710 // usual arithmetic conversions are applied to the operands.
12711 QualType Type =
12712 S.UsualArithmeticConversions(LHS, RHS, Loc, ACK: ArithConvKind::Comparison);
12713 if (LHS.isInvalid() || RHS.isInvalid())
12714 return QualType();
12715 if (Type.isNull()) {
12716 QualType ResultTy = S.InvalidOperands(Loc, LHS, RHS);
12717 diagnoseScopedEnums(S, Loc, LHS, RHS, Opc: BO_Cmp);
12718 return ResultTy;
12719 }
12720
12721 std::optional<ComparisonCategoryType> CCT =
12722 getComparisonCategoryForBuiltinCmp(T: Type);
12723 if (!CCT)
12724 return S.InvalidOperands(Loc, LHS, RHS);
12725
12726 bool HasNarrowing = checkThreeWayNarrowingConversion(
12727 S, ToType: Type, E: LHS.get(), FromType: LHSType, Loc: LHS.get()->getBeginLoc());
12728 HasNarrowing |= checkThreeWayNarrowingConversion(S, ToType: Type, E: RHS.get(), FromType: RHSType,
12729 Loc: RHS.get()->getBeginLoc());
12730 if (HasNarrowing)
12731 return QualType();
12732
12733 assert(!Type.isNull() && "composite type for <=> has not been set");
12734
12735 return S.CheckComparisonCategoryType(
12736 Kind: *CCT, Loc, Usage: Sema::ComparisonCategoryUsage::OperatorInExpression);
12737}
12738
12739static QualType checkArithmeticOrEnumeralCompare(Sema &S, ExprResult &LHS,
12740 ExprResult &RHS,
12741 SourceLocation Loc,
12742 BinaryOperatorKind Opc) {
12743 if (Opc == BO_Cmp)
12744 return checkArithmeticOrEnumeralThreeWayCompare(S, LHS, RHS, Loc);
12745
12746 // C99 6.5.8p3 / C99 6.5.9p4
12747 QualType Type =
12748 S.UsualArithmeticConversions(LHS, RHS, Loc, ACK: ArithConvKind::Comparison);
12749 if (LHS.isInvalid() || RHS.isInvalid())
12750 return QualType();
12751 if (Type.isNull()) {
12752 QualType ResultTy = S.InvalidOperands(Loc, LHS, RHS);
12753 diagnoseScopedEnums(S, Loc, LHS, RHS, Opc);
12754 return ResultTy;
12755 }
12756 assert(Type->isArithmeticType() || Type->isEnumeralType());
12757
12758 if (Type->isAnyComplexType() && BinaryOperator::isRelationalOp(Opc))
12759 return S.InvalidOperands(Loc, LHS, RHS);
12760
12761 // Check for comparisons of floating point operands using != and ==.
12762 if (Type->hasFloatingRepresentation())
12763 S.CheckFloatComparison(Loc, LHS: LHS.get(), RHS: RHS.get(), Opcode: Opc);
12764
12765 // The result of comparisons is 'bool' in C++, 'int' in C.
12766 return S.Context.getLogicalOperationType();
12767}
12768
12769void Sema::CheckPtrComparisonWithNullChar(ExprResult &E, ExprResult &NullE) {
12770 if (!NullE.get()->getType()->isAnyPointerType())
12771 return;
12772 int NullValue = PP.isMacroDefined(Id: "NULL") ? 0 : 1;
12773 if (!E.get()->getType()->isAnyPointerType() &&
12774 E.get()->isNullPointerConstant(Ctx&: Context,
12775 NPC: Expr::NPC_ValueDependentIsNotNull) ==
12776 Expr::NPCK_ZeroExpression) {
12777 if (const auto *CL = dyn_cast<CharacterLiteral>(Val: E.get())) {
12778 if (CL->getValue() == 0)
12779 Diag(Loc: E.get()->getExprLoc(), DiagID: diag::warn_pointer_compare)
12780 << NullValue
12781 << FixItHint::CreateReplacement(RemoveRange: E.get()->getExprLoc(),
12782 Code: NullValue ? "NULL" : "(void *)0");
12783 } else if (const auto *CE = dyn_cast<CStyleCastExpr>(Val: E.get())) {
12784 TypeSourceInfo *TI = CE->getTypeInfoAsWritten();
12785 QualType T = Context.getCanonicalType(T: TI->getType()).getUnqualifiedType();
12786 if (T == Context.CharTy)
12787 Diag(Loc: E.get()->getExprLoc(), DiagID: diag::warn_pointer_compare)
12788 << NullValue
12789 << FixItHint::CreateReplacement(RemoveRange: E.get()->getExprLoc(),
12790 Code: NullValue ? "NULL" : "(void *)0");
12791 }
12792 }
12793}
12794
12795// C99 6.5.8, C++ [expr.rel]
12796QualType Sema::CheckCompareOperands(ExprResult &LHS, ExprResult &RHS,
12797 SourceLocation Loc,
12798 BinaryOperatorKind Opc) {
12799 bool IsRelational = BinaryOperator::isRelationalOp(Opc);
12800 bool IsThreeWay = Opc == BO_Cmp;
12801 bool IsOrdered = IsRelational || IsThreeWay;
12802 auto IsAnyPointerType = [](ExprResult E) {
12803 QualType Ty = E.get()->getType();
12804 return Ty->isPointerType() || Ty->isMemberPointerType();
12805 };
12806
12807 // C++2a [expr.spaceship]p6: If at least one of the operands is of pointer
12808 // type, array-to-pointer, ..., conversions are performed on both operands to
12809 // bring them to their composite type.
12810 // Otherwise, all comparisons expect an rvalue, so convert to rvalue before
12811 // any type-related checks.
12812 if (!IsThreeWay || IsAnyPointerType(LHS) || IsAnyPointerType(RHS)) {
12813 LHS = DefaultFunctionArrayLvalueConversion(E: LHS.get());
12814 if (LHS.isInvalid())
12815 return QualType();
12816 RHS = DefaultFunctionArrayLvalueConversion(E: RHS.get());
12817 if (RHS.isInvalid())
12818 return QualType();
12819 } else {
12820 LHS = DefaultLvalueConversion(E: LHS.get());
12821 if (LHS.isInvalid())
12822 return QualType();
12823 RHS = DefaultLvalueConversion(E: RHS.get());
12824 if (RHS.isInvalid())
12825 return QualType();
12826 }
12827
12828 checkArithmeticNull(S&: *this, LHS, RHS, Loc, /*IsCompare=*/true);
12829 if (!getLangOpts().CPlusPlus && BinaryOperator::isEqualityOp(Opc)) {
12830 CheckPtrComparisonWithNullChar(E&: LHS, NullE&: RHS);
12831 CheckPtrComparisonWithNullChar(E&: RHS, NullE&: LHS);
12832 }
12833
12834 // Handle vector comparisons separately.
12835 if (LHS.get()->getType()->isVectorType() ||
12836 RHS.get()->getType()->isVectorType())
12837 return CheckVectorCompareOperands(LHS, RHS, Loc, Opc);
12838
12839 if (LHS.get()->getType()->isSveVLSBuiltinType() ||
12840 RHS.get()->getType()->isSveVLSBuiltinType())
12841 return CheckSizelessVectorCompareOperands(LHS, RHS, Loc, Opc);
12842
12843 diagnoseLogicalNotOnLHSofCheck(S&: *this, LHS, RHS, Loc, Opc);
12844 diagnoseTautologicalComparison(S&: *this, Loc, LHS: LHS.get(), RHS: RHS.get(), Opc);
12845
12846 QualType LHSType = LHS.get()->getType();
12847 QualType RHSType = RHS.get()->getType();
12848 if ((LHSType->isArithmeticType() || LHSType->isEnumeralType()) &&
12849 (RHSType->isArithmeticType() || RHSType->isEnumeralType()))
12850 return checkArithmeticOrEnumeralCompare(S&: *this, LHS, RHS, Loc, Opc);
12851
12852 if ((LHSType->isPointerType() &&
12853 LHSType->getPointeeType().isWebAssemblyReferenceType()) ||
12854 (RHSType->isPointerType() &&
12855 RHSType->getPointeeType().isWebAssemblyReferenceType()))
12856 return InvalidOperands(Loc, LHS, RHS);
12857
12858 const Expr::NullPointerConstantKind LHSNullKind =
12859 LHS.get()->isNullPointerConstant(Ctx&: Context, NPC: Expr::NPC_ValueDependentIsNull);
12860 const Expr::NullPointerConstantKind RHSNullKind =
12861 RHS.get()->isNullPointerConstant(Ctx&: Context, NPC: Expr::NPC_ValueDependentIsNull);
12862 bool LHSIsNull = LHSNullKind != Expr::NPCK_NotNull;
12863 bool RHSIsNull = RHSNullKind != Expr::NPCK_NotNull;
12864
12865 auto computeResultTy = [&]() {
12866 if (Opc != BO_Cmp)
12867 return QualType(Context.getLogicalOperationType());
12868 assert(getLangOpts().CPlusPlus);
12869 assert(Context.hasSameType(LHS.get()->getType(), RHS.get()->getType()));
12870
12871 QualType CompositeTy = LHS.get()->getType();
12872 assert(!CompositeTy->isReferenceType());
12873
12874 std::optional<ComparisonCategoryType> CCT =
12875 getComparisonCategoryForBuiltinCmp(T: CompositeTy);
12876 if (!CCT)
12877 return InvalidOperands(Loc, LHS, RHS);
12878
12879 if (CompositeTy->isPointerType() && LHSIsNull != RHSIsNull) {
12880 // P0946R0: Comparisons between a null pointer constant and an object
12881 // pointer result in std::strong_equality, which is ill-formed under
12882 // P1959R0.
12883 Diag(Loc, DiagID: diag::err_typecheck_three_way_comparison_of_pointer_and_zero)
12884 << (LHSIsNull ? LHS.get()->getSourceRange()
12885 : RHS.get()->getSourceRange());
12886 return QualType();
12887 }
12888
12889 return CheckComparisonCategoryType(
12890 Kind: *CCT, Loc, Usage: ComparisonCategoryUsage::OperatorInExpression);
12891 };
12892
12893 if (!IsOrdered && LHSIsNull != RHSIsNull) {
12894 bool IsEquality = Opc == BO_EQ;
12895 if (RHSIsNull)
12896 DiagnoseAlwaysNonNullPointer(E: LHS.get(), NullType: RHSNullKind, IsEqual: IsEquality,
12897 Range: RHS.get()->getSourceRange());
12898 else
12899 DiagnoseAlwaysNonNullPointer(E: RHS.get(), NullType: LHSNullKind, IsEqual: IsEquality,
12900 Range: LHS.get()->getSourceRange());
12901 }
12902
12903 if (IsOrdered && LHSType->isFunctionPointerType() &&
12904 RHSType->isFunctionPointerType()) {
12905 // Valid unless a relational comparison of function pointers
12906 bool IsError = Opc == BO_Cmp;
12907 auto DiagID =
12908 IsError ? diag::err_typecheck_ordered_comparison_of_function_pointers
12909 : getLangOpts().CPlusPlus
12910 ? diag::warn_typecheck_ordered_comparison_of_function_pointers
12911 : diag::ext_typecheck_ordered_comparison_of_function_pointers;
12912 Diag(Loc, DiagID) << LHSType << RHSType << LHS.get()->getSourceRange()
12913 << RHS.get()->getSourceRange();
12914 if (IsError)
12915 return QualType();
12916 }
12917
12918 if ((LHSType->isIntegerType() && !LHSIsNull) ||
12919 (RHSType->isIntegerType() && !RHSIsNull)) {
12920 // Skip normal pointer conversion checks in this case; we have better
12921 // diagnostics for this below.
12922 } else if (getLangOpts().CPlusPlus) {
12923 // Equality comparison of a function pointer to a void pointer is invalid,
12924 // but we allow it as an extension.
12925 // FIXME: If we really want to allow this, should it be part of composite
12926 // pointer type computation so it works in conditionals too?
12927 if (!IsOrdered &&
12928 ((LHSType->isFunctionPointerType() && RHSType->isVoidPointerType()) ||
12929 (RHSType->isFunctionPointerType() && LHSType->isVoidPointerType()))) {
12930 // This is a gcc extension compatibility comparison.
12931 // In a SFINAE context, we treat this as a hard error to maintain
12932 // conformance with the C++ standard.
12933 bool IsError = isSFINAEContext();
12934 diagnoseFunctionPointerToVoidComparison(S&: *this, Loc, LHS, RHS, IsError);
12935
12936 if (IsError)
12937 return QualType();
12938
12939 RHS = ImpCastExprToType(E: RHS.get(), Type: LHSType, CK: CK_BitCast);
12940 return computeResultTy();
12941 }
12942
12943 // C++ [expr.eq]p2:
12944 // If at least one operand is a pointer [...] bring them to their
12945 // composite pointer type.
12946 // C++ [expr.spaceship]p6
12947 // If at least one of the operands is of pointer type, [...] bring them
12948 // to their composite pointer type.
12949 // C++ [expr.rel]p2:
12950 // If both operands are pointers, [...] bring them to their composite
12951 // pointer type.
12952 // For <=>, the only valid non-pointer types are arrays and functions, and
12953 // we already decayed those, so this is really the same as the relational
12954 // comparison rule.
12955 if ((int)LHSType->isPointerType() + (int)RHSType->isPointerType() >=
12956 (IsOrdered ? 2 : 1) &&
12957 (!LangOpts.ObjCAutoRefCount || !(LHSType->isObjCObjectPointerType() ||
12958 RHSType->isObjCObjectPointerType()))) {
12959 if (convertPointersToCompositeType(S&: *this, Loc, LHS, RHS))
12960 return QualType();
12961 return computeResultTy();
12962 }
12963 } else if (LHSType->isPointerType() &&
12964 RHSType->isPointerType()) { // C99 6.5.8p2
12965 // All of the following pointer-related warnings are GCC extensions, except
12966 // when handling null pointer constants.
12967 QualType LCanPointeeTy =
12968 LHSType->castAs<PointerType>()->getPointeeType().getCanonicalType();
12969 QualType RCanPointeeTy =
12970 RHSType->castAs<PointerType>()->getPointeeType().getCanonicalType();
12971
12972 // C99 6.5.9p2 and C99 6.5.8p2
12973 if (Context.typesAreCompatible(T1: LCanPointeeTy.getUnqualifiedType(),
12974 T2: RCanPointeeTy.getUnqualifiedType())) {
12975 if (IsRelational) {
12976 // Pointers both need to point to complete or incomplete types
12977 if ((LCanPointeeTy->isIncompleteType() !=
12978 RCanPointeeTy->isIncompleteType()) &&
12979 !getLangOpts().C11) {
12980 Diag(Loc, DiagID: diag::ext_typecheck_compare_complete_incomplete_pointers)
12981 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange()
12982 << LHSType << RHSType << LCanPointeeTy->isIncompleteType()
12983 << RCanPointeeTy->isIncompleteType();
12984 }
12985 }
12986 } else if (!IsRelational &&
12987 (LCanPointeeTy->isVoidType() || RCanPointeeTy->isVoidType())) {
12988 // Valid unless comparison between non-null pointer and function pointer
12989 if ((LCanPointeeTy->isFunctionType() || RCanPointeeTy->isFunctionType())
12990 && !LHSIsNull && !RHSIsNull)
12991 diagnoseFunctionPointerToVoidComparison(S&: *this, Loc, LHS, RHS,
12992 /*isError*/IsError: false);
12993 } else {
12994 // Invalid
12995 diagnoseDistinctPointerComparison(S&: *this, Loc, LHS, RHS, /*isError*/IsError: false);
12996 }
12997 if (LCanPointeeTy != RCanPointeeTy) {
12998 // Treat NULL constant as a special case in OpenCL.
12999 if (getLangOpts().OpenCL && !LHSIsNull && !RHSIsNull) {
13000 if (!LCanPointeeTy.isAddressSpaceOverlapping(T: RCanPointeeTy,
13001 Ctx: getASTContext())) {
13002 Diag(Loc,
13003 DiagID: diag::err_typecheck_op_on_nonoverlapping_address_space_pointers)
13004 << LHSType << RHSType << 0 /* comparison */
13005 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
13006 }
13007 }
13008 LangAS AddrSpaceL = LCanPointeeTy.getAddressSpace();
13009 LangAS AddrSpaceR = RCanPointeeTy.getAddressSpace();
13010 CastKind Kind = AddrSpaceL != AddrSpaceR ? CK_AddressSpaceConversion
13011 : CK_BitCast;
13012
13013 const FunctionType *LFn = LCanPointeeTy->getAs<FunctionType>();
13014 const FunctionType *RFn = RCanPointeeTy->getAs<FunctionType>();
13015 bool LHSHasCFIUncheckedCallee = LFn && LFn->getCFIUncheckedCalleeAttr();
13016 bool RHSHasCFIUncheckedCallee = RFn && RFn->getCFIUncheckedCalleeAttr();
13017 bool ChangingCFIUncheckedCallee =
13018 LHSHasCFIUncheckedCallee != RHSHasCFIUncheckedCallee;
13019
13020 if (LHSIsNull && !RHSIsNull)
13021 LHS = ImpCastExprToType(E: LHS.get(), Type: RHSType, CK: Kind);
13022 else if (!ChangingCFIUncheckedCallee)
13023 RHS = ImpCastExprToType(E: RHS.get(), Type: LHSType, CK: Kind);
13024 }
13025 return computeResultTy();
13026 }
13027
13028
13029 // C++ [expr.eq]p4:
13030 // Two operands of type std::nullptr_t or one operand of type
13031 // std::nullptr_t and the other a null pointer constant compare
13032 // equal.
13033 // C23 6.5.9p5:
13034 // If both operands have type nullptr_t or one operand has type nullptr_t
13035 // and the other is a null pointer constant, they compare equal if the
13036 // former is a null pointer.
13037 if (!IsOrdered && LHSIsNull && RHSIsNull) {
13038 if (LHSType->isNullPtrType()) {
13039 RHS = ImpCastExprToType(E: RHS.get(), Type: LHSType, CK: CK_NullToPointer);
13040 return computeResultTy();
13041 }
13042 if (RHSType->isNullPtrType()) {
13043 LHS = ImpCastExprToType(E: LHS.get(), Type: RHSType, CK: CK_NullToPointer);
13044 return computeResultTy();
13045 }
13046 }
13047
13048 if (!getLangOpts().CPlusPlus && !IsOrdered && (LHSIsNull || RHSIsNull)) {
13049 // C23 6.5.9p6:
13050 // Otherwise, at least one operand is a pointer. If one is a pointer and
13051 // the other is a null pointer constant or has type nullptr_t, they
13052 // compare equal
13053 if (LHSIsNull && RHSType->isPointerType()) {
13054 LHS = ImpCastExprToType(E: LHS.get(), Type: RHSType, CK: CK_NullToPointer);
13055 return computeResultTy();
13056 }
13057 if (RHSIsNull && LHSType->isPointerType()) {
13058 RHS = ImpCastExprToType(E: RHS.get(), Type: LHSType, CK: CK_NullToPointer);
13059 return computeResultTy();
13060 }
13061 }
13062
13063 // Comparison of Objective-C pointers and block pointers against nullptr_t.
13064 // These aren't covered by the composite pointer type rules.
13065 if (!IsOrdered && RHSType->isNullPtrType() &&
13066 (LHSType->isObjCObjectPointerType() || LHSType->isBlockPointerType())) {
13067 RHS = ImpCastExprToType(E: RHS.get(), Type: LHSType, CK: CK_NullToPointer);
13068 return computeResultTy();
13069 }
13070 if (!IsOrdered && LHSType->isNullPtrType() &&
13071 (RHSType->isObjCObjectPointerType() || RHSType->isBlockPointerType())) {
13072 LHS = ImpCastExprToType(E: LHS.get(), Type: RHSType, CK: CK_NullToPointer);
13073 return computeResultTy();
13074 }
13075
13076 if (getLangOpts().CPlusPlus) {
13077 if (IsRelational &&
13078 ((LHSType->isNullPtrType() && RHSType->isPointerType()) ||
13079 (RHSType->isNullPtrType() && LHSType->isPointerType()))) {
13080 // HACK: Relational comparison of nullptr_t against a pointer type is
13081 // invalid per DR583, but we allow it within std::less<> and friends,
13082 // since otherwise common uses of it break.
13083 // FIXME: Consider removing this hack once LWG fixes std::less<> and
13084 // friends to have std::nullptr_t overload candidates.
13085 DeclContext *DC = CurContext;
13086 if (isa<FunctionDecl>(Val: DC))
13087 DC = DC->getParent();
13088 if (auto *CTSD = dyn_cast<ClassTemplateSpecializationDecl>(Val: DC)) {
13089 if (CTSD->isInStdNamespace() &&
13090 llvm::StringSwitch<bool>(CTSD->getName())
13091 .Cases(CaseStrings: {"less", "less_equal", "greater", "greater_equal"}, Value: true)
13092 .Default(Value: false)) {
13093 if (RHSType->isNullPtrType())
13094 RHS = ImpCastExprToType(E: RHS.get(), Type: LHSType, CK: CK_NullToPointer);
13095 else
13096 LHS = ImpCastExprToType(E: LHS.get(), Type: RHSType, CK: CK_NullToPointer);
13097 return computeResultTy();
13098 }
13099 }
13100 }
13101
13102 // C++ [expr.eq]p2:
13103 // If at least one operand is a pointer to member, [...] bring them to
13104 // their composite pointer type.
13105 if (!IsOrdered &&
13106 (LHSType->isMemberPointerType() || RHSType->isMemberPointerType())) {
13107 if (convertPointersToCompositeType(S&: *this, Loc, LHS, RHS))
13108 return QualType();
13109 else
13110 return computeResultTy();
13111 }
13112 }
13113
13114 // Handle block pointer types.
13115 if (!IsOrdered && LHSType->isBlockPointerType() &&
13116 RHSType->isBlockPointerType()) {
13117 QualType lpointee = LHSType->castAs<BlockPointerType>()->getPointeeType();
13118 QualType rpointee = RHSType->castAs<BlockPointerType>()->getPointeeType();
13119
13120 if (!LHSIsNull && !RHSIsNull &&
13121 !Context.typesAreCompatible(T1: lpointee, T2: rpointee)) {
13122 Diag(Loc, DiagID: diag::err_typecheck_comparison_of_distinct_blocks)
13123 << LHSType << RHSType << LHS.get()->getSourceRange()
13124 << RHS.get()->getSourceRange();
13125 }
13126 RHS = ImpCastExprToType(E: RHS.get(), Type: LHSType, CK: CK_BitCast);
13127 return computeResultTy();
13128 }
13129
13130 // Allow block pointers to be compared with null pointer constants.
13131 if (!IsOrdered
13132 && ((LHSType->isBlockPointerType() && RHSType->isPointerType())
13133 || (LHSType->isPointerType() && RHSType->isBlockPointerType()))) {
13134 if (!LHSIsNull && !RHSIsNull) {
13135 if (!((RHSType->isPointerType() && RHSType->castAs<PointerType>()
13136 ->getPointeeType()->isVoidType())
13137 || (LHSType->isPointerType() && LHSType->castAs<PointerType>()
13138 ->getPointeeType()->isVoidType())))
13139 Diag(Loc, DiagID: diag::err_typecheck_comparison_of_distinct_blocks)
13140 << LHSType << RHSType << LHS.get()->getSourceRange()
13141 << RHS.get()->getSourceRange();
13142 }
13143 if (LHSIsNull && !RHSIsNull)
13144 LHS = ImpCastExprToType(E: LHS.get(), Type: RHSType,
13145 CK: RHSType->isPointerType() ? CK_BitCast
13146 : CK_AnyPointerToBlockPointerCast);
13147 else
13148 RHS = ImpCastExprToType(E: RHS.get(), Type: LHSType,
13149 CK: LHSType->isPointerType() ? CK_BitCast
13150 : CK_AnyPointerToBlockPointerCast);
13151 return computeResultTy();
13152 }
13153
13154 if (LHSType->isObjCObjectPointerType() ||
13155 RHSType->isObjCObjectPointerType()) {
13156 const PointerType *LPT = LHSType->getAs<PointerType>();
13157 const PointerType *RPT = RHSType->getAs<PointerType>();
13158 if (LPT || RPT) {
13159 bool LPtrToVoid = LPT ? LPT->getPointeeType()->isVoidType() : false;
13160 bool RPtrToVoid = RPT ? RPT->getPointeeType()->isVoidType() : false;
13161
13162 if (!LPtrToVoid && !RPtrToVoid &&
13163 !Context.typesAreCompatible(T1: LHSType, T2: RHSType)) {
13164 diagnoseDistinctPointerComparison(S&: *this, Loc, LHS, RHS,
13165 /*isError*/IsError: false);
13166 }
13167 // FIXME: If LPtrToVoid, we should presumably convert the LHS rather than
13168 // the RHS, but we have test coverage for this behavior.
13169 // FIXME: Consider using convertPointersToCompositeType in C++.
13170 if (LHSIsNull && !RHSIsNull) {
13171 Expr *E = LHS.get();
13172 if (getLangOpts().ObjCAutoRefCount)
13173 ObjC().CheckObjCConversion(castRange: SourceRange(), castType: RHSType, op&: E,
13174 CCK: CheckedConversionKind::Implicit);
13175 LHS = ImpCastExprToType(E, Type: RHSType,
13176 CK: RPT ? CK_BitCast :CK_CPointerToObjCPointerCast);
13177 }
13178 else {
13179 Expr *E = RHS.get();
13180 if (getLangOpts().ObjCAutoRefCount)
13181 ObjC().CheckObjCConversion(castRange: SourceRange(), castType: LHSType, op&: E,
13182 CCK: CheckedConversionKind::Implicit,
13183 /*Diagnose=*/true,
13184 /*DiagnoseCFAudited=*/false, Opc);
13185 RHS = ImpCastExprToType(E, Type: LHSType,
13186 CK: LPT ? CK_BitCast :CK_CPointerToObjCPointerCast);
13187 }
13188 return computeResultTy();
13189 }
13190 if (LHSType->isObjCObjectPointerType() &&
13191 RHSType->isObjCObjectPointerType()) {
13192 if (!Context.areComparableObjCPointerTypes(LHS: LHSType, RHS: RHSType))
13193 diagnoseDistinctPointerComparison(S&: *this, Loc, LHS, RHS,
13194 /*isError*/IsError: false);
13195 if (isObjCObjectLiteral(E&: LHS) || isObjCObjectLiteral(E&: RHS))
13196 diagnoseObjCLiteralComparison(S&: *this, Loc, LHS, RHS, Opc);
13197
13198 if (LHSIsNull && !RHSIsNull)
13199 LHS = ImpCastExprToType(E: LHS.get(), Type: RHSType, CK: CK_BitCast);
13200 else
13201 RHS = ImpCastExprToType(E: RHS.get(), Type: LHSType, CK: CK_BitCast);
13202 return computeResultTy();
13203 }
13204
13205 if (!IsOrdered && LHSType->isBlockPointerType() &&
13206 RHSType->isBlockCompatibleObjCPointerType(ctx&: Context)) {
13207 LHS = ImpCastExprToType(E: LHS.get(), Type: RHSType,
13208 CK: CK_BlockPointerToObjCPointerCast);
13209 return computeResultTy();
13210 } else if (!IsOrdered &&
13211 LHSType->isBlockCompatibleObjCPointerType(ctx&: Context) &&
13212 RHSType->isBlockPointerType()) {
13213 RHS = ImpCastExprToType(E: RHS.get(), Type: LHSType,
13214 CK: CK_BlockPointerToObjCPointerCast);
13215 return computeResultTy();
13216 }
13217 }
13218 if ((LHSType->isAnyPointerType() && RHSType->isIntegerType()) ||
13219 (LHSType->isIntegerType() && RHSType->isAnyPointerType())) {
13220 unsigned DiagID = 0;
13221 bool isError = false;
13222 if (LangOpts.DebuggerSupport) {
13223 // Under a debugger, allow the comparison of pointers to integers,
13224 // since users tend to want to compare addresses.
13225 } else if ((LHSIsNull && LHSType->isIntegerType()) ||
13226 (RHSIsNull && RHSType->isIntegerType())) {
13227 if (IsOrdered) {
13228 isError = getLangOpts().CPlusPlus;
13229 DiagID =
13230 isError ? diag::err_typecheck_ordered_comparison_of_pointer_and_zero
13231 : diag::ext_typecheck_ordered_comparison_of_pointer_and_zero;
13232 }
13233 } else if (getLangOpts().CPlusPlus) {
13234 DiagID = diag::err_typecheck_comparison_of_pointer_integer;
13235 isError = true;
13236 } else if (IsOrdered)
13237 DiagID = diag::ext_typecheck_ordered_comparison_of_pointer_integer;
13238 else
13239 DiagID = diag::ext_typecheck_comparison_of_pointer_integer;
13240
13241 if (DiagID) {
13242 Diag(Loc, DiagID)
13243 << LHSType << RHSType << LHS.get()->getSourceRange()
13244 << RHS.get()->getSourceRange();
13245 if (isError)
13246 return QualType();
13247 }
13248
13249 if (LHSType->isIntegerType())
13250 LHS = ImpCastExprToType(E: LHS.get(), Type: RHSType,
13251 CK: LHSIsNull ? CK_NullToPointer : CK_IntegralToPointer);
13252 else
13253 RHS = ImpCastExprToType(E: RHS.get(), Type: LHSType,
13254 CK: RHSIsNull ? CK_NullToPointer : CK_IntegralToPointer);
13255 return computeResultTy();
13256 }
13257
13258 // Handle block pointers.
13259 if (!IsOrdered && RHSIsNull
13260 && LHSType->isBlockPointerType() && RHSType->isIntegerType()) {
13261 RHS = ImpCastExprToType(E: RHS.get(), Type: LHSType, CK: CK_NullToPointer);
13262 return computeResultTy();
13263 }
13264 if (!IsOrdered && LHSIsNull
13265 && LHSType->isIntegerType() && RHSType->isBlockPointerType()) {
13266 LHS = ImpCastExprToType(E: LHS.get(), Type: RHSType, CK: CK_NullToPointer);
13267 return computeResultTy();
13268 }
13269
13270 if (getLangOpts().getOpenCLCompatibleVersion() >= 200) {
13271 if (LHSType->isClkEventT() && RHSType->isClkEventT()) {
13272 return computeResultTy();
13273 }
13274
13275 if (LHSType->isQueueT() && RHSType->isQueueT()) {
13276 return computeResultTy();
13277 }
13278
13279 if (LHSIsNull && RHSType->isQueueT()) {
13280 LHS = ImpCastExprToType(E: LHS.get(), Type: RHSType, CK: CK_NullToPointer);
13281 return computeResultTy();
13282 }
13283
13284 if (LHSType->isQueueT() && RHSIsNull) {
13285 RHS = ImpCastExprToType(E: RHS.get(), Type: LHSType, CK: CK_NullToPointer);
13286 return computeResultTy();
13287 }
13288 }
13289
13290 return InvalidOperands(Loc, LHS, RHS);
13291}
13292
13293QualType Sema::GetSignedVectorType(QualType V) {
13294 const VectorType *VTy = V->castAs<VectorType>();
13295 unsigned TypeSize = Context.getTypeSize(T: VTy->getElementType());
13296
13297 if (isa<ExtVectorType>(Val: VTy)) {
13298 if (VTy->isExtVectorBoolType())
13299 return Context.getExtVectorType(VectorType: Context.BoolTy, NumElts: VTy->getNumElements());
13300 if (TypeSize == Context.getTypeSize(T: Context.CharTy))
13301 return Context.getExtVectorType(VectorType: Context.CharTy, NumElts: VTy->getNumElements());
13302 if (TypeSize == Context.getTypeSize(T: Context.ShortTy))
13303 return Context.getExtVectorType(VectorType: Context.ShortTy, NumElts: VTy->getNumElements());
13304 if (TypeSize == Context.getTypeSize(T: Context.IntTy))
13305 return Context.getExtVectorType(VectorType: Context.IntTy, NumElts: VTy->getNumElements());
13306 if (TypeSize == Context.getTypeSize(T: Context.Int128Ty))
13307 return Context.getExtVectorType(VectorType: Context.Int128Ty, NumElts: VTy->getNumElements());
13308 if (TypeSize == Context.getTypeSize(T: Context.LongTy))
13309 return Context.getExtVectorType(VectorType: Context.LongTy, NumElts: VTy->getNumElements());
13310 assert(TypeSize == Context.getTypeSize(Context.LongLongTy) &&
13311 "Unhandled vector element size in vector compare");
13312 return Context.getExtVectorType(VectorType: Context.LongLongTy, NumElts: VTy->getNumElements());
13313 }
13314
13315 if (TypeSize == Context.getTypeSize(T: Context.Int128Ty))
13316 return Context.getVectorType(VectorType: Context.Int128Ty, NumElts: VTy->getNumElements(),
13317 VecKind: VectorKind::Generic);
13318 if (TypeSize == Context.getTypeSize(T: Context.LongLongTy))
13319 return Context.getVectorType(VectorType: Context.LongLongTy, NumElts: VTy->getNumElements(),
13320 VecKind: VectorKind::Generic);
13321 if (TypeSize == Context.getTypeSize(T: Context.LongTy))
13322 return Context.getVectorType(VectorType: Context.LongTy, NumElts: VTy->getNumElements(),
13323 VecKind: VectorKind::Generic);
13324 if (TypeSize == Context.getTypeSize(T: Context.IntTy))
13325 return Context.getVectorType(VectorType: Context.IntTy, NumElts: VTy->getNumElements(),
13326 VecKind: VectorKind::Generic);
13327 if (TypeSize == Context.getTypeSize(T: Context.ShortTy))
13328 return Context.getVectorType(VectorType: Context.ShortTy, NumElts: VTy->getNumElements(),
13329 VecKind: VectorKind::Generic);
13330 assert(TypeSize == Context.getTypeSize(Context.CharTy) &&
13331 "Unhandled vector element size in vector compare");
13332 return Context.getVectorType(VectorType: Context.CharTy, NumElts: VTy->getNumElements(),
13333 VecKind: VectorKind::Generic);
13334}
13335
13336QualType Sema::GetSignedSizelessVectorType(QualType V) {
13337 const BuiltinType *VTy = V->castAs<BuiltinType>();
13338 assert(VTy->isSizelessBuiltinType() && "expected sizeless type");
13339
13340 const QualType ETy = V->getSveEltType(Ctx: Context);
13341 const auto TypeSize = Context.getTypeSize(T: ETy);
13342
13343 const QualType IntTy = Context.getIntTypeForBitwidth(DestWidth: TypeSize, Signed: true);
13344 const llvm::ElementCount VecSize = Context.getBuiltinVectorTypeInfo(VecTy: VTy).EC;
13345 return Context.getScalableVectorType(EltTy: IntTy, NumElts: VecSize.getKnownMinValue());
13346}
13347
13348QualType Sema::CheckVectorCompareOperands(ExprResult &LHS, ExprResult &RHS,
13349 SourceLocation Loc,
13350 BinaryOperatorKind Opc) {
13351 if (Opc == BO_Cmp) {
13352 Diag(Loc, DiagID: diag::err_three_way_vector_comparison);
13353 return QualType();
13354 }
13355
13356 // Check to make sure we're operating on vectors of the same type and width,
13357 // Allowing one side to be a scalar of element type.
13358 QualType vType =
13359 CheckVectorOperands(LHS, RHS, Loc, /*isCompAssign*/ IsCompAssign: false,
13360 /*AllowBothBool*/ true,
13361 /*AllowBoolConversions*/ getLangOpts().ZVector,
13362 /*AllowBooleanOperation*/ AllowBoolOperation: true,
13363 /*ReportInvalid*/ true);
13364 if (vType.isNull())
13365 return vType;
13366
13367 QualType LHSType = LHS.get()->getType();
13368
13369 // Determine the return type of a vector compare. By default clang will return
13370 // a scalar for all vector compares except vector bool and vector pixel.
13371 // With the gcc compiler we will always return a vector type and with the xl
13372 // compiler we will always return a scalar type. This switch allows choosing
13373 // which behavior is prefered.
13374 if (getLangOpts().AltiVec) {
13375 switch (getLangOpts().getAltivecSrcCompat()) {
13376 case LangOptions::AltivecSrcCompatKind::Mixed:
13377 // If AltiVec, the comparison results in a numeric type, i.e.
13378 // bool for C++, int for C
13379 if (vType->castAs<VectorType>()->getVectorKind() ==
13380 VectorKind::AltiVecVector)
13381 return Context.getLogicalOperationType();
13382 else
13383 Diag(Loc, DiagID: diag::warn_deprecated_altivec_src_compat);
13384 break;
13385 case LangOptions::AltivecSrcCompatKind::GCC:
13386 // For GCC we always return the vector type.
13387 break;
13388 case LangOptions::AltivecSrcCompatKind::XL:
13389 return Context.getLogicalOperationType();
13390 break;
13391 }
13392 }
13393
13394 // For non-floating point types, check for self-comparisons of the form
13395 // x == x, x != x, x < x, etc. These always evaluate to a constant, and
13396 // often indicate logic errors in the program.
13397 diagnoseTautologicalComparison(S&: *this, Loc, LHS: LHS.get(), RHS: RHS.get(), Opc);
13398
13399 // Check for comparisons of floating point operands using != and ==.
13400 if (LHSType->hasFloatingRepresentation()) {
13401 assert(RHS.get()->getType()->hasFloatingRepresentation());
13402 CheckFloatComparison(Loc, LHS: LHS.get(), RHS: RHS.get(), Opcode: Opc);
13403 }
13404
13405 // Return a signed type for the vector.
13406 return GetSignedVectorType(V: vType);
13407}
13408
13409QualType Sema::CheckSizelessVectorCompareOperands(ExprResult &LHS,
13410 ExprResult &RHS,
13411 SourceLocation Loc,
13412 BinaryOperatorKind Opc) {
13413 if (Opc == BO_Cmp) {
13414 Diag(Loc, DiagID: diag::err_three_way_vector_comparison);
13415 return QualType();
13416 }
13417
13418 // Check to make sure we're operating on vectors of the same type and width,
13419 // Allowing one side to be a scalar of element type.
13420 QualType vType = CheckSizelessVectorOperands(
13421 LHS, RHS, Loc, /*isCompAssign*/ IsCompAssign: false, OperationKind: ArithConvKind::Comparison);
13422
13423 if (vType.isNull())
13424 return vType;
13425
13426 QualType LHSType = LHS.get()->getType();
13427
13428 // For non-floating point types, check for self-comparisons of the form
13429 // x == x, x != x, x < x, etc. These always evaluate to a constant, and
13430 // often indicate logic errors in the program.
13431 diagnoseTautologicalComparison(S&: *this, Loc, LHS: LHS.get(), RHS: RHS.get(), Opc);
13432
13433 // Check for comparisons of floating point operands using != and ==.
13434 if (LHSType->hasFloatingRepresentation()) {
13435 assert(RHS.get()->getType()->hasFloatingRepresentation());
13436 CheckFloatComparison(Loc, LHS: LHS.get(), RHS: RHS.get(), Opcode: Opc);
13437 }
13438
13439 const BuiltinType *LHSBuiltinTy = LHSType->getAs<BuiltinType>();
13440 const BuiltinType *RHSBuiltinTy = RHS.get()->getType()->getAs<BuiltinType>();
13441
13442 if (LHSBuiltinTy && RHSBuiltinTy && LHSBuiltinTy->isSVEBool() &&
13443 RHSBuiltinTy->isSVEBool())
13444 return LHSType;
13445
13446 // Return a signed type for the vector.
13447 return GetSignedSizelessVectorType(V: vType);
13448}
13449
13450static void diagnoseXorMisusedAsPow(Sema &S, const ExprResult &XorLHS,
13451 const ExprResult &XorRHS,
13452 const SourceLocation Loc) {
13453 // Do not diagnose macros.
13454 if (Loc.isMacroID())
13455 return;
13456
13457 // Do not diagnose if both LHS and RHS are macros.
13458 if (XorLHS.get()->getExprLoc().isMacroID() &&
13459 XorRHS.get()->getExprLoc().isMacroID())
13460 return;
13461
13462 bool Negative = false;
13463 bool ExplicitPlus = false;
13464 const auto *LHSInt = dyn_cast<IntegerLiteral>(Val: XorLHS.get());
13465 const auto *RHSInt = dyn_cast<IntegerLiteral>(Val: XorRHS.get());
13466
13467 if (!LHSInt)
13468 return;
13469 if (!RHSInt) {
13470 // Check negative literals.
13471 if (const auto *UO = dyn_cast<UnaryOperator>(Val: XorRHS.get())) {
13472 UnaryOperatorKind Opc = UO->getOpcode();
13473 if (Opc != UO_Minus && Opc != UO_Plus)
13474 return;
13475 RHSInt = dyn_cast<IntegerLiteral>(Val: UO->getSubExpr());
13476 if (!RHSInt)
13477 return;
13478 Negative = (Opc == UO_Minus);
13479 ExplicitPlus = !Negative;
13480 } else {
13481 return;
13482 }
13483 }
13484
13485 const llvm::APInt &LeftSideValue = LHSInt->getValue();
13486 llvm::APInt RightSideValue = RHSInt->getValue();
13487 if (LeftSideValue != 2 && LeftSideValue != 10)
13488 return;
13489
13490 if (LeftSideValue.getBitWidth() != RightSideValue.getBitWidth())
13491 return;
13492
13493 CharSourceRange ExprRange = CharSourceRange::getCharRange(
13494 B: LHSInt->getBeginLoc(), E: S.getLocForEndOfToken(Loc: RHSInt->getLocation()));
13495 llvm::StringRef ExprStr =
13496 Lexer::getSourceText(Range: ExprRange, SM: S.getSourceManager(), LangOpts: S.getLangOpts());
13497
13498 CharSourceRange XorRange =
13499 CharSourceRange::getCharRange(B: Loc, E: S.getLocForEndOfToken(Loc));
13500 llvm::StringRef XorStr =
13501 Lexer::getSourceText(Range: XorRange, SM: S.getSourceManager(), LangOpts: S.getLangOpts());
13502 // Do not diagnose if xor keyword/macro is used.
13503 if (XorStr == "xor")
13504 return;
13505
13506 std::string LHSStr = std::string(Lexer::getSourceText(
13507 Range: CharSourceRange::getTokenRange(R: LHSInt->getSourceRange()),
13508 SM: S.getSourceManager(), LangOpts: S.getLangOpts()));
13509 std::string RHSStr = std::string(Lexer::getSourceText(
13510 Range: CharSourceRange::getTokenRange(R: RHSInt->getSourceRange()),
13511 SM: S.getSourceManager(), LangOpts: S.getLangOpts()));
13512
13513 if (Negative) {
13514 RightSideValue = -RightSideValue;
13515 RHSStr = "-" + RHSStr;
13516 } else if (ExplicitPlus) {
13517 RHSStr = "+" + RHSStr;
13518 }
13519
13520 StringRef LHSStrRef = LHSStr;
13521 StringRef RHSStrRef = RHSStr;
13522 // Do not diagnose literals with digit separators, binary, hexadecimal, octal
13523 // literals.
13524 if (LHSStrRef.starts_with(Prefix: "0b") || LHSStrRef.starts_with(Prefix: "0B") ||
13525 RHSStrRef.starts_with(Prefix: "0b") || RHSStrRef.starts_with(Prefix: "0B") ||
13526 LHSStrRef.starts_with(Prefix: "0x") || LHSStrRef.starts_with(Prefix: "0X") ||
13527 RHSStrRef.starts_with(Prefix: "0x") || RHSStrRef.starts_with(Prefix: "0X") ||
13528 (LHSStrRef.size() > 1 && LHSStrRef.starts_with(Prefix: "0")) ||
13529 (RHSStrRef.size() > 1 && RHSStrRef.starts_with(Prefix: "0")) ||
13530 LHSStrRef.contains(C: '\'') || RHSStrRef.contains(C: '\''))
13531 return;
13532
13533 bool SuggestXor =
13534 S.getLangOpts().CPlusPlus || S.getPreprocessor().isMacroDefined(Id: "xor");
13535 const llvm::APInt XorValue = LeftSideValue ^ RightSideValue;
13536 int64_t RightSideIntValue = RightSideValue.getSExtValue();
13537 if (LeftSideValue == 2 && RightSideIntValue >= 0) {
13538 std::string SuggestedExpr = "1 << " + RHSStr;
13539 bool Overflow = false;
13540 llvm::APInt One = (LeftSideValue - 1);
13541 llvm::APInt PowValue = One.sshl_ov(Amt: RightSideValue, Overflow);
13542 if (Overflow) {
13543 if (RightSideIntValue < 64)
13544 S.Diag(Loc, DiagID: diag::warn_xor_used_as_pow_base)
13545 << ExprStr << toString(I: XorValue, Radix: 10, Signed: true) << ("1LL << " + RHSStr)
13546 << FixItHint::CreateReplacement(RemoveRange: ExprRange, Code: "1LL << " + RHSStr);
13547 else if (RightSideIntValue == 64)
13548 S.Diag(Loc, DiagID: diag::warn_xor_used_as_pow)
13549 << ExprStr << toString(I: XorValue, Radix: 10, Signed: true);
13550 else
13551 return;
13552 } else {
13553 S.Diag(Loc, DiagID: diag::warn_xor_used_as_pow_base_extra)
13554 << ExprStr << toString(I: XorValue, Radix: 10, Signed: true) << SuggestedExpr
13555 << toString(I: PowValue, Radix: 10, Signed: true)
13556 << FixItHint::CreateReplacement(
13557 RemoveRange: ExprRange, Code: (RightSideIntValue == 0) ? "1" : SuggestedExpr);
13558 }
13559
13560 S.Diag(Loc, DiagID: diag::note_xor_used_as_pow_silence)
13561 << ("0x2 ^ " + RHSStr) << SuggestXor;
13562 } else if (LeftSideValue == 10) {
13563 std::string SuggestedValue = "1e" + std::to_string(val: RightSideIntValue);
13564 S.Diag(Loc, DiagID: diag::warn_xor_used_as_pow_base)
13565 << ExprStr << toString(I: XorValue, Radix: 10, Signed: true) << SuggestedValue
13566 << FixItHint::CreateReplacement(RemoveRange: ExprRange, Code: SuggestedValue);
13567 S.Diag(Loc, DiagID: diag::note_xor_used_as_pow_silence)
13568 << ("0xA ^ " + RHSStr) << SuggestXor;
13569 }
13570}
13571
13572QualType Sema::CheckVectorLogicalOperands(ExprResult &LHS, ExprResult &RHS,
13573 SourceLocation Loc,
13574 BinaryOperatorKind Opc) {
13575 // Ensure that either both operands are of the same vector type, or
13576 // one operand is of a vector type and the other is of its element type.
13577 QualType vType = CheckVectorOperands(LHS, RHS, Loc, IsCompAssign: false,
13578 /*AllowBothBool*/ true,
13579 /*AllowBoolConversions*/ false,
13580 /*AllowBooleanOperation*/ AllowBoolOperation: false,
13581 /*ReportInvalid*/ false);
13582 if (vType.isNull())
13583 return InvalidOperands(Loc, LHS, RHS);
13584 if (getLangOpts().OpenCL &&
13585 getLangOpts().getOpenCLCompatibleVersion() < 120 &&
13586 vType->hasFloatingRepresentation())
13587 return InvalidOperands(Loc, LHS, RHS);
13588 // FIXME: The check for C++ here is for GCC compatibility. GCC rejects the
13589 // usage of the logical operators && and || with vectors in C. This
13590 // check could be notionally dropped.
13591 if (!getLangOpts().CPlusPlus &&
13592 !(isa<ExtVectorType>(Val: vType->getAs<VectorType>())))
13593 return InvalidLogicalVectorOperands(Loc, LHS, RHS);
13594 // Beginning with HLSL 2021, HLSL disallows logical operators on vector
13595 // operands and instead requires the use of the `and`, `or`, `any`, `all`, and
13596 // `select` functions.
13597 if (getLangOpts().HLSL &&
13598 getLangOpts().getHLSLVersion() >= LangOptionsBase::HLSL_2021) {
13599 (void)InvalidOperands(Loc, LHS, RHS);
13600 HLSL().emitLogicalOperatorFixIt(LHS: LHS.get(), RHS: RHS.get(), Opc);
13601 return QualType();
13602 }
13603
13604 return GetSignedVectorType(V: LHS.get()->getType());
13605}
13606
13607QualType Sema::CheckMatrixLogicalOperands(ExprResult &LHS, ExprResult &RHS,
13608 SourceLocation Loc,
13609 BinaryOperatorKind Opc) {
13610
13611 if (!getLangOpts().HLSL) {
13612 assert(false && "Logical operands are not supported in C\\C++");
13613 return QualType();
13614 }
13615
13616 if (getLangOpts().getHLSLVersion() >= LangOptionsBase::HLSL_2021) {
13617 (void)InvalidOperands(Loc, LHS, RHS);
13618 HLSL().emitLogicalOperatorFixIt(LHS: LHS.get(), RHS: RHS.get(), Opc);
13619 return QualType();
13620 }
13621 SemaRef.Diag(Loc: LHS.get()->getBeginLoc(), DiagID: diag::err_hlsl_langstd_unimplemented)
13622 << getLangOpts().getHLSLVersion();
13623 return QualType();
13624}
13625
13626QualType Sema::CheckMatrixElementwiseOperands(ExprResult &LHS, ExprResult &RHS,
13627 SourceLocation Loc,
13628 bool IsCompAssign) {
13629 if (!IsCompAssign) {
13630 LHS = DefaultFunctionArrayLvalueConversion(E: LHS.get());
13631 if (LHS.isInvalid())
13632 return QualType();
13633 }
13634 RHS = DefaultFunctionArrayLvalueConversion(E: RHS.get());
13635 if (RHS.isInvalid())
13636 return QualType();
13637
13638 // For conversion purposes, we ignore any qualifiers.
13639 // For example, "const float" and "float" are equivalent.
13640 QualType LHSType = LHS.get()->getType().getUnqualifiedType();
13641 QualType RHSType = RHS.get()->getType().getUnqualifiedType();
13642
13643 const MatrixType *LHSMatType = LHSType->getAs<MatrixType>();
13644 const MatrixType *RHSMatType = RHSType->getAs<MatrixType>();
13645 assert((LHSMatType || RHSMatType) && "At least one operand must be a matrix");
13646
13647 if (Context.hasSameType(T1: LHSType, T2: RHSType))
13648 return Context.getCommonSugaredType(X: LHSType, Y: RHSType);
13649
13650 // Type conversion may change LHS/RHS. Keep copies to the original results, in
13651 // case we have to return InvalidOperands.
13652 ExprResult OriginalLHS = LHS;
13653 ExprResult OriginalRHS = RHS;
13654 if (LHSMatType && !RHSMatType) {
13655 RHS = tryConvertExprToType(E: RHS.get(), Ty: LHSMatType->getElementType());
13656 if (!RHS.isInvalid())
13657 return LHSType;
13658
13659 return InvalidOperands(Loc, LHS&: OriginalLHS, RHS&: OriginalRHS);
13660 }
13661
13662 if (!LHSMatType && RHSMatType) {
13663 LHS = tryConvertExprToType(E: LHS.get(), Ty: RHSMatType->getElementType());
13664 if (!LHS.isInvalid())
13665 return RHSType;
13666 return InvalidOperands(Loc, LHS&: OriginalLHS, RHS&: OriginalRHS);
13667 }
13668
13669 return InvalidOperands(Loc, LHS, RHS);
13670}
13671
13672QualType Sema::CheckMatrixMultiplyOperands(ExprResult &LHS, ExprResult &RHS,
13673 SourceLocation Loc,
13674 bool IsCompAssign) {
13675 if (!IsCompAssign) {
13676 LHS = DefaultFunctionArrayLvalueConversion(E: LHS.get());
13677 if (LHS.isInvalid())
13678 return QualType();
13679 }
13680 RHS = DefaultFunctionArrayLvalueConversion(E: RHS.get());
13681 if (RHS.isInvalid())
13682 return QualType();
13683
13684 auto *LHSMatType = LHS.get()->getType()->getAs<ConstantMatrixType>();
13685 auto *RHSMatType = RHS.get()->getType()->getAs<ConstantMatrixType>();
13686 assert((LHSMatType || RHSMatType) && "At least one operand must be a matrix");
13687
13688 if (LHSMatType && RHSMatType) {
13689 if (LHSMatType->getNumColumns() != RHSMatType->getNumRows())
13690 return InvalidOperands(Loc, LHS, RHS);
13691
13692 if (Context.hasSameType(T1: LHSMatType, T2: RHSMatType))
13693 return Context.getCommonSugaredType(
13694 X: LHS.get()->getType().getUnqualifiedType(),
13695 Y: RHS.get()->getType().getUnqualifiedType());
13696
13697 QualType LHSELTy = LHSMatType->getElementType(),
13698 RHSELTy = RHSMatType->getElementType();
13699 if (!Context.hasSameType(T1: LHSELTy, T2: RHSELTy))
13700 return InvalidOperands(Loc, LHS, RHS);
13701
13702 return Context.getConstantMatrixType(
13703 ElementType: Context.getCommonSugaredType(X: LHSELTy, Y: RHSELTy),
13704 NumRows: LHSMatType->getNumRows(), NumColumns: RHSMatType->getNumColumns());
13705 }
13706 return CheckMatrixElementwiseOperands(LHS, RHS, Loc, IsCompAssign);
13707}
13708
13709static bool isLegalBoolVectorBinaryOp(BinaryOperatorKind Opc) {
13710 switch (Opc) {
13711 default:
13712 return false;
13713 case BO_And:
13714 case BO_AndAssign:
13715 case BO_Or:
13716 case BO_OrAssign:
13717 case BO_Xor:
13718 case BO_XorAssign:
13719 return true;
13720 }
13721}
13722
13723inline QualType Sema::CheckBitwiseOperands(ExprResult &LHS, ExprResult &RHS,
13724 SourceLocation Loc,
13725 BinaryOperatorKind Opc) {
13726 checkArithmeticNull(S&: *this, LHS, RHS, Loc, /*IsCompare=*/false);
13727
13728 bool IsCompAssign =
13729 Opc == BO_AndAssign || Opc == BO_OrAssign || Opc == BO_XorAssign;
13730
13731 bool LegalBoolVecOperator = isLegalBoolVectorBinaryOp(Opc);
13732
13733 if (LHS.get()->getType()->isVectorType() ||
13734 RHS.get()->getType()->isVectorType()) {
13735 if (LHS.get()->getType()->hasIntegerRepresentation() &&
13736 RHS.get()->getType()->hasIntegerRepresentation())
13737 return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign,
13738 /*AllowBothBool*/ true,
13739 /*AllowBoolConversions*/ getLangOpts().ZVector,
13740 /*AllowBooleanOperation*/ AllowBoolOperation: LegalBoolVecOperator,
13741 /*ReportInvalid*/ true);
13742 return InvalidOperands(Loc, LHS, RHS);
13743 }
13744
13745 if (LHS.get()->getType()->isSveVLSBuiltinType() ||
13746 RHS.get()->getType()->isSveVLSBuiltinType()) {
13747 if (LHS.get()->getType()->hasIntegerRepresentation() &&
13748 RHS.get()->getType()->hasIntegerRepresentation())
13749 return CheckSizelessVectorOperands(LHS, RHS, Loc, IsCompAssign,
13750 OperationKind: ArithConvKind::BitwiseOp);
13751 return InvalidOperands(Loc, LHS, RHS);
13752 }
13753
13754 if (LHS.get()->getType()->isSveVLSBuiltinType() ||
13755 RHS.get()->getType()->isSveVLSBuiltinType()) {
13756 if (LHS.get()->getType()->hasIntegerRepresentation() &&
13757 RHS.get()->getType()->hasIntegerRepresentation())
13758 return CheckSizelessVectorOperands(LHS, RHS, Loc, IsCompAssign,
13759 OperationKind: ArithConvKind::BitwiseOp);
13760 return InvalidOperands(Loc, LHS, RHS);
13761 }
13762
13763 if (Opc == BO_And)
13764 diagnoseLogicalNotOnLHSofCheck(S&: *this, LHS, RHS, Loc, Opc);
13765
13766 if (LHS.get()->getType()->hasFloatingRepresentation() ||
13767 RHS.get()->getType()->hasFloatingRepresentation())
13768 return InvalidOperands(Loc, LHS, RHS);
13769
13770 ExprResult LHSResult = LHS, RHSResult = RHS;
13771 QualType compType = UsualArithmeticConversions(
13772 LHS&: LHSResult, RHS&: RHSResult, Loc,
13773 ACK: IsCompAssign ? ArithConvKind::CompAssign : ArithConvKind::BitwiseOp);
13774 if (LHSResult.isInvalid() || RHSResult.isInvalid())
13775 return QualType();
13776 LHS = LHSResult.get();
13777 RHS = RHSResult.get();
13778
13779 if (Opc == BO_Xor)
13780 diagnoseXorMisusedAsPow(S&: *this, XorLHS: LHS, XorRHS: RHS, Loc);
13781
13782 if (!compType.isNull() && compType->isIntegralOrUnscopedEnumerationType())
13783 return compType;
13784 QualType ResultTy = InvalidOperands(Loc, LHS, RHS);
13785 diagnoseScopedEnums(S&: *this, Loc, LHS, RHS, Opc);
13786 return ResultTy;
13787}
13788
13789// C99 6.5.[13,14]
13790inline QualType Sema::CheckLogicalOperands(ExprResult &LHS, ExprResult &RHS,
13791 SourceLocation Loc,
13792 BinaryOperatorKind Opc) {
13793 // Check vector operands differently.
13794 if (LHS.get()->getType()->isVectorType() ||
13795 RHS.get()->getType()->isVectorType())
13796 return CheckVectorLogicalOperands(LHS, RHS, Loc, Opc);
13797
13798 if (LHS.get()->getType()->isConstantMatrixType() ||
13799 RHS.get()->getType()->isConstantMatrixType())
13800 return CheckMatrixLogicalOperands(LHS, RHS, Loc, Opc);
13801
13802 bool EnumConstantInBoolContext = false;
13803 for (const ExprResult &HS : {LHS, RHS}) {
13804 if (const auto *DREHS = dyn_cast<DeclRefExpr>(Val: HS.get())) {
13805 const auto *ECDHS = dyn_cast<EnumConstantDecl>(Val: DREHS->getDecl());
13806 if (ECDHS && ECDHS->getInitVal() != 0 && ECDHS->getInitVal() != 1)
13807 EnumConstantInBoolContext = true;
13808 }
13809 }
13810
13811 if (EnumConstantInBoolContext)
13812 Diag(Loc, DiagID: diag::warn_enum_constant_in_bool_context);
13813
13814 // WebAssembly tables can't be used with logical operators.
13815 QualType LHSTy = LHS.get()->getType();
13816 QualType RHSTy = RHS.get()->getType();
13817 const auto *LHSATy = dyn_cast<ArrayType>(Val&: LHSTy);
13818 const auto *RHSATy = dyn_cast<ArrayType>(Val&: RHSTy);
13819 if ((LHSATy && LHSATy->getElementType().isWebAssemblyReferenceType()) ||
13820 (RHSATy && RHSATy->getElementType().isWebAssemblyReferenceType())) {
13821 return InvalidOperands(Loc, LHS, RHS);
13822 }
13823
13824 // Diagnose cases where the user write a logical and/or but probably meant a
13825 // bitwise one. We do this when the LHS is a non-bool integer and the RHS
13826 // is a constant.
13827 if (!EnumConstantInBoolContext && LHS.get()->getType()->isIntegerType() &&
13828 !LHS.get()->getType()->isBooleanType() &&
13829 RHS.get()->getType()->isIntegerType() && !RHS.get()->isValueDependent() &&
13830 // Don't warn in macros or template instantiations.
13831 !Loc.isMacroID() && !inTemplateInstantiation()) {
13832 // If the RHS can be constant folded, and if it constant folds to something
13833 // that isn't 0 or 1 (which indicate a potential logical operation that
13834 // happened to fold to true/false) then warn.
13835 // Parens on the RHS are ignored.
13836 Expr::EvalResult EVResult;
13837 if (RHS.get()->EvaluateAsInt(Result&: EVResult, Ctx: Context)) {
13838 llvm::APSInt Result = EVResult.Val.getInt();
13839 if ((getLangOpts().CPlusPlus && !RHS.get()->getType()->isBooleanType() &&
13840 !RHS.get()->getExprLoc().isMacroID()) ||
13841 (Result != 0 && Result != 1)) {
13842 Diag(Loc, DiagID: diag::warn_logical_instead_of_bitwise)
13843 << RHS.get()->getSourceRange() << (Opc == BO_LAnd ? "&&" : "||");
13844 // Suggest replacing the logical operator with the bitwise version
13845 Diag(Loc, DiagID: diag::note_logical_instead_of_bitwise_change_operator)
13846 << (Opc == BO_LAnd ? "&" : "|")
13847 << FixItHint::CreateReplacement(
13848 RemoveRange: SourceRange(Loc, getLocForEndOfToken(Loc)),
13849 Code: Opc == BO_LAnd ? "&" : "|");
13850 if (Opc == BO_LAnd)
13851 // Suggest replacing "Foo() && kNonZero" with "Foo()"
13852 Diag(Loc, DiagID: diag::note_logical_instead_of_bitwise_remove_constant)
13853 << FixItHint::CreateRemoval(
13854 RemoveRange: SourceRange(getLocForEndOfToken(Loc: LHS.get()->getEndLoc()),
13855 RHS.get()->getEndLoc()));
13856 }
13857 }
13858 }
13859
13860 if (!Context.getLangOpts().CPlusPlus) {
13861 // OpenCL v1.1 s6.3.g: The logical operators and (&&), or (||) do
13862 // not operate on the built-in scalar and vector float types.
13863 if (Context.getLangOpts().OpenCL &&
13864 Context.getLangOpts().OpenCLVersion < 120) {
13865 if (LHS.get()->getType()->isFloatingType() ||
13866 RHS.get()->getType()->isFloatingType())
13867 return InvalidOperands(Loc, LHS, RHS);
13868 }
13869
13870 LHS = UsualUnaryConversions(E: LHS.get());
13871 if (LHS.isInvalid())
13872 return QualType();
13873
13874 RHS = UsualUnaryConversions(E: RHS.get());
13875 if (RHS.isInvalid())
13876 return QualType();
13877
13878 if (!LHS.get()->getType()->isScalarType() ||
13879 !RHS.get()->getType()->isScalarType())
13880 return InvalidOperands(Loc, LHS, RHS);
13881
13882 return Context.IntTy;
13883 }
13884
13885 // The following is safe because we only use this method for
13886 // non-overloadable operands.
13887
13888 // C++ [expr.log.and]p1
13889 // C++ [expr.log.or]p1
13890 // The operands are both contextually converted to type bool.
13891 ExprResult LHSRes = PerformContextuallyConvertToBool(From: LHS.get());
13892 if (LHSRes.isInvalid()) {
13893 QualType ResultTy = InvalidOperands(Loc, LHS, RHS);
13894 diagnoseScopedEnums(S&: *this, Loc, LHS, RHS, Opc);
13895 return ResultTy;
13896 }
13897 LHS = LHSRes;
13898
13899 ExprResult RHSRes = PerformContextuallyConvertToBool(From: RHS.get());
13900 if (RHSRes.isInvalid()) {
13901 QualType ResultTy = InvalidOperands(Loc, LHS, RHS);
13902 diagnoseScopedEnums(S&: *this, Loc, LHS, RHS, Opc);
13903 return ResultTy;
13904 }
13905 RHS = RHSRes;
13906
13907 // C++ [expr.log.and]p2
13908 // C++ [expr.log.or]p2
13909 // The result is a bool.
13910 return Context.BoolTy;
13911}
13912
13913static bool IsReadonlyMessage(Expr *E, Sema &S) {
13914 const MemberExpr *ME = dyn_cast<MemberExpr>(Val: E);
13915 if (!ME) return false;
13916 if (!isa<FieldDecl>(Val: ME->getMemberDecl())) return false;
13917 ObjCMessageExpr *Base = dyn_cast<ObjCMessageExpr>(
13918 Val: ME->getBase()->IgnoreImplicit()->IgnoreParenImpCasts());
13919 if (!Base) return false;
13920 return Base->getMethodDecl() != nullptr;
13921}
13922
13923/// Is the given expression (which must be 'const') a reference to a
13924/// variable which was originally non-const, but which has become
13925/// 'const' due to being captured within a block?
13926enum NonConstCaptureKind { NCCK_None, NCCK_Block, NCCK_Lambda };
13927static NonConstCaptureKind isReferenceToNonConstCapture(Sema &S, Expr *E) {
13928 assert(E->isLValue() && E->getType().isConstQualified());
13929 E = E->IgnoreParens();
13930
13931 // Must be a reference to a declaration from an enclosing scope.
13932 DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Val: E);
13933 if (!DRE) return NCCK_None;
13934 if (!DRE->refersToEnclosingVariableOrCapture()) return NCCK_None;
13935
13936 ValueDecl *Value = dyn_cast<ValueDecl>(Val: DRE->getDecl());
13937
13938 // The declaration must be a value which is not declared 'const'.
13939 if (!Value || Value->getType().isConstQualified())
13940 return NCCK_None;
13941
13942 BindingDecl *Binding = dyn_cast<BindingDecl>(Val: Value);
13943 if (Binding) {
13944 assert(S.getLangOpts().CPlusPlus && "BindingDecl outside of C++?");
13945 assert(!isa<BlockDecl>(Binding->getDeclContext()));
13946 return NCCK_Lambda;
13947 }
13948
13949 VarDecl *Var = dyn_cast<VarDecl>(Val: Value);
13950 if (!Var)
13951 return NCCK_None;
13952 if (Var->getType()->isReferenceType())
13953 return NCCK_None;
13954
13955 assert(Var->hasLocalStorage() && "capture added 'const' to non-local?");
13956
13957 // Decide whether the first capture was for a block or a lambda.
13958 DeclContext *DC = S.CurContext, *Prev = nullptr;
13959 // Decide whether the first capture was for a block or a lambda.
13960 while (DC) {
13961 // For init-capture, it is possible that the variable belongs to the
13962 // template pattern of the current context.
13963 if (auto *FD = dyn_cast<FunctionDecl>(Val: DC))
13964 if (Var->isInitCapture() &&
13965 FD->getTemplateInstantiationPattern() == Var->getDeclContext())
13966 break;
13967 if (DC == Var->getDeclContext())
13968 break;
13969 Prev = DC;
13970 DC = DC->getParent();
13971 }
13972 // Unless we have an init-capture, we've gone one step too far.
13973 if (!Var->isInitCapture())
13974 DC = Prev;
13975 return (isa<BlockDecl>(Val: DC) ? NCCK_Block : NCCK_Lambda);
13976}
13977
13978static bool IsTypeModifiable(QualType Ty, bool IsDereference) {
13979 Ty = Ty.getNonReferenceType();
13980 if (IsDereference && Ty->isPointerType())
13981 Ty = Ty->getPointeeType();
13982 return !Ty.isConstQualified();
13983}
13984
13985// Update err_typecheck_assign_const and note_typecheck_assign_const
13986// when this enum is changed.
13987enum {
13988 ConstFunction,
13989 ConstVariable,
13990 ConstMember,
13991 NestedConstMember,
13992 ConstUnknown, // Keep as last element
13993};
13994
13995/// Emit the "read-only variable not assignable" error and print notes to give
13996/// more information about why the variable is not assignable, such as pointing
13997/// to the declaration of a const variable, showing that a method is const, or
13998/// that the function is returning a const reference.
13999static void DiagnoseConstAssignment(Sema &S, const Expr *E,
14000 SourceLocation Loc) {
14001 SourceRange ExprRange = E->getSourceRange();
14002
14003 // Only emit one error on the first const found. All other consts will emit
14004 // a note to the error.
14005 bool DiagnosticEmitted = false;
14006
14007 // Track if the current expression is the result of a dereference, and if the
14008 // next checked expression is the result of a dereference.
14009 bool IsDereference = false;
14010 bool NextIsDereference = false;
14011
14012 // Loop to process MemberExpr chains.
14013 while (true) {
14014 IsDereference = NextIsDereference;
14015
14016 E = E->IgnoreImplicit()->IgnoreParenImpCasts();
14017 if (const MemberExpr *ME = dyn_cast<MemberExpr>(Val: E)) {
14018 NextIsDereference = ME->isArrow();
14019 const ValueDecl *VD = ME->getMemberDecl();
14020 if (const FieldDecl *Field = dyn_cast<FieldDecl>(Val: VD)) {
14021 // Mutable fields can be modified even if the class is const.
14022 if (Field->isMutable()) {
14023 assert(DiagnosticEmitted && "Expected diagnostic not emitted.");
14024 break;
14025 }
14026
14027 if (!IsTypeModifiable(Ty: Field->getType(), IsDereference)) {
14028 if (!DiagnosticEmitted) {
14029 S.Diag(Loc, DiagID: diag::err_typecheck_assign_const)
14030 << ExprRange << ConstMember << false /*static*/ << Field
14031 << Field->getType();
14032 DiagnosticEmitted = true;
14033 }
14034 S.Diag(Loc: VD->getLocation(), DiagID: diag::note_typecheck_assign_const)
14035 << ConstMember << false /*static*/ << Field << Field->getType()
14036 << Field->getSourceRange();
14037 }
14038 E = ME->getBase();
14039 continue;
14040 } else if (const VarDecl *VDecl = dyn_cast<VarDecl>(Val: VD)) {
14041 if (VDecl->getType().isConstQualified()) {
14042 if (!DiagnosticEmitted) {
14043 S.Diag(Loc, DiagID: diag::err_typecheck_assign_const)
14044 << ExprRange << ConstMember << true /*static*/ << VDecl
14045 << VDecl->getType();
14046 DiagnosticEmitted = true;
14047 }
14048 S.Diag(Loc: VD->getLocation(), DiagID: diag::note_typecheck_assign_const)
14049 << ConstMember << true /*static*/ << VDecl << VDecl->getType()
14050 << VDecl->getSourceRange();
14051 }
14052 // Static fields do not inherit constness from parents.
14053 break;
14054 }
14055 break; // End MemberExpr
14056 } else if (const ArraySubscriptExpr *ASE =
14057 dyn_cast<ArraySubscriptExpr>(Val: E)) {
14058 E = ASE->getBase()->IgnoreParenImpCasts();
14059 continue;
14060 } else if (const ExtVectorElementExpr *EVE =
14061 dyn_cast<ExtVectorElementExpr>(Val: E)) {
14062 E = EVE->getBase()->IgnoreParenImpCasts();
14063 continue;
14064 }
14065 break;
14066 }
14067
14068 if (const CallExpr *CE = dyn_cast<CallExpr>(Val: E)) {
14069 // Function calls
14070 const FunctionDecl *FD = CE->getDirectCallee();
14071 if (FD && !IsTypeModifiable(Ty: FD->getReturnType(), IsDereference)) {
14072 if (!DiagnosticEmitted) {
14073 S.Diag(Loc, DiagID: diag::err_typecheck_assign_const) << ExprRange
14074 << ConstFunction << FD;
14075 DiagnosticEmitted = true;
14076 }
14077 S.Diag(Loc: FD->getReturnTypeSourceRange().getBegin(),
14078 DiagID: diag::note_typecheck_assign_const)
14079 << ConstFunction << FD << FD->getReturnType()
14080 << FD->getReturnTypeSourceRange();
14081 }
14082 } else if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Val: E)) {
14083 // Point to variable declaration.
14084 if (const ValueDecl *VD = DRE->getDecl()) {
14085 if (!IsTypeModifiable(Ty: VD->getType(), IsDereference)) {
14086 if (!DiagnosticEmitted) {
14087 S.Diag(Loc, DiagID: diag::err_typecheck_assign_const)
14088 << ExprRange << ConstVariable << VD << VD->getType();
14089 DiagnosticEmitted = true;
14090 }
14091 S.Diag(Loc: VD->getLocation(), DiagID: diag::note_typecheck_assign_const)
14092 << ConstVariable << VD << VD->getType() << VD->getSourceRange();
14093 }
14094 }
14095 } else if (isa<CXXThisExpr>(Val: E)) {
14096 if (const DeclContext *DC = S.getFunctionLevelDeclContext()) {
14097 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Val: DC)) {
14098 if (MD->isConst()) {
14099 if (!DiagnosticEmitted) {
14100 S.Diag(Loc, DiagID: diag::err_typecheck_assign_const_method)
14101 << ExprRange << MD;
14102 DiagnosticEmitted = true;
14103 }
14104 S.Diag(Loc: MD->getLocation(), DiagID: diag::note_typecheck_assign_const_method)
14105 << MD << MD->getSourceRange();
14106 }
14107 }
14108 }
14109 }
14110
14111 if (DiagnosticEmitted)
14112 return;
14113
14114 // Can't determine a more specific message, so display the generic error.
14115 S.Diag(Loc, DiagID: diag::err_typecheck_assign_const) << ExprRange << ConstUnknown;
14116}
14117
14118enum OriginalExprKind {
14119 OEK_Variable,
14120 OEK_Member,
14121 OEK_LValue
14122};
14123
14124static void DiagnoseRecursiveConstFields(Sema &S, const ValueDecl *VD,
14125 const RecordType *Ty,
14126 SourceLocation Loc, SourceRange Range,
14127 OriginalExprKind OEK,
14128 bool &DiagnosticEmitted) {
14129 std::vector<const RecordType *> RecordTypeList;
14130 RecordTypeList.push_back(x: Ty);
14131 unsigned NextToCheckIndex = 0;
14132 // We walk the record hierarchy breadth-first to ensure that we print
14133 // diagnostics in field nesting order.
14134 while (RecordTypeList.size() > NextToCheckIndex) {
14135 bool IsNested = NextToCheckIndex > 0;
14136 for (const FieldDecl *Field : RecordTypeList[NextToCheckIndex]
14137 ->getDecl()
14138 ->getDefinitionOrSelf()
14139 ->fields()) {
14140 // First, check every field for constness.
14141 QualType FieldTy = Field->getType();
14142 if (FieldTy.isConstQualified()) {
14143 if (!DiagnosticEmitted) {
14144 S.Diag(Loc, DiagID: diag::err_typecheck_assign_const)
14145 << Range << NestedConstMember << OEK << VD
14146 << IsNested << Field;
14147 DiagnosticEmitted = true;
14148 }
14149 S.Diag(Loc: Field->getLocation(), DiagID: diag::note_typecheck_assign_const)
14150 << NestedConstMember << IsNested << Field
14151 << FieldTy << Field->getSourceRange();
14152 }
14153
14154 // Then we append it to the list to check next in order.
14155 FieldTy = FieldTy.getCanonicalType();
14156 if (const auto *FieldRecTy = FieldTy->getAsCanonical<RecordType>()) {
14157 if (!llvm::is_contained(Range&: RecordTypeList, Element: FieldRecTy))
14158 RecordTypeList.push_back(x: FieldRecTy);
14159 }
14160 }
14161 ++NextToCheckIndex;
14162 }
14163}
14164
14165/// Emit an error for the case where a record we are trying to assign to has a
14166/// const-qualified field somewhere in its hierarchy.
14167static void DiagnoseRecursiveConstFields(Sema &S, const Expr *E,
14168 SourceLocation Loc) {
14169 QualType Ty = E->getType();
14170 assert(Ty->isRecordType() && "lvalue was not record?");
14171 SourceRange Range = E->getSourceRange();
14172 const auto *RTy = Ty->getAsCanonical<RecordType>();
14173 bool DiagEmitted = false;
14174
14175 if (const MemberExpr *ME = dyn_cast<MemberExpr>(Val: E))
14176 DiagnoseRecursiveConstFields(S, VD: ME->getMemberDecl(), Ty: RTy, Loc,
14177 Range, OEK: OEK_Member, DiagnosticEmitted&: DiagEmitted);
14178 else if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Val: E))
14179 DiagnoseRecursiveConstFields(S, VD: DRE->getDecl(), Ty: RTy, Loc,
14180 Range, OEK: OEK_Variable, DiagnosticEmitted&: DiagEmitted);
14181 else
14182 DiagnoseRecursiveConstFields(S, VD: nullptr, Ty: RTy, Loc,
14183 Range, OEK: OEK_LValue, DiagnosticEmitted&: DiagEmitted);
14184 if (!DiagEmitted)
14185 DiagnoseConstAssignment(S, E, Loc);
14186}
14187
14188/// CheckForModifiableLvalue - Verify that E is a modifiable lvalue. If not,
14189/// emit an error and return true. If so, return false.
14190static bool CheckForModifiableLvalue(Expr *E, SourceLocation Loc, Sema &S) {
14191 assert(!E->hasPlaceholderType(BuiltinType::PseudoObject));
14192
14193 S.CheckShadowingDeclModification(E, Loc);
14194
14195 SourceLocation OrigLoc = Loc;
14196 Expr::isModifiableLvalueResult IsLV = E->isModifiableLvalue(Ctx&: S.Context,
14197 Loc: &Loc);
14198 if (IsLV == Expr::MLV_ClassTemporary && IsReadonlyMessage(E, S))
14199 IsLV = Expr::MLV_InvalidMessageExpression;
14200 if (IsLV == Expr::MLV_Valid)
14201 return false;
14202
14203 unsigned DiagID = 0;
14204 bool NeedType = false;
14205 switch (IsLV) { // C99 6.5.16p2
14206 case Expr::MLV_ConstQualified:
14207 // Use a specialized diagnostic when we're assigning to an object
14208 // from an enclosing function or block.
14209 if (NonConstCaptureKind NCCK = isReferenceToNonConstCapture(S, E)) {
14210 if (NCCK == NCCK_Block)
14211 DiagID = diag::err_block_decl_ref_not_modifiable_lvalue;
14212 else
14213 DiagID = diag::err_lambda_decl_ref_not_modifiable_lvalue;
14214 break;
14215 }
14216
14217 // In ARC, use some specialized diagnostics for occasions where we
14218 // infer 'const'. These are always pseudo-strong variables.
14219 if (S.getLangOpts().ObjCAutoRefCount) {
14220 DeclRefExpr *declRef = dyn_cast<DeclRefExpr>(Val: E->IgnoreParenCasts());
14221 if (declRef && isa<VarDecl>(Val: declRef->getDecl())) {
14222 VarDecl *var = cast<VarDecl>(Val: declRef->getDecl());
14223
14224 // Use the normal diagnostic if it's pseudo-__strong but the
14225 // user actually wrote 'const'.
14226 if (var->isARCPseudoStrong() &&
14227 (!var->getTypeSourceInfo() ||
14228 !var->getTypeSourceInfo()->getType().isConstQualified())) {
14229 // There are three pseudo-strong cases:
14230 // - self
14231 ObjCMethodDecl *method = S.getCurMethodDecl();
14232 if (method && var == method->getSelfDecl()) {
14233 DiagID = method->isClassMethod()
14234 ? diag::err_typecheck_arc_assign_self_class_method
14235 : diag::err_typecheck_arc_assign_self;
14236
14237 // - Objective-C externally_retained attribute.
14238 } else if (var->hasAttr<ObjCExternallyRetainedAttr>() ||
14239 isa<ParmVarDecl>(Val: var)) {
14240 DiagID = diag::err_typecheck_arc_assign_externally_retained;
14241
14242 // - fast enumeration variables
14243 } else {
14244 DiagID = diag::err_typecheck_arr_assign_enumeration;
14245 }
14246
14247 SourceRange Assign;
14248 if (Loc != OrigLoc)
14249 Assign = SourceRange(OrigLoc, OrigLoc);
14250 S.Diag(Loc, DiagID) << E->getSourceRange() << Assign;
14251 // We need to preserve the AST regardless, so migration tool
14252 // can do its job.
14253 return false;
14254 }
14255 }
14256 }
14257
14258 // If none of the special cases above are triggered, then this is a
14259 // simple const assignment.
14260 if (DiagID == 0) {
14261 DiagnoseConstAssignment(S, E, Loc);
14262 return true;
14263 }
14264
14265 break;
14266 case Expr::MLV_ConstAddrSpace:
14267 DiagnoseConstAssignment(S, E, Loc);
14268 return true;
14269 case Expr::MLV_ConstQualifiedField:
14270 DiagnoseRecursiveConstFields(S, E, Loc);
14271 return true;
14272 case Expr::MLV_ArrayType:
14273 case Expr::MLV_ArrayTemporary:
14274 DiagID = diag::err_typecheck_array_not_modifiable_lvalue;
14275 NeedType = true;
14276 break;
14277 case Expr::MLV_NotObjectType:
14278 DiagID = diag::err_typecheck_non_object_not_modifiable_lvalue;
14279 NeedType = true;
14280 break;
14281 case Expr::MLV_LValueCast:
14282 DiagID = diag::err_typecheck_lvalue_casts_not_supported;
14283 break;
14284 case Expr::MLV_Valid:
14285 llvm_unreachable("did not take early return for MLV_Valid");
14286 case Expr::MLV_InvalidExpression:
14287 case Expr::MLV_MemberFunction:
14288 case Expr::MLV_ClassTemporary:
14289 DiagID = diag::err_typecheck_expression_not_modifiable_lvalue;
14290 break;
14291 case Expr::MLV_IncompleteType:
14292 case Expr::MLV_IncompleteVoidType:
14293 return S.RequireCompleteType(Loc, T: E->getType(),
14294 DiagID: diag::err_typecheck_incomplete_type_not_modifiable_lvalue, Args: E);
14295 case Expr::MLV_DuplicateVectorComponents:
14296 DiagID = diag::err_typecheck_duplicate_vector_components_not_mlvalue;
14297 break;
14298 case Expr::MLV_DuplicateMatrixComponents:
14299 DiagID = diag::err_typecheck_duplicate_matrix_components_not_mlvalue;
14300 break;
14301 case Expr::MLV_NoSetterProperty:
14302 llvm_unreachable("readonly properties should be processed differently");
14303 case Expr::MLV_InvalidMessageExpression:
14304 DiagID = diag::err_readonly_message_assignment;
14305 break;
14306 case Expr::MLV_SubObjCPropertySetting:
14307 DiagID = diag::err_no_subobject_property_setting;
14308 break;
14309 }
14310
14311 SourceRange Assign;
14312 if (Loc != OrigLoc)
14313 Assign = SourceRange(OrigLoc, OrigLoc);
14314 if (NeedType)
14315 S.Diag(Loc, DiagID) << E->getType() << E->getSourceRange() << Assign;
14316 else
14317 S.Diag(Loc, DiagID) << E->getSourceRange() << Assign;
14318 return true;
14319}
14320
14321static void CheckIdentityFieldAssignment(Expr *LHSExpr, Expr *RHSExpr,
14322 SourceLocation Loc,
14323 Sema &Sema) {
14324 if (Sema.inTemplateInstantiation())
14325 return;
14326 if (Sema.isUnevaluatedContext())
14327 return;
14328 if (Loc.isInvalid() || Loc.isMacroID())
14329 return;
14330 if (LHSExpr->getExprLoc().isMacroID() || RHSExpr->getExprLoc().isMacroID())
14331 return;
14332
14333 // C / C++ fields
14334 MemberExpr *ML = dyn_cast<MemberExpr>(Val: LHSExpr);
14335 MemberExpr *MR = dyn_cast<MemberExpr>(Val: RHSExpr);
14336 if (ML && MR) {
14337 if (!(isa<CXXThisExpr>(Val: ML->getBase()) && isa<CXXThisExpr>(Val: MR->getBase())))
14338 return;
14339 const ValueDecl *LHSDecl =
14340 cast<ValueDecl>(Val: ML->getMemberDecl()->getCanonicalDecl());
14341 const ValueDecl *RHSDecl =
14342 cast<ValueDecl>(Val: MR->getMemberDecl()->getCanonicalDecl());
14343 if (LHSDecl != RHSDecl)
14344 return;
14345 if (LHSDecl->getType().isVolatileQualified())
14346 return;
14347 if (const ReferenceType *RefTy = LHSDecl->getType()->getAs<ReferenceType>())
14348 if (RefTy->getPointeeType().isVolatileQualified())
14349 return;
14350
14351 Sema.Diag(Loc, DiagID: diag::warn_identity_field_assign) << 0;
14352 }
14353
14354 // Objective-C instance variables
14355 ObjCIvarRefExpr *OL = dyn_cast<ObjCIvarRefExpr>(Val: LHSExpr);
14356 ObjCIvarRefExpr *OR = dyn_cast<ObjCIvarRefExpr>(Val: RHSExpr);
14357 if (OL && OR && OL->getDecl() == OR->getDecl()) {
14358 DeclRefExpr *RL = dyn_cast<DeclRefExpr>(Val: OL->getBase()->IgnoreImpCasts());
14359 DeclRefExpr *RR = dyn_cast<DeclRefExpr>(Val: OR->getBase()->IgnoreImpCasts());
14360 if (RL && RR && RL->getDecl() == RR->getDecl())
14361 Sema.Diag(Loc, DiagID: diag::warn_identity_field_assign) << 1;
14362 }
14363}
14364
14365// C99 6.5.16.1
14366QualType Sema::CheckAssignmentOperands(Expr *LHSExpr, ExprResult &RHS,
14367 SourceLocation Loc,
14368 QualType CompoundType,
14369 BinaryOperatorKind Opc) {
14370 assert(!LHSExpr->hasPlaceholderType(BuiltinType::PseudoObject));
14371
14372 // Verify that LHS is a modifiable lvalue, and emit error if not.
14373 if (CheckForModifiableLvalue(E: LHSExpr, Loc, S&: *this))
14374 return QualType();
14375
14376 QualType LHSType = LHSExpr->getType();
14377 QualType RHSType = CompoundType.isNull() ? RHS.get()->getType() :
14378 CompoundType;
14379
14380 if (RHS.isUsable()) {
14381 // Even if this check fails don't return early to allow the best
14382 // possible error recovery and to allow any subsequent diagnostics to
14383 // work.
14384 const ValueDecl *Assignee = nullptr;
14385 bool ShowFullyQualifiedAssigneeName = false;
14386 // In simple cases describe what is being assigned to
14387 if (auto *DR = dyn_cast<DeclRefExpr>(Val: LHSExpr->IgnoreParenCasts())) {
14388 Assignee = DR->getDecl();
14389 } else if (auto *ME = dyn_cast<MemberExpr>(Val: LHSExpr->IgnoreParenCasts())) {
14390 Assignee = ME->getMemberDecl();
14391 ShowFullyQualifiedAssigneeName = true;
14392 }
14393
14394 BoundsSafetyCheckAssignmentToCountAttrPtr(
14395 LHSTy: LHSType, RHSExpr: RHS.get(), Action: AssignmentAction::Assigning, Loc, Assignee,
14396 ShowFullyQualifiedAssigneeName);
14397 }
14398
14399 // OpenCL v1.2 s6.1.1.1 p2:
14400 // The half data type can only be used to declare a pointer to a buffer that
14401 // contains half values
14402 if (getLangOpts().OpenCL &&
14403 !getOpenCLOptions().isAvailableOption(Ext: "cl_khr_fp16", LO: getLangOpts()) &&
14404 LHSType->isHalfType()) {
14405 Diag(Loc, DiagID: diag::err_opencl_half_load_store) << 1
14406 << LHSType.getUnqualifiedType();
14407 return QualType();
14408 }
14409
14410 // WebAssembly tables can't be used on RHS of an assignment expression.
14411 if (RHSType->isWebAssemblyTableType()) {
14412 Diag(Loc, DiagID: diag::err_wasm_table_art) << 0;
14413 return QualType();
14414 }
14415
14416 AssignConvertType ConvTy;
14417 if (CompoundType.isNull()) {
14418 Expr *RHSCheck = RHS.get();
14419
14420 CheckIdentityFieldAssignment(LHSExpr, RHSExpr: RHSCheck, Loc, Sema&: *this);
14421
14422 QualType LHSTy(LHSType);
14423 ConvTy = CheckSingleAssignmentConstraints(LHSType: LHSTy, CallerRHS&: RHS);
14424 if (RHS.isInvalid())
14425 return QualType();
14426 // Special case of NSObject attributes on c-style pointer types.
14427 if (ConvTy == AssignConvertType::IncompatiblePointer &&
14428 ((Context.isObjCNSObjectType(Ty: LHSType) &&
14429 RHSType->isObjCObjectPointerType()) ||
14430 (Context.isObjCNSObjectType(Ty: RHSType) &&
14431 LHSType->isObjCObjectPointerType())))
14432 ConvTy = AssignConvertType::Compatible;
14433
14434 if (IsAssignConvertCompatible(ConvTy) && LHSType->isObjCObjectType())
14435 Diag(Loc, DiagID: diag::err_objc_object_assignment) << LHSType;
14436
14437 // If the RHS is a unary plus or minus, check to see if they = and + are
14438 // right next to each other. If so, the user may have typo'd "x =+ 4"
14439 // instead of "x += 4".
14440 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Val: RHSCheck))
14441 RHSCheck = ICE->getSubExpr();
14442 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(Val: RHSCheck)) {
14443 if ((UO->getOpcode() == UO_Plus || UO->getOpcode() == UO_Minus) &&
14444 Loc.isFileID() && UO->getOperatorLoc().isFileID() &&
14445 // Only if the two operators are exactly adjacent.
14446 Loc.getLocWithOffset(Offset: 1) == UO->getOperatorLoc() &&
14447 // And there is a space or other character before the subexpr of the
14448 // unary +/-. We don't want to warn on "x=-1".
14449 Loc.getLocWithOffset(Offset: 2) != UO->getSubExpr()->getBeginLoc() &&
14450 UO->getSubExpr()->getBeginLoc().isFileID()) {
14451 Diag(Loc, DiagID: diag::warn_not_compound_assign)
14452 << (UO->getOpcode() == UO_Plus ? "+" : "-")
14453 << SourceRange(UO->getOperatorLoc(), UO->getOperatorLoc());
14454 }
14455 }
14456
14457 if (IsAssignConvertCompatible(ConvTy)) {
14458 if (LHSType.getObjCLifetime() == Qualifiers::OCL_Strong) {
14459 // Warn about retain cycles where a block captures the LHS, but
14460 // not if the LHS is a simple variable into which the block is
14461 // being stored...unless that variable can be captured by reference!
14462 const Expr *InnerLHS = LHSExpr->IgnoreParenCasts();
14463 const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Val: InnerLHS);
14464 if (!DRE || DRE->getDecl()->hasAttr<BlocksAttr>())
14465 ObjC().checkRetainCycles(receiver: LHSExpr, argument: RHS.get());
14466 }
14467
14468 if (LHSType.getObjCLifetime() == Qualifiers::OCL_Strong ||
14469 LHSType.isNonWeakInMRRWithObjCWeak(Context)) {
14470 // It is safe to assign a weak reference into a strong variable.
14471 // Although this code can still have problems:
14472 // id x = self.weakProp;
14473 // id y = self.weakProp;
14474 // we do not warn to warn spuriously when 'x' and 'y' are on separate
14475 // paths through the function. This should be revisited if
14476 // -Wrepeated-use-of-weak is made flow-sensitive.
14477 // For ObjCWeak only, we do not warn if the assign is to a non-weak
14478 // variable, which will be valid for the current autorelease scope.
14479 if (!Diags.isIgnored(DiagID: diag::warn_arc_repeated_use_of_weak,
14480 Loc: RHS.get()->getBeginLoc()))
14481 getCurFunction()->markSafeWeakUse(E: RHS.get());
14482
14483 } else if (getLangOpts().ObjCAutoRefCount || getLangOpts().ObjCWeak) {
14484 checkUnsafeExprAssigns(Loc, LHS: LHSExpr, RHS: RHS.get());
14485 }
14486 }
14487 } else {
14488 // Compound assignment "x += y"
14489 ConvTy = CheckAssignmentConstraints(Loc, LHSType, RHSType);
14490 }
14491
14492 if (DiagnoseAssignmentResult(ConvTy, Loc, DstType: LHSType, SrcType: RHSType, SrcExpr: RHS.get(),
14493 Action: AssignmentAction::Assigning))
14494 return QualType();
14495
14496 CheckForNullPointerDereference(S&: *this, E: LHSExpr);
14497
14498 AssignedEntity AE{.LHS: LHSExpr};
14499 checkAssignmentLifetime(SemaRef&: *this, Entity: AE, Init: RHS.get());
14500
14501 if (getLangOpts().CPlusPlus20 && LHSType.isVolatileQualified()) {
14502 if (CompoundType.isNull()) {
14503 // C++2a [expr.ass]p5:
14504 // A simple-assignment whose left operand is of a volatile-qualified
14505 // type is deprecated unless the assignment is either a discarded-value
14506 // expression or an unevaluated operand
14507 ExprEvalContexts.back().VolatileAssignmentLHSs.push_back(Elt: LHSExpr);
14508 }
14509 }
14510
14511 // C11 6.5.16p3: The type of an assignment expression is the type of the
14512 // left operand would have after lvalue conversion.
14513 // C11 6.3.2.1p2: ...this is called lvalue conversion. If the lvalue has
14514 // qualified type, the value has the unqualified version of the type of the
14515 // lvalue; additionally, if the lvalue has atomic type, the value has the
14516 // non-atomic version of the type of the lvalue.
14517 // C++ 5.17p1: the type of the assignment expression is that of its left
14518 // operand.
14519 return getLangOpts().CPlusPlus ? LHSType : LHSType.getAtomicUnqualifiedType();
14520}
14521
14522// Scenarios to ignore if expression E is:
14523// 1. an explicit cast expression into void
14524// 2. a function call expression that returns void
14525static bool IgnoreCommaOperand(const Expr *E, const ASTContext &Context) {
14526 E = E->IgnoreParens();
14527
14528 if (const CastExpr *CE = dyn_cast<CastExpr>(Val: E)) {
14529 if (CE->getCastKind() == CK_ToVoid) {
14530 return true;
14531 }
14532
14533 // static_cast<void> on a dependent type will not show up as CK_ToVoid.
14534 if (CE->getCastKind() == CK_Dependent && E->getType()->isVoidType() &&
14535 CE->getSubExpr()->getType()->isDependentType()) {
14536 return true;
14537 }
14538 }
14539
14540 if (const auto *CE = dyn_cast<CallExpr>(Val: E))
14541 return CE->getCallReturnType(Ctx: Context)->isVoidType();
14542 return false;
14543}
14544
14545void Sema::DiagnoseCommaOperator(const Expr *LHS, SourceLocation Loc) {
14546 // No warnings in macros
14547 if (Loc.isMacroID())
14548 return;
14549
14550 // Don't warn in template instantiations.
14551 if (inTemplateInstantiation())
14552 return;
14553
14554 // Scope isn't fine-grained enough to explicitly list the specific cases, so
14555 // instead, skip more than needed, then call back into here with the
14556 // CommaVisitor in SemaStmt.cpp.
14557 // The listed locations are the initialization and increment portions
14558 // of a for loop. The additional checks are on the condition of
14559 // if statements, do/while loops, and for loops.
14560 // Differences in scope flags for C89 mode requires the extra logic.
14561 const unsigned ForIncrementFlags =
14562 getLangOpts().C99 || getLangOpts().CPlusPlus
14563 ? Scope::ControlScope | Scope::ContinueScope | Scope::BreakScope
14564 : Scope::ContinueScope | Scope::BreakScope;
14565 const unsigned ForInitFlags = Scope::ControlScope | Scope::DeclScope;
14566 const unsigned ScopeFlags = getCurScope()->getFlags();
14567 if ((ScopeFlags & ForIncrementFlags) == ForIncrementFlags ||
14568 (ScopeFlags & ForInitFlags) == ForInitFlags)
14569 return;
14570
14571 // If there are multiple comma operators used together, get the RHS of the
14572 // of the comma operator as the LHS.
14573 while (const BinaryOperator *BO = dyn_cast<BinaryOperator>(Val: LHS)) {
14574 if (BO->getOpcode() != BO_Comma)
14575 break;
14576 LHS = BO->getRHS();
14577 }
14578
14579 // Only allow some expressions on LHS to not warn.
14580 if (IgnoreCommaOperand(E: LHS, Context))
14581 return;
14582
14583 Diag(Loc, DiagID: diag::warn_comma_operator);
14584 Diag(Loc: LHS->getBeginLoc(), DiagID: diag::note_cast_to_void)
14585 << LHS->getSourceRange()
14586 << FixItHint::CreateInsertion(InsertionLoc: LHS->getBeginLoc(),
14587 Code: LangOpts.CPlusPlus ? "static_cast<void>("
14588 : "(void)(")
14589 << FixItHint::CreateInsertion(InsertionLoc: PP.getLocForEndOfToken(Loc: LHS->getEndLoc()),
14590 Code: ")");
14591}
14592
14593// C99 6.5.17
14594static QualType CheckCommaOperands(Sema &S, ExprResult &LHS, ExprResult &RHS,
14595 SourceLocation Loc) {
14596 LHS = S.CheckPlaceholderExpr(E: LHS.get());
14597 RHS = S.CheckPlaceholderExpr(E: RHS.get());
14598 if (LHS.isInvalid() || RHS.isInvalid())
14599 return QualType();
14600
14601 // C's comma performs lvalue conversion (C99 6.3.2.1) on both its
14602 // operands, but not unary promotions.
14603 // C++'s comma does not do any conversions at all (C++ [expr.comma]p1).
14604
14605 // So we treat the LHS as a ignored value, and in C++ we allow the
14606 // containing site to determine what should be done with the RHS.
14607 LHS = S.IgnoredValueConversions(E: LHS.get());
14608 if (LHS.isInvalid())
14609 return QualType();
14610
14611 S.DiagnoseUnusedExprResult(S: LHS.get(), DiagID: diag::warn_unused_comma_left_operand);
14612
14613 if (!S.getLangOpts().CPlusPlus) {
14614 RHS = S.DefaultFunctionArrayLvalueConversion(E: RHS.get());
14615 if (RHS.isInvalid())
14616 return QualType();
14617 if (!RHS.get()->getType()->isVoidType())
14618 S.RequireCompleteType(Loc, T: RHS.get()->getType(),
14619 DiagID: diag::err_incomplete_type);
14620 }
14621
14622 if (!S.getDiagnostics().isIgnored(DiagID: diag::warn_comma_operator, Loc))
14623 S.DiagnoseCommaOperator(LHS: LHS.get(), Loc);
14624
14625 return RHS.get()->getType();
14626}
14627
14628/// CheckIncrementDecrementOperand - unlike most "Check" methods, this routine
14629/// doesn't need to call UsualUnaryConversions or UsualArithmeticConversions.
14630static QualType CheckIncrementDecrementOperand(Sema &S, Expr *Op,
14631 ExprValueKind &VK,
14632 ExprObjectKind &OK,
14633 SourceLocation OpLoc, bool IsInc,
14634 bool IsPrefix) {
14635 QualType ResType = Op->getType();
14636 // Atomic types can be used for increment / decrement where the non-atomic
14637 // versions can, so ignore the _Atomic() specifier for the purpose of
14638 // checking.
14639 if (const AtomicType *ResAtomicType = ResType->getAs<AtomicType>())
14640 ResType = ResAtomicType->getValueType();
14641
14642 assert(!ResType.isNull() && "no type for increment/decrement expression");
14643
14644 if (S.getLangOpts().CPlusPlus && ResType->isBooleanType()) {
14645 // Decrement of bool is not allowed.
14646 if (!IsInc) {
14647 S.Diag(Loc: OpLoc, DiagID: diag::err_decrement_bool) << Op->getSourceRange();
14648 return QualType();
14649 }
14650 // Increment of bool sets it to true, but is deprecated.
14651 S.Diag(Loc: OpLoc, DiagID: S.getLangOpts().CPlusPlus17 ? diag::ext_increment_bool
14652 : diag::warn_increment_bool)
14653 << Op->getSourceRange();
14654 } else if (S.getLangOpts().CPlusPlus && ResType->isEnumeralType()) {
14655 // Error on enum increments and decrements in C++ mode
14656 S.Diag(Loc: OpLoc, DiagID: diag::err_increment_decrement_enum) << IsInc << ResType;
14657 return QualType();
14658 } else if (ResType->isRealType()) {
14659 // OK!
14660 } else if (ResType->isPointerType()) {
14661 // C99 6.5.2.4p2, 6.5.6p2
14662 if (!checkArithmeticOpPointerOperand(S, Loc: OpLoc, Operand: Op))
14663 return QualType();
14664 } else if (ResType->isOverflowBehaviorType()) {
14665 // OK!
14666 } else if (ResType->isObjCObjectPointerType()) {
14667 // On modern runtimes, ObjC pointer arithmetic is forbidden.
14668 // Otherwise, we just need a complete type.
14669 if (checkArithmeticIncompletePointerType(S, Loc: OpLoc, Operand: Op) ||
14670 checkArithmeticOnObjCPointer(S, opLoc: OpLoc, op: Op))
14671 return QualType();
14672 } else if (ResType->isAnyComplexType()) {
14673 // C99 does not support ++/-- on complex types, we allow as an extension.
14674 S.Diag(Loc: OpLoc, DiagID: S.getLangOpts().C2y ? diag::warn_c2y_compat_increment_complex
14675 : diag::ext_c2y_increment_complex)
14676 << IsInc << Op->getSourceRange();
14677 } else if (ResType->isPlaceholderType()) {
14678 ExprResult PR = S.CheckPlaceholderExpr(E: Op);
14679 if (PR.isInvalid()) return QualType();
14680 return CheckIncrementDecrementOperand(S, Op: PR.get(), VK, OK, OpLoc,
14681 IsInc, IsPrefix);
14682 } else if (S.getLangOpts().AltiVec && ResType->isVectorType()) {
14683 // OK! ( C/C++ Language Extensions for CBEA(Version 2.6) 10.3 )
14684 } else if (S.getLangOpts().ZVector && ResType->isVectorType() &&
14685 (ResType->castAs<VectorType>()->getVectorKind() !=
14686 VectorKind::AltiVecBool)) {
14687 // The z vector extensions allow ++ and -- for non-bool vectors.
14688 } else if (S.getLangOpts().OpenCL && ResType->isVectorType() &&
14689 ResType->castAs<VectorType>()->getElementType()->isIntegerType()) {
14690 // OpenCL V1.2 6.3 says dec/inc ops operate on integer vector types.
14691 } else {
14692 S.Diag(Loc: OpLoc, DiagID: diag::err_typecheck_illegal_increment_decrement)
14693 << ResType << int(IsInc) << Op->getSourceRange();
14694 return QualType();
14695 }
14696 // At this point, we know we have a real, complex or pointer type.
14697 // Now make sure the operand is a modifiable lvalue.
14698 if (CheckForModifiableLvalue(E: Op, Loc: OpLoc, S))
14699 return QualType();
14700 if (S.getLangOpts().CPlusPlus20 && ResType.isVolatileQualified()) {
14701 // C++2a [expr.pre.inc]p1, [expr.post.inc]p1:
14702 // An operand with volatile-qualified type is deprecated
14703 S.Diag(Loc: OpLoc, DiagID: diag::warn_deprecated_increment_decrement_volatile)
14704 << IsInc << ResType;
14705 }
14706 // In C++, a prefix increment is the same type as the operand. Otherwise
14707 // (in C or with postfix), the increment is the unqualified type of the
14708 // operand.
14709 if (IsPrefix && S.getLangOpts().CPlusPlus) {
14710 VK = VK_LValue;
14711 OK = Op->getObjectKind();
14712 return ResType;
14713 } else {
14714 VK = VK_PRValue;
14715 return ResType.getUnqualifiedType();
14716 }
14717}
14718
14719/// getPrimaryDecl - Helper function for CheckAddressOfOperand().
14720/// This routine allows us to typecheck complex/recursive expressions
14721/// where the declaration is needed for type checking. We only need to
14722/// handle cases when the expression references a function designator
14723/// or is an lvalue. Here are some examples:
14724/// - &(x) => x
14725/// - &*****f => f for f a function designator.
14726/// - &s.xx => s
14727/// - &s.zz[1].yy -> s, if zz is an array
14728/// - *(x + 1) -> x, if x is an array
14729/// - &"123"[2] -> 0
14730/// - & __real__ x -> x
14731///
14732/// FIXME: We don't recurse to the RHS of a comma, nor handle pointers to
14733/// members.
14734static ValueDecl *getPrimaryDecl(Expr *E) {
14735 switch (E->getStmtClass()) {
14736 case Stmt::DeclRefExprClass:
14737 return cast<DeclRefExpr>(Val: E)->getDecl();
14738 case Stmt::MemberExprClass:
14739 // If this is an arrow operator, the address is an offset from
14740 // the base's value, so the object the base refers to is
14741 // irrelevant.
14742 if (cast<MemberExpr>(Val: E)->isArrow())
14743 return nullptr;
14744 // Otherwise, the expression refers to a part of the base
14745 return getPrimaryDecl(E: cast<MemberExpr>(Val: E)->getBase());
14746 case Stmt::ArraySubscriptExprClass: {
14747 // FIXME: This code shouldn't be necessary! We should catch the implicit
14748 // promotion of register arrays earlier.
14749 Expr* Base = cast<ArraySubscriptExpr>(Val: E)->getBase();
14750 if (ImplicitCastExpr* ICE = dyn_cast<ImplicitCastExpr>(Val: Base)) {
14751 if (ICE->getSubExpr()->getType()->isArrayType())
14752 return getPrimaryDecl(E: ICE->getSubExpr());
14753 }
14754 return nullptr;
14755 }
14756 case Stmt::UnaryOperatorClass: {
14757 UnaryOperator *UO = cast<UnaryOperator>(Val: E);
14758
14759 switch(UO->getOpcode()) {
14760 case UO_Real:
14761 case UO_Imag:
14762 case UO_Extension:
14763 return getPrimaryDecl(E: UO->getSubExpr());
14764 default:
14765 return nullptr;
14766 }
14767 }
14768 case Stmt::ParenExprClass:
14769 return getPrimaryDecl(E: cast<ParenExpr>(Val: E)->getSubExpr());
14770 case Stmt::ImplicitCastExprClass:
14771 // If the result of an implicit cast is an l-value, we care about
14772 // the sub-expression; otherwise, the result here doesn't matter.
14773 return getPrimaryDecl(E: cast<ImplicitCastExpr>(Val: E)->getSubExpr());
14774 case Stmt::CXXUuidofExprClass:
14775 return cast<CXXUuidofExpr>(Val: E)->getGuidDecl();
14776 default:
14777 return nullptr;
14778 }
14779}
14780
14781namespace {
14782enum {
14783 AO_Bit_Field = 0,
14784 AO_Vector_Element = 1,
14785 AO_Property_Expansion = 2,
14786 AO_Register_Variable = 3,
14787 AO_Matrix_Element = 4,
14788 AO_No_Error = 5
14789};
14790}
14791/// Diagnose invalid operand for address of operations.
14792///
14793/// \param Type The type of operand which cannot have its address taken.
14794static void diagnoseAddressOfInvalidType(Sema &S, SourceLocation Loc,
14795 Expr *E, unsigned Type) {
14796 S.Diag(Loc, DiagID: diag::err_typecheck_address_of) << Type << E->getSourceRange();
14797}
14798
14799bool Sema::CheckUseOfCXXMethodAsAddressOfOperand(SourceLocation OpLoc,
14800 const Expr *Op,
14801 const CXXMethodDecl *MD) {
14802 const auto *DRE = cast<DeclRefExpr>(Val: Op->IgnoreParens());
14803
14804 if (Op != DRE)
14805 return Diag(Loc: OpLoc, DiagID: diag::err_parens_pointer_member_function)
14806 << Op->getSourceRange();
14807
14808 // Taking the address of a dtor is illegal per C++ [class.dtor]p2.
14809 if (isa<CXXDestructorDecl>(Val: MD))
14810 return Diag(Loc: OpLoc, DiagID: diag::err_typecheck_addrof_dtor)
14811 << DRE->getSourceRange();
14812
14813 if (DRE->getQualifier())
14814 return false;
14815
14816 if (MD->getParent()->getName().empty())
14817 return Diag(Loc: OpLoc, DiagID: diag::err_unqualified_pointer_member_function)
14818 << DRE->getSourceRange();
14819
14820 SmallString<32> Str;
14821 StringRef Qual = (MD->getParent()->getName() + "::").toStringRef(Out&: Str);
14822 return Diag(Loc: OpLoc, DiagID: diag::err_unqualified_pointer_member_function)
14823 << DRE->getSourceRange()
14824 << FixItHint::CreateInsertion(InsertionLoc: DRE->getSourceRange().getBegin(), Code: Qual);
14825}
14826
14827QualType Sema::CheckAddressOfOperand(ExprResult &OrigOp, SourceLocation OpLoc) {
14828 if (const BuiltinType *PTy = OrigOp.get()->getType()->getAsPlaceholderType()){
14829 if (PTy->getKind() == BuiltinType::Overload) {
14830 Expr *E = OrigOp.get()->IgnoreParens();
14831 if (!isa<OverloadExpr>(Val: E)) {
14832 assert(cast<UnaryOperator>(E)->getOpcode() == UO_AddrOf);
14833 Diag(Loc: OpLoc, DiagID: diag::err_typecheck_invalid_lvalue_addrof_addrof_function)
14834 << OrigOp.get()->getSourceRange();
14835 return QualType();
14836 }
14837
14838 OverloadExpr *Ovl = cast<OverloadExpr>(Val: E);
14839 if (isa<UnresolvedMemberExpr>(Val: Ovl))
14840 if (!ResolveSingleFunctionTemplateSpecialization(ovl: Ovl)) {
14841 Diag(Loc: OpLoc, DiagID: diag::err_invalid_form_pointer_member_function)
14842 << OrigOp.get()->getSourceRange();
14843 return QualType();
14844 }
14845
14846 return Context.OverloadTy;
14847 }
14848
14849 if (PTy->getKind() == BuiltinType::UnknownAny)
14850 return Context.UnknownAnyTy;
14851
14852 if (PTy->getKind() == BuiltinType::BoundMember) {
14853 Diag(Loc: OpLoc, DiagID: diag::err_invalid_form_pointer_member_function)
14854 << OrigOp.get()->getSourceRange();
14855 return QualType();
14856 }
14857
14858 OrigOp = CheckPlaceholderExpr(E: OrigOp.get());
14859 if (OrigOp.isInvalid()) return QualType();
14860 }
14861
14862 if (OrigOp.get()->isTypeDependent())
14863 return Context.DependentTy;
14864
14865 assert(!OrigOp.get()->hasPlaceholderType());
14866
14867 // Make sure to ignore parentheses in subsequent checks
14868 Expr *op = OrigOp.get()->IgnoreParens();
14869
14870 // In OpenCL captures for blocks called as lambda functions
14871 // are located in the private address space. Blocks used in
14872 // enqueue_kernel can be located in a different address space
14873 // depending on a vendor implementation. Thus preventing
14874 // taking an address of the capture to avoid invalid AS casts.
14875 if (LangOpts.OpenCL) {
14876 auto* VarRef = dyn_cast<DeclRefExpr>(Val: op);
14877 if (VarRef && VarRef->refersToEnclosingVariableOrCapture()) {
14878 Diag(Loc: op->getExprLoc(), DiagID: diag::err_opencl_taking_address_capture);
14879 return QualType();
14880 }
14881 }
14882
14883 if (getLangOpts().C99) {
14884 // Implement C99-only parts of addressof rules.
14885 if (UnaryOperator* uOp = dyn_cast<UnaryOperator>(Val: op)) {
14886 if (uOp->getOpcode() == UO_Deref)
14887 // Per C99 6.5.3.2, the address of a deref always returns a valid result
14888 // (assuming the deref expression is valid).
14889 return uOp->getSubExpr()->getType();
14890 }
14891 // Technically, there should be a check for array subscript
14892 // expressions here, but the result of one is always an lvalue anyway.
14893 }
14894 ValueDecl *dcl = getPrimaryDecl(E: op);
14895
14896 if (auto *FD = dyn_cast_or_null<FunctionDecl>(Val: dcl))
14897 if (!checkAddressOfFunctionIsAvailable(Function: FD, /*Complain=*/true,
14898 Loc: op->getBeginLoc()))
14899 return QualType();
14900
14901 Expr::LValueClassification lval = op->ClassifyLValue(Ctx&: Context);
14902 unsigned AddressOfError = AO_No_Error;
14903
14904 if (lval == Expr::LV_ClassTemporary || lval == Expr::LV_ArrayTemporary) {
14905 bool IsError = isSFINAEContext();
14906 Diag(Loc: OpLoc, DiagID: IsError ? diag::err_typecheck_addrof_temporary
14907 : diag::ext_typecheck_addrof_temporary)
14908 << op->getType() << op->getSourceRange();
14909 if (IsError)
14910 return QualType();
14911 // Materialize the temporary as an lvalue so that we can take its address.
14912 OrigOp = op =
14913 CreateMaterializeTemporaryExpr(T: op->getType(), Temporary: OrigOp.get(), BoundToLvalueReference: true);
14914 } else if (isa<ObjCSelectorExpr>(Val: op)) {
14915 return Context.getPointerType(T: op->getType());
14916 } else if (lval == Expr::LV_MemberFunction) {
14917 // If it's an instance method, make a member pointer.
14918 // The expression must have exactly the form &A::foo.
14919
14920 // If the underlying expression isn't a decl ref, give up.
14921 if (!isa<DeclRefExpr>(Val: op)) {
14922 Diag(Loc: OpLoc, DiagID: diag::err_invalid_form_pointer_member_function)
14923 << OrigOp.get()->getSourceRange();
14924 return QualType();
14925 }
14926 DeclRefExpr *DRE = cast<DeclRefExpr>(Val: op);
14927 CXXMethodDecl *MD = cast<CXXMethodDecl>(Val: DRE->getDecl());
14928
14929 CheckUseOfCXXMethodAsAddressOfOperand(OpLoc, Op: OrigOp.get(), MD);
14930 QualType MPTy = Context.getMemberPointerType(
14931 T: op->getType(), Qualifier: DRE->getQualifier(), Cls: MD->getParent());
14932
14933 if (getLangOpts().PointerAuthCalls && MD->isVirtual() &&
14934 !isUnevaluatedContext() && !MPTy->isDependentType()) {
14935 // When pointer authentication is enabled, argument and return types of
14936 // vitual member functions must be complete. This is because vitrual
14937 // member function pointers are implemented using virtual dispatch
14938 // thunks and the thunks cannot be emitted if the argument or return
14939 // types are incomplete.
14940 auto ReturnOrParamTypeIsIncomplete = [&](QualType T,
14941 SourceLocation DeclRefLoc,
14942 SourceLocation RetArgTypeLoc) {
14943 if (RequireCompleteType(Loc: DeclRefLoc, T, DiagID: diag::err_incomplete_type)) {
14944 Diag(Loc: DeclRefLoc,
14945 DiagID: diag::note_ptrauth_virtual_function_pointer_incomplete_arg_ret);
14946 Diag(Loc: RetArgTypeLoc,
14947 DiagID: diag::note_ptrauth_virtual_function_incomplete_arg_ret_type)
14948 << T;
14949 return true;
14950 }
14951 return false;
14952 };
14953 QualType RetTy = MD->getReturnType();
14954 bool IsIncomplete =
14955 !RetTy->isVoidType() &&
14956 ReturnOrParamTypeIsIncomplete(
14957 RetTy, OpLoc, MD->getReturnTypeSourceRange().getBegin());
14958 for (auto *PVD : MD->parameters())
14959 IsIncomplete |= ReturnOrParamTypeIsIncomplete(PVD->getType(), OpLoc,
14960 PVD->getBeginLoc());
14961 if (IsIncomplete)
14962 return QualType();
14963 }
14964
14965 // Under the MS ABI, lock down the inheritance model now.
14966 if (Context.getTargetInfo().getCXXABI().isMicrosoft())
14967 (void)isCompleteType(Loc: OpLoc, T: MPTy);
14968 return MPTy;
14969 } else if (lval != Expr::LV_Valid && lval != Expr::LV_IncompleteVoidType) {
14970 // C99 6.5.3.2p1
14971 // The operand must be either an l-value or a function designator
14972 if (!op->getType()->isFunctionType()) {
14973 // Use a special diagnostic for loads from property references.
14974 if (isa<PseudoObjectExpr>(Val: op)) {
14975 AddressOfError = AO_Property_Expansion;
14976 } else {
14977 Diag(Loc: OpLoc, DiagID: diag::err_typecheck_invalid_lvalue_addrof)
14978 << op->getType() << op->getSourceRange();
14979 return QualType();
14980 }
14981 } else if (const auto *DRE = dyn_cast<DeclRefExpr>(Val: op)) {
14982 if (const auto *MD = dyn_cast_or_null<CXXMethodDecl>(Val: DRE->getDecl()))
14983 CheckUseOfCXXMethodAsAddressOfOperand(OpLoc, Op: OrigOp.get(), MD);
14984 }
14985
14986 } else if (op->getObjectKind() == OK_BitField) { // C99 6.5.3.2p1
14987 // The operand cannot be a bit-field
14988 AddressOfError = AO_Bit_Field;
14989 } else if (op->getObjectKind() == OK_VectorComponent) {
14990 // The operand cannot be an element of a vector
14991 AddressOfError = AO_Vector_Element;
14992 } else if (op->getObjectKind() == OK_MatrixComponent) {
14993 // The operand cannot be an element of a matrix.
14994 AddressOfError = AO_Matrix_Element;
14995 } else if (dcl) { // C99 6.5.3.2p1
14996 // We have an lvalue with a decl. Make sure the decl is not declared
14997 // with the register storage-class specifier.
14998 if (const VarDecl *vd = dyn_cast<VarDecl>(Val: dcl)) {
14999 // in C++ it is not error to take address of a register
15000 // variable (c++03 7.1.1P3)
15001 if (vd->getStorageClass() == SC_Register &&
15002 !getLangOpts().CPlusPlus) {
15003 AddressOfError = AO_Register_Variable;
15004 }
15005 } else if (isa<MSPropertyDecl>(Val: dcl)) {
15006 AddressOfError = AO_Property_Expansion;
15007 } else if (isa<FunctionTemplateDecl>(Val: dcl)) {
15008 return Context.OverloadTy;
15009 } else if (isa<FieldDecl>(Val: dcl) || isa<IndirectFieldDecl>(Val: dcl)) {
15010 // Okay: we can take the address of a field.
15011 // Could be a pointer to member, though, if there is an explicit
15012 // scope qualifier for the class.
15013
15014 // [C++26] [expr.prim.id.general]
15015 // If an id-expression E denotes a non-static non-type member
15016 // of some class C [...] and if E is a qualified-id, E is
15017 // not the un-parenthesized operand of the unary & operator [...]
15018 // the id-expression is transformed into a class member access expression.
15019 if (auto *DRE = dyn_cast<DeclRefExpr>(Val: op);
15020 DRE && DRE->getQualifier() && !isa<ParenExpr>(Val: OrigOp.get())) {
15021 DeclContext *Ctx = dcl->getDeclContext();
15022 if (Ctx && Ctx->isRecord()) {
15023 if (dcl->getType()->isReferenceType()) {
15024 Diag(Loc: OpLoc,
15025 DiagID: diag::err_cannot_form_pointer_to_member_of_reference_type)
15026 << dcl->getDeclName() << dcl->getType();
15027 return QualType();
15028 }
15029
15030 while (cast<RecordDecl>(Val: Ctx)->isAnonymousStructOrUnion())
15031 Ctx = Ctx->getParent();
15032
15033 QualType MPTy = Context.getMemberPointerType(
15034 T: op->getType(), Qualifier: DRE->getQualifier(), Cls: cast<CXXRecordDecl>(Val: Ctx));
15035 // Under the MS ABI, lock down the inheritance model now.
15036 if (Context.getTargetInfo().getCXXABI().isMicrosoft())
15037 (void)isCompleteType(Loc: OpLoc, T: MPTy);
15038 return MPTy;
15039 }
15040 }
15041 } else if (!isa<FunctionDecl, TemplateParamObjectDecl,
15042 NonTypeTemplateParmDecl, BindingDecl, MSGuidDecl,
15043 UnnamedGlobalConstantDecl>(Val: dcl))
15044 llvm_unreachable("Unknown/unexpected decl type");
15045 }
15046
15047 if (AddressOfError != AO_No_Error) {
15048 diagnoseAddressOfInvalidType(S&: *this, Loc: OpLoc, E: op, Type: AddressOfError);
15049 return QualType();
15050 }
15051
15052 if (lval == Expr::LV_IncompleteVoidType) {
15053 // Taking the address of a void variable is technically illegal, but we
15054 // allow it in cases which are otherwise valid.
15055 // Example: "extern void x; void* y = &x;".
15056 Diag(Loc: OpLoc, DiagID: diag::ext_typecheck_addrof_void) << op->getSourceRange();
15057 }
15058
15059 // If the operand has type "type", the result has type "pointer to type".
15060 if (op->getType()->isObjCObjectType())
15061 return Context.getObjCObjectPointerType(OIT: op->getType());
15062
15063 // Cannot take the address of WebAssembly references or tables.
15064 if (Context.getTargetInfo().getTriple().isWasm()) {
15065 QualType OpTy = op->getType();
15066 if (OpTy.isWebAssemblyReferenceType()) {
15067 Diag(Loc: OpLoc, DiagID: diag::err_wasm_ca_reference)
15068 << 1 << OrigOp.get()->getSourceRange();
15069 return QualType();
15070 }
15071 if (OpTy->isWebAssemblyTableType()) {
15072 Diag(Loc: OpLoc, DiagID: diag::err_wasm_table_pr)
15073 << 1 << OrigOp.get()->getSourceRange();
15074 return QualType();
15075 }
15076 }
15077
15078 CheckAddressOfPackedMember(rhs: op);
15079
15080 return Context.getPointerType(T: op->getType());
15081}
15082
15083static void RecordModifiableNonNullParam(Sema &S, const Expr *Exp) {
15084 const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Val: Exp);
15085 if (!DRE)
15086 return;
15087 const Decl *D = DRE->getDecl();
15088 if (!D)
15089 return;
15090 const ParmVarDecl *Param = dyn_cast<ParmVarDecl>(Val: D);
15091 if (!Param)
15092 return;
15093 if (const FunctionDecl* FD = dyn_cast<FunctionDecl>(Val: Param->getDeclContext()))
15094 if (!FD->hasAttr<NonNullAttr>() && !Param->hasAttr<NonNullAttr>())
15095 return;
15096 if (FunctionScopeInfo *FD = S.getCurFunction())
15097 FD->ModifiedNonNullParams.insert(Ptr: Param);
15098}
15099
15100/// CheckIndirectionOperand - Type check unary indirection (prefix '*').
15101static QualType CheckIndirectionOperand(Sema &S, Expr *Op, ExprValueKind &VK,
15102 SourceLocation OpLoc,
15103 bool IsAfterAmp = false) {
15104 ExprResult ConvResult = S.UsualUnaryConversions(E: Op);
15105 if (ConvResult.isInvalid())
15106 return QualType();
15107 Op = ConvResult.get();
15108 QualType OpTy = Op->getType();
15109 QualType Result;
15110
15111 if (isa<CXXReinterpretCastExpr>(Val: Op->IgnoreParens())) {
15112 QualType OpOrigType = Op->IgnoreParenCasts()->getType();
15113 S.CheckCompatibleReinterpretCast(SrcType: OpOrigType, DestType: OpTy, /*IsDereference*/true,
15114 Range: Op->getSourceRange());
15115 }
15116
15117 if (const PointerType *PT = OpTy->getAs<PointerType>())
15118 {
15119 Result = PT->getPointeeType();
15120 }
15121 else if (const ObjCObjectPointerType *OPT =
15122 OpTy->getAs<ObjCObjectPointerType>())
15123 Result = OPT->getPointeeType();
15124 else {
15125 ExprResult PR = S.CheckPlaceholderExpr(E: Op);
15126 if (PR.isInvalid()) return QualType();
15127 if (PR.get() != Op)
15128 return CheckIndirectionOperand(S, Op: PR.get(), VK, OpLoc);
15129 }
15130
15131 if (Result.isNull()) {
15132 S.Diag(Loc: OpLoc, DiagID: diag::err_typecheck_indirection_requires_pointer)
15133 << OpTy << Op->getSourceRange();
15134 return QualType();
15135 }
15136
15137 if (Result->isVoidType()) {
15138 // C++ [expr.unary.op]p1:
15139 // [...] the expression to which [the unary * operator] is applied shall
15140 // be a pointer to an object type, or a pointer to a function type
15141 LangOptions LO = S.getLangOpts();
15142 if (LO.CPlusPlus)
15143 S.Diag(Loc: OpLoc, DiagID: diag::err_typecheck_indirection_through_void_pointer_cpp)
15144 << OpTy << Op->getSourceRange();
15145 else if (!(LO.C99 && IsAfterAmp) && !S.isUnevaluatedContext())
15146 S.Diag(Loc: OpLoc, DiagID: diag::ext_typecheck_indirection_through_void_pointer)
15147 << OpTy << Op->getSourceRange();
15148 }
15149
15150 // Dereferences are usually l-values...
15151 VK = VK_LValue;
15152
15153 // ...except that certain expressions are never l-values in C.
15154 if (!S.getLangOpts().CPlusPlus && Result.isCForbiddenLValueType())
15155 VK = VK_PRValue;
15156
15157 return Result;
15158}
15159
15160BinaryOperatorKind Sema::ConvertTokenKindToBinaryOpcode(tok::TokenKind Kind) {
15161 BinaryOperatorKind Opc;
15162 switch (Kind) {
15163 default: llvm_unreachable("Unknown binop!");
15164 case tok::periodstar: Opc = BO_PtrMemD; break;
15165 case tok::arrowstar: Opc = BO_PtrMemI; break;
15166 case tok::star: Opc = BO_Mul; break;
15167 case tok::slash: Opc = BO_Div; break;
15168 case tok::percent: Opc = BO_Rem; break;
15169 case tok::plus: Opc = BO_Add; break;
15170 case tok::minus: Opc = BO_Sub; break;
15171 case tok::lessless: Opc = BO_Shl; break;
15172 case tok::greatergreater: Opc = BO_Shr; break;
15173 case tok::lessequal: Opc = BO_LE; break;
15174 case tok::less: Opc = BO_LT; break;
15175 case tok::greaterequal: Opc = BO_GE; break;
15176 case tok::greater: Opc = BO_GT; break;
15177 case tok::exclaimequal: Opc = BO_NE; break;
15178 case tok::equalequal: Opc = BO_EQ; break;
15179 case tok::spaceship: Opc = BO_Cmp; break;
15180 case tok::amp: Opc = BO_And; break;
15181 case tok::caret: Opc = BO_Xor; break;
15182 case tok::pipe: Opc = BO_Or; break;
15183 case tok::ampamp: Opc = BO_LAnd; break;
15184 case tok::pipepipe: Opc = BO_LOr; break;
15185 case tok::equal: Opc = BO_Assign; break;
15186 case tok::starequal: Opc = BO_MulAssign; break;
15187 case tok::slashequal: Opc = BO_DivAssign; break;
15188 case tok::percentequal: Opc = BO_RemAssign; break;
15189 case tok::plusequal: Opc = BO_AddAssign; break;
15190 case tok::minusequal: Opc = BO_SubAssign; break;
15191 case tok::lesslessequal: Opc = BO_ShlAssign; break;
15192 case tok::greatergreaterequal: Opc = BO_ShrAssign; break;
15193 case tok::ampequal: Opc = BO_AndAssign; break;
15194 case tok::caretequal: Opc = BO_XorAssign; break;
15195 case tok::pipeequal: Opc = BO_OrAssign; break;
15196 case tok::comma: Opc = BO_Comma; break;
15197 }
15198 return Opc;
15199}
15200
15201static inline UnaryOperatorKind ConvertTokenKindToUnaryOpcode(
15202 tok::TokenKind Kind) {
15203 UnaryOperatorKind Opc;
15204 switch (Kind) {
15205 default: llvm_unreachable("Unknown unary op!");
15206 case tok::plusplus: Opc = UO_PreInc; break;
15207 case tok::minusminus: Opc = UO_PreDec; break;
15208 case tok::amp: Opc = UO_AddrOf; break;
15209 case tok::star: Opc = UO_Deref; break;
15210 case tok::plus: Opc = UO_Plus; break;
15211 case tok::minus: Opc = UO_Minus; break;
15212 case tok::tilde: Opc = UO_Not; break;
15213 case tok::exclaim: Opc = UO_LNot; break;
15214 case tok::kw___real: Opc = UO_Real; break;
15215 case tok::kw___imag: Opc = UO_Imag; break;
15216 case tok::kw___extension__: Opc = UO_Extension; break;
15217 }
15218 return Opc;
15219}
15220
15221const FieldDecl *
15222Sema::getSelfAssignmentClassMemberCandidate(const ValueDecl *SelfAssigned) {
15223 // Explore the case for adding 'this->' to the LHS of a self assignment, very
15224 // common for setters.
15225 // struct A {
15226 // int X;
15227 // -void setX(int X) { X = X; }
15228 // +void setX(int X) { this->X = X; }
15229 // };
15230
15231 // Only consider parameters for self assignment fixes.
15232 if (!isa<ParmVarDecl>(Val: SelfAssigned))
15233 return nullptr;
15234 const auto *Method =
15235 dyn_cast_or_null<CXXMethodDecl>(Val: getCurFunctionDecl(AllowLambda: true));
15236 if (!Method)
15237 return nullptr;
15238
15239 const CXXRecordDecl *Parent = Method->getParent();
15240 // In theory this is fixable if the lambda explicitly captures this, but
15241 // that's added complexity that's rarely going to be used.
15242 if (Parent->isLambda())
15243 return nullptr;
15244
15245 // FIXME: Use an actual Lookup operation instead of just traversing fields
15246 // in order to get base class fields.
15247 auto Field =
15248 llvm::find_if(Range: Parent->fields(),
15249 P: [Name(SelfAssigned->getDeclName())](const FieldDecl *F) {
15250 return F->getDeclName() == Name;
15251 });
15252 return (Field != Parent->field_end()) ? *Field : nullptr;
15253}
15254
15255/// DiagnoseSelfAssignment - Emits a warning if a value is assigned to itself.
15256/// This warning suppressed in the event of macro expansions.
15257static void DiagnoseSelfAssignment(Sema &S, Expr *LHSExpr, Expr *RHSExpr,
15258 SourceLocation OpLoc, bool IsBuiltin) {
15259 if (S.inTemplateInstantiation())
15260 return;
15261 if (S.isUnevaluatedContext())
15262 return;
15263 if (OpLoc.isInvalid() || OpLoc.isMacroID())
15264 return;
15265 LHSExpr = LHSExpr->IgnoreParenImpCasts();
15266 RHSExpr = RHSExpr->IgnoreParenImpCasts();
15267 const DeclRefExpr *LHSDeclRef = dyn_cast<DeclRefExpr>(Val: LHSExpr);
15268 const DeclRefExpr *RHSDeclRef = dyn_cast<DeclRefExpr>(Val: RHSExpr);
15269 if (!LHSDeclRef || !RHSDeclRef ||
15270 LHSDeclRef->getLocation().isMacroID() ||
15271 RHSDeclRef->getLocation().isMacroID())
15272 return;
15273 const ValueDecl *LHSDecl =
15274 cast<ValueDecl>(Val: LHSDeclRef->getDecl()->getCanonicalDecl());
15275 const ValueDecl *RHSDecl =
15276 cast<ValueDecl>(Val: RHSDeclRef->getDecl()->getCanonicalDecl());
15277 if (LHSDecl != RHSDecl)
15278 return;
15279 if (LHSDecl->getType().isVolatileQualified())
15280 return;
15281 if (const ReferenceType *RefTy = LHSDecl->getType()->getAs<ReferenceType>())
15282 if (RefTy->getPointeeType().isVolatileQualified())
15283 return;
15284
15285 auto Diag = S.Diag(Loc: OpLoc, DiagID: IsBuiltin ? diag::warn_self_assignment_builtin
15286 : diag::warn_self_assignment_overloaded)
15287 << LHSDeclRef->getType() << LHSExpr->getSourceRange()
15288 << RHSExpr->getSourceRange();
15289 if (const FieldDecl *SelfAssignField =
15290 S.getSelfAssignmentClassMemberCandidate(SelfAssigned: RHSDecl))
15291 Diag << 1 << SelfAssignField
15292 << FixItHint::CreateInsertion(InsertionLoc: LHSDeclRef->getBeginLoc(), Code: "this->");
15293 else
15294 Diag << 0;
15295}
15296
15297/// Check if a bitwise-& is performed on an Objective-C pointer. This
15298/// is usually indicative of introspection within the Objective-C pointer.
15299static void checkObjCPointerIntrospection(Sema &S, ExprResult &L, ExprResult &R,
15300 SourceLocation OpLoc) {
15301 if (!S.getLangOpts().ObjC)
15302 return;
15303
15304 const Expr *ObjCPointerExpr = nullptr, *OtherExpr = nullptr;
15305 const Expr *LHS = L.get();
15306 const Expr *RHS = R.get();
15307
15308 if (LHS->IgnoreParenCasts()->getType()->isObjCObjectPointerType()) {
15309 ObjCPointerExpr = LHS;
15310 OtherExpr = RHS;
15311 }
15312 else if (RHS->IgnoreParenCasts()->getType()->isObjCObjectPointerType()) {
15313 ObjCPointerExpr = RHS;
15314 OtherExpr = LHS;
15315 }
15316
15317 // This warning is deliberately made very specific to reduce false
15318 // positives with logic that uses '&' for hashing. This logic mainly
15319 // looks for code trying to introspect into tagged pointers, which
15320 // code should generally never do.
15321 if (ObjCPointerExpr && isa<IntegerLiteral>(Val: OtherExpr->IgnoreParenCasts())) {
15322 unsigned Diag = diag::warn_objc_pointer_masking;
15323 // Determine if we are introspecting the result of performSelectorXXX.
15324 const Expr *Ex = ObjCPointerExpr->IgnoreParenCasts();
15325 // Special case messages to -performSelector and friends, which
15326 // can return non-pointer values boxed in a pointer value.
15327 // Some clients may wish to silence warnings in this subcase.
15328 if (const ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(Val: Ex)) {
15329 Selector S = ME->getSelector();
15330 StringRef SelArg0 = S.getNameForSlot(argIndex: 0);
15331 if (SelArg0.starts_with(Prefix: "performSelector"))
15332 Diag = diag::warn_objc_pointer_masking_performSelector;
15333 }
15334
15335 S.Diag(Loc: OpLoc, DiagID: Diag)
15336 << ObjCPointerExpr->getSourceRange();
15337 }
15338}
15339
15340// This helper function promotes a binary operator's operands (which are of a
15341// half vector type) to a vector of floats and then truncates the result to
15342// a vector of either half or short.
15343static ExprResult convertHalfVecBinOp(Sema &S, ExprResult LHS, ExprResult RHS,
15344 BinaryOperatorKind Opc, QualType ResultTy,
15345 ExprValueKind VK, ExprObjectKind OK,
15346 bool IsCompAssign, SourceLocation OpLoc,
15347 FPOptionsOverride FPFeatures) {
15348 auto &Context = S.getASTContext();
15349 assert((isVector(ResultTy, Context.HalfTy) ||
15350 isVector(ResultTy, Context.ShortTy)) &&
15351 "Result must be a vector of half or short");
15352 assert(isVector(LHS.get()->getType(), Context.HalfTy) &&
15353 isVector(RHS.get()->getType(), Context.HalfTy) &&
15354 "both operands expected to be a half vector");
15355
15356 RHS = convertVector(E: RHS.get(), ElementType: Context.FloatTy, S);
15357 QualType BinOpResTy = RHS.get()->getType();
15358
15359 // If Opc is a comparison, ResultType is a vector of shorts. In that case,
15360 // change BinOpResTy to a vector of ints.
15361 if (isVector(QT: ResultTy, ElementType: Context.ShortTy))
15362 BinOpResTy = S.GetSignedVectorType(V: BinOpResTy);
15363
15364 if (IsCompAssign)
15365 return CompoundAssignOperator::Create(C: Context, lhs: LHS.get(), rhs: RHS.get(), opc: Opc,
15366 ResTy: ResultTy, VK, OK, opLoc: OpLoc, FPFeatures,
15367 CompLHSType: BinOpResTy, CompResultType: BinOpResTy);
15368
15369 LHS = convertVector(E: LHS.get(), ElementType: Context.FloatTy, S);
15370 auto *BO = BinaryOperator::Create(C: Context, lhs: LHS.get(), rhs: RHS.get(), opc: Opc,
15371 ResTy: BinOpResTy, VK, OK, opLoc: OpLoc, FPFeatures);
15372 return convertVector(E: BO, ElementType: ResultTy->castAs<VectorType>()->getElementType(), S);
15373}
15374
15375/// Returns true if conversion between vectors of halfs and vectors of floats
15376/// is needed.
15377static bool needsConversionOfHalfVec(bool OpRequiresConversion, ASTContext &Ctx,
15378 Expr *E0, Expr *E1 = nullptr) {
15379 if (!OpRequiresConversion || Ctx.getLangOpts().NativeHalfType ||
15380 Ctx.getTargetInfo().useFP16ConversionIntrinsics())
15381 return false;
15382
15383 auto HasVectorOfHalfType = [&Ctx](Expr *E) {
15384 QualType Ty = E->IgnoreImplicit()->getType();
15385
15386 // Don't promote half precision neon vectors like float16x4_t in arm_neon.h
15387 // to vectors of floats. Although the element type of the vectors is __fp16,
15388 // the vectors shouldn't be treated as storage-only types. See the
15389 // discussion here: https://reviews.llvm.org/rG825235c140e7
15390 if (const VectorType *VT = Ty->getAs<VectorType>()) {
15391 if (VT->getVectorKind() == VectorKind::Neon)
15392 return false;
15393 return VT->getElementType().getCanonicalType() == Ctx.HalfTy;
15394 }
15395 return false;
15396 };
15397
15398 return HasVectorOfHalfType(E0) && (!E1 || HasVectorOfHalfType(E1));
15399}
15400
15401ExprResult Sema::CreateBuiltinBinOp(SourceLocation OpLoc,
15402 BinaryOperatorKind Opc, Expr *LHSExpr,
15403 Expr *RHSExpr, bool ForFoldExpression) {
15404 if (getLangOpts().CPlusPlus11 && isa<InitListExpr>(Val: RHSExpr)) {
15405 // The syntax only allows initializer lists on the RHS of assignment,
15406 // so we don't need to worry about accepting invalid code for
15407 // non-assignment operators.
15408 // C++11 5.17p9:
15409 // The meaning of x = {v} [...] is that of x = T(v) [...]. The meaning
15410 // of x = {} is x = T().
15411 InitializationKind Kind = InitializationKind::CreateDirectList(
15412 InitLoc: RHSExpr->getBeginLoc(), LBraceLoc: RHSExpr->getBeginLoc(), RBraceLoc: RHSExpr->getEndLoc());
15413 InitializedEntity Entity =
15414 InitializedEntity::InitializeTemporary(Type: LHSExpr->getType());
15415 InitializationSequence InitSeq(*this, Entity, Kind, RHSExpr);
15416 ExprResult Init = InitSeq.Perform(S&: *this, Entity, Kind, Args: RHSExpr);
15417 if (Init.isInvalid())
15418 return Init;
15419 RHSExpr = Init.get();
15420 }
15421
15422 ExprResult LHS = LHSExpr, RHS = RHSExpr;
15423 QualType ResultTy; // Result type of the binary operator.
15424 // The following two variables are used for compound assignment operators
15425 QualType CompLHSTy; // Type of LHS after promotions for computation
15426 QualType CompResultTy; // Type of computation result
15427 ExprValueKind VK = VK_PRValue;
15428 ExprObjectKind OK = OK_Ordinary;
15429 bool ConvertHalfVec = false;
15430
15431 if (!LHS.isUsable() || !RHS.isUsable())
15432 return ExprError();
15433
15434 if (getLangOpts().OpenCL) {
15435 QualType LHSTy = LHSExpr->getType();
15436 QualType RHSTy = RHSExpr->getType();
15437 // OpenCLC v2.0 s6.13.11.1 allows atomic variables to be initialized by
15438 // the ATOMIC_VAR_INIT macro.
15439 if (LHSTy->isAtomicType() || RHSTy->isAtomicType()) {
15440 SourceRange SR(LHSExpr->getBeginLoc(), RHSExpr->getEndLoc());
15441 if (BO_Assign == Opc)
15442 Diag(Loc: OpLoc, DiagID: diag::err_opencl_atomic_init) << 0 << SR;
15443 else
15444 ResultTy = InvalidOperands(Loc: OpLoc, LHS, RHS);
15445 return ExprError();
15446 }
15447
15448 // OpenCL special types - image, sampler, pipe, and blocks are to be used
15449 // only with a builtin functions and therefore should be disallowed here.
15450 if (LHSTy->isImageType() || RHSTy->isImageType() ||
15451 LHSTy->isSamplerT() || RHSTy->isSamplerT() ||
15452 LHSTy->isPipeType() || RHSTy->isPipeType() ||
15453 LHSTy->isBlockPointerType() || RHSTy->isBlockPointerType()) {
15454 ResultTy = InvalidOperands(Loc: OpLoc, LHS, RHS);
15455 return ExprError();
15456 }
15457 }
15458
15459 checkTypeSupport(Ty: LHSExpr->getType(), Loc: OpLoc, /*ValueDecl*/ D: nullptr);
15460 checkTypeSupport(Ty: RHSExpr->getType(), Loc: OpLoc, /*ValueDecl*/ D: nullptr);
15461
15462 switch (Opc) {
15463 case BO_Assign:
15464 ResultTy = CheckAssignmentOperands(LHSExpr: LHS.get(), RHS, Loc: OpLoc, CompoundType: QualType(), Opc);
15465 if (getLangOpts().CPlusPlus &&
15466 LHS.get()->getObjectKind() != OK_ObjCProperty) {
15467 VK = LHS.get()->getValueKind();
15468 OK = LHS.get()->getObjectKind();
15469 }
15470 if (!ResultTy.isNull()) {
15471 DiagnoseSelfAssignment(S&: *this, LHSExpr: LHS.get(), RHSExpr: RHS.get(), OpLoc, IsBuiltin: true);
15472 DiagnoseSelfMove(LHSExpr: LHS.get(), RHSExpr: RHS.get(), OpLoc);
15473
15474 // Avoid copying a block to the heap if the block is assigned to a local
15475 // auto variable that is declared in the same scope as the block. This
15476 // optimization is unsafe if the local variable is declared in an outer
15477 // scope. For example:
15478 //
15479 // BlockTy b;
15480 // {
15481 // b = ^{...};
15482 // }
15483 // // It is unsafe to invoke the block here if it wasn't copied to the
15484 // // heap.
15485 // b();
15486
15487 if (auto *BE = dyn_cast<BlockExpr>(Val: RHS.get()->IgnoreParens()))
15488 if (auto *DRE = dyn_cast<DeclRefExpr>(Val: LHS.get()->IgnoreParens()))
15489 if (auto *VD = dyn_cast<VarDecl>(Val: DRE->getDecl()))
15490 if (VD->hasLocalStorage() && getCurScope()->isDeclScope(D: VD))
15491 BE->getBlockDecl()->setCanAvoidCopyToHeap();
15492
15493 if (LHS.get()->getType().hasNonTrivialToPrimitiveCopyCUnion())
15494 checkNonTrivialCUnion(QT: LHS.get()->getType(), Loc: LHS.get()->getExprLoc(),
15495 UseContext: NonTrivialCUnionContext::Assignment, NonTrivialKind: NTCUK_Copy);
15496 }
15497 RecordModifiableNonNullParam(S&: *this, Exp: LHS.get());
15498 break;
15499 case BO_PtrMemD:
15500 case BO_PtrMemI:
15501 ResultTy = CheckPointerToMemberOperands(LHS, RHS, VK, OpLoc,
15502 isIndirect: Opc == BO_PtrMemI);
15503 break;
15504 case BO_Mul:
15505 case BO_Div:
15506 ConvertHalfVec = true;
15507 ResultTy = CheckMultiplyDivideOperands(LHS, RHS, Loc: OpLoc, Opc);
15508 break;
15509 case BO_Rem:
15510 ResultTy = CheckRemainderOperands(LHS, RHS, Loc: OpLoc);
15511 break;
15512 case BO_Add:
15513 ConvertHalfVec = true;
15514 ResultTy = CheckAdditionOperands(LHS, RHS, Loc: OpLoc, Opc);
15515 break;
15516 case BO_Sub:
15517 ConvertHalfVec = true;
15518 ResultTy = CheckSubtractionOperands(LHS, RHS, Loc: OpLoc, Opc);
15519 break;
15520 case BO_Shl:
15521 case BO_Shr:
15522 ResultTy = CheckShiftOperands(LHS, RHS, Loc: OpLoc, Opc);
15523 break;
15524 case BO_LE:
15525 case BO_LT:
15526 case BO_GE:
15527 case BO_GT:
15528 ConvertHalfVec = true;
15529 ResultTy = CheckCompareOperands(LHS, RHS, Loc: OpLoc, Opc);
15530
15531 if (const auto *BI = dyn_cast<BinaryOperator>(Val: LHSExpr);
15532 !ForFoldExpression && BI && BI->isComparisonOp())
15533 Diag(Loc: OpLoc, DiagID: diag::warn_consecutive_comparison)
15534 << BI->getOpcodeStr() << BinaryOperator::getOpcodeStr(Op: Opc);
15535
15536 break;
15537 case BO_EQ:
15538 case BO_NE:
15539 ConvertHalfVec = true;
15540 ResultTy = CheckCompareOperands(LHS, RHS, Loc: OpLoc, Opc);
15541 break;
15542 case BO_Cmp:
15543 ConvertHalfVec = true;
15544 ResultTy = CheckCompareOperands(LHS, RHS, Loc: OpLoc, Opc);
15545 assert(ResultTy.isNull() || ResultTy->getAsCXXRecordDecl());
15546 break;
15547 case BO_And:
15548 checkObjCPointerIntrospection(S&: *this, L&: LHS, R&: RHS, OpLoc);
15549 [[fallthrough]];
15550 case BO_Xor:
15551 case BO_Or:
15552 ResultTy = CheckBitwiseOperands(LHS, RHS, Loc: OpLoc, Opc);
15553 break;
15554 case BO_LAnd:
15555 case BO_LOr:
15556 ConvertHalfVec = true;
15557 ResultTy = CheckLogicalOperands(LHS, RHS, Loc: OpLoc, Opc);
15558 break;
15559 case BO_MulAssign:
15560 case BO_DivAssign:
15561 ConvertHalfVec = true;
15562 CompResultTy = CheckMultiplyDivideOperands(LHS, RHS, Loc: OpLoc, Opc);
15563 CompLHSTy = CompResultTy;
15564 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
15565 ResultTy =
15566 CheckAssignmentOperands(LHSExpr: LHS.get(), RHS, Loc: OpLoc, CompoundType: CompResultTy, Opc);
15567 break;
15568 case BO_RemAssign:
15569 CompResultTy = CheckRemainderOperands(LHS, RHS, Loc: OpLoc, IsCompAssign: true);
15570 CompLHSTy = CompResultTy;
15571 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
15572 ResultTy =
15573 CheckAssignmentOperands(LHSExpr: LHS.get(), RHS, Loc: OpLoc, CompoundType: CompResultTy, Opc);
15574 break;
15575 case BO_AddAssign:
15576 ConvertHalfVec = true;
15577 CompResultTy = CheckAdditionOperands(LHS, RHS, Loc: OpLoc, Opc, CompLHSTy: &CompLHSTy);
15578 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
15579 ResultTy =
15580 CheckAssignmentOperands(LHSExpr: LHS.get(), RHS, Loc: OpLoc, CompoundType: CompResultTy, Opc);
15581 break;
15582 case BO_SubAssign:
15583 ConvertHalfVec = true;
15584 CompResultTy = CheckSubtractionOperands(LHS, RHS, Loc: OpLoc, Opc, CompLHSTy: &CompLHSTy);
15585 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
15586 ResultTy =
15587 CheckAssignmentOperands(LHSExpr: LHS.get(), RHS, Loc: OpLoc, CompoundType: CompResultTy, Opc);
15588 break;
15589 case BO_ShlAssign:
15590 case BO_ShrAssign:
15591 CompResultTy = CheckShiftOperands(LHS, RHS, Loc: OpLoc, Opc, IsCompAssign: true);
15592 CompLHSTy = CompResultTy;
15593 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
15594 ResultTy =
15595 CheckAssignmentOperands(LHSExpr: LHS.get(), RHS, Loc: OpLoc, CompoundType: CompResultTy, Opc);
15596 break;
15597 case BO_AndAssign:
15598 case BO_OrAssign: // fallthrough
15599 DiagnoseSelfAssignment(S&: *this, LHSExpr: LHS.get(), RHSExpr: RHS.get(), OpLoc, IsBuiltin: true);
15600 [[fallthrough]];
15601 case BO_XorAssign:
15602 CompResultTy = CheckBitwiseOperands(LHS, RHS, Loc: OpLoc, Opc);
15603 CompLHSTy = CompResultTy;
15604 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
15605 ResultTy =
15606 CheckAssignmentOperands(LHSExpr: LHS.get(), RHS, Loc: OpLoc, CompoundType: CompResultTy, Opc);
15607 break;
15608 case BO_Comma:
15609 ResultTy = CheckCommaOperands(S&: *this, LHS, RHS, Loc: OpLoc);
15610 if (getLangOpts().CPlusPlus && !RHS.isInvalid()) {
15611 VK = RHS.get()->getValueKind();
15612 OK = RHS.get()->getObjectKind();
15613 }
15614 break;
15615 }
15616 if (ResultTy.isNull() || LHS.isInvalid() || RHS.isInvalid())
15617 return ExprError();
15618
15619 // Some of the binary operations require promoting operands of half vector to
15620 // float vectors and truncating the result back to half vector. For now, we do
15621 // this only when HalfArgsAndReturn is set (that is, when the target is arm or
15622 // arm64).
15623 assert(
15624 (Opc == BO_Comma || isVector(RHS.get()->getType(), Context.HalfTy) ==
15625 isVector(LHS.get()->getType(), Context.HalfTy)) &&
15626 "both sides are half vectors or neither sides are");
15627 ConvertHalfVec =
15628 needsConversionOfHalfVec(OpRequiresConversion: ConvertHalfVec, Ctx&: Context, E0: LHS.get(), E1: RHS.get());
15629
15630 // Check for array bounds violations for both sides of the BinaryOperator
15631 CheckArrayAccess(E: LHS.get());
15632 CheckArrayAccess(E: RHS.get());
15633
15634 if (const ObjCIsaExpr *OISA = dyn_cast<ObjCIsaExpr>(Val: LHS.get()->IgnoreParenCasts())) {
15635 NamedDecl *ObjectSetClass = LookupSingleName(S: TUScope,
15636 Name: &Context.Idents.get(Name: "object_setClass"),
15637 Loc: SourceLocation(), NameKind: LookupOrdinaryName);
15638 if (ObjectSetClass && isa<ObjCIsaExpr>(Val: LHS.get())) {
15639 SourceLocation RHSLocEnd = getLocForEndOfToken(Loc: RHS.get()->getEndLoc());
15640 Diag(Loc: LHS.get()->getExprLoc(), DiagID: diag::warn_objc_isa_assign)
15641 << FixItHint::CreateInsertion(InsertionLoc: LHS.get()->getBeginLoc(),
15642 Code: "object_setClass(")
15643 << FixItHint::CreateReplacement(RemoveRange: SourceRange(OISA->getOpLoc(), OpLoc),
15644 Code: ",")
15645 << FixItHint::CreateInsertion(InsertionLoc: RHSLocEnd, Code: ")");
15646 }
15647 else
15648 Diag(Loc: LHS.get()->getExprLoc(), DiagID: diag::warn_objc_isa_assign);
15649 }
15650 else if (const ObjCIvarRefExpr *OIRE =
15651 dyn_cast<ObjCIvarRefExpr>(Val: LHS.get()->IgnoreParenCasts()))
15652 DiagnoseDirectIsaAccess(S&: *this, OIRE, AssignLoc: OpLoc, RHS: RHS.get());
15653
15654 // Opc is not a compound assignment if CompResultTy is null.
15655 if (CompResultTy.isNull()) {
15656 if (ConvertHalfVec)
15657 return convertHalfVecBinOp(S&: *this, LHS, RHS, Opc, ResultTy, VK, OK, IsCompAssign: false,
15658 OpLoc, FPFeatures: CurFPFeatureOverrides());
15659 return BinaryOperator::Create(C: Context, lhs: LHS.get(), rhs: RHS.get(), opc: Opc, ResTy: ResultTy,
15660 VK, OK, opLoc: OpLoc, FPFeatures: CurFPFeatureOverrides());
15661 }
15662
15663 // Handle compound assignments.
15664 if (getLangOpts().CPlusPlus && LHS.get()->getObjectKind() !=
15665 OK_ObjCProperty) {
15666 VK = VK_LValue;
15667 OK = LHS.get()->getObjectKind();
15668 }
15669
15670 // The LHS is not converted to the result type for fixed-point compound
15671 // assignment as the common type is computed on demand. Reset the CompLHSTy
15672 // to the LHS type we would have gotten after unary conversions.
15673 if (CompResultTy->isFixedPointType())
15674 CompLHSTy = UsualUnaryConversions(E: LHS.get()).get()->getType();
15675
15676 if (ConvertHalfVec)
15677 return convertHalfVecBinOp(S&: *this, LHS, RHS, Opc, ResultTy, VK, OK, IsCompAssign: true,
15678 OpLoc, FPFeatures: CurFPFeatureOverrides());
15679
15680 return CompoundAssignOperator::Create(
15681 C: Context, lhs: LHS.get(), rhs: RHS.get(), opc: Opc, ResTy: ResultTy, VK, OK, opLoc: OpLoc,
15682 FPFeatures: CurFPFeatureOverrides(), CompLHSType: CompLHSTy, CompResultType: CompResultTy);
15683}
15684
15685/// DiagnoseBitwisePrecedence - Emit a warning when bitwise and comparison
15686/// operators are mixed in a way that suggests that the programmer forgot that
15687/// comparison operators have higher precedence. The most typical example of
15688/// such code is "flags & 0x0020 != 0", which is equivalent to "flags & 1".
15689static void DiagnoseBitwisePrecedence(Sema &Self, BinaryOperatorKind Opc,
15690 SourceLocation OpLoc, Expr *LHSExpr,
15691 Expr *RHSExpr) {
15692 BinaryOperator *LHSBO = dyn_cast<BinaryOperator>(Val: LHSExpr);
15693 BinaryOperator *RHSBO = dyn_cast<BinaryOperator>(Val: RHSExpr);
15694
15695 // Check that one of the sides is a comparison operator and the other isn't.
15696 bool isLeftComp = LHSBO && LHSBO->isComparisonOp();
15697 bool isRightComp = RHSBO && RHSBO->isComparisonOp();
15698 if (isLeftComp == isRightComp)
15699 return;
15700
15701 // Bitwise operations are sometimes used as eager logical ops.
15702 // Don't diagnose this.
15703 bool isLeftBitwise = LHSBO && LHSBO->isBitwiseOp();
15704 bool isRightBitwise = RHSBO && RHSBO->isBitwiseOp();
15705 if (isLeftBitwise || isRightBitwise)
15706 return;
15707
15708 SourceRange DiagRange = isLeftComp
15709 ? SourceRange(LHSExpr->getBeginLoc(), OpLoc)
15710 : SourceRange(OpLoc, RHSExpr->getEndLoc());
15711 StringRef OpStr = isLeftComp ? LHSBO->getOpcodeStr() : RHSBO->getOpcodeStr();
15712 SourceRange ParensRange =
15713 isLeftComp
15714 ? SourceRange(LHSBO->getRHS()->getBeginLoc(), RHSExpr->getEndLoc())
15715 : SourceRange(LHSExpr->getBeginLoc(), RHSBO->getLHS()->getEndLoc());
15716
15717 Self.Diag(Loc: OpLoc, DiagID: diag::warn_precedence_bitwise_rel)
15718 << DiagRange << BinaryOperator::getOpcodeStr(Op: Opc) << OpStr;
15719 SuggestParentheses(Self, Loc: OpLoc,
15720 Note: Self.PDiag(DiagID: diag::note_precedence_silence) << OpStr,
15721 ParenRange: (isLeftComp ? LHSExpr : RHSExpr)->getSourceRange());
15722 SuggestParentheses(Self, Loc: OpLoc,
15723 Note: Self.PDiag(DiagID: diag::note_precedence_bitwise_first)
15724 << BinaryOperator::getOpcodeStr(Op: Opc),
15725 ParenRange: ParensRange);
15726}
15727
15728/// It accepts a '&&' expr that is inside a '||' one.
15729/// Emit a diagnostic together with a fixit hint that wraps the '&&' expression
15730/// in parentheses.
15731static void
15732EmitDiagnosticForLogicalAndInLogicalOr(Sema &Self, SourceLocation OpLoc,
15733 BinaryOperator *Bop) {
15734 assert(Bop->getOpcode() == BO_LAnd);
15735 Self.Diag(Loc: Bop->getOperatorLoc(), DiagID: diag::warn_logical_and_in_logical_or)
15736 << Bop->getSourceRange() << OpLoc;
15737 SuggestParentheses(Self, Loc: Bop->getOperatorLoc(),
15738 Note: Self.PDiag(DiagID: diag::note_precedence_silence)
15739 << Bop->getOpcodeStr(),
15740 ParenRange: Bop->getSourceRange());
15741}
15742
15743/// Look for '&&' in the left hand of a '||' expr.
15744static void DiagnoseLogicalAndInLogicalOrLHS(Sema &S, SourceLocation OpLoc,
15745 Expr *LHSExpr, Expr *RHSExpr) {
15746 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(Val: LHSExpr)) {
15747 if (Bop->getOpcode() == BO_LAnd) {
15748 // If it's "string_literal && a || b" don't warn since the precedence
15749 // doesn't matter.
15750 if (!isa<StringLiteral>(Val: Bop->getLHS()->IgnoreParenImpCasts()))
15751 return EmitDiagnosticForLogicalAndInLogicalOr(Self&: S, OpLoc, Bop);
15752 } else if (Bop->getOpcode() == BO_LOr) {
15753 if (BinaryOperator *RBop = dyn_cast<BinaryOperator>(Val: Bop->getRHS())) {
15754 // If it's "a || b && string_literal || c" we didn't warn earlier for
15755 // "a || b && string_literal", but warn now.
15756 if (RBop->getOpcode() == BO_LAnd &&
15757 isa<StringLiteral>(Val: RBop->getRHS()->IgnoreParenImpCasts()))
15758 return EmitDiagnosticForLogicalAndInLogicalOr(Self&: S, OpLoc, Bop: RBop);
15759 }
15760 }
15761 }
15762}
15763
15764/// Look for '&&' in the right hand of a '||' expr.
15765static void DiagnoseLogicalAndInLogicalOrRHS(Sema &S, SourceLocation OpLoc,
15766 Expr *LHSExpr, Expr *RHSExpr) {
15767 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(Val: RHSExpr)) {
15768 if (Bop->getOpcode() == BO_LAnd) {
15769 // If it's "a || b && string_literal" don't warn since the precedence
15770 // doesn't matter.
15771 if (!isa<StringLiteral>(Val: Bop->getRHS()->IgnoreParenImpCasts()))
15772 return EmitDiagnosticForLogicalAndInLogicalOr(Self&: S, OpLoc, Bop);
15773 }
15774 }
15775}
15776
15777/// Look for bitwise op in the left or right hand of a bitwise op with
15778/// lower precedence and emit a diagnostic together with a fixit hint that wraps
15779/// the '&' expression in parentheses.
15780static void DiagnoseBitwiseOpInBitwiseOp(Sema &S, BinaryOperatorKind Opc,
15781 SourceLocation OpLoc, Expr *SubExpr) {
15782 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(Val: SubExpr)) {
15783 if (Bop->isBitwiseOp() && Bop->getOpcode() < Opc) {
15784 S.Diag(Loc: Bop->getOperatorLoc(), DiagID: diag::warn_bitwise_op_in_bitwise_op)
15785 << Bop->getOpcodeStr() << BinaryOperator::getOpcodeStr(Op: Opc)
15786 << Bop->getSourceRange() << OpLoc;
15787 SuggestParentheses(Self&: S, Loc: Bop->getOperatorLoc(),
15788 Note: S.PDiag(DiagID: diag::note_precedence_silence)
15789 << Bop->getOpcodeStr(),
15790 ParenRange: Bop->getSourceRange());
15791 }
15792 }
15793}
15794
15795static void DiagnoseAdditionInShift(Sema &S, SourceLocation OpLoc,
15796 Expr *SubExpr, StringRef Shift) {
15797 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(Val: SubExpr)) {
15798 if (Bop->getOpcode() == BO_Add || Bop->getOpcode() == BO_Sub) {
15799 StringRef Op = Bop->getOpcodeStr();
15800 S.Diag(Loc: Bop->getOperatorLoc(), DiagID: diag::warn_addition_in_bitshift)
15801 << Bop->getSourceRange() << OpLoc << Shift << Op;
15802 SuggestParentheses(Self&: S, Loc: Bop->getOperatorLoc(),
15803 Note: S.PDiag(DiagID: diag::note_precedence_silence) << Op,
15804 ParenRange: Bop->getSourceRange());
15805 }
15806 }
15807}
15808
15809static void DiagnoseShiftCompare(Sema &S, SourceLocation OpLoc,
15810 Expr *LHSExpr, Expr *RHSExpr) {
15811 CXXOperatorCallExpr *OCE = dyn_cast<CXXOperatorCallExpr>(Val: LHSExpr);
15812 if (!OCE)
15813 return;
15814
15815 FunctionDecl *FD = OCE->getDirectCallee();
15816 if (!FD || !FD->isOverloadedOperator())
15817 return;
15818
15819 OverloadedOperatorKind Kind = FD->getOverloadedOperator();
15820 if (Kind != OO_LessLess && Kind != OO_GreaterGreater)
15821 return;
15822
15823 S.Diag(Loc: OpLoc, DiagID: diag::warn_overloaded_shift_in_comparison)
15824 << LHSExpr->getSourceRange() << RHSExpr->getSourceRange()
15825 << (Kind == OO_LessLess);
15826 SuggestParentheses(Self&: S, Loc: OCE->getOperatorLoc(),
15827 Note: S.PDiag(DiagID: diag::note_precedence_silence)
15828 << (Kind == OO_LessLess ? "<<" : ">>"),
15829 ParenRange: OCE->getSourceRange());
15830 SuggestParentheses(
15831 Self&: S, Loc: OpLoc, Note: S.PDiag(DiagID: diag::note_evaluate_comparison_first),
15832 ParenRange: SourceRange(OCE->getArg(Arg: 1)->getBeginLoc(), RHSExpr->getEndLoc()));
15833}
15834
15835/// DiagnoseBinOpPrecedence - Emit warnings for expressions with tricky
15836/// precedence.
15837static void DiagnoseBinOpPrecedence(Sema &Self, BinaryOperatorKind Opc,
15838 SourceLocation OpLoc, Expr *LHSExpr,
15839 Expr *RHSExpr){
15840 // Diagnose "arg1 'bitwise' arg2 'eq' arg3".
15841 if (BinaryOperator::isBitwiseOp(Opc))
15842 DiagnoseBitwisePrecedence(Self, Opc, OpLoc, LHSExpr, RHSExpr);
15843
15844 // Diagnose "arg1 & arg2 | arg3"
15845 if ((Opc == BO_Or || Opc == BO_Xor) &&
15846 !OpLoc.isMacroID()/* Don't warn in macros. */) {
15847 DiagnoseBitwiseOpInBitwiseOp(S&: Self, Opc, OpLoc, SubExpr: LHSExpr);
15848 DiagnoseBitwiseOpInBitwiseOp(S&: Self, Opc, OpLoc, SubExpr: RHSExpr);
15849 }
15850
15851 // Warn about arg1 || arg2 && arg3, as GCC 4.3+ does.
15852 // We don't warn for 'assert(a || b && "bad")' since this is safe.
15853 if (Opc == BO_LOr && !OpLoc.isMacroID()/* Don't warn in macros. */) {
15854 DiagnoseLogicalAndInLogicalOrLHS(S&: Self, OpLoc, LHSExpr, RHSExpr);
15855 DiagnoseLogicalAndInLogicalOrRHS(S&: Self, OpLoc, LHSExpr, RHSExpr);
15856 }
15857
15858 if ((Opc == BO_Shl && LHSExpr->getType()->isIntegralType(Ctx: Self.getASTContext()))
15859 || Opc == BO_Shr) {
15860 StringRef Shift = BinaryOperator::getOpcodeStr(Op: Opc);
15861 DiagnoseAdditionInShift(S&: Self, OpLoc, SubExpr: LHSExpr, Shift);
15862 DiagnoseAdditionInShift(S&: Self, OpLoc, SubExpr: RHSExpr, Shift);
15863 }
15864
15865 // Warn on overloaded shift operators and comparisons, such as:
15866 // cout << 5 == 4;
15867 if (BinaryOperator::isComparisonOp(Opc))
15868 DiagnoseShiftCompare(S&: Self, OpLoc, LHSExpr, RHSExpr);
15869}
15870
15871ExprResult Sema::ActOnBinOp(Scope *S, SourceLocation TokLoc,
15872 tok::TokenKind Kind,
15873 Expr *LHSExpr, Expr *RHSExpr) {
15874 BinaryOperatorKind Opc = ConvertTokenKindToBinaryOpcode(Kind);
15875 assert(LHSExpr && "ActOnBinOp(): missing left expression");
15876 assert(RHSExpr && "ActOnBinOp(): missing right expression");
15877
15878 // Emit warnings for tricky precedence issues, e.g. "bitfield & 0x4 == 0"
15879 DiagnoseBinOpPrecedence(Self&: *this, Opc, OpLoc: TokLoc, LHSExpr, RHSExpr);
15880
15881 BuiltinCountedByRefKind K = BinaryOperator::isAssignmentOp(Opc)
15882 ? BuiltinCountedByRefKind::Assignment
15883 : BuiltinCountedByRefKind::BinaryExpr;
15884
15885 CheckInvalidBuiltinCountedByRef(E: LHSExpr, K);
15886 CheckInvalidBuiltinCountedByRef(E: RHSExpr, K);
15887
15888 return BuildBinOp(S, OpLoc: TokLoc, Opc, LHSExpr, RHSExpr);
15889}
15890
15891void Sema::LookupBinOp(Scope *S, SourceLocation OpLoc, BinaryOperatorKind Opc,
15892 UnresolvedSetImpl &Functions) {
15893 OverloadedOperatorKind OverOp = BinaryOperator::getOverloadedOperator(Opc);
15894 if (OverOp != OO_None && OverOp != OO_Equal)
15895 LookupOverloadedOperatorName(Op: OverOp, S, Functions);
15896
15897 // In C++20 onwards, we may have a second operator to look up.
15898 if (getLangOpts().CPlusPlus20) {
15899 if (OverloadedOperatorKind ExtraOp = getRewrittenOverloadedOperator(Kind: OverOp))
15900 LookupOverloadedOperatorName(Op: ExtraOp, S, Functions);
15901 }
15902}
15903
15904/// Build an overloaded binary operator expression in the given scope.
15905static ExprResult BuildOverloadedBinOp(Sema &S, Scope *Sc, SourceLocation OpLoc,
15906 BinaryOperatorKind Opc,
15907 Expr *LHS, Expr *RHS) {
15908 switch (Opc) {
15909 case BO_Assign:
15910 // In the non-overloaded case, we warn about self-assignment (x = x) for
15911 // both simple assignment and certain compound assignments where algebra
15912 // tells us the operation yields a constant result. When the operator is
15913 // overloaded, we can't do the latter because we don't want to assume that
15914 // those algebraic identities still apply; for example, a path-building
15915 // library might use operator/= to append paths. But it's still reasonable
15916 // to assume that simple assignment is just moving/copying values around
15917 // and so self-assignment is likely a bug.
15918 DiagnoseSelfAssignment(S, LHSExpr: LHS, RHSExpr: RHS, OpLoc, IsBuiltin: false);
15919 [[fallthrough]];
15920 case BO_DivAssign:
15921 case BO_RemAssign:
15922 case BO_SubAssign:
15923 case BO_AndAssign:
15924 case BO_OrAssign:
15925 case BO_XorAssign:
15926 CheckIdentityFieldAssignment(LHSExpr: LHS, RHSExpr: RHS, Loc: OpLoc, Sema&: S);
15927 break;
15928 default:
15929 break;
15930 }
15931
15932 // Find all of the overloaded operators visible from this point.
15933 UnresolvedSet<16> Functions;
15934 S.LookupBinOp(S: Sc, OpLoc, Opc, Functions);
15935
15936 // Build the (potentially-overloaded, potentially-dependent)
15937 // binary operation.
15938 return S.CreateOverloadedBinOp(OpLoc, Opc, Fns: Functions, LHS, RHS);
15939}
15940
15941ExprResult Sema::BuildBinOp(Scope *S, SourceLocation OpLoc,
15942 BinaryOperatorKind Opc, Expr *LHSExpr,
15943 Expr *RHSExpr, bool ForFoldExpression) {
15944 if (!LHSExpr || !RHSExpr)
15945 return ExprError();
15946
15947 // We want to end up calling one of SemaPseudoObject::checkAssignment
15948 // (if the LHS is a pseudo-object), BuildOverloadedBinOp (if
15949 // both expressions are overloadable or either is type-dependent),
15950 // or CreateBuiltinBinOp (in any other case). We also want to get
15951 // any placeholder types out of the way.
15952
15953 // Handle pseudo-objects in the LHS.
15954 if (const BuiltinType *pty = LHSExpr->getType()->getAsPlaceholderType()) {
15955 // Assignments with a pseudo-object l-value need special analysis.
15956 if (pty->getKind() == BuiltinType::PseudoObject &&
15957 BinaryOperator::isAssignmentOp(Opc))
15958 return PseudoObject().checkAssignment(S, OpLoc, Opcode: Opc, LHS: LHSExpr, RHS: RHSExpr);
15959
15960 // Don't resolve overloads if the other type is overloadable.
15961 if (getLangOpts().CPlusPlus && pty->getKind() == BuiltinType::Overload) {
15962 // We can't actually test that if we still have a placeholder,
15963 // though. Fortunately, none of the exceptions we see in that
15964 // code below are valid when the LHS is an overload set. Note
15965 // that an overload set can be dependently-typed, but it never
15966 // instantiates to having an overloadable type.
15967 ExprResult resolvedRHS = CheckPlaceholderExpr(E: RHSExpr);
15968 if (resolvedRHS.isInvalid()) return ExprError();
15969 RHSExpr = resolvedRHS.get();
15970
15971 if (RHSExpr->isTypeDependent() ||
15972 RHSExpr->getType()->isOverloadableType())
15973 return BuildOverloadedBinOp(S&: *this, Sc: S, OpLoc, Opc, LHS: LHSExpr, RHS: RHSExpr);
15974 }
15975
15976 // If we're instantiating "a.x < b" or "A::x < b" and 'x' names a function
15977 // template, diagnose the missing 'template' keyword instead of diagnosing
15978 // an invalid use of a bound member function.
15979 //
15980 // Note that "A::x < b" might be valid if 'b' has an overloadable type due
15981 // to C++1z [over.over]/1.4, but we already checked for that case above.
15982 if (Opc == BO_LT && inTemplateInstantiation() &&
15983 (pty->getKind() == BuiltinType::BoundMember ||
15984 pty->getKind() == BuiltinType::Overload)) {
15985 auto *OE = dyn_cast<OverloadExpr>(Val: LHSExpr);
15986 if (OE && !OE->hasTemplateKeyword() && !OE->hasExplicitTemplateArgs() &&
15987 llvm::any_of(Range: OE->decls(), P: [](NamedDecl *ND) {
15988 return isa<FunctionTemplateDecl>(Val: ND);
15989 })) {
15990 Diag(Loc: OE->getQualifier() ? OE->getQualifierLoc().getBeginLoc()
15991 : OE->getNameLoc(),
15992 DiagID: diag::err_template_kw_missing)
15993 << OE->getName().getAsIdentifierInfo();
15994 return ExprError();
15995 }
15996 }
15997
15998 ExprResult LHS = CheckPlaceholderExpr(E: LHSExpr);
15999 if (LHS.isInvalid()) return ExprError();
16000 LHSExpr = LHS.get();
16001 }
16002
16003 // Handle pseudo-objects in the RHS.
16004 if (const BuiltinType *pty = RHSExpr->getType()->getAsPlaceholderType()) {
16005 // An overload in the RHS can potentially be resolved by the type
16006 // being assigned to.
16007 if (Opc == BO_Assign && pty->getKind() == BuiltinType::Overload) {
16008 if (getLangOpts().CPlusPlus &&
16009 (LHSExpr->isTypeDependent() || RHSExpr->isTypeDependent() ||
16010 LHSExpr->getType()->isOverloadableType()))
16011 return BuildOverloadedBinOp(S&: *this, Sc: S, OpLoc, Opc, LHS: LHSExpr, RHS: RHSExpr);
16012
16013 return CreateBuiltinBinOp(OpLoc, Opc, LHSExpr, RHSExpr,
16014 ForFoldExpression);
16015 }
16016
16017 // Don't resolve overloads if the other type is overloadable.
16018 if (getLangOpts().CPlusPlus && pty->getKind() == BuiltinType::Overload &&
16019 LHSExpr->getType()->isOverloadableType())
16020 return BuildOverloadedBinOp(S&: *this, Sc: S, OpLoc, Opc, LHS: LHSExpr, RHS: RHSExpr);
16021
16022 ExprResult resolvedRHS = CheckPlaceholderExpr(E: RHSExpr);
16023 if (!resolvedRHS.isUsable()) return ExprError();
16024 RHSExpr = resolvedRHS.get();
16025 }
16026
16027 if (getLangOpts().HLSL && (LHSExpr->getType()->isHLSLResourceRecord() ||
16028 LHSExpr->getType()->isHLSLResourceRecordArray())) {
16029 if (!HLSL().CheckResourceBinOp(Opc, LHSExpr, RHSExpr, Loc: OpLoc))
16030 return ExprError();
16031 }
16032
16033 if (getLangOpts().CPlusPlus) {
16034 // Otherwise, build an overloaded op if either expression is type-dependent
16035 // or has an overloadable type.
16036 if (LHSExpr->isTypeDependent() || RHSExpr->isTypeDependent() ||
16037 LHSExpr->getType()->isOverloadableType() ||
16038 RHSExpr->getType()->isOverloadableType())
16039 return BuildOverloadedBinOp(S&: *this, Sc: S, OpLoc, Opc, LHS: LHSExpr, RHS: RHSExpr);
16040 }
16041
16042 if (getLangOpts().RecoveryAST &&
16043 (LHSExpr->isTypeDependent() || RHSExpr->isTypeDependent())) {
16044 assert(!getLangOpts().CPlusPlus);
16045 assert((LHSExpr->containsErrors() || RHSExpr->containsErrors()) &&
16046 "Should only occur in error-recovery path.");
16047 if (BinaryOperator::isCompoundAssignmentOp(Opc))
16048 // C [6.15.16] p3:
16049 // An assignment expression has the value of the left operand after the
16050 // assignment, but is not an lvalue.
16051 return CompoundAssignOperator::Create(
16052 C: Context, lhs: LHSExpr, rhs: RHSExpr, opc: Opc,
16053 ResTy: LHSExpr->getType().getUnqualifiedType(), VK: VK_PRValue, OK: OK_Ordinary,
16054 opLoc: OpLoc, FPFeatures: CurFPFeatureOverrides());
16055 QualType ResultType;
16056 switch (Opc) {
16057 case BO_Assign:
16058 ResultType = LHSExpr->getType().getUnqualifiedType();
16059 break;
16060 case BO_LT:
16061 case BO_GT:
16062 case BO_LE:
16063 case BO_GE:
16064 case BO_EQ:
16065 case BO_NE:
16066 case BO_LAnd:
16067 case BO_LOr:
16068 // These operators have a fixed result type regardless of operands.
16069 ResultType = Context.IntTy;
16070 break;
16071 case BO_Comma:
16072 ResultType = RHSExpr->getType();
16073 break;
16074 default:
16075 ResultType = Context.DependentTy;
16076 break;
16077 }
16078 return BinaryOperator::Create(C: Context, lhs: LHSExpr, rhs: RHSExpr, opc: Opc, ResTy: ResultType,
16079 VK: VK_PRValue, OK: OK_Ordinary, opLoc: OpLoc,
16080 FPFeatures: CurFPFeatureOverrides());
16081 }
16082
16083 // Build a built-in binary operation.
16084 return CreateBuiltinBinOp(OpLoc, Opc, LHSExpr, RHSExpr, ForFoldExpression);
16085}
16086
16087static bool isOverflowingIntegerType(ASTContext &Ctx, QualType T) {
16088 if (T.isNull() || T->isDependentType())
16089 return false;
16090
16091 if (!Ctx.isPromotableIntegerType(T))
16092 return true;
16093
16094 return Ctx.getIntWidth(T) >= Ctx.getIntWidth(T: Ctx.IntTy);
16095}
16096
16097ExprResult Sema::CreateBuiltinUnaryOp(SourceLocation OpLoc,
16098 UnaryOperatorKind Opc, Expr *InputExpr,
16099 bool IsAfterAmp) {
16100 ExprResult Input = InputExpr;
16101 ExprValueKind VK = VK_PRValue;
16102 ExprObjectKind OK = OK_Ordinary;
16103 QualType resultType;
16104 bool CanOverflow = false;
16105
16106 bool ConvertHalfVec = false;
16107 if (getLangOpts().OpenCL) {
16108 QualType Ty = InputExpr->getType();
16109 // The only legal unary operation for atomics is '&'.
16110 if ((Opc != UO_AddrOf && Ty->isAtomicType()) ||
16111 // OpenCL special types - image, sampler, pipe, and blocks are to be used
16112 // only with a builtin functions and therefore should be disallowed here.
16113 (Ty->isImageType() || Ty->isSamplerT() || Ty->isPipeType()
16114 || Ty->isBlockPointerType())) {
16115 return ExprError(Diag(Loc: OpLoc, DiagID: diag::err_typecheck_unary_expr)
16116 << InputExpr->getType()
16117 << Input.get()->getSourceRange());
16118 }
16119 }
16120
16121 if (getLangOpts().HLSL && OpLoc.isValid()) {
16122 if (Opc == UO_AddrOf)
16123 return ExprError(Diag(Loc: OpLoc, DiagID: diag::err_hlsl_operator_unsupported) << 0);
16124 if (Opc == UO_Deref)
16125 return ExprError(Diag(Loc: OpLoc, DiagID: diag::err_hlsl_operator_unsupported) << 1);
16126 }
16127
16128 if (InputExpr->isTypeDependent() &&
16129 InputExpr->getType()->isSpecificBuiltinType(K: BuiltinType::Dependent)) {
16130 resultType = Context.DependentTy;
16131 } else {
16132 switch (Opc) {
16133 case UO_PreInc:
16134 case UO_PreDec:
16135 case UO_PostInc:
16136 case UO_PostDec:
16137 resultType =
16138 CheckIncrementDecrementOperand(S&: *this, Op: Input.get(), VK, OK, OpLoc,
16139 IsInc: Opc == UO_PreInc || Opc == UO_PostInc,
16140 IsPrefix: Opc == UO_PreInc || Opc == UO_PreDec);
16141 CanOverflow = isOverflowingIntegerType(Ctx&: Context, T: resultType);
16142 break;
16143 case UO_AddrOf:
16144 resultType = CheckAddressOfOperand(OrigOp&: Input, OpLoc);
16145 CheckAddressOfNoDeref(E: InputExpr);
16146 RecordModifiableNonNullParam(S&: *this, Exp: InputExpr);
16147 break;
16148 case UO_Deref: {
16149 Input = DefaultFunctionArrayLvalueConversion(E: Input.get());
16150 if (Input.isInvalid())
16151 return ExprError();
16152 resultType =
16153 CheckIndirectionOperand(S&: *this, Op: Input.get(), VK, OpLoc, IsAfterAmp);
16154 break;
16155 }
16156 case UO_Plus:
16157 case UO_Minus:
16158 CanOverflow = Opc == UO_Minus &&
16159 isOverflowingIntegerType(Ctx&: Context, T: Input.get()->getType());
16160 Input = UsualUnaryConversions(E: Input.get());
16161 if (Input.isInvalid())
16162 return ExprError();
16163 // Unary plus and minus require promoting an operand of half vector to a
16164 // float vector and truncating the result back to a half vector. For now,
16165 // we do this only when HalfArgsAndReturns is set (that is, when the
16166 // target is arm or arm64).
16167 ConvertHalfVec = needsConversionOfHalfVec(OpRequiresConversion: true, Ctx&: Context, E0: Input.get());
16168
16169 // If the operand is a half vector, promote it to a float vector.
16170 if (ConvertHalfVec)
16171 Input = convertVector(E: Input.get(), ElementType: Context.FloatTy, S&: *this);
16172 resultType = Input.get()->getType();
16173 if (resultType->isArithmeticType()) // C99 6.5.3.3p1
16174 break;
16175 else if (resultType->isVectorType() &&
16176 // The z vector extensions don't allow + or - with bool vectors.
16177 (!Context.getLangOpts().ZVector ||
16178 resultType->castAs<VectorType>()->getVectorKind() !=
16179 VectorKind::AltiVecBool))
16180 break;
16181 else if (resultType->isSveVLSBuiltinType()) // SVE vectors allow + and -
16182 break;
16183 else if (getLangOpts().CPlusPlus && // C++ [expr.unary.op]p6
16184 Opc == UO_Plus && resultType->isPointerType())
16185 break;
16186
16187 return ExprError(Diag(Loc: OpLoc, DiagID: diag::err_typecheck_unary_expr)
16188 << resultType << Input.get()->getSourceRange());
16189
16190 case UO_Not: // bitwise complement
16191 Input = UsualUnaryConversions(E: Input.get());
16192 if (Input.isInvalid())
16193 return ExprError();
16194 resultType = Input.get()->getType();
16195 // C99 6.5.3.3p1. We allow complex int and float as a GCC extension.
16196 if (resultType->isComplexType() || resultType->isComplexIntegerType())
16197 // C99 does not support '~' for complex conjugation.
16198 Diag(Loc: OpLoc, DiagID: diag::ext_integer_complement_complex)
16199 << resultType << Input.get()->getSourceRange();
16200 else if (resultType->hasIntegerRepresentation())
16201 break;
16202 else if (resultType->isExtVectorType() && Context.getLangOpts().OpenCL) {
16203 // OpenCL v1.1 s6.3.f: The bitwise operator not (~) does not operate
16204 // on vector float types.
16205 QualType T = resultType->castAs<ExtVectorType>()->getElementType();
16206 if (!T->isIntegerType())
16207 return ExprError(Diag(Loc: OpLoc, DiagID: diag::err_typecheck_unary_expr)
16208 << resultType << Input.get()->getSourceRange());
16209 } else {
16210 return ExprError(Diag(Loc: OpLoc, DiagID: diag::err_typecheck_unary_expr)
16211 << resultType << Input.get()->getSourceRange());
16212 }
16213 break;
16214
16215 case UO_LNot: // logical negation
16216 // Unlike +/-/~, integer promotions aren't done here (C99 6.5.3.3p5).
16217 Input = DefaultFunctionArrayLvalueConversion(E: Input.get());
16218 if (Input.isInvalid())
16219 return ExprError();
16220 resultType = Input.get()->getType();
16221
16222 // Though we still have to promote half FP to float...
16223 if (resultType->isHalfType() && !Context.getLangOpts().NativeHalfType) {
16224 Input = ImpCastExprToType(E: Input.get(), Type: Context.FloatTy, CK: CK_FloatingCast)
16225 .get();
16226 resultType = Context.FloatTy;
16227 }
16228
16229 // WebAsembly tables can't be used in unary expressions.
16230 if (resultType->isPointerType() &&
16231 resultType->getPointeeType().isWebAssemblyReferenceType()) {
16232 return ExprError(Diag(Loc: OpLoc, DiagID: diag::err_typecheck_unary_expr)
16233 << resultType << Input.get()->getSourceRange());
16234 }
16235
16236 if (resultType->isScalarType() && !isScopedEnumerationType(T: resultType)) {
16237 // C99 6.5.3.3p1: ok, fallthrough;
16238 if (Context.getLangOpts().CPlusPlus) {
16239 // C++03 [expr.unary.op]p8, C++0x [expr.unary.op]p9:
16240 // operand contextually converted to bool.
16241 Input = ImpCastExprToType(E: Input.get(), Type: Context.BoolTy,
16242 CK: ScalarTypeToBooleanCastKind(ScalarTy: resultType));
16243 } else if (Context.getLangOpts().OpenCL &&
16244 Context.getLangOpts().OpenCLVersion < 120) {
16245 // OpenCL v1.1 6.3.h: The logical operator not (!) does not
16246 // operate on scalar float types.
16247 if (!resultType->isIntegerType() && !resultType->isPointerType())
16248 return ExprError(Diag(Loc: OpLoc, DiagID: diag::err_typecheck_unary_expr)
16249 << resultType << Input.get()->getSourceRange());
16250 }
16251 } else if (Context.getLangOpts().HLSL && resultType->isVectorType() &&
16252 !resultType->hasBooleanRepresentation()) {
16253 // HLSL unary logical 'not' behaves like C++, which states that the
16254 // operand is converted to bool and the result is bool, however HLSL
16255 // extends this property to vectors.
16256 const VectorType *VTy = resultType->castAs<VectorType>();
16257 resultType =
16258 Context.getExtVectorType(VectorType: Context.BoolTy, NumElts: VTy->getNumElements());
16259
16260 Input = ImpCastExprToType(
16261 E: Input.get(), Type: resultType,
16262 CK: ScalarTypeToBooleanCastKind(ScalarTy: VTy->getElementType()))
16263 .get();
16264 break;
16265 } else if (resultType->isExtVectorType()) {
16266 if (Context.getLangOpts().OpenCL &&
16267 Context.getLangOpts().getOpenCLCompatibleVersion() < 120) {
16268 // OpenCL v1.1 6.3.h: The logical operator not (!) does not
16269 // operate on vector float types.
16270 QualType T = resultType->castAs<ExtVectorType>()->getElementType();
16271 if (!T->isIntegerType())
16272 return ExprError(Diag(Loc: OpLoc, DiagID: diag::err_typecheck_unary_expr)
16273 << resultType << Input.get()->getSourceRange());
16274 }
16275 // Vector logical not returns the signed variant of the operand type.
16276 resultType = GetSignedVectorType(V: resultType);
16277 break;
16278 } else if (Context.getLangOpts().CPlusPlus &&
16279 resultType->isVectorType()) {
16280 const VectorType *VTy = resultType->castAs<VectorType>();
16281 if (VTy->getVectorKind() != VectorKind::Generic)
16282 return ExprError(Diag(Loc: OpLoc, DiagID: diag::err_typecheck_unary_expr)
16283 << resultType << Input.get()->getSourceRange());
16284
16285 // Vector logical not returns the signed variant of the operand type.
16286 resultType = GetSignedVectorType(V: resultType);
16287 break;
16288 } else {
16289 return ExprError(Diag(Loc: OpLoc, DiagID: diag::err_typecheck_unary_expr)
16290 << resultType << Input.get()->getSourceRange());
16291 }
16292
16293 // LNot always has type int. C99 6.5.3.3p5.
16294 // In C++, it's bool. C++ 5.3.1p8
16295 resultType = Context.getLogicalOperationType();
16296 break;
16297 case UO_Real:
16298 case UO_Imag:
16299 resultType = CheckRealImagOperand(S&: *this, V&: Input, Loc: OpLoc, IsReal: Opc == UO_Real);
16300 // _Real maps ordinary l-values into ordinary l-values. _Imag maps
16301 // ordinary complex l-values to ordinary l-values and all other values to
16302 // r-values.
16303 if (Input.isInvalid())
16304 return ExprError();
16305 if (Opc == UO_Real || Input.get()->getType()->isAnyComplexType()) {
16306 if (Input.get()->isGLValue() &&
16307 Input.get()->getObjectKind() == OK_Ordinary)
16308 VK = Input.get()->getValueKind();
16309 } else if (!getLangOpts().CPlusPlus) {
16310 // In C, a volatile scalar is read by __imag. In C++, it is not.
16311 Input = DefaultLvalueConversion(E: Input.get());
16312 }
16313 break;
16314 case UO_Extension:
16315 resultType = Input.get()->getType();
16316 VK = Input.get()->getValueKind();
16317 OK = Input.get()->getObjectKind();
16318 break;
16319 case UO_Coawait:
16320 // It's unnecessary to represent the pass-through operator co_await in the
16321 // AST; just return the input expression instead.
16322 assert(!Input.get()->getType()->isDependentType() &&
16323 "the co_await expression must be non-dependant before "
16324 "building operator co_await");
16325 return Input;
16326 }
16327 }
16328 if (resultType.isNull() || Input.isInvalid())
16329 return ExprError();
16330
16331 // Check for array bounds violations in the operand of the UnaryOperator,
16332 // except for the '*' and '&' operators that have to be handled specially
16333 // by CheckArrayAccess (as there are special cases like &array[arraysize]
16334 // that are explicitly defined as valid by the standard).
16335 if (Opc != UO_AddrOf && Opc != UO_Deref)
16336 CheckArrayAccess(E: Input.get());
16337
16338 auto *UO =
16339 UnaryOperator::Create(C: Context, input: Input.get(), opc: Opc, type: resultType, VK, OK,
16340 l: OpLoc, CanOverflow, FPFeatures: CurFPFeatureOverrides());
16341
16342 if (Opc == UO_Deref && UO->getType()->hasAttr(AK: attr::NoDeref) &&
16343 !isa<ArrayType>(Val: UO->getType().getDesugaredType(Context)) &&
16344 !isUnevaluatedContext())
16345 ExprEvalContexts.back().PossibleDerefs.insert(Ptr: UO);
16346
16347 // Convert the result back to a half vector.
16348 if (ConvertHalfVec)
16349 return convertVector(E: UO, ElementType: Context.HalfTy, S&: *this);
16350 return UO;
16351}
16352
16353bool Sema::isQualifiedMemberAccess(Expr *E) {
16354 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Val: E)) {
16355 if (!DRE->getQualifier())
16356 return false;
16357
16358 ValueDecl *VD = DRE->getDecl();
16359 if (!VD->isCXXClassMember())
16360 return false;
16361
16362 if (isa<FieldDecl>(Val: VD) || isa<IndirectFieldDecl>(Val: VD))
16363 return true;
16364 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Val: VD))
16365 return Method->isImplicitObjectMemberFunction();
16366
16367 return false;
16368 }
16369
16370 if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(Val: E)) {
16371 if (!ULE->getQualifier())
16372 return false;
16373
16374 for (NamedDecl *D : ULE->decls()) {
16375 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Val: D)) {
16376 if (Method->isImplicitObjectMemberFunction())
16377 return true;
16378 } else {
16379 // Overload set does not contain methods.
16380 break;
16381 }
16382 }
16383
16384 return false;
16385 }
16386
16387 return false;
16388}
16389
16390ExprResult Sema::BuildUnaryOp(Scope *S, SourceLocation OpLoc,
16391 UnaryOperatorKind Opc, Expr *Input,
16392 bool IsAfterAmp) {
16393 // First things first: handle placeholders so that the
16394 // overloaded-operator check considers the right type.
16395 if (const BuiltinType *pty = Input->getType()->getAsPlaceholderType()) {
16396 // Increment and decrement of pseudo-object references.
16397 if (pty->getKind() == BuiltinType::PseudoObject &&
16398 UnaryOperator::isIncrementDecrementOp(Op: Opc))
16399 return PseudoObject().checkIncDec(S, OpLoc, Opcode: Opc, Op: Input);
16400
16401 // extension is always a builtin operator.
16402 if (Opc == UO_Extension)
16403 return CreateBuiltinUnaryOp(OpLoc, Opc, InputExpr: Input);
16404
16405 // & gets special logic for several kinds of placeholder.
16406 // The builtin code knows what to do.
16407 if (Opc == UO_AddrOf &&
16408 (pty->getKind() == BuiltinType::Overload ||
16409 pty->getKind() == BuiltinType::UnknownAny ||
16410 pty->getKind() == BuiltinType::BoundMember))
16411 return CreateBuiltinUnaryOp(OpLoc, Opc, InputExpr: Input);
16412
16413 // Anything else needs to be handled now.
16414 ExprResult Result = CheckPlaceholderExpr(E: Input);
16415 if (Result.isInvalid()) return ExprError();
16416 Input = Result.get();
16417 }
16418
16419 if (getLangOpts().CPlusPlus && Input->getType()->isOverloadableType() &&
16420 UnaryOperator::getOverloadedOperator(Opc) != OO_None &&
16421 !(Opc == UO_AddrOf && isQualifiedMemberAccess(E: Input))) {
16422 // Find all of the overloaded operators visible from this point.
16423 UnresolvedSet<16> Functions;
16424 OverloadedOperatorKind OverOp = UnaryOperator::getOverloadedOperator(Opc);
16425 if (S && OverOp != OO_None)
16426 LookupOverloadedOperatorName(Op: OverOp, S, Functions);
16427
16428 return CreateOverloadedUnaryOp(OpLoc, Opc, Fns: Functions, input: Input);
16429 }
16430
16431 return CreateBuiltinUnaryOp(OpLoc, Opc, InputExpr: Input, IsAfterAmp);
16432}
16433
16434ExprResult Sema::ActOnUnaryOp(Scope *S, SourceLocation OpLoc, tok::TokenKind Op,
16435 Expr *Input, bool IsAfterAmp) {
16436 return BuildUnaryOp(S, OpLoc, Opc: ConvertTokenKindToUnaryOpcode(Kind: Op), Input,
16437 IsAfterAmp);
16438}
16439
16440ExprResult Sema::ActOnAddrLabel(SourceLocation OpLoc, SourceLocation LabLoc,
16441 LabelDecl *TheDecl) {
16442 TheDecl->markUsed(C&: Context);
16443 // Create the AST node. The address of a label always has type 'void*'.
16444 auto *Res = new (Context) AddrLabelExpr(
16445 OpLoc, LabLoc, TheDecl, Context.getPointerType(T: Context.VoidTy));
16446
16447 if (getCurFunction())
16448 getCurFunction()->AddrLabels.push_back(Elt: Res);
16449
16450 return Res;
16451}
16452
16453void Sema::ActOnStartStmtExpr() {
16454 PushExpressionEvaluationContext(NewContext: ExprEvalContexts.back().Context);
16455 // Make sure we diagnose jumping into a statement expression.
16456 setFunctionHasBranchProtectedScope();
16457}
16458
16459void Sema::ActOnStmtExprError() {
16460 // Note that function is also called by TreeTransform when leaving a
16461 // StmtExpr scope without rebuilding anything.
16462
16463 DiscardCleanupsInEvaluationContext();
16464 PopExpressionEvaluationContext();
16465}
16466
16467ExprResult Sema::ActOnStmtExpr(Scope *S, SourceLocation LPLoc, Stmt *SubStmt,
16468 SourceLocation RPLoc) {
16469 return BuildStmtExpr(LPLoc, SubStmt, RPLoc, TemplateDepth: getTemplateDepth(S));
16470}
16471
16472ExprResult Sema::BuildStmtExpr(SourceLocation LPLoc, Stmt *SubStmt,
16473 SourceLocation RPLoc, unsigned TemplateDepth) {
16474 assert(SubStmt && isa<CompoundStmt>(SubStmt) && "Invalid action invocation!");
16475 CompoundStmt *Compound = cast<CompoundStmt>(Val: SubStmt);
16476
16477 if (hasAnyUnrecoverableErrorsInThisFunction())
16478 DiscardCleanupsInEvaluationContext();
16479 assert(!Cleanup.exprNeedsCleanups() &&
16480 "cleanups within StmtExpr not correctly bound!");
16481 PopExpressionEvaluationContext();
16482
16483 // FIXME: there are a variety of strange constraints to enforce here, for
16484 // example, it is not possible to goto into a stmt expression apparently.
16485 // More semantic analysis is needed.
16486
16487 // If there are sub-stmts in the compound stmt, take the type of the last one
16488 // as the type of the stmtexpr.
16489 QualType Ty = Context.VoidTy;
16490 bool StmtExprMayBindToTemp = false;
16491 if (!Compound->body_empty()) {
16492 if (const auto *LastStmt = dyn_cast<ValueStmt>(Val: Compound->body_back())) {
16493 if (const Expr *Value = LastStmt->getExprStmt()) {
16494 StmtExprMayBindToTemp = true;
16495 Ty = Value->getType();
16496 }
16497 }
16498 }
16499
16500 // FIXME: Check that expression type is complete/non-abstract; statement
16501 // expressions are not lvalues.
16502 Expr *ResStmtExpr =
16503 new (Context) StmtExpr(Compound, Ty, LPLoc, RPLoc, TemplateDepth);
16504 if (StmtExprMayBindToTemp)
16505 return MaybeBindToTemporary(E: ResStmtExpr);
16506 return ResStmtExpr;
16507}
16508
16509ExprResult Sema::ActOnStmtExprResult(ExprResult ER) {
16510 if (ER.isInvalid())
16511 return ExprError();
16512
16513 // Do function/array conversion on the last expression, but not
16514 // lvalue-to-rvalue. However, initialize an unqualified type.
16515 ER = DefaultFunctionArrayConversion(E: ER.get());
16516 if (ER.isInvalid())
16517 return ExprError();
16518 Expr *E = ER.get();
16519
16520 if (E->isTypeDependent())
16521 return E;
16522
16523 // In ARC, if the final expression ends in a consume, splice
16524 // the consume out and bind it later. In the alternate case
16525 // (when dealing with a retainable type), the result
16526 // initialization will create a produce. In both cases the
16527 // result will be +1, and we'll need to balance that out with
16528 // a bind.
16529 auto *Cast = dyn_cast<ImplicitCastExpr>(Val: E);
16530 if (Cast && Cast->getCastKind() == CK_ARCConsumeObject)
16531 return Cast->getSubExpr();
16532
16533 // FIXME: Provide a better location for the initialization.
16534 return PerformCopyInitialization(
16535 Entity: InitializedEntity::InitializeStmtExprResult(
16536 ReturnLoc: E->getBeginLoc(), Type: E->getType().getAtomicUnqualifiedType()),
16537 EqualLoc: SourceLocation(), Init: E);
16538}
16539
16540ExprResult Sema::BuildBuiltinOffsetOf(SourceLocation BuiltinLoc,
16541 TypeSourceInfo *TInfo,
16542 ArrayRef<OffsetOfComponent> Components,
16543 SourceLocation RParenLoc) {
16544 QualType ArgTy = TInfo->getType();
16545 bool Dependent = ArgTy->isDependentType();
16546 SourceRange TypeRange = TInfo->getTypeLoc().getLocalSourceRange();
16547
16548 // We must have at least one component that refers to the type, and the first
16549 // one is known to be a field designator. Verify that the ArgTy represents
16550 // a struct/union/class.
16551 if (!Dependent && !ArgTy->isRecordType())
16552 return ExprError(Diag(Loc: BuiltinLoc, DiagID: diag::err_offsetof_record_type)
16553 << ArgTy << TypeRange);
16554
16555 // Type must be complete per C99 7.17p3 because a declaring a variable
16556 // with an incomplete type would be ill-formed.
16557 if (!Dependent
16558 && RequireCompleteType(Loc: BuiltinLoc, T: ArgTy,
16559 DiagID: diag::err_offsetof_incomplete_type, Args: TypeRange))
16560 return ExprError();
16561
16562 bool DidWarnAboutNonPOD = false;
16563 QualType CurrentType = ArgTy;
16564 SmallVector<OffsetOfNode, 4> Comps;
16565 SmallVector<Expr*, 4> Exprs;
16566 for (const OffsetOfComponent &OC : Components) {
16567 if (OC.isBrackets) {
16568 // Offset of an array sub-field. TODO: Should we allow vector elements?
16569 if (!CurrentType->isDependentType()) {
16570 const ArrayType *AT = Context.getAsArrayType(T: CurrentType);
16571 if(!AT)
16572 return ExprError(Diag(Loc: OC.LocEnd, DiagID: diag::err_offsetof_array_type)
16573 << CurrentType);
16574 CurrentType = AT->getElementType();
16575 } else
16576 CurrentType = Context.DependentTy;
16577
16578 ExprResult IdxRval = DefaultLvalueConversion(E: static_cast<Expr*>(OC.U.E));
16579 if (IdxRval.isInvalid())
16580 return ExprError();
16581 Expr *Idx = IdxRval.get();
16582
16583 // The expression must be an integral expression.
16584 // FIXME: An integral constant expression?
16585 if (!Idx->isTypeDependent() && !Idx->isValueDependent() &&
16586 !Idx->getType()->isIntegerType())
16587 return ExprError(
16588 Diag(Loc: Idx->getBeginLoc(), DiagID: diag::err_typecheck_subscript_not_integer)
16589 << Idx->getSourceRange());
16590
16591 // Record this array index.
16592 Comps.push_back(Elt: OffsetOfNode(OC.LocStart, Exprs.size(), OC.LocEnd));
16593 Exprs.push_back(Elt: Idx);
16594 continue;
16595 }
16596
16597 // Offset of a field.
16598 if (CurrentType->isDependentType()) {
16599 // We have the offset of a field, but we can't look into the dependent
16600 // type. Just record the identifier of the field.
16601 Comps.push_back(Elt: OffsetOfNode(OC.LocStart, OC.U.IdentInfo, OC.LocEnd));
16602 CurrentType = Context.DependentTy;
16603 continue;
16604 }
16605
16606 // We need to have a complete type to look into.
16607 if (RequireCompleteType(Loc: OC.LocStart, T: CurrentType,
16608 DiagID: diag::err_offsetof_incomplete_type))
16609 return ExprError();
16610
16611 // Look for the designated field.
16612 auto *RD = CurrentType->getAsRecordDecl();
16613 if (!RD)
16614 return ExprError(Diag(Loc: OC.LocEnd, DiagID: diag::err_offsetof_record_type)
16615 << CurrentType);
16616
16617 // C++ [lib.support.types]p5:
16618 // The macro offsetof accepts a restricted set of type arguments in this
16619 // International Standard. type shall be a POD structure or a POD union
16620 // (clause 9).
16621 // C++11 [support.types]p4:
16622 // If type is not a standard-layout class (Clause 9), the results are
16623 // undefined.
16624 if (CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(Val: RD)) {
16625 bool IsSafe = LangOpts.CPlusPlus11? CRD->isStandardLayout() : CRD->isPOD();
16626 unsigned DiagID =
16627 LangOpts.CPlusPlus11? diag::ext_offsetof_non_standardlayout_type
16628 : diag::ext_offsetof_non_pod_type;
16629
16630 if (!IsSafe && !DidWarnAboutNonPOD && !isUnevaluatedContext()) {
16631 Diag(Loc: BuiltinLoc, DiagID)
16632 << SourceRange(Components[0].LocStart, OC.LocEnd) << CurrentType;
16633 DidWarnAboutNonPOD = true;
16634 }
16635 }
16636
16637 // Look for the field.
16638 LookupResult R(*this, OC.U.IdentInfo, OC.LocStart, LookupMemberName);
16639 LookupQualifiedName(R, LookupCtx: RD);
16640 FieldDecl *MemberDecl = R.getAsSingle<FieldDecl>();
16641 IndirectFieldDecl *IndirectMemberDecl = nullptr;
16642 if (!MemberDecl) {
16643 if ((IndirectMemberDecl = R.getAsSingle<IndirectFieldDecl>()))
16644 MemberDecl = IndirectMemberDecl->getAnonField();
16645 }
16646
16647 if (!MemberDecl) {
16648 // Lookup could be ambiguous when looking up a placeholder variable
16649 // __builtin_offsetof(S, _).
16650 // In that case we would already have emitted a diagnostic
16651 if (!R.isAmbiguous())
16652 Diag(Loc: BuiltinLoc, DiagID: diag::err_no_member)
16653 << OC.U.IdentInfo << RD << SourceRange(OC.LocStart, OC.LocEnd);
16654 return ExprError();
16655 }
16656
16657 // C99 7.17p3:
16658 // (If the specified member is a bit-field, the behavior is undefined.)
16659 //
16660 // We diagnose this as an error.
16661 if (MemberDecl->isBitField()) {
16662 Diag(Loc: OC.LocEnd, DiagID: diag::err_offsetof_bitfield)
16663 << MemberDecl->getDeclName()
16664 << SourceRange(BuiltinLoc, RParenLoc);
16665 Diag(Loc: MemberDecl->getLocation(), DiagID: diag::note_bitfield_decl);
16666 return ExprError();
16667 }
16668
16669 RecordDecl *Parent = MemberDecl->getParent();
16670 if (IndirectMemberDecl)
16671 Parent = cast<RecordDecl>(Val: IndirectMemberDecl->getDeclContext());
16672
16673 // If the member was found in a base class, introduce OffsetOfNodes for
16674 // the base class indirections.
16675 CXXBasePaths Paths;
16676 if (IsDerivedFrom(Loc: OC.LocStart, Derived: CurrentType,
16677 Base: Context.getCanonicalTagType(TD: Parent), Paths)) {
16678 if (Paths.getDetectedVirtual()) {
16679 Diag(Loc: OC.LocEnd, DiagID: diag::err_offsetof_field_of_virtual_base)
16680 << MemberDecl->getDeclName()
16681 << SourceRange(BuiltinLoc, RParenLoc);
16682 return ExprError();
16683 }
16684
16685 CXXBasePath &Path = Paths.front();
16686 for (const CXXBasePathElement &B : Path)
16687 Comps.push_back(Elt: OffsetOfNode(B.Base));
16688 }
16689
16690 if (IndirectMemberDecl) {
16691 for (auto *FI : IndirectMemberDecl->chain()) {
16692 assert(isa<FieldDecl>(FI));
16693 Comps.push_back(Elt: OffsetOfNode(OC.LocStart,
16694 cast<FieldDecl>(Val: FI), OC.LocEnd));
16695 }
16696 } else
16697 Comps.push_back(Elt: OffsetOfNode(OC.LocStart, MemberDecl, OC.LocEnd));
16698
16699 CurrentType = MemberDecl->getType().getNonReferenceType();
16700 }
16701
16702 return OffsetOfExpr::Create(C: Context, type: Context.getSizeType(), OperatorLoc: BuiltinLoc, tsi: TInfo,
16703 comps: Comps, exprs: Exprs, RParenLoc);
16704}
16705
16706ExprResult Sema::ActOnBuiltinOffsetOf(Scope *S,
16707 SourceLocation BuiltinLoc,
16708 SourceLocation TypeLoc,
16709 ParsedType ParsedArgTy,
16710 ArrayRef<OffsetOfComponent> Components,
16711 SourceLocation RParenLoc) {
16712
16713 TypeSourceInfo *ArgTInfo;
16714 QualType ArgTy = GetTypeFromParser(Ty: ParsedArgTy, TInfo: &ArgTInfo);
16715 if (ArgTy.isNull())
16716 return ExprError();
16717
16718 if (!ArgTInfo)
16719 ArgTInfo = Context.getTrivialTypeSourceInfo(T: ArgTy, Loc: TypeLoc);
16720
16721 return BuildBuiltinOffsetOf(BuiltinLoc, TInfo: ArgTInfo, Components, RParenLoc);
16722}
16723
16724
16725ExprResult Sema::ActOnChooseExpr(SourceLocation BuiltinLoc,
16726 Expr *CondExpr,
16727 Expr *LHSExpr, Expr *RHSExpr,
16728 SourceLocation RPLoc) {
16729 assert((CondExpr && LHSExpr && RHSExpr) && "Missing type argument(s)");
16730
16731 ExprValueKind VK = VK_PRValue;
16732 ExprObjectKind OK = OK_Ordinary;
16733 QualType resType;
16734 bool CondIsTrue = false;
16735 if (CondExpr->isTypeDependent() || CondExpr->isValueDependent()) {
16736 resType = Context.DependentTy;
16737 } else {
16738 // The conditional expression is required to be a constant expression.
16739 llvm::APSInt condEval(32);
16740 ExprResult CondICE = VerifyIntegerConstantExpression(
16741 E: CondExpr, Result: &condEval, DiagID: diag::err_typecheck_choose_expr_requires_constant);
16742 if (CondICE.isInvalid())
16743 return ExprError();
16744 CondExpr = CondICE.get();
16745 CondIsTrue = condEval.getZExtValue();
16746
16747 // If the condition is > zero, then the AST type is the same as the LHSExpr.
16748 Expr *ActiveExpr = CondIsTrue ? LHSExpr : RHSExpr;
16749
16750 resType = ActiveExpr->getType();
16751 VK = ActiveExpr->getValueKind();
16752 OK = ActiveExpr->getObjectKind();
16753 }
16754
16755 return new (Context) ChooseExpr(BuiltinLoc, CondExpr, LHSExpr, RHSExpr,
16756 resType, VK, OK, RPLoc, CondIsTrue);
16757}
16758
16759//===----------------------------------------------------------------------===//
16760// Clang Extensions.
16761//===----------------------------------------------------------------------===//
16762
16763void Sema::ActOnBlockStart(SourceLocation CaretLoc, Scope *CurScope) {
16764 BlockDecl *Block = BlockDecl::Create(C&: Context, DC: CurContext, L: CaretLoc);
16765
16766 if (LangOpts.CPlusPlus) {
16767 MangleNumberingContext *MCtx;
16768 Decl *ManglingContextDecl;
16769 std::tie(args&: MCtx, args&: ManglingContextDecl) =
16770 getCurrentMangleNumberContext(DC: Block->getDeclContext());
16771 if (MCtx) {
16772 unsigned ManglingNumber = MCtx->getManglingNumber(BD: Block);
16773 Block->setBlockMangling(Number: ManglingNumber, Ctx: ManglingContextDecl);
16774 }
16775 }
16776
16777 PushBlockScope(BlockScope: CurScope, Block);
16778 CurContext->addDecl(D: Block);
16779 if (CurScope)
16780 PushDeclContext(S: CurScope, DC: Block);
16781 else
16782 CurContext = Block;
16783
16784 getCurBlock()->HasImplicitReturnType = true;
16785
16786 // Enter a new evaluation context to insulate the block from any
16787 // cleanups from the enclosing full-expression.
16788 PushExpressionEvaluationContext(
16789 NewContext: ExpressionEvaluationContext::PotentiallyEvaluated);
16790}
16791
16792void Sema::ActOnBlockArguments(SourceLocation CaretLoc, Declarator &ParamInfo,
16793 Scope *CurScope) {
16794 assert(ParamInfo.getIdentifier() == nullptr &&
16795 "block-id should have no identifier!");
16796 assert(ParamInfo.getContext() == DeclaratorContext::BlockLiteral);
16797 BlockScopeInfo *CurBlock = getCurBlock();
16798
16799 TypeSourceInfo *Sig = GetTypeForDeclarator(D&: ParamInfo);
16800 QualType T = Sig->getType();
16801 DiagnoseUnexpandedParameterPack(Loc: CaretLoc, T: Sig, UPPC: UPPC_Block);
16802
16803 // GetTypeForDeclarator always produces a function type for a block
16804 // literal signature. Furthermore, it is always a FunctionProtoType
16805 // unless the function was written with a typedef.
16806 assert(T->isFunctionType() &&
16807 "GetTypeForDeclarator made a non-function block signature");
16808
16809 // Look for an explicit signature in that function type.
16810 FunctionProtoTypeLoc ExplicitSignature;
16811
16812 if ((ExplicitSignature = Sig->getTypeLoc()
16813 .getAsAdjusted<FunctionProtoTypeLoc>())) {
16814
16815 // Check whether that explicit signature was synthesized by
16816 // GetTypeForDeclarator. If so, don't save that as part of the
16817 // written signature.
16818 if (ExplicitSignature.getLocalRangeBegin() ==
16819 ExplicitSignature.getLocalRangeEnd()) {
16820 // This would be much cheaper if we stored TypeLocs instead of
16821 // TypeSourceInfos.
16822 TypeLoc Result = ExplicitSignature.getReturnLoc();
16823 unsigned Size = Result.getFullDataSize();
16824 Sig = Context.CreateTypeSourceInfo(T: Result.getType(), Size);
16825 Sig->getTypeLoc().initializeFullCopy(Other: Result, Size);
16826
16827 ExplicitSignature = FunctionProtoTypeLoc();
16828 }
16829 }
16830
16831 CurBlock->TheDecl->setSignatureAsWritten(Sig);
16832 CurBlock->FunctionType = T;
16833
16834 const auto *Fn = T->castAs<FunctionType>();
16835 QualType RetTy = Fn->getReturnType();
16836 bool isVariadic =
16837 (isa<FunctionProtoType>(Val: Fn) && cast<FunctionProtoType>(Val: Fn)->isVariadic());
16838
16839 CurBlock->TheDecl->setIsVariadic(isVariadic);
16840
16841 // Context.DependentTy is used as a placeholder for a missing block
16842 // return type. TODO: what should we do with declarators like:
16843 // ^ * { ... }
16844 // If the answer is "apply template argument deduction"....
16845 if (RetTy != Context.DependentTy) {
16846 CurBlock->ReturnType = RetTy;
16847 CurBlock->TheDecl->setBlockMissingReturnType(false);
16848 CurBlock->HasImplicitReturnType = false;
16849 }
16850
16851 // Push block parameters from the declarator if we had them.
16852 SmallVector<ParmVarDecl*, 8> Params;
16853 if (ExplicitSignature) {
16854 for (unsigned I = 0, E = ExplicitSignature.getNumParams(); I != E; ++I) {
16855 ParmVarDecl *Param = ExplicitSignature.getParam(i: I);
16856 if (Param->getIdentifier() == nullptr && !Param->isImplicit() &&
16857 !Param->isInvalidDecl() && !getLangOpts().CPlusPlus) {
16858 // Diagnose this as an extension in C17 and earlier.
16859 if (!getLangOpts().C23)
16860 Diag(Loc: Param->getLocation(), DiagID: diag::ext_parameter_name_omitted_c23);
16861 }
16862 Params.push_back(Elt: Param);
16863 }
16864
16865 // Fake up parameter variables if we have a typedef, like
16866 // ^ fntype { ... }
16867 } else if (const FunctionProtoType *Fn = T->getAs<FunctionProtoType>()) {
16868 for (const auto &I : Fn->param_types()) {
16869 ParmVarDecl *Param = BuildParmVarDeclForTypedef(
16870 DC: CurBlock->TheDecl, Loc: ParamInfo.getBeginLoc(), T: I);
16871 Params.push_back(Elt: Param);
16872 }
16873 }
16874
16875 // Set the parameters on the block decl.
16876 if (!Params.empty()) {
16877 CurBlock->TheDecl->setParams(Params);
16878 CheckParmsForFunctionDef(Parameters: CurBlock->TheDecl->parameters(),
16879 /*CheckParameterNames=*/false);
16880 }
16881
16882 // Finally we can process decl attributes.
16883 ProcessDeclAttributes(S: CurScope, D: CurBlock->TheDecl, PD: ParamInfo);
16884
16885 // Put the parameter variables in scope.
16886 for (auto *AI : CurBlock->TheDecl->parameters()) {
16887 AI->setOwningFunction(CurBlock->TheDecl);
16888
16889 // If this has an identifier, add it to the scope stack.
16890 if (AI->getIdentifier()) {
16891 CheckShadow(S: CurBlock->TheScope, D: AI);
16892
16893 PushOnScopeChains(D: AI, S: CurBlock->TheScope);
16894 }
16895
16896 if (AI->isInvalidDecl())
16897 CurBlock->TheDecl->setInvalidDecl();
16898 }
16899}
16900
16901void Sema::ActOnBlockError(SourceLocation CaretLoc, Scope *CurScope) {
16902 // Leave the expression-evaluation context.
16903 DiscardCleanupsInEvaluationContext();
16904 PopExpressionEvaluationContext();
16905
16906 // Pop off CurBlock, handle nested blocks.
16907 PopDeclContext();
16908 PopFunctionScopeInfo();
16909}
16910
16911ExprResult Sema::ActOnBlockStmtExpr(SourceLocation CaretLoc,
16912 Stmt *Body, Scope *CurScope) {
16913 // If blocks are disabled, emit an error.
16914 if (!LangOpts.Blocks)
16915 Diag(Loc: CaretLoc, DiagID: diag::err_blocks_disable) << LangOpts.OpenCL;
16916
16917 // Leave the expression-evaluation context.
16918 if (hasAnyUnrecoverableErrorsInThisFunction())
16919 DiscardCleanupsInEvaluationContext();
16920 assert(!Cleanup.exprNeedsCleanups() &&
16921 "cleanups within block not correctly bound!");
16922 PopExpressionEvaluationContext();
16923
16924 BlockScopeInfo *BSI = cast<BlockScopeInfo>(Val: FunctionScopes.back());
16925 BlockDecl *BD = BSI->TheDecl;
16926
16927 maybeAddDeclWithEffects(D: BD);
16928
16929 if (BSI->HasImplicitReturnType)
16930 deduceClosureReturnType(CSI&: *BSI);
16931
16932 QualType RetTy = Context.VoidTy;
16933 if (!BSI->ReturnType.isNull())
16934 RetTy = BSI->ReturnType;
16935
16936 bool NoReturn = BD->hasAttr<NoReturnAttr>();
16937 QualType BlockTy;
16938
16939 // If the user wrote a function type in some form, try to use that.
16940 if (!BSI->FunctionType.isNull()) {
16941 const FunctionType *FTy = BSI->FunctionType->castAs<FunctionType>();
16942
16943 FunctionType::ExtInfo Ext = FTy->getExtInfo();
16944 if (NoReturn && !Ext.getNoReturn()) Ext = Ext.withNoReturn(noReturn: true);
16945
16946 // Turn protoless block types into nullary block types.
16947 if (isa<FunctionNoProtoType>(Val: FTy)) {
16948 FunctionProtoType::ExtProtoInfo EPI;
16949 EPI.ExtInfo = Ext;
16950 BlockTy = Context.getFunctionType(ResultTy: RetTy, Args: {}, EPI);
16951
16952 // Otherwise, if we don't need to change anything about the function type,
16953 // preserve its sugar structure.
16954 } else if (FTy->getReturnType() == RetTy &&
16955 (!NoReturn || FTy->getNoReturnAttr())) {
16956 BlockTy = BSI->FunctionType;
16957
16958 // Otherwise, make the minimal modifications to the function type.
16959 } else {
16960 const FunctionProtoType *FPT = cast<FunctionProtoType>(Val: FTy);
16961 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
16962 EPI.TypeQuals = Qualifiers();
16963 EPI.ExtInfo = Ext;
16964 BlockTy = Context.getFunctionType(ResultTy: RetTy, Args: FPT->getParamTypes(), EPI);
16965 }
16966
16967 // If we don't have a function type, just build one from nothing.
16968 } else {
16969 FunctionProtoType::ExtProtoInfo EPI;
16970 EPI.ExtInfo = FunctionType::ExtInfo().withNoReturn(noReturn: NoReturn);
16971 BlockTy = Context.getFunctionType(ResultTy: RetTy, Args: {}, EPI);
16972 }
16973
16974 DiagnoseUnusedParameters(Parameters: BD->parameters());
16975 BlockTy = Context.getBlockPointerType(T: BlockTy);
16976
16977 // If needed, diagnose invalid gotos and switches in the block.
16978 if (getCurFunction()->NeedsScopeChecking() &&
16979 !PP.isCodeCompletionEnabled())
16980 DiagnoseInvalidJumps(Body: cast<CompoundStmt>(Val: Body));
16981
16982 BD->setBody(cast<CompoundStmt>(Val: Body));
16983
16984 if (Body && getCurFunction()->HasPotentialAvailabilityViolations)
16985 DiagnoseUnguardedAvailabilityViolations(FD: BD);
16986
16987 // Try to apply the named return value optimization. We have to check again
16988 // if we can do this, though, because blocks keep return statements around
16989 // to deduce an implicit return type.
16990 if (getLangOpts().CPlusPlus && RetTy->isRecordType() &&
16991 !BD->isDependentContext())
16992 computeNRVO(Body, Scope: BSI);
16993
16994 if (RetTy.hasNonTrivialToPrimitiveDestructCUnion() ||
16995 RetTy.hasNonTrivialToPrimitiveCopyCUnion())
16996 checkNonTrivialCUnion(QT: RetTy, Loc: BD->getCaretLocation(),
16997 UseContext: NonTrivialCUnionContext::FunctionReturn,
16998 NonTrivialKind: NTCUK_Destruct | NTCUK_Copy);
16999
17000 PopDeclContext();
17001
17002 // Set the captured variables on the block.
17003 SmallVector<BlockDecl::Capture, 4> Captures;
17004 for (Capture &Cap : BSI->Captures) {
17005 if (Cap.isInvalid() || Cap.isThisCapture())
17006 continue;
17007 // Cap.getVariable() is always a VarDecl because
17008 // blocks cannot capture structured bindings or other ValueDecl kinds.
17009 auto *Var = cast<VarDecl>(Val: Cap.getVariable());
17010 Expr *CopyExpr = nullptr;
17011 if (getLangOpts().CPlusPlus && Cap.isCopyCapture()) {
17012 if (auto *Record = Cap.getCaptureType()->getAsCXXRecordDecl()) {
17013 // The capture logic needs the destructor, so make sure we mark it.
17014 // Usually this is unnecessary because most local variables have
17015 // their destructors marked at declaration time, but parameters are
17016 // an exception because it's technically only the call site that
17017 // actually requires the destructor.
17018 if (isa<ParmVarDecl>(Val: Var))
17019 FinalizeVarWithDestructor(VD: Var, DeclInit: Record);
17020
17021 // Enter a separate potentially-evaluated context while building block
17022 // initializers to isolate their cleanups from those of the block
17023 // itself.
17024 // FIXME: Is this appropriate even when the block itself occurs in an
17025 // unevaluated operand?
17026 EnterExpressionEvaluationContext EvalContext(
17027 *this, ExpressionEvaluationContext::PotentiallyEvaluated);
17028
17029 SourceLocation Loc = Cap.getLocation();
17030
17031 ExprResult Result = BuildDeclarationNameExpr(
17032 SS: CXXScopeSpec(), NameInfo: DeclarationNameInfo(Var->getDeclName(), Loc), D: Var);
17033
17034 // According to the blocks spec, the capture of a variable from
17035 // the stack requires a const copy constructor. This is not true
17036 // of the copy/move done to move a __block variable to the heap.
17037 if (!Result.isInvalid() &&
17038 !Result.get()->getType().isConstQualified()) {
17039 Result = ImpCastExprToType(E: Result.get(),
17040 Type: Result.get()->getType().withConst(),
17041 CK: CK_NoOp, VK: VK_LValue);
17042 }
17043
17044 if (!Result.isInvalid()) {
17045 Result = PerformCopyInitialization(
17046 Entity: InitializedEntity::InitializeBlock(BlockVarLoc: Var->getLocation(),
17047 Type: Cap.getCaptureType()),
17048 EqualLoc: Loc, Init: Result.get());
17049 }
17050
17051 // Build a full-expression copy expression if initialization
17052 // succeeded and used a non-trivial constructor. Recover from
17053 // errors by pretending that the copy isn't necessary.
17054 if (!Result.isInvalid() &&
17055 !cast<CXXConstructExpr>(Val: Result.get())->getConstructor()
17056 ->isTrivial()) {
17057 Result = MaybeCreateExprWithCleanups(SubExpr: Result);
17058 CopyExpr = Result.get();
17059 }
17060 }
17061 }
17062
17063 BlockDecl::Capture NewCap(Var, Cap.isBlockCapture(), Cap.isNested(),
17064 CopyExpr);
17065 Captures.push_back(Elt: NewCap);
17066 }
17067 BD->setCaptures(Context, Captures, CapturesCXXThis: BSI->CXXThisCaptureIndex != 0);
17068
17069 // Pop the block scope now but keep it alive to the end of this function.
17070 AnalysisBasedWarnings::Policy WP =
17071 AnalysisWarnings.getPolicyInEffectAt(Loc: Body->getEndLoc());
17072 PoppedFunctionScopePtr ScopeRAII = PopFunctionScopeInfo(WP: &WP, D: BD, BlockType: BlockTy);
17073
17074 BlockExpr *Result = new (Context)
17075 BlockExpr(BD, BlockTy, BSI->ContainsUnexpandedParameterPack);
17076
17077 // If the block isn't obviously global, i.e. it captures anything at
17078 // all, then we need to do a few things in the surrounding context:
17079 if (Result->getBlockDecl()->hasCaptures()) {
17080 // First, this expression has a new cleanup object.
17081 ExprCleanupObjects.push_back(Elt: Result->getBlockDecl());
17082 Cleanup.setExprNeedsCleanups(true);
17083
17084 // It also gets a branch-protected scope if any of the captured
17085 // variables needs destruction.
17086 for (const auto &CI : Result->getBlockDecl()->captures()) {
17087 const VarDecl *var = CI.getVariable();
17088 if (var->getType().isDestructedType() != QualType::DK_none) {
17089 setFunctionHasBranchProtectedScope();
17090 break;
17091 }
17092 }
17093 }
17094
17095 if (getCurFunction())
17096 getCurFunction()->addBlock(BD);
17097
17098 // This can happen if the block's return type is deduced, but
17099 // the return expression is invalid.
17100 if (BD->isInvalidDecl())
17101 return CreateRecoveryExpr(Begin: Result->getBeginLoc(), End: Result->getEndLoc(),
17102 SubExprs: {Result}, T: Result->getType());
17103 return Result;
17104}
17105
17106ExprResult Sema::ActOnVAArg(SourceLocation BuiltinLoc, Expr *E, ParsedType Ty,
17107 SourceLocation RPLoc) {
17108 TypeSourceInfo *TInfo;
17109 GetTypeFromParser(Ty, TInfo: &TInfo);
17110 return BuildVAArgExpr(BuiltinLoc, E, TInfo, RPLoc);
17111}
17112
17113ExprResult Sema::BuildVAArgExpr(SourceLocation BuiltinLoc,
17114 Expr *E, TypeSourceInfo *TInfo,
17115 SourceLocation RPLoc) {
17116 Expr *OrigExpr = E;
17117 bool IsMS = false;
17118
17119 // CUDA device global function does not support varargs.
17120 if (getLangOpts().CUDA && getLangOpts().CUDAIsDevice) {
17121 if (const FunctionDecl *F = dyn_cast<FunctionDecl>(Val: CurContext)) {
17122 CUDAFunctionTarget T = CUDA().IdentifyTarget(D: F);
17123 if (T == CUDAFunctionTarget::Global)
17124 return ExprError(Diag(Loc: E->getBeginLoc(), DiagID: diag::err_va_arg_in_device));
17125 }
17126 }
17127
17128 // NVPTX does not support va_arg expression.
17129 if (getLangOpts().OpenMP && getLangOpts().OpenMPIsTargetDevice &&
17130 Context.getTargetInfo().getTriple().isNVPTX())
17131 targetDiag(Loc: E->getBeginLoc(), DiagID: diag::err_va_arg_in_device);
17132
17133 // It might be a __builtin_ms_va_list. (But don't ever mark a va_arg()
17134 // as Microsoft ABI on an actual Microsoft platform, where
17135 // __builtin_ms_va_list and __builtin_va_list are the same.)
17136 if (!E->isTypeDependent() && Context.getTargetInfo().hasBuiltinMSVaList() &&
17137 Context.getTargetInfo().getBuiltinVaListKind() != TargetInfo::CharPtrBuiltinVaList) {
17138 QualType MSVaListType = Context.getBuiltinMSVaListType();
17139 if (Context.hasSameType(T1: MSVaListType, T2: E->getType())) {
17140 if (CheckForModifiableLvalue(E, Loc: BuiltinLoc, S&: *this))
17141 return ExprError();
17142 IsMS = true;
17143 }
17144 }
17145
17146 // Get the va_list type
17147 QualType VaListType = Context.getBuiltinVaListType();
17148 if (!IsMS) {
17149 if (VaListType->isArrayType()) {
17150 // Deal with implicit array decay; for example, on x86-64,
17151 // va_list is an array, but it's supposed to decay to
17152 // a pointer for va_arg.
17153 VaListType = Context.getArrayDecayedType(T: VaListType);
17154 // Make sure the input expression also decays appropriately.
17155 ExprResult Result = UsualUnaryConversions(E);
17156 if (Result.isInvalid())
17157 return ExprError();
17158 E = Result.get();
17159 } else if (VaListType->isRecordType() && getLangOpts().CPlusPlus) {
17160 // If va_list is a record type and we are compiling in C++ mode,
17161 // check the argument using reference binding.
17162 InitializedEntity Entity = InitializedEntity::InitializeParameter(
17163 Context, Type: Context.getLValueReferenceType(T: VaListType), Consumed: false);
17164 ExprResult Init = PerformCopyInitialization(Entity, EqualLoc: SourceLocation(), Init: E);
17165 if (Init.isInvalid())
17166 return ExprError();
17167 E = Init.getAs<Expr>();
17168 } else {
17169 // Otherwise, the va_list argument must be an l-value because
17170 // it is modified by va_arg.
17171 if (!E->isTypeDependent() &&
17172 CheckForModifiableLvalue(E, Loc: BuiltinLoc, S&: *this))
17173 return ExprError();
17174 }
17175 }
17176
17177 if (!IsMS && !E->isTypeDependent() &&
17178 !Context.hasSameType(T1: VaListType, T2: E->getType()))
17179 return ExprError(
17180 Diag(Loc: E->getBeginLoc(),
17181 DiagID: diag::err_first_argument_to_va_arg_not_of_type_va_list)
17182 << OrigExpr->getType() << E->getSourceRange());
17183
17184 if (!TInfo->getType()->isDependentType()) {
17185 if (RequireCompleteType(Loc: TInfo->getTypeLoc().getBeginLoc(), T: TInfo->getType(),
17186 DiagID: diag::err_second_parameter_to_va_arg_incomplete,
17187 Args: TInfo->getTypeLoc()))
17188 return ExprError();
17189
17190 if (RequireNonAbstractType(Loc: TInfo->getTypeLoc().getBeginLoc(),
17191 T: TInfo->getType(),
17192 DiagID: diag::err_second_parameter_to_va_arg_abstract,
17193 Args: TInfo->getTypeLoc()))
17194 return ExprError();
17195
17196 if (!TInfo->getType().isPODType(Context)) {
17197 Diag(Loc: TInfo->getTypeLoc().getBeginLoc(),
17198 DiagID: TInfo->getType()->isObjCLifetimeType()
17199 ? diag::warn_second_parameter_to_va_arg_ownership_qualified
17200 : diag::warn_second_parameter_to_va_arg_not_pod)
17201 << TInfo->getType()
17202 << TInfo->getTypeLoc().getSourceRange();
17203 }
17204
17205 if (TInfo->getType()->isArrayType()) {
17206 DiagRuntimeBehavior(Loc: TInfo->getTypeLoc().getBeginLoc(), Statement: E,
17207 PD: PDiag(DiagID: diag::warn_second_parameter_to_va_arg_array)
17208 << TInfo->getType()
17209 << TInfo->getTypeLoc().getSourceRange());
17210 }
17211
17212 // Check for va_arg where arguments of the given type will be promoted
17213 // (i.e. this va_arg is guaranteed to have undefined behavior).
17214 QualType PromoteType;
17215 if (Context.isPromotableIntegerType(T: TInfo->getType())) {
17216 PromoteType = Context.getPromotedIntegerType(PromotableType: TInfo->getType());
17217 // [cstdarg.syn]p1 defers the C++ behavior to what the C standard says,
17218 // and C23 7.16.1.1p2 says, in part:
17219 // If type is not compatible with the type of the actual next argument
17220 // (as promoted according to the default argument promotions), the
17221 // behavior is undefined, except for the following cases:
17222 // - both types are pointers to qualified or unqualified versions of
17223 // compatible types;
17224 // - one type is compatible with a signed integer type, the other
17225 // type is compatible with the corresponding unsigned integer type,
17226 // and the value is representable in both types;
17227 // - one type is pointer to qualified or unqualified void and the
17228 // other is a pointer to a qualified or unqualified character type;
17229 // - or, the type of the next argument is nullptr_t and type is a
17230 // pointer type that has the same representation and alignment
17231 // requirements as a pointer to a character type.
17232 // Given that type compatibility is the primary requirement (ignoring
17233 // qualifications), you would think we could call typesAreCompatible()
17234 // directly to test this. However, in C++, that checks for *same type*,
17235 // which causes false positives when passing an enumeration type to
17236 // va_arg. Instead, get the underlying type of the enumeration and pass
17237 // that.
17238 QualType UnderlyingType = TInfo->getType();
17239 if (const auto *ED = UnderlyingType->getAsEnumDecl())
17240 UnderlyingType = ED->getIntegerType();
17241 if (Context.typesAreCompatible(T1: PromoteType, T2: UnderlyingType,
17242 /*CompareUnqualified*/ true))
17243 PromoteType = QualType();
17244
17245 // If the types are still not compatible, we need to test whether the
17246 // promoted type and the underlying type are the same except for
17247 // signedness. Ask the AST for the correctly corresponding type and see
17248 // if that's compatible.
17249 if (!PromoteType.isNull() && !UnderlyingType->isBooleanType() &&
17250 PromoteType->isUnsignedIntegerType() !=
17251 UnderlyingType->isUnsignedIntegerType()) {
17252 UnderlyingType =
17253 UnderlyingType->isUnsignedIntegerType()
17254 ? Context.getCorrespondingSignedType(T: UnderlyingType)
17255 : Context.getCorrespondingUnsignedType(T: UnderlyingType);
17256 if (Context.typesAreCompatible(T1: PromoteType, T2: UnderlyingType,
17257 /*CompareUnqualified*/ true))
17258 PromoteType = QualType();
17259 }
17260 }
17261 if (TInfo->getType()->isSpecificBuiltinType(K: BuiltinType::Float))
17262 PromoteType = Context.DoubleTy;
17263 if (!PromoteType.isNull())
17264 DiagRuntimeBehavior(Loc: TInfo->getTypeLoc().getBeginLoc(), Statement: E,
17265 PD: PDiag(DiagID: diag::warn_second_parameter_to_va_arg_never_compatible)
17266 << TInfo->getType()
17267 << PromoteType
17268 << TInfo->getTypeLoc().getSourceRange());
17269 }
17270
17271 QualType T = TInfo->getType().getNonLValueExprType(Context);
17272 return new (Context) VAArgExpr(BuiltinLoc, E, TInfo, RPLoc, T, IsMS);
17273}
17274
17275ExprResult Sema::ActOnGNUNullExpr(SourceLocation TokenLoc) {
17276 // The type of __null will be int or long, depending on the size of
17277 // pointers on the target.
17278 QualType Ty;
17279 unsigned pw = Context.getTargetInfo().getPointerWidth(AddrSpace: LangAS::Default);
17280 if (pw == Context.getTargetInfo().getIntWidth())
17281 Ty = Context.IntTy;
17282 else if (pw == Context.getTargetInfo().getLongWidth())
17283 Ty = Context.LongTy;
17284 else if (pw == Context.getTargetInfo().getLongLongWidth())
17285 Ty = Context.LongLongTy;
17286 else {
17287 llvm_unreachable("I don't know size of pointer!");
17288 }
17289
17290 return new (Context) GNUNullExpr(Ty, TokenLoc);
17291}
17292
17293static CXXRecordDecl *LookupStdSourceLocationImpl(Sema &S, SourceLocation Loc) {
17294 CXXRecordDecl *ImplDecl = nullptr;
17295
17296 // Fetch the std::source_location::__impl decl.
17297 if (NamespaceDecl *Std = S.getStdNamespace()) {
17298 LookupResult ResultSL(S, &S.PP.getIdentifierTable().get(Name: "source_location"),
17299 Loc, Sema::LookupOrdinaryName);
17300 if (S.LookupQualifiedName(R&: ResultSL, LookupCtx: Std)) {
17301 if (auto *SLDecl = ResultSL.getAsSingle<RecordDecl>()) {
17302 LookupResult ResultImpl(S, &S.PP.getIdentifierTable().get(Name: "__impl"),
17303 Loc, Sema::LookupOrdinaryName);
17304 if ((SLDecl->isCompleteDefinition() || SLDecl->isBeingDefined()) &&
17305 S.LookupQualifiedName(R&: ResultImpl, LookupCtx: SLDecl)) {
17306 ImplDecl = ResultImpl.getAsSingle<CXXRecordDecl>();
17307 }
17308 }
17309 }
17310 }
17311
17312 if (!ImplDecl || !ImplDecl->isCompleteDefinition()) {
17313 S.Diag(Loc, DiagID: diag::err_std_source_location_impl_not_found);
17314 return nullptr;
17315 }
17316
17317 // Verify that __impl is a trivial struct type, with no base classes, and with
17318 // only the four expected fields.
17319 if (ImplDecl->isUnion() || !ImplDecl->isStandardLayout() ||
17320 ImplDecl->getNumBases() != 0) {
17321 S.Diag(Loc, DiagID: diag::err_std_source_location_impl_malformed);
17322 return nullptr;
17323 }
17324
17325 unsigned Count = 0;
17326 for (FieldDecl *F : ImplDecl->fields()) {
17327 StringRef Name = F->getName();
17328
17329 if (Name == "_M_file_name") {
17330 if (F->getType() !=
17331 S.Context.getPointerType(T: S.Context.CharTy.withConst()))
17332 break;
17333 Count++;
17334 } else if (Name == "_M_function_name") {
17335 if (F->getType() !=
17336 S.Context.getPointerType(T: S.Context.CharTy.withConst()))
17337 break;
17338 Count++;
17339 } else if (Name == "_M_line") {
17340 if (!F->getType()->isIntegerType())
17341 break;
17342 Count++;
17343 } else if (Name == "_M_column") {
17344 if (!F->getType()->isIntegerType())
17345 break;
17346 Count++;
17347 } else {
17348 Count = 100; // invalid
17349 break;
17350 }
17351 }
17352 if (Count != 4) {
17353 S.Diag(Loc, DiagID: diag::err_std_source_location_impl_malformed);
17354 return nullptr;
17355 }
17356
17357 return ImplDecl;
17358}
17359
17360ExprResult Sema::ActOnSourceLocExpr(SourceLocIdentKind Kind,
17361 SourceLocation BuiltinLoc,
17362 SourceLocation RPLoc) {
17363 QualType ResultTy;
17364 switch (Kind) {
17365 case SourceLocIdentKind::File:
17366 case SourceLocIdentKind::FileName:
17367 case SourceLocIdentKind::Function:
17368 case SourceLocIdentKind::FuncSig: {
17369 QualType ArrTy = Context.getStringLiteralArrayType(EltTy: Context.CharTy, Length: 0);
17370 ResultTy =
17371 Context.getPointerType(T: ArrTy->getAsArrayTypeUnsafe()->getElementType());
17372 break;
17373 }
17374 case SourceLocIdentKind::Line:
17375 case SourceLocIdentKind::Column:
17376 ResultTy = Context.UnsignedIntTy;
17377 break;
17378 case SourceLocIdentKind::SourceLocStruct:
17379 if (!StdSourceLocationImplDecl) {
17380 StdSourceLocationImplDecl =
17381 LookupStdSourceLocationImpl(S&: *this, Loc: BuiltinLoc);
17382 if (!StdSourceLocationImplDecl)
17383 return ExprError();
17384 }
17385 ResultTy = Context.getPointerType(
17386 T: Context.getCanonicalTagType(TD: StdSourceLocationImplDecl).withConst());
17387 break;
17388 }
17389
17390 return BuildSourceLocExpr(Kind, ResultTy, BuiltinLoc, RPLoc, ParentContext: CurContext);
17391}
17392
17393ExprResult Sema::BuildSourceLocExpr(SourceLocIdentKind Kind, QualType ResultTy,
17394 SourceLocation BuiltinLoc,
17395 SourceLocation RPLoc,
17396 DeclContext *ParentContext) {
17397 return new (Context)
17398 SourceLocExpr(Context, Kind, ResultTy, BuiltinLoc, RPLoc, ParentContext);
17399}
17400
17401ExprResult Sema::ActOnEmbedExpr(SourceLocation EmbedKeywordLoc,
17402 StringLiteral *BinaryData, StringRef FileName) {
17403 EmbedDataStorage *Data = new (Context) EmbedDataStorage;
17404 Data->BinaryData = BinaryData;
17405 Data->FileName = FileName;
17406 return new (Context)
17407 EmbedExpr(Context, EmbedKeywordLoc, Data, /*NumOfElements=*/0,
17408 Data->getDataElementCount());
17409}
17410
17411static bool maybeDiagnoseAssignmentToFunction(Sema &S, QualType DstType,
17412 const Expr *SrcExpr) {
17413 if (!DstType->isFunctionPointerType() ||
17414 !SrcExpr->getType()->isFunctionType())
17415 return false;
17416
17417 auto *DRE = dyn_cast<DeclRefExpr>(Val: SrcExpr->IgnoreParenImpCasts());
17418 if (!DRE)
17419 return false;
17420
17421 auto *FD = dyn_cast<FunctionDecl>(Val: DRE->getDecl());
17422 if (!FD)
17423 return false;
17424
17425 return !S.checkAddressOfFunctionIsAvailable(Function: FD,
17426 /*Complain=*/true,
17427 Loc: SrcExpr->getBeginLoc());
17428}
17429
17430bool Sema::DiagnoseAssignmentResult(AssignConvertType ConvTy,
17431 SourceLocation Loc,
17432 QualType DstType, QualType SrcType,
17433 Expr *SrcExpr, AssignmentAction Action,
17434 bool *Complained) {
17435 if (Complained)
17436 *Complained = false;
17437
17438 // Decode the result (notice that AST's are still created for extensions).
17439 bool CheckInferredResultType = false;
17440 bool isInvalid = false;
17441 unsigned DiagKind = 0;
17442 ConversionFixItGenerator ConvHints;
17443 bool MayHaveConvFixit = false;
17444 bool MayHaveFunctionDiff = false;
17445 const ObjCInterfaceDecl *IFace = nullptr;
17446 const ObjCProtocolDecl *PDecl = nullptr;
17447
17448 switch (ConvTy) {
17449 case AssignConvertType::Compatible:
17450 DiagnoseAssignmentEnum(DstType, SrcType, SrcExpr);
17451 return false;
17452 case AssignConvertType::CompatibleVoidPtrToNonVoidPtr:
17453 // Still a valid conversion, but we may want to diagnose for C++
17454 // compatibility reasons.
17455 DiagKind = diag::warn_compatible_implicit_pointer_conv;
17456 break;
17457 case AssignConvertType::PointerToInt:
17458 if (getLangOpts().CPlusPlus) {
17459 DiagKind = diag::err_typecheck_convert_pointer_int;
17460 isInvalid = true;
17461 } else {
17462 DiagKind = diag::ext_typecheck_convert_pointer_int;
17463 }
17464 ConvHints.tryToFixConversion(FromExpr: SrcExpr, FromQTy: SrcType, ToQTy: DstType, S&: *this);
17465 MayHaveConvFixit = true;
17466 break;
17467 case AssignConvertType::IntToPointer:
17468 if (getLangOpts().CPlusPlus) {
17469 DiagKind = diag::err_typecheck_convert_int_pointer;
17470 isInvalid = true;
17471 } else {
17472 DiagKind = diag::ext_typecheck_convert_int_pointer;
17473 }
17474 ConvHints.tryToFixConversion(FromExpr: SrcExpr, FromQTy: SrcType, ToQTy: DstType, S&: *this);
17475 MayHaveConvFixit = true;
17476 break;
17477 case AssignConvertType::IncompatibleFunctionPointerStrict:
17478 DiagKind =
17479 diag::warn_typecheck_convert_incompatible_function_pointer_strict;
17480 ConvHints.tryToFixConversion(FromExpr: SrcExpr, FromQTy: SrcType, ToQTy: DstType, S&: *this);
17481 MayHaveConvFixit = true;
17482 break;
17483 case AssignConvertType::IncompatibleFunctionPointer:
17484 if (getLangOpts().CPlusPlus) {
17485 DiagKind = diag::err_typecheck_convert_incompatible_function_pointer;
17486 isInvalid = true;
17487 } else {
17488 DiagKind = diag::ext_typecheck_convert_incompatible_function_pointer;
17489 }
17490 ConvHints.tryToFixConversion(FromExpr: SrcExpr, FromQTy: SrcType, ToQTy: DstType, S&: *this);
17491 MayHaveConvFixit = true;
17492 break;
17493 case AssignConvertType::IncompatiblePointer:
17494 if (Action == AssignmentAction::Passing_CFAudited) {
17495 DiagKind = diag::err_arc_typecheck_convert_incompatible_pointer;
17496 } else if (getLangOpts().CPlusPlus) {
17497 DiagKind = diag::err_typecheck_convert_incompatible_pointer;
17498 isInvalid = true;
17499 } else {
17500 DiagKind = diag::ext_typecheck_convert_incompatible_pointer;
17501 }
17502 CheckInferredResultType = DstType->isObjCObjectPointerType() &&
17503 SrcType->isObjCObjectPointerType();
17504 if (CheckInferredResultType) {
17505 SrcType = SrcType.getUnqualifiedType();
17506 DstType = DstType.getUnqualifiedType();
17507 } else {
17508 ConvHints.tryToFixConversion(FromExpr: SrcExpr, FromQTy: SrcType, ToQTy: DstType, S&: *this);
17509 }
17510 MayHaveConvFixit = true;
17511 break;
17512 case AssignConvertType::IncompatiblePointerSign:
17513 if (getLangOpts().CPlusPlus) {
17514 DiagKind = diag::err_typecheck_convert_incompatible_pointer_sign;
17515 isInvalid = true;
17516 } else {
17517 DiagKind = diag::ext_typecheck_convert_incompatible_pointer_sign;
17518 }
17519 break;
17520 case AssignConvertType::FunctionVoidPointer:
17521 if (getLangOpts().CPlusPlus) {
17522 DiagKind = diag::err_typecheck_convert_pointer_void_func;
17523 isInvalid = true;
17524 } else {
17525 DiagKind = diag::ext_typecheck_convert_pointer_void_func;
17526 }
17527 break;
17528 case AssignConvertType::IncompatiblePointerDiscardsQualifiers: {
17529 // Perform array-to-pointer decay if necessary.
17530 if (SrcType->isArrayType()) SrcType = Context.getArrayDecayedType(T: SrcType);
17531
17532 isInvalid = true;
17533
17534 Qualifiers lhq = SrcType->getPointeeType().getQualifiers();
17535 Qualifiers rhq = DstType->getPointeeType().getQualifiers();
17536 if (lhq.getAddressSpace() != rhq.getAddressSpace()) {
17537 DiagKind = diag::err_typecheck_incompatible_address_space;
17538 break;
17539 } else if (lhq.getObjCLifetime() != rhq.getObjCLifetime()) {
17540 DiagKind = diag::err_typecheck_incompatible_ownership;
17541 break;
17542 } else if (!lhq.getPointerAuth().isEquivalent(Other: rhq.getPointerAuth())) {
17543 DiagKind = diag::err_typecheck_incompatible_ptrauth;
17544 break;
17545 }
17546
17547 llvm_unreachable("unknown error case for discarding qualifiers!");
17548 // fallthrough
17549 }
17550 case AssignConvertType::IncompatiblePointerDiscardsOverflowBehavior:
17551 if (SrcType->isArrayType())
17552 SrcType = Context.getArrayDecayedType(T: SrcType);
17553
17554 DiagKind = diag::ext_typecheck_convert_discards_overflow_behavior;
17555 break;
17556 case AssignConvertType::CompatiblePointerDiscardsQualifiers:
17557 // If the qualifiers lost were because we were applying the
17558 // (deprecated) C++ conversion from a string literal to a char*
17559 // (or wchar_t*), then there was no error (C++ 4.2p2). FIXME:
17560 // Ideally, this check would be performed in
17561 // checkPointerTypesForAssignment. However, that would require a
17562 // bit of refactoring (so that the second argument is an
17563 // expression, rather than a type), which should be done as part
17564 // of a larger effort to fix checkPointerTypesForAssignment for
17565 // C++ semantics.
17566 if (getLangOpts().CPlusPlus &&
17567 IsStringLiteralToNonConstPointerConversion(From: SrcExpr, ToType: DstType))
17568 return false;
17569 if (getLangOpts().CPlusPlus) {
17570 DiagKind = diag::err_typecheck_convert_discards_qualifiers;
17571 isInvalid = true;
17572 } else {
17573 DiagKind = diag::ext_typecheck_convert_discards_qualifiers;
17574 }
17575
17576 break;
17577 case AssignConvertType::IncompatibleNestedPointerQualifiers:
17578 if (getLangOpts().CPlusPlus) {
17579 isInvalid = true;
17580 DiagKind = diag::err_nested_pointer_qualifier_mismatch;
17581 } else {
17582 DiagKind = diag::ext_nested_pointer_qualifier_mismatch;
17583 }
17584 break;
17585 case AssignConvertType::IncompatibleNestedPointerAddressSpaceMismatch:
17586 DiagKind = diag::err_typecheck_incompatible_nested_address_space;
17587 isInvalid = true;
17588 break;
17589 case AssignConvertType::IntToBlockPointer:
17590 DiagKind = diag::err_int_to_block_pointer;
17591 isInvalid = true;
17592 break;
17593 case AssignConvertType::IncompatibleBlockPointer:
17594 DiagKind = diag::err_typecheck_convert_incompatible_block_pointer;
17595 isInvalid = true;
17596 break;
17597 case AssignConvertType::IncompatibleObjCQualifiedId: {
17598 if (SrcType->isObjCQualifiedIdType()) {
17599 const ObjCObjectPointerType *srcOPT =
17600 SrcType->castAs<ObjCObjectPointerType>();
17601 for (auto *srcProto : srcOPT->quals()) {
17602 PDecl = srcProto;
17603 break;
17604 }
17605 if (const ObjCInterfaceType *IFaceT =
17606 DstType->castAs<ObjCObjectPointerType>()->getInterfaceType())
17607 IFace = IFaceT->getDecl();
17608 }
17609 else if (DstType->isObjCQualifiedIdType()) {
17610 const ObjCObjectPointerType *dstOPT =
17611 DstType->castAs<ObjCObjectPointerType>();
17612 for (auto *dstProto : dstOPT->quals()) {
17613 PDecl = dstProto;
17614 break;
17615 }
17616 if (const ObjCInterfaceType *IFaceT =
17617 SrcType->castAs<ObjCObjectPointerType>()->getInterfaceType())
17618 IFace = IFaceT->getDecl();
17619 }
17620 if (getLangOpts().CPlusPlus) {
17621 DiagKind = diag::err_incompatible_qualified_id;
17622 isInvalid = true;
17623 } else {
17624 DiagKind = diag::warn_incompatible_qualified_id;
17625 }
17626 break;
17627 }
17628 case AssignConvertType::IncompatibleVectors:
17629 if (getLangOpts().CPlusPlus) {
17630 DiagKind = diag::err_incompatible_vectors;
17631 isInvalid = true;
17632 } else {
17633 DiagKind = diag::warn_incompatible_vectors;
17634 }
17635 break;
17636 case AssignConvertType::IncompatibleObjCWeakRef:
17637 DiagKind = diag::err_arc_weak_unavailable_assign;
17638 isInvalid = true;
17639 break;
17640 case AssignConvertType::CompatibleOBTDiscards:
17641 return false;
17642 case AssignConvertType::IncompatibleOBTKinds: {
17643 auto getOBTKindName = [](QualType Ty) -> StringRef {
17644 if (Ty->isPointerType())
17645 Ty = Ty->getPointeeType();
17646 if (const auto *OBT = Ty->getAs<OverflowBehaviorType>()) {
17647 return OBT->getBehaviorKind() ==
17648 OverflowBehaviorType::OverflowBehaviorKind::Trap
17649 ? "__ob_trap"
17650 : "__ob_wrap";
17651 }
17652 llvm_unreachable("OBT kind unhandled");
17653 };
17654
17655 Diag(Loc, DiagID: diag::err_incompatible_obt_kinds_assignment)
17656 << DstType << SrcType << getOBTKindName(DstType)
17657 << getOBTKindName(SrcType);
17658 isInvalid = true;
17659 return true;
17660 }
17661 case AssignConvertType::Incompatible:
17662 if (maybeDiagnoseAssignmentToFunction(S&: *this, DstType, SrcExpr)) {
17663 if (Complained)
17664 *Complained = true;
17665 return true;
17666 }
17667
17668 DiagKind = diag::err_typecheck_convert_incompatible;
17669 ConvHints.tryToFixConversion(FromExpr: SrcExpr, FromQTy: SrcType, ToQTy: DstType, S&: *this);
17670 MayHaveConvFixit = true;
17671 isInvalid = true;
17672 MayHaveFunctionDiff = true;
17673 break;
17674 }
17675
17676 QualType FirstType, SecondType;
17677 switch (Action) {
17678 case AssignmentAction::Assigning:
17679 case AssignmentAction::Initializing:
17680 // The destination type comes first.
17681 FirstType = DstType;
17682 SecondType = SrcType;
17683 break;
17684
17685 case AssignmentAction::Returning:
17686 case AssignmentAction::Passing:
17687 case AssignmentAction::Passing_CFAudited:
17688 case AssignmentAction::Converting:
17689 case AssignmentAction::Sending:
17690 case AssignmentAction::Casting:
17691 // The source type comes first.
17692 FirstType = SrcType;
17693 SecondType = DstType;
17694 break;
17695 }
17696
17697 PartialDiagnostic FDiag = PDiag(DiagID: DiagKind);
17698 AssignmentAction ActionForDiag = Action;
17699 if (Action == AssignmentAction::Passing_CFAudited)
17700 ActionForDiag = AssignmentAction::Passing;
17701
17702 FDiag << FirstType << SecondType << ActionForDiag
17703 << SrcExpr->getSourceRange();
17704
17705 if (DiagKind == diag::ext_typecheck_convert_incompatible_pointer_sign ||
17706 DiagKind == diag::err_typecheck_convert_incompatible_pointer_sign) {
17707 auto isPlainChar = [](const clang::Type *Type) {
17708 return Type->isSpecificBuiltinType(K: BuiltinType::Char_S) ||
17709 Type->isSpecificBuiltinType(K: BuiltinType::Char_U);
17710 };
17711 FDiag << (isPlainChar(FirstType->getPointeeOrArrayElementType()) ||
17712 isPlainChar(SecondType->getPointeeOrArrayElementType()));
17713 }
17714
17715 // If we can fix the conversion, suggest the FixIts.
17716 if (!ConvHints.isNull()) {
17717 for (FixItHint &H : ConvHints.Hints)
17718 FDiag << H;
17719 }
17720
17721 if (MayHaveConvFixit) { FDiag << (unsigned) (ConvHints.Kind); }
17722
17723 if (MayHaveFunctionDiff)
17724 HandleFunctionTypeMismatch(PDiag&: FDiag, FromType: SecondType, ToType: FirstType);
17725
17726 Diag(Loc, PD: FDiag);
17727 if ((DiagKind == diag::warn_incompatible_qualified_id ||
17728 DiagKind == diag::err_incompatible_qualified_id) &&
17729 PDecl && IFace && !IFace->hasDefinition())
17730 Diag(Loc: IFace->getLocation(), DiagID: diag::note_incomplete_class_and_qualified_id)
17731 << IFace << PDecl;
17732
17733 if (SecondType == Context.OverloadTy)
17734 NoteAllOverloadCandidates(E: OverloadExpr::find(E: SrcExpr).Expression,
17735 DestType: FirstType, /*TakingAddress=*/true);
17736
17737 if (CheckInferredResultType)
17738 ObjC().EmitRelatedResultTypeNote(E: SrcExpr);
17739
17740 if (Action == AssignmentAction::Returning &&
17741 ConvTy == AssignConvertType::IncompatiblePointer)
17742 ObjC().EmitRelatedResultTypeNoteForReturn(destType: DstType);
17743
17744 if (Complained)
17745 *Complained = true;
17746 return isInvalid;
17747}
17748
17749ExprResult Sema::VerifyIntegerConstantExpression(Expr *E,
17750 llvm::APSInt *Result,
17751 AllowFoldKind CanFold) {
17752 class SimpleICEDiagnoser : public VerifyICEDiagnoser {
17753 public:
17754 SemaDiagnosticBuilder diagnoseNotICEType(Sema &S, SourceLocation Loc,
17755 QualType T) override {
17756 return S.Diag(Loc, DiagID: diag::err_ice_not_integral)
17757 << T << S.LangOpts.CPlusPlus;
17758 }
17759 SemaDiagnosticBuilder diagnoseNotICE(Sema &S, SourceLocation Loc) override {
17760 return S.Diag(Loc, DiagID: diag::err_expr_not_ice) << S.LangOpts.CPlusPlus;
17761 }
17762 } Diagnoser;
17763
17764 return VerifyIntegerConstantExpression(E, Result, Diagnoser, CanFold);
17765}
17766
17767ExprResult Sema::VerifyIntegerConstantExpression(Expr *E,
17768 llvm::APSInt *Result,
17769 unsigned DiagID,
17770 AllowFoldKind CanFold) {
17771 class IDDiagnoser : public VerifyICEDiagnoser {
17772 unsigned DiagID;
17773
17774 public:
17775 IDDiagnoser(unsigned DiagID)
17776 : VerifyICEDiagnoser(DiagID == 0), DiagID(DiagID) { }
17777
17778 SemaDiagnosticBuilder diagnoseNotICE(Sema &S, SourceLocation Loc) override {
17779 return S.Diag(Loc, DiagID);
17780 }
17781 } Diagnoser(DiagID);
17782
17783 return VerifyIntegerConstantExpression(E, Result, Diagnoser, CanFold);
17784}
17785
17786Sema::SemaDiagnosticBuilder
17787Sema::VerifyICEDiagnoser::diagnoseNotICEType(Sema &S, SourceLocation Loc,
17788 QualType T) {
17789 return diagnoseNotICE(S, Loc);
17790}
17791
17792Sema::SemaDiagnosticBuilder
17793Sema::VerifyICEDiagnoser::diagnoseFold(Sema &S, SourceLocation Loc) {
17794 return S.Diag(Loc, DiagID: diag::ext_expr_not_ice) << S.LangOpts.CPlusPlus;
17795}
17796
17797ExprResult
17798Sema::VerifyIntegerConstantExpression(Expr *E, llvm::APSInt *Result,
17799 VerifyICEDiagnoser &Diagnoser,
17800 AllowFoldKind CanFold) {
17801 SourceLocation DiagLoc = E->getBeginLoc();
17802
17803 if (getLangOpts().CPlusPlus11) {
17804 // C++11 [expr.const]p5:
17805 // If an expression of literal class type is used in a context where an
17806 // integral constant expression is required, then that class type shall
17807 // have a single non-explicit conversion function to an integral or
17808 // unscoped enumeration type
17809 ExprResult Converted;
17810 class CXX11ConvertDiagnoser : public ICEConvertDiagnoser {
17811 VerifyICEDiagnoser &BaseDiagnoser;
17812 public:
17813 CXX11ConvertDiagnoser(VerifyICEDiagnoser &BaseDiagnoser)
17814 : ICEConvertDiagnoser(/*AllowScopedEnumerations*/ false,
17815 BaseDiagnoser.Suppress, true),
17816 BaseDiagnoser(BaseDiagnoser) {}
17817
17818 SemaDiagnosticBuilder diagnoseNotInt(Sema &S, SourceLocation Loc,
17819 QualType T) override {
17820 return BaseDiagnoser.diagnoseNotICEType(S, Loc, T);
17821 }
17822
17823 SemaDiagnosticBuilder diagnoseIncomplete(
17824 Sema &S, SourceLocation Loc, QualType T) override {
17825 return S.Diag(Loc, DiagID: diag::err_ice_incomplete_type) << T;
17826 }
17827
17828 SemaDiagnosticBuilder diagnoseExplicitConv(
17829 Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) override {
17830 return S.Diag(Loc, DiagID: diag::err_ice_explicit_conversion) << T << ConvTy;
17831 }
17832
17833 SemaDiagnosticBuilder noteExplicitConv(
17834 Sema &S, CXXConversionDecl *Conv, QualType ConvTy) override {
17835 return S.Diag(Loc: Conv->getLocation(), DiagID: diag::note_ice_conversion_here)
17836 << ConvTy->isEnumeralType() << ConvTy;
17837 }
17838
17839 SemaDiagnosticBuilder diagnoseAmbiguous(
17840 Sema &S, SourceLocation Loc, QualType T) override {
17841 return S.Diag(Loc, DiagID: diag::err_ice_ambiguous_conversion) << T;
17842 }
17843
17844 SemaDiagnosticBuilder noteAmbiguous(
17845 Sema &S, CXXConversionDecl *Conv, QualType ConvTy) override {
17846 return S.Diag(Loc: Conv->getLocation(), DiagID: diag::note_ice_conversion_here)
17847 << ConvTy->isEnumeralType() << ConvTy;
17848 }
17849
17850 SemaDiagnosticBuilder diagnoseConversion(
17851 Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) override {
17852 llvm_unreachable("conversion functions are permitted");
17853 }
17854 } ConvertDiagnoser(Diagnoser);
17855
17856 Converted = PerformContextualImplicitConversion(Loc: DiagLoc, FromE: E,
17857 Converter&: ConvertDiagnoser);
17858 if (Converted.isInvalid())
17859 return Converted;
17860 E = Converted.get();
17861 // The 'explicit' case causes us to get a RecoveryExpr. Give up here so we
17862 // don't try to evaluate it later. We also don't want to return the
17863 // RecoveryExpr here, as it results in this call succeeding, thus callers of
17864 // this function will attempt to use 'Value'.
17865 if (isa<RecoveryExpr>(Val: E))
17866 return ExprError();
17867 if (!E->getType()->isIntegralOrUnscopedEnumerationType())
17868 return ExprError();
17869 } else if (!E->getType()->isIntegralOrUnscopedEnumerationType()) {
17870 // An ICE must be of integral or unscoped enumeration type.
17871 if (!Diagnoser.Suppress)
17872 Diagnoser.diagnoseNotICEType(S&: *this, Loc: DiagLoc, T: E->getType())
17873 << E->getSourceRange();
17874 return ExprError();
17875 }
17876
17877 ExprResult RValueExpr = DefaultLvalueConversion(E);
17878 if (RValueExpr.isInvalid())
17879 return ExprError();
17880
17881 E = RValueExpr.get();
17882
17883 // Circumvent ICE checking in C++11 to avoid evaluating the expression twice
17884 // in the non-ICE case.
17885 if (!getLangOpts().CPlusPlus11 && E->isIntegerConstantExpr(Ctx: Context)) {
17886 SmallVector<PartialDiagnosticAt, 8> Notes;
17887 if (Result)
17888 *Result = E->EvaluateKnownConstIntCheckOverflow(Ctx: Context, Diag: &Notes);
17889 if (!isa<ConstantExpr>(Val: E))
17890 E = Result ? ConstantExpr::Create(Context, E, Result: APValue(*Result))
17891 : ConstantExpr::Create(Context, E);
17892
17893 if (Notes.empty())
17894 return E;
17895
17896 // If our only note is the usual "invalid subexpression" note, just point
17897 // the caret at its location rather than producing an essentially
17898 // redundant note.
17899 if (Notes.size() == 1 && Notes[0].second.getDiagID() ==
17900 diag::note_invalid_subexpr_in_const_expr) {
17901 DiagLoc = Notes[0].first;
17902 Notes.clear();
17903 }
17904
17905 if (getLangOpts().CPlusPlus) {
17906 if (!Diagnoser.Suppress) {
17907 Diagnoser.diagnoseNotICE(S&: *this, Loc: DiagLoc) << E->getSourceRange();
17908 for (const PartialDiagnosticAt &Note : Notes)
17909 Diag(Loc: Note.first, PD: Note.second);
17910 }
17911 return ExprError();
17912 }
17913
17914 Diagnoser.diagnoseFold(S&: *this, Loc: DiagLoc) << E->getSourceRange();
17915 for (const PartialDiagnosticAt &Note : Notes)
17916 Diag(Loc: Note.first, PD: Note.second);
17917
17918 return E;
17919 }
17920
17921 Expr::EvalResult EvalResult;
17922 SmallVector<PartialDiagnosticAt, 8> Notes;
17923 EvalResult.Diag = &Notes;
17924
17925 // Try to evaluate the expression, and produce diagnostics explaining why it's
17926 // not a constant expression as a side-effect.
17927 bool Folded =
17928 E->EvaluateAsRValue(Result&: EvalResult, Ctx: Context, /*isConstantContext*/ InConstantContext: true) &&
17929 EvalResult.Val.isInt() && !EvalResult.HasSideEffects &&
17930 (!getLangOpts().CPlusPlus || !EvalResult.HasUndefinedBehavior);
17931
17932 if (!isa<ConstantExpr>(Val: E))
17933 E = ConstantExpr::Create(Context, E, Result: EvalResult.Val);
17934
17935 // In C++11, we can rely on diagnostics being produced for any expression
17936 // which is not a constant expression. If no diagnostics were produced, then
17937 // this is a constant expression.
17938 if (Folded && getLangOpts().CPlusPlus11 && Notes.empty()) {
17939 if (Result)
17940 *Result = EvalResult.Val.getInt();
17941 return E;
17942 }
17943
17944 // If our only note is the usual "invalid subexpression" note, just point
17945 // the caret at its location rather than producing an essentially
17946 // redundant note.
17947 if (Notes.size() == 1 && Notes[0].second.getDiagID() ==
17948 diag::note_invalid_subexpr_in_const_expr) {
17949 DiagLoc = Notes[0].first;
17950 Notes.clear();
17951 }
17952
17953 if (!Folded || CanFold == AllowFoldKind::No) {
17954 if (!Diagnoser.Suppress) {
17955 Diagnoser.diagnoseNotICE(S&: *this, Loc: DiagLoc) << E->getSourceRange();
17956 for (const PartialDiagnosticAt &Note : Notes)
17957 Diag(Loc: Note.first, PD: Note.second);
17958 }
17959
17960 return ExprError();
17961 }
17962
17963 Diagnoser.diagnoseFold(S&: *this, Loc: DiagLoc) << E->getSourceRange();
17964 for (const PartialDiagnosticAt &Note : Notes)
17965 Diag(Loc: Note.first, PD: Note.second);
17966
17967 if (Result)
17968 *Result = EvalResult.Val.getInt();
17969 return E;
17970}
17971
17972namespace {
17973 // Handle the case where we conclude a expression which we speculatively
17974 // considered to be unevaluated is actually evaluated.
17975 class TransformToPE : public TreeTransform<TransformToPE> {
17976 typedef TreeTransform<TransformToPE> BaseTransform;
17977
17978 public:
17979 TransformToPE(Sema &SemaRef) : BaseTransform(SemaRef) { }
17980
17981 // Make sure we redo semantic analysis
17982 bool AlwaysRebuild() { return true; }
17983 bool ReplacingOriginal() { return true; }
17984
17985 // We need to special-case DeclRefExprs referring to FieldDecls which
17986 // are not part of a member pointer formation; normal TreeTransforming
17987 // doesn't catch this case because of the way we represent them in the AST.
17988 // FIXME: This is a bit ugly; is it really the best way to handle this
17989 // case?
17990 //
17991 // Error on DeclRefExprs referring to FieldDecls.
17992 ExprResult TransformDeclRefExpr(DeclRefExpr *E) {
17993 if (isa<FieldDecl>(Val: E->getDecl()) &&
17994 !SemaRef.isUnevaluatedContext())
17995 return SemaRef.Diag(Loc: E->getLocation(),
17996 DiagID: diag::err_invalid_non_static_member_use)
17997 << E->getDecl() << E->getSourceRange();
17998
17999 return BaseTransform::TransformDeclRefExpr(E);
18000 }
18001
18002 // Exception: filter out member pointer formation
18003 ExprResult TransformUnaryOperator(UnaryOperator *E) {
18004 if (E->getOpcode() == UO_AddrOf && E->getType()->isMemberPointerType())
18005 return E;
18006
18007 return BaseTransform::TransformUnaryOperator(E);
18008 }
18009
18010 // The body of a lambda-expression is in a separate expression evaluation
18011 // context so never needs to be transformed.
18012 // FIXME: Ideally we wouldn't transform the closure type either, and would
18013 // just recreate the capture expressions and lambda expression.
18014 StmtResult TransformLambdaBody(LambdaExpr *E, Stmt *Body) {
18015 return SkipLambdaBody(E, S: Body);
18016 }
18017 };
18018}
18019
18020ExprResult Sema::TransformToPotentiallyEvaluated(Expr *E) {
18021 assert(isUnevaluatedContext() &&
18022 "Should only transform unevaluated expressions");
18023 ExprEvalContexts.back().Context =
18024 ExprEvalContexts[ExprEvalContexts.size()-2].Context;
18025 if (isUnevaluatedContext())
18026 return E;
18027 return TransformToPE(*this).TransformExpr(E);
18028}
18029
18030TypeSourceInfo *Sema::TransformToPotentiallyEvaluated(TypeSourceInfo *TInfo) {
18031 assert(isUnevaluatedContext() &&
18032 "Should only transform unevaluated expressions");
18033 ExprEvalContexts.back().Context = parentEvaluationContext().Context;
18034 if (isUnevaluatedContext())
18035 return TInfo;
18036 return TransformToPE(*this).TransformType(TSI: TInfo);
18037}
18038
18039void
18040Sema::PushExpressionEvaluationContext(
18041 ExpressionEvaluationContext NewContext, Decl *LambdaContextDecl,
18042 ExpressionEvaluationContextRecord::ExpressionKind ExprContext) {
18043 ExprEvalContexts.emplace_back(Args&: NewContext, Args: ExprCleanupObjects.size(), Args&: Cleanup,
18044 Args&: LambdaContextDecl, Args&: ExprContext);
18045
18046 // Discarded statements and immediate contexts nested in other
18047 // discarded statements or immediate context are themselves
18048 // a discarded statement or an immediate context, respectively.
18049 ExprEvalContexts.back().InDiscardedStatement =
18050 parentEvaluationContext().isDiscardedStatementContext();
18051
18052 // C++23 [expr.const]/p15
18053 // An expression or conversion is in an immediate function context if [...]
18054 // it is a subexpression of a manifestly constant-evaluated expression or
18055 // conversion.
18056 const auto &Prev = parentEvaluationContext();
18057 ExprEvalContexts.back().InImmediateFunctionContext =
18058 Prev.isImmediateFunctionContext() || Prev.isConstantEvaluated();
18059
18060 ExprEvalContexts.back().InImmediateEscalatingFunctionContext =
18061 Prev.InImmediateEscalatingFunctionContext;
18062
18063 Cleanup.reset();
18064 if (!MaybeODRUseExprs.empty())
18065 std::swap(LHS&: MaybeODRUseExprs, RHS&: ExprEvalContexts.back().SavedMaybeODRUseExprs);
18066}
18067
18068void
18069Sema::PushExpressionEvaluationContext(
18070 ExpressionEvaluationContext NewContext, ReuseLambdaContextDecl_t,
18071 ExpressionEvaluationContextRecord::ExpressionKind ExprContext) {
18072 Decl *ClosureContextDecl = ExprEvalContexts.back().ManglingContextDecl;
18073 PushExpressionEvaluationContext(NewContext, LambdaContextDecl: ClosureContextDecl, ExprContext);
18074}
18075
18076void Sema::PushExpressionEvaluationContextForFunction(
18077 ExpressionEvaluationContext NewContext, FunctionDecl *FD) {
18078 // [expr.const]/p14.1
18079 // An expression or conversion is in an immediate function context if it is
18080 // potentially evaluated and either: its innermost enclosing non-block scope
18081 // is a function parameter scope of an immediate function.
18082 PushExpressionEvaluationContext(
18083 NewContext: FD && FD->isConsteval()
18084 ? ExpressionEvaluationContext::ImmediateFunctionContext
18085 : NewContext);
18086 const Sema::ExpressionEvaluationContextRecord &Parent =
18087 parentEvaluationContext();
18088 Sema::ExpressionEvaluationContextRecord &Current = currentEvaluationContext();
18089
18090 Current.InDiscardedStatement = false;
18091
18092 if (FD) {
18093
18094 // Each ExpressionEvaluationContextRecord also keeps track of whether the
18095 // context is nested in an immediate function context, so smaller contexts
18096 // that appear inside immediate functions (like variable initializers) are
18097 // considered to be inside an immediate function context even though by
18098 // themselves they are not immediate function contexts. But when a new
18099 // function is entered, we need to reset this tracking, since the entered
18100 // function might be not an immediate function.
18101
18102 Current.InImmediateEscalatingFunctionContext =
18103 getLangOpts().CPlusPlus20 && FD->isImmediateEscalating();
18104
18105 if (isLambdaMethod(DC: FD))
18106 Current.InImmediateFunctionContext =
18107 FD->isConsteval() ||
18108 (isLambdaMethod(DC: FD) && (Parent.isConstantEvaluated() ||
18109 Parent.isImmediateFunctionContext()));
18110 else
18111 Current.InImmediateFunctionContext = FD->isConsteval();
18112 }
18113}
18114
18115ExprResult Sema::ActOnCXXReflectExpr(SourceLocation CaretCaretLoc,
18116 TypeSourceInfo *TSI) {
18117 return BuildCXXReflectExpr(OperatorLoc: CaretCaretLoc, TSI);
18118}
18119
18120ExprResult Sema::BuildCXXReflectExpr(SourceLocation CaretCaretLoc,
18121 TypeSourceInfo *TSI) {
18122 return CXXReflectExpr::Create(C&: Context, OperatorLoc: CaretCaretLoc, TL: TSI);
18123}
18124
18125namespace {
18126
18127const DeclRefExpr *CheckPossibleDeref(Sema &S, const Expr *PossibleDeref) {
18128 PossibleDeref = PossibleDeref->IgnoreParenImpCasts();
18129 if (const auto *E = dyn_cast<UnaryOperator>(Val: PossibleDeref)) {
18130 if (E->getOpcode() == UO_Deref)
18131 return CheckPossibleDeref(S, PossibleDeref: E->getSubExpr());
18132 } else if (const auto *E = dyn_cast<ArraySubscriptExpr>(Val: PossibleDeref)) {
18133 return CheckPossibleDeref(S, PossibleDeref: E->getBase());
18134 } else if (const auto *E = dyn_cast<MemberExpr>(Val: PossibleDeref)) {
18135 return CheckPossibleDeref(S, PossibleDeref: E->getBase());
18136 } else if (const auto E = dyn_cast<DeclRefExpr>(Val: PossibleDeref)) {
18137 QualType Inner;
18138 QualType Ty = E->getType();
18139 if (const auto *Ptr = Ty->getAs<PointerType>())
18140 Inner = Ptr->getPointeeType();
18141 else if (const auto *Arr = S.Context.getAsArrayType(T: Ty))
18142 Inner = Arr->getElementType();
18143 else
18144 return nullptr;
18145
18146 if (Inner->hasAttr(AK: attr::NoDeref))
18147 return E;
18148 }
18149 return nullptr;
18150}
18151
18152} // namespace
18153
18154void Sema::WarnOnPendingNoDerefs(ExpressionEvaluationContextRecord &Rec) {
18155 for (const Expr *E : Rec.PossibleDerefs) {
18156 const DeclRefExpr *DeclRef = CheckPossibleDeref(S&: *this, PossibleDeref: E);
18157 if (DeclRef) {
18158 const ValueDecl *Decl = DeclRef->getDecl();
18159 Diag(Loc: E->getExprLoc(), DiagID: diag::warn_dereference_of_noderef_type)
18160 << Decl->getName() << E->getSourceRange();
18161 Diag(Loc: Decl->getLocation(), DiagID: diag::note_previous_decl) << Decl->getName();
18162 } else {
18163 Diag(Loc: E->getExprLoc(), DiagID: diag::warn_dereference_of_noderef_type_no_decl)
18164 << E->getSourceRange();
18165 }
18166 }
18167 Rec.PossibleDerefs.clear();
18168}
18169
18170void Sema::CheckUnusedVolatileAssignment(Expr *E) {
18171 if (!E->getType().isVolatileQualified() || !getLangOpts().CPlusPlus20)
18172 return;
18173
18174 // Note: ignoring parens here is not justified by the standard rules, but
18175 // ignoring parentheses seems like a more reasonable approach, and this only
18176 // drives a deprecation warning so doesn't affect conformance.
18177 if (auto *BO = dyn_cast<BinaryOperator>(Val: E->IgnoreParenImpCasts())) {
18178 if (BO->getOpcode() == BO_Assign) {
18179 auto &LHSs = ExprEvalContexts.back().VolatileAssignmentLHSs;
18180 llvm::erase(C&: LHSs, V: BO->getLHS());
18181 }
18182 }
18183}
18184
18185void Sema::MarkExpressionAsImmediateEscalating(Expr *E) {
18186 assert(getLangOpts().CPlusPlus20 &&
18187 ExprEvalContexts.back().InImmediateEscalatingFunctionContext &&
18188 "Cannot mark an immediate escalating expression outside of an "
18189 "immediate escalating context");
18190 if (auto *Call = dyn_cast<CallExpr>(Val: E->IgnoreImplicit());
18191 Call && Call->getCallee()) {
18192 if (auto *DeclRef =
18193 dyn_cast<DeclRefExpr>(Val: Call->getCallee()->IgnoreImplicit()))
18194 DeclRef->setIsImmediateEscalating(true);
18195 } else if (auto *Ctr = dyn_cast<CXXConstructExpr>(Val: E->IgnoreImplicit())) {
18196 Ctr->setIsImmediateEscalating(true);
18197 } else if (auto *DeclRef = dyn_cast<DeclRefExpr>(Val: E->IgnoreImplicit())) {
18198 DeclRef->setIsImmediateEscalating(true);
18199 } else {
18200 assert(false && "expected an immediately escalating expression");
18201 }
18202 if (FunctionScopeInfo *FI = getCurFunction())
18203 FI->FoundImmediateEscalatingExpression = true;
18204}
18205
18206ExprResult Sema::CheckForImmediateInvocation(ExprResult E, FunctionDecl *Decl) {
18207 if (isUnevaluatedContext() || !E.isUsable() || !Decl ||
18208 !Decl->isImmediateFunction() || isAlwaysConstantEvaluatedContext() ||
18209 isCheckingDefaultArgumentOrInitializer() ||
18210 RebuildingImmediateInvocation || isImmediateFunctionContext())
18211 return E;
18212
18213 /// Opportunistically remove the callee from ReferencesToConsteval if we can.
18214 /// It's OK if this fails; we'll also remove this in
18215 /// HandleImmediateInvocations, but catching it here allows us to avoid
18216 /// walking the AST looking for it in simple cases.
18217 if (auto *Call = dyn_cast<CallExpr>(Val: E.get()->IgnoreImplicit()))
18218 if (auto *DeclRef =
18219 dyn_cast<DeclRefExpr>(Val: Call->getCallee()->IgnoreImplicit()))
18220 ExprEvalContexts.back().ReferenceToConsteval.erase(Ptr: DeclRef);
18221
18222 // C++23 [expr.const]/p16
18223 // An expression or conversion is immediate-escalating if it is not initially
18224 // in an immediate function context and it is [...] an immediate invocation
18225 // that is not a constant expression and is not a subexpression of an
18226 // immediate invocation.
18227 APValue Cached;
18228 auto CheckConstantExpressionAndKeepResult = [&]() {
18229 llvm::SmallVector<PartialDiagnosticAt, 8> Notes;
18230 Expr::EvalResult Eval;
18231 Eval.Diag = &Notes;
18232 bool Res = E.get()->EvaluateAsConstantExpr(
18233 Result&: Eval, Ctx: getASTContext(), Kind: ConstantExprKind::ImmediateInvocation);
18234 if (Res && Notes.empty()) {
18235 Cached = std::move(Eval.Val);
18236 return true;
18237 }
18238 return false;
18239 };
18240
18241 if (!E.get()->isValueDependent() &&
18242 ExprEvalContexts.back().InImmediateEscalatingFunctionContext &&
18243 !CheckConstantExpressionAndKeepResult()) {
18244 MarkExpressionAsImmediateEscalating(E: E.get());
18245 return E;
18246 }
18247
18248 if (Cleanup.exprNeedsCleanups()) {
18249 // Since an immediate invocation is a full expression itself - it requires
18250 // an additional ExprWithCleanups node, but it can participate to a bigger
18251 // full expression which actually requires cleanups to be run after so
18252 // create ExprWithCleanups without using MaybeCreateExprWithCleanups as it
18253 // may discard cleanups for outer expression too early.
18254
18255 // Note that ExprWithCleanups created here must always have empty cleanup
18256 // objects:
18257 // - compound literals do not create cleanup objects in C++ and immediate
18258 // invocations are C++-only.
18259 // - blocks are not allowed inside constant expressions and compiler will
18260 // issue an error if they appear there.
18261 //
18262 // Hence, in correct code any cleanup objects created inside current
18263 // evaluation context must be outside the immediate invocation.
18264 E = ExprWithCleanups::Create(C: getASTContext(), subexpr: E.get(),
18265 CleanupsHaveSideEffects: Cleanup.cleanupsHaveSideEffects(), objects: {});
18266 }
18267
18268 ConstantExpr *Res = ConstantExpr::Create(
18269 Context: getASTContext(), E: E.get(),
18270 Storage: ConstantExpr::getStorageKind(T: Decl->getReturnType().getTypePtr(),
18271 Context: getASTContext()),
18272 /*IsImmediateInvocation*/ true);
18273 if (Cached.hasValue())
18274 Res->MoveIntoResult(Value&: Cached, Context: getASTContext());
18275 /// Value-dependent constant expressions should not be immediately
18276 /// evaluated until they are instantiated.
18277 if (!Res->isValueDependent())
18278 ExprEvalContexts.back().ImmediateInvocationCandidates.emplace_back(Args&: Res, Args: 0);
18279 return Res;
18280}
18281
18282static void EvaluateAndDiagnoseImmediateInvocation(
18283 Sema &SemaRef, Sema::ImmediateInvocationCandidate Candidate) {
18284 llvm::SmallVector<PartialDiagnosticAt, 8> Notes;
18285 Expr::EvalResult Eval;
18286 Eval.Diag = &Notes;
18287 ConstantExpr *CE = Candidate.getPointer();
18288 bool Result = CE->EvaluateAsConstantExpr(
18289 Result&: Eval, Ctx: SemaRef.getASTContext(), Kind: ConstantExprKind::ImmediateInvocation);
18290 if (!Result || !Notes.empty()) {
18291 SemaRef.FailedImmediateInvocations.insert(Ptr: CE);
18292 Expr *InnerExpr = CE->getSubExpr()->IgnoreImplicit();
18293 if (auto *FunctionalCast = dyn_cast<CXXFunctionalCastExpr>(Val: InnerExpr))
18294 InnerExpr = FunctionalCast->getSubExpr()->IgnoreImplicit();
18295 FunctionDecl *FD = nullptr;
18296 if (auto *Call = dyn_cast<CallExpr>(Val: InnerExpr))
18297 FD = cast<FunctionDecl>(Val: Call->getCalleeDecl());
18298 else if (auto *Call = dyn_cast<CXXConstructExpr>(Val: InnerExpr))
18299 FD = Call->getConstructor();
18300 else if (auto *Cast = dyn_cast<CastExpr>(Val: InnerExpr))
18301 FD = dyn_cast_or_null<FunctionDecl>(Val: Cast->getConversionFunction());
18302
18303 assert(FD && FD->isImmediateFunction() &&
18304 "could not find an immediate function in this expression");
18305 if (FD->isInvalidDecl())
18306 return;
18307 SemaRef.Diag(Loc: CE->getBeginLoc(), DiagID: diag::err_invalid_consteval_call)
18308 << FD << FD->isConsteval();
18309 if (auto Context =
18310 SemaRef.InnermostDeclarationWithDelayedImmediateInvocations()) {
18311 SemaRef.Diag(Loc: Context->Loc, DiagID: diag::note_invalid_consteval_initializer)
18312 << Context->Decl;
18313 SemaRef.Diag(Loc: Context->Decl->getBeginLoc(), DiagID: diag::note_declared_at);
18314 }
18315 if (!FD->isConsteval())
18316 SemaRef.DiagnoseImmediateEscalatingReason(FD);
18317 for (auto &Note : Notes)
18318 SemaRef.Diag(Loc: Note.first, PD: Note.second);
18319 return;
18320 }
18321 CE->MoveIntoResult(Value&: Eval.Val, Context: SemaRef.getASTContext());
18322}
18323
18324static void RemoveNestedImmediateInvocation(
18325 Sema &SemaRef, Sema::ExpressionEvaluationContextRecord &Rec,
18326 SmallVector<Sema::ImmediateInvocationCandidate, 4>::reverse_iterator It) {
18327 struct ComplexRemove : TreeTransform<ComplexRemove> {
18328 using Base = TreeTransform<ComplexRemove>;
18329 llvm::SmallPtrSetImpl<DeclRefExpr *> &DRSet;
18330 SmallVector<Sema::ImmediateInvocationCandidate, 4> &IISet;
18331 SmallVector<Sema::ImmediateInvocationCandidate, 4>::reverse_iterator
18332 CurrentII;
18333 ComplexRemove(Sema &SemaRef, llvm::SmallPtrSetImpl<DeclRefExpr *> &DR,
18334 SmallVector<Sema::ImmediateInvocationCandidate, 4> &II,
18335 SmallVector<Sema::ImmediateInvocationCandidate,
18336 4>::reverse_iterator Current)
18337 : Base(SemaRef), DRSet(DR), IISet(II), CurrentII(Current) {}
18338 void RemoveImmediateInvocation(ConstantExpr* E) {
18339 auto It = std::find_if(first: CurrentII, last: IISet.rend(),
18340 pred: [E](Sema::ImmediateInvocationCandidate Elem) {
18341 return Elem.getPointer() == E;
18342 });
18343 // It is possible that some subexpression of the current immediate
18344 // invocation was handled from another expression evaluation context. Do
18345 // not handle the current immediate invocation if some of its
18346 // subexpressions failed before.
18347 if (It == IISet.rend()) {
18348 if (SemaRef.FailedImmediateInvocations.contains(Ptr: E))
18349 CurrentII->setInt(1);
18350 } else {
18351 It->setInt(1); // Mark as deleted
18352 }
18353 }
18354 ExprResult TransformConstantExpr(ConstantExpr *E) {
18355 if (!E->isImmediateInvocation())
18356 return Base::TransformConstantExpr(E);
18357 RemoveImmediateInvocation(E);
18358 return Base::TransformExpr(E: E->getSubExpr());
18359 }
18360 /// Base::TransfromCXXOperatorCallExpr doesn't traverse the callee so
18361 /// we need to remove its DeclRefExpr from the DRSet.
18362 ExprResult TransformCXXOperatorCallExpr(CXXOperatorCallExpr *E) {
18363 DRSet.erase(Ptr: cast<DeclRefExpr>(Val: E->getCallee()->IgnoreImplicit()));
18364 return Base::TransformCXXOperatorCallExpr(E);
18365 }
18366 /// Base::TransformUserDefinedLiteral doesn't preserve the
18367 /// UserDefinedLiteral node.
18368 ExprResult TransformUserDefinedLiteral(UserDefinedLiteral *E) { return E; }
18369 /// Base::TransformInitializer skips ConstantExpr so we need to visit them
18370 /// here.
18371 ExprResult TransformInitializer(Expr *Init, bool NotCopyInit) {
18372 if (!Init)
18373 return Init;
18374
18375 // We cannot use IgnoreImpCasts because we need to preserve
18376 // full expressions.
18377 while (true) {
18378 if (auto *ICE = dyn_cast<ImplicitCastExpr>(Val: Init))
18379 Init = ICE->getSubExpr();
18380 else if (auto *ICE = dyn_cast<MaterializeTemporaryExpr>(Val: Init))
18381 Init = ICE->getSubExpr();
18382 else
18383 break;
18384 }
18385 /// ConstantExprs are the first layer of implicit node to be removed so if
18386 /// Init isn't a ConstantExpr, no ConstantExpr will be skipped.
18387 if (auto *CE = dyn_cast<ConstantExpr>(Val: Init);
18388 CE && CE->isImmediateInvocation())
18389 RemoveImmediateInvocation(E: CE);
18390 return Base::TransformInitializer(Init, NotCopyInit);
18391 }
18392 ExprResult TransformDeclRefExpr(DeclRefExpr *E) {
18393 DRSet.erase(Ptr: E);
18394 return E;
18395 }
18396 ExprResult TransformLambdaExpr(LambdaExpr *E) {
18397 // Do not rebuild lambdas to avoid creating a new type.
18398 // Lambdas have already been processed inside their eval contexts.
18399 return E;
18400 }
18401 bool AlwaysRebuild() { return false; }
18402 bool ReplacingOriginal() { return true; }
18403 bool AllowSkippingCXXConstructExpr() {
18404 bool Res = AllowSkippingFirstCXXConstructExpr;
18405 AllowSkippingFirstCXXConstructExpr = true;
18406 return Res;
18407 }
18408 bool AllowSkippingFirstCXXConstructExpr = true;
18409 } Transformer(SemaRef, Rec.ReferenceToConsteval,
18410 Rec.ImmediateInvocationCandidates, It);
18411
18412 /// CXXConstructExpr with a single argument are getting skipped by
18413 /// TreeTransform in some situtation because they could be implicit. This
18414 /// can only occur for the top-level CXXConstructExpr because it is used
18415 /// nowhere in the expression being transformed therefore will not be rebuilt.
18416 /// Setting AllowSkippingFirstCXXConstructExpr to false will prevent from
18417 /// skipping the first CXXConstructExpr.
18418 if (isa<CXXConstructExpr>(Val: It->getPointer()->IgnoreImplicit()))
18419 Transformer.AllowSkippingFirstCXXConstructExpr = false;
18420
18421 ExprResult Res = Transformer.TransformExpr(E: It->getPointer()->getSubExpr());
18422 // The result may not be usable in case of previous compilation errors.
18423 // In this case evaluation of the expression may result in crash so just
18424 // don't do anything further with the result.
18425 if (Res.isUsable()) {
18426 Res = SemaRef.MaybeCreateExprWithCleanups(SubExpr: Res);
18427 It->getPointer()->setSubExpr(Res.get());
18428 }
18429}
18430
18431static void
18432HandleImmediateInvocations(Sema &SemaRef,
18433 Sema::ExpressionEvaluationContextRecord &Rec) {
18434 if ((Rec.ImmediateInvocationCandidates.size() == 0 &&
18435 Rec.ReferenceToConsteval.size() == 0) ||
18436 Rec.isImmediateFunctionContext() || SemaRef.RebuildingImmediateInvocation)
18437 return;
18438
18439 // An expression or conversion is 'manifestly constant-evaluated' if it is:
18440 // [...]
18441 // - the initializer of a variable that is usable in constant expressions or
18442 // has constant initialization.
18443 if (SemaRef.getLangOpts().CPlusPlus23 &&
18444 Rec.ExprContext ==
18445 Sema::ExpressionEvaluationContextRecord::EK_VariableInit) {
18446 auto *VD = cast<VarDecl>(Val: Rec.ManglingContextDecl);
18447 if (VD->isUsableInConstantExpressions(C: SemaRef.Context) ||
18448 VD->hasConstantInitialization()) {
18449 // An expression or conversion is in an 'immediate function context' if it
18450 // is potentially evaluated and either:
18451 // [...]
18452 // - it is a subexpression of a manifestly constant-evaluated expression
18453 // or conversion.
18454 return;
18455 }
18456 }
18457
18458 /// When we have more than 1 ImmediateInvocationCandidates or previously
18459 /// failed immediate invocations, we need to check for nested
18460 /// ImmediateInvocationCandidates in order to avoid duplicate diagnostics.
18461 /// Otherwise we only need to remove ReferenceToConsteval in the immediate
18462 /// invocation.
18463 if (Rec.ImmediateInvocationCandidates.size() > 1 ||
18464 !SemaRef.FailedImmediateInvocations.empty()) {
18465
18466 /// Prevent sema calls during the tree transform from adding pointers that
18467 /// are already in the sets.
18468 llvm::SaveAndRestore DisableIITracking(
18469 SemaRef.RebuildingImmediateInvocation, true);
18470
18471 /// Prevent diagnostic during tree transfrom as they are duplicates
18472 Sema::TentativeAnalysisScope DisableDiag(SemaRef);
18473
18474 for (auto It = Rec.ImmediateInvocationCandidates.rbegin();
18475 It != Rec.ImmediateInvocationCandidates.rend(); It++)
18476 if (!It->getInt())
18477 RemoveNestedImmediateInvocation(SemaRef, Rec, It);
18478 } else if (Rec.ImmediateInvocationCandidates.size() == 1 &&
18479 Rec.ReferenceToConsteval.size()) {
18480 struct SimpleRemove : DynamicRecursiveASTVisitor {
18481 llvm::SmallPtrSetImpl<DeclRefExpr *> &DRSet;
18482 SimpleRemove(llvm::SmallPtrSetImpl<DeclRefExpr *> &S) : DRSet(S) {}
18483 bool VisitDeclRefExpr(DeclRefExpr *E) override {
18484 DRSet.erase(Ptr: E);
18485 return DRSet.size();
18486 }
18487 } Visitor(Rec.ReferenceToConsteval);
18488 Visitor.TraverseStmt(
18489 S: Rec.ImmediateInvocationCandidates.front().getPointer()->getSubExpr());
18490 }
18491 for (auto CE : Rec.ImmediateInvocationCandidates)
18492 if (!CE.getInt())
18493 EvaluateAndDiagnoseImmediateInvocation(SemaRef, Candidate: CE);
18494 for (auto *DR : Rec.ReferenceToConsteval) {
18495 // If the expression is immediate escalating, it is not an error;
18496 // The outer context itself becomes immediate and further errors,
18497 // if any, will be handled by DiagnoseImmediateEscalatingReason.
18498 if (DR->isImmediateEscalating())
18499 continue;
18500 auto *FD = cast<FunctionDecl>(Val: DR->getDecl());
18501 const NamedDecl *ND = FD;
18502 if (const auto *MD = dyn_cast<CXXMethodDecl>(Val: ND);
18503 MD && (MD->isLambdaStaticInvoker() || isLambdaCallOperator(MD)))
18504 ND = MD->getParent();
18505
18506 // C++23 [expr.const]/p16
18507 // An expression or conversion is immediate-escalating if it is not
18508 // initially in an immediate function context and it is [...] a
18509 // potentially-evaluated id-expression that denotes an immediate function
18510 // that is not a subexpression of an immediate invocation.
18511 bool ImmediateEscalating = false;
18512 bool IsPotentiallyEvaluated =
18513 Rec.Context ==
18514 Sema::ExpressionEvaluationContext::PotentiallyEvaluated ||
18515 Rec.Context ==
18516 Sema::ExpressionEvaluationContext::PotentiallyEvaluatedIfUsed;
18517 if (SemaRef.inTemplateInstantiation() && IsPotentiallyEvaluated)
18518 ImmediateEscalating = Rec.InImmediateEscalatingFunctionContext;
18519
18520 if (!Rec.InImmediateEscalatingFunctionContext ||
18521 (SemaRef.inTemplateInstantiation() && !ImmediateEscalating)) {
18522 SemaRef.Diag(Loc: DR->getBeginLoc(), DiagID: diag::err_invalid_consteval_take_address)
18523 << ND << isa<CXXRecordDecl>(Val: ND) << FD->isConsteval();
18524 if (!FD->getBuiltinID())
18525 SemaRef.Diag(Loc: ND->getLocation(), DiagID: diag::note_declared_at);
18526 if (auto Context =
18527 SemaRef.InnermostDeclarationWithDelayedImmediateInvocations()) {
18528 SemaRef.Diag(Loc: Context->Loc, DiagID: diag::note_invalid_consteval_initializer)
18529 << Context->Decl;
18530 SemaRef.Diag(Loc: Context->Decl->getBeginLoc(), DiagID: diag::note_declared_at);
18531 }
18532 if (FD->isImmediateEscalating() && !FD->isConsteval())
18533 SemaRef.DiagnoseImmediateEscalatingReason(FD);
18534
18535 } else {
18536 SemaRef.MarkExpressionAsImmediateEscalating(E: DR);
18537 }
18538 }
18539}
18540
18541void Sema::PopExpressionEvaluationContext() {
18542 ExpressionEvaluationContextRecord& Rec = ExprEvalContexts.back();
18543 if (!Rec.Lambdas.empty()) {
18544 using ExpressionKind = ExpressionEvaluationContextRecord::ExpressionKind;
18545 if (!getLangOpts().CPlusPlus20 &&
18546 (Rec.ExprContext == ExpressionKind::EK_TemplateArgument ||
18547 Rec.isUnevaluated() ||
18548 (Rec.isConstantEvaluated() && !getLangOpts().CPlusPlus17))) {
18549 unsigned D;
18550 if (Rec.isUnevaluated()) {
18551 // C++11 [expr.prim.lambda]p2:
18552 // A lambda-expression shall not appear in an unevaluated operand
18553 // (Clause 5).
18554 D = diag::err_lambda_unevaluated_operand;
18555 } else if (Rec.isConstantEvaluated() && !getLangOpts().CPlusPlus17) {
18556 // C++1y [expr.const]p2:
18557 // A conditional-expression e is a core constant expression unless the
18558 // evaluation of e, following the rules of the abstract machine, would
18559 // evaluate [...] a lambda-expression.
18560 D = diag::err_lambda_in_constant_expression;
18561 } else if (Rec.ExprContext == ExpressionKind::EK_TemplateArgument) {
18562 // C++17 [expr.prim.lamda]p2:
18563 // A lambda-expression shall not appear [...] in a template-argument.
18564 D = diag::err_lambda_in_invalid_context;
18565 } else
18566 llvm_unreachable("Couldn't infer lambda error message.");
18567
18568 for (const auto *L : Rec.Lambdas)
18569 Diag(Loc: L->getBeginLoc(), DiagID: D);
18570 }
18571 }
18572
18573 // Append the collected materialized temporaries into previous context before
18574 // exit if the previous also is a lifetime extending context.
18575 if (getLangOpts().CPlusPlus23 && Rec.InLifetimeExtendingContext &&
18576 parentEvaluationContext().InLifetimeExtendingContext &&
18577 !Rec.ForRangeLifetimeExtendTemps.empty()) {
18578 parentEvaluationContext().ForRangeLifetimeExtendTemps.append(
18579 RHS: Rec.ForRangeLifetimeExtendTemps);
18580 }
18581
18582 WarnOnPendingNoDerefs(Rec);
18583 HandleImmediateInvocations(SemaRef&: *this, Rec);
18584
18585 // Warn on any volatile-qualified simple-assignments that are not discarded-
18586 // value expressions nor unevaluated operands (those cases get removed from
18587 // this list by CheckUnusedVolatileAssignment).
18588 for (auto *BO : Rec.VolatileAssignmentLHSs)
18589 Diag(Loc: BO->getBeginLoc(), DiagID: diag::warn_deprecated_simple_assign_volatile)
18590 << BO->getType();
18591
18592 // When are coming out of an unevaluated context, clear out any
18593 // temporaries that we may have created as part of the evaluation of
18594 // the expression in that context: they aren't relevant because they
18595 // will never be constructed.
18596 if (Rec.isUnevaluated() || Rec.isConstantEvaluated()) {
18597 ExprCleanupObjects.erase(CS: ExprCleanupObjects.begin() + Rec.NumCleanupObjects,
18598 CE: ExprCleanupObjects.end());
18599 Cleanup = Rec.ParentCleanup;
18600 CleanupVarDeclMarking();
18601 std::swap(LHS&: MaybeODRUseExprs, RHS&: Rec.SavedMaybeODRUseExprs);
18602 // Otherwise, merge the contexts together.
18603 } else {
18604 Cleanup.mergeFrom(Rhs: Rec.ParentCleanup);
18605 MaybeODRUseExprs.insert_range(R&: Rec.SavedMaybeODRUseExprs);
18606 }
18607
18608 DiagnoseMisalignedMembers();
18609
18610 // Pop the current expression evaluation context off the stack.
18611 ExprEvalContexts.pop_back();
18612}
18613
18614void Sema::DiscardCleanupsInEvaluationContext() {
18615 ExprCleanupObjects.erase(
18616 CS: ExprCleanupObjects.begin() + ExprEvalContexts.back().NumCleanupObjects,
18617 CE: ExprCleanupObjects.end());
18618 Cleanup.reset();
18619 MaybeODRUseExprs.clear();
18620}
18621
18622ExprResult Sema::HandleExprEvaluationContextForTypeof(Expr *E) {
18623 ExprResult Result = CheckPlaceholderExpr(E);
18624 if (Result.isInvalid())
18625 return ExprError();
18626 E = Result.get();
18627 if (!E->getType()->isVariablyModifiedType())
18628 return E;
18629 return TransformToPotentiallyEvaluated(E);
18630}
18631
18632/// Are we in a context that is potentially constant evaluated per C++20
18633/// [expr.const]p12?
18634static bool isPotentiallyConstantEvaluatedContext(Sema &SemaRef) {
18635 /// C++2a [expr.const]p12:
18636 // An expression or conversion is potentially constant evaluated if it is
18637 switch (SemaRef.ExprEvalContexts.back().Context) {
18638 case Sema::ExpressionEvaluationContext::ConstantEvaluated:
18639 case Sema::ExpressionEvaluationContext::ImmediateFunctionContext:
18640
18641 // -- a manifestly constant-evaluated expression,
18642 case Sema::ExpressionEvaluationContext::PotentiallyEvaluated:
18643 case Sema::ExpressionEvaluationContext::PotentiallyEvaluatedIfUsed:
18644 case Sema::ExpressionEvaluationContext::DiscardedStatement:
18645 // -- a potentially-evaluated expression,
18646 case Sema::ExpressionEvaluationContext::UnevaluatedList:
18647 // -- an immediate subexpression of a braced-init-list,
18648
18649 // -- [FIXME] an expression of the form & cast-expression that occurs
18650 // within a templated entity
18651 // -- a subexpression of one of the above that is not a subexpression of
18652 // a nested unevaluated operand.
18653 return true;
18654
18655 case Sema::ExpressionEvaluationContext::Unevaluated:
18656 case Sema::ExpressionEvaluationContext::UnevaluatedAbstract:
18657 // Expressions in this context are never evaluated.
18658 return false;
18659 }
18660 llvm_unreachable("Invalid context");
18661}
18662
18663/// Return true if this function has a calling convention that requires mangling
18664/// in the size of the parameter pack.
18665static bool funcHasParameterSizeMangling(Sema &S, FunctionDecl *FD) {
18666 // These manglings are only applicable for targets whcih use Microsoft
18667 // mangling scheme for C.
18668 if (!S.Context.getTargetInfo().shouldUseMicrosoftCCforMangling())
18669 return false;
18670
18671 // If this is C++ and this isn't an extern "C" function, parameters do not
18672 // need to be complete. In this case, C++ mangling will apply, which doesn't
18673 // use the size of the parameters.
18674 if (S.getLangOpts().CPlusPlus && !FD->isExternC())
18675 return false;
18676
18677 // Stdcall, fastcall, and vectorcall need this special treatment.
18678 CallingConv CC = FD->getType()->castAs<FunctionType>()->getCallConv();
18679 switch (CC) {
18680 case CC_X86StdCall:
18681 case CC_X86FastCall:
18682 case CC_X86VectorCall:
18683 return true;
18684 default:
18685 break;
18686 }
18687 return false;
18688}
18689
18690/// Require that all of the parameter types of function be complete. Normally,
18691/// parameter types are only required to be complete when a function is called
18692/// or defined, but to mangle functions with certain calling conventions, the
18693/// mangler needs to know the size of the parameter list. In this situation,
18694/// MSVC doesn't emit an error or instantiate templates. Instead, MSVC mangles
18695/// the function as _foo@0, i.e. zero bytes of parameters, which will usually
18696/// result in a linker error. Clang doesn't implement this behavior, and instead
18697/// attempts to error at compile time.
18698static void CheckCompleteParameterTypesForMangler(Sema &S, FunctionDecl *FD,
18699 SourceLocation Loc) {
18700 class ParamIncompleteTypeDiagnoser : public Sema::TypeDiagnoser {
18701 FunctionDecl *FD;
18702 ParmVarDecl *Param;
18703
18704 public:
18705 ParamIncompleteTypeDiagnoser(FunctionDecl *FD, ParmVarDecl *Param)
18706 : FD(FD), Param(Param) {}
18707
18708 void diagnose(Sema &S, SourceLocation Loc, QualType T) override {
18709 CallingConv CC = FD->getType()->castAs<FunctionType>()->getCallConv();
18710 StringRef CCName;
18711 switch (CC) {
18712 case CC_X86StdCall:
18713 CCName = "stdcall";
18714 break;
18715 case CC_X86FastCall:
18716 CCName = "fastcall";
18717 break;
18718 case CC_X86VectorCall:
18719 CCName = "vectorcall";
18720 break;
18721 default:
18722 llvm_unreachable("CC does not need mangling");
18723 }
18724
18725 S.Diag(Loc, DiagID: diag::err_cconv_incomplete_param_type)
18726 << Param->getDeclName() << FD->getDeclName() << CCName;
18727 }
18728 };
18729
18730 for (ParmVarDecl *Param : FD->parameters()) {
18731 ParamIncompleteTypeDiagnoser Diagnoser(FD, Param);
18732 S.RequireCompleteType(Loc, T: Param->getType(), Diagnoser);
18733 }
18734}
18735
18736namespace {
18737enum class OdrUseContext {
18738 /// Declarations in this context are not odr-used.
18739 None,
18740 /// Declarations in this context are formally odr-used, but this is a
18741 /// dependent context.
18742 Dependent,
18743 /// Declarations in this context are odr-used but not actually used (yet).
18744 FormallyOdrUsed,
18745 /// Declarations in this context are used.
18746 Used
18747};
18748}
18749
18750/// Are we within a context in which references to resolved functions or to
18751/// variables result in odr-use?
18752static OdrUseContext isOdrUseContext(Sema &SemaRef) {
18753 const Sema::ExpressionEvaluationContextRecord &Context =
18754 SemaRef.currentEvaluationContext();
18755
18756 if (Context.isUnevaluated())
18757 return OdrUseContext::None;
18758
18759 if (SemaRef.CurContext->isDependentContext())
18760 return OdrUseContext::Dependent;
18761
18762 if (Context.isDiscardedStatementContext())
18763 return OdrUseContext::FormallyOdrUsed;
18764
18765 else if (Context.Context ==
18766 Sema::ExpressionEvaluationContext::PotentiallyEvaluatedIfUsed)
18767 return OdrUseContext::FormallyOdrUsed;
18768
18769 return OdrUseContext::Used;
18770}
18771
18772static bool isImplicitlyDefinableConstexprFunction(FunctionDecl *Func) {
18773 if (!Func->isConstexpr())
18774 return false;
18775
18776 if (Func->isImplicitlyInstantiable() || !Func->isUserProvided())
18777 return true;
18778
18779 // Lambda conversion operators are never user provided.
18780 if (CXXConversionDecl *Conv = dyn_cast<CXXConversionDecl>(Val: Func))
18781 return isLambdaConversionOperator(C: Conv);
18782
18783 auto *CCD = dyn_cast<CXXConstructorDecl>(Val: Func);
18784 return CCD && CCD->getInheritedConstructor();
18785}
18786
18787void Sema::MarkFunctionReferenced(SourceLocation Loc, FunctionDecl *Func,
18788 bool MightBeOdrUse) {
18789 assert(Func && "No function?");
18790
18791 Func->setReferenced();
18792
18793 // Recursive functions aren't really used until they're used from some other
18794 // context.
18795 bool IsRecursiveCall = CurContext == Func;
18796
18797 // C++11 [basic.def.odr]p3:
18798 // A function whose name appears as a potentially-evaluated expression is
18799 // odr-used if it is the unique lookup result or the selected member of a
18800 // set of overloaded functions [...].
18801 //
18802 // We (incorrectly) mark overload resolution as an unevaluated context, so we
18803 // can just check that here.
18804 OdrUseContext OdrUse =
18805 MightBeOdrUse ? isOdrUseContext(SemaRef&: *this) : OdrUseContext::None;
18806 if (IsRecursiveCall && OdrUse == OdrUseContext::Used)
18807 OdrUse = OdrUseContext::FormallyOdrUsed;
18808
18809 // Trivial default constructors and destructors are never actually used.
18810 // FIXME: What about other special members?
18811 if (Func->isTrivial() && !Func->hasAttr<DLLExportAttr>() &&
18812 OdrUse == OdrUseContext::Used) {
18813 if (auto *Constructor = dyn_cast<CXXConstructorDecl>(Val: Func))
18814 if (Constructor->isDefaultConstructor())
18815 OdrUse = OdrUseContext::FormallyOdrUsed;
18816 if (isa<CXXDestructorDecl>(Val: Func))
18817 OdrUse = OdrUseContext::FormallyOdrUsed;
18818 }
18819
18820 // C++20 [expr.const]p12:
18821 // A function [...] is needed for constant evaluation if it is [...] a
18822 // constexpr function that is named by an expression that is potentially
18823 // constant evaluated
18824 bool NeededForConstantEvaluation =
18825 isPotentiallyConstantEvaluatedContext(SemaRef&: *this) &&
18826 isImplicitlyDefinableConstexprFunction(Func);
18827
18828 // Determine whether we require a function definition to exist, per
18829 // C++11 [temp.inst]p3:
18830 // Unless a function template specialization has been explicitly
18831 // instantiated or explicitly specialized, the function template
18832 // specialization is implicitly instantiated when the specialization is
18833 // referenced in a context that requires a function definition to exist.
18834 // C++20 [temp.inst]p7:
18835 // The existence of a definition of a [...] function is considered to
18836 // affect the semantics of the program if the [...] function is needed for
18837 // constant evaluation by an expression
18838 // C++20 [basic.def.odr]p10:
18839 // Every program shall contain exactly one definition of every non-inline
18840 // function or variable that is odr-used in that program outside of a
18841 // discarded statement
18842 // C++20 [special]p1:
18843 // The implementation will implicitly define [defaulted special members]
18844 // if they are odr-used or needed for constant evaluation.
18845 //
18846 // Note that we skip the implicit instantiation of templates that are only
18847 // used in unused default arguments or by recursive calls to themselves.
18848 // This is formally non-conforming, but seems reasonable in practice.
18849 bool NeedDefinition =
18850 !IsRecursiveCall &&
18851 (OdrUse == OdrUseContext::Used ||
18852 (NeededForConstantEvaluation && !Func->isPureVirtual()));
18853
18854 // C++14 [temp.expl.spec]p6:
18855 // If a template [...] is explicitly specialized then that specialization
18856 // shall be declared before the first use of that specialization that would
18857 // cause an implicit instantiation to take place, in every translation unit
18858 // in which such a use occurs
18859 if (NeedDefinition &&
18860 (Func->getTemplateSpecializationKind() != TSK_Undeclared ||
18861 Func->getMemberSpecializationInfo()))
18862 checkSpecializationReachability(Loc, Spec: Func);
18863
18864 if (getLangOpts().CUDA)
18865 CUDA().CheckCall(Loc, Callee: Func);
18866
18867 // If we need a definition, try to create one.
18868 if (NeedDefinition && !Func->getBody()) {
18869 runWithSufficientStackSpace(Loc, Fn: [&] {
18870 if (CXXConstructorDecl *Constructor =
18871 dyn_cast<CXXConstructorDecl>(Val: Func)) {
18872 Constructor = cast<CXXConstructorDecl>(Val: Constructor->getFirstDecl());
18873 if (Constructor->isDefaulted() && !Constructor->isDeleted()) {
18874 if (Constructor->isDefaultConstructor()) {
18875 if (Constructor->isTrivial() &&
18876 !Constructor->hasAttr<DLLExportAttr>())
18877 return;
18878 DefineImplicitDefaultConstructor(CurrentLocation: Loc, Constructor);
18879 } else if (Constructor->isCopyConstructor()) {
18880 DefineImplicitCopyConstructor(CurrentLocation: Loc, Constructor);
18881 } else if (Constructor->isMoveConstructor()) {
18882 DefineImplicitMoveConstructor(CurrentLocation: Loc, Constructor);
18883 }
18884 } else if (Constructor->getInheritedConstructor()) {
18885 DefineInheritingConstructor(UseLoc: Loc, Constructor);
18886 }
18887 } else if (CXXDestructorDecl *Destructor =
18888 dyn_cast<CXXDestructorDecl>(Val: Func)) {
18889 Destructor = cast<CXXDestructorDecl>(Val: Destructor->getFirstDecl());
18890 if (Destructor->isDefaulted() && !Destructor->isDeleted()) {
18891 if (Destructor->isTrivial() && !Destructor->hasAttr<DLLExportAttr>())
18892 return;
18893 DefineImplicitDestructor(CurrentLocation: Loc, Destructor);
18894 }
18895 if (Destructor->isVirtual() && getLangOpts().AppleKext)
18896 MarkVTableUsed(Loc, Class: Destructor->getParent());
18897 } else if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(Val: Func)) {
18898 if (MethodDecl->isOverloadedOperator() &&
18899 MethodDecl->getOverloadedOperator() == OO_Equal) {
18900 MethodDecl = cast<CXXMethodDecl>(Val: MethodDecl->getFirstDecl());
18901 if (MethodDecl->isDefaulted() && !MethodDecl->isDeleted()) {
18902 if (MethodDecl->isCopyAssignmentOperator())
18903 DefineImplicitCopyAssignment(CurrentLocation: Loc, MethodDecl);
18904 else if (MethodDecl->isMoveAssignmentOperator())
18905 DefineImplicitMoveAssignment(CurrentLocation: Loc, MethodDecl);
18906 }
18907 } else if (isa<CXXConversionDecl>(Val: MethodDecl) &&
18908 MethodDecl->getParent()->isLambda()) {
18909 CXXConversionDecl *Conversion =
18910 cast<CXXConversionDecl>(Val: MethodDecl->getFirstDecl());
18911 if (Conversion->isLambdaToBlockPointerConversion())
18912 DefineImplicitLambdaToBlockPointerConversion(CurrentLoc: Loc, Conv: Conversion);
18913 else
18914 DefineImplicitLambdaToFunctionPointerConversion(CurrentLoc: Loc, Conv: Conversion);
18915 } else if (MethodDecl->isVirtual() && getLangOpts().AppleKext)
18916 MarkVTableUsed(Loc, Class: MethodDecl->getParent());
18917 }
18918
18919 if (Func->isDefaulted() && !Func->isDeleted()) {
18920 DefaultedComparisonKind DCK = getDefaultedComparisonKind(FD: Func);
18921 if (DCK != DefaultedComparisonKind::None)
18922 DefineDefaultedComparison(Loc, FD: Func, DCK);
18923 }
18924
18925 // Implicit instantiation of function templates and member functions of
18926 // class templates.
18927 if (Func->isImplicitlyInstantiable()) {
18928 TemplateSpecializationKind TSK =
18929 Func->getTemplateSpecializationKindForInstantiation();
18930 SourceLocation PointOfInstantiation = Func->getPointOfInstantiation();
18931 bool FirstInstantiation = PointOfInstantiation.isInvalid();
18932 if (FirstInstantiation) {
18933 PointOfInstantiation = Loc;
18934 if (auto *MSI = Func->getMemberSpecializationInfo())
18935 MSI->setPointOfInstantiation(Loc);
18936 // FIXME: Notify listener.
18937 else
18938 Func->setTemplateSpecializationKind(TSK, PointOfInstantiation);
18939 } else if (TSK != TSK_ImplicitInstantiation) {
18940 // Use the point of use as the point of instantiation, instead of the
18941 // point of explicit instantiation (which we track as the actual point
18942 // of instantiation). This gives better backtraces in diagnostics.
18943 PointOfInstantiation = Loc;
18944 }
18945
18946 if (FirstInstantiation || TSK != TSK_ImplicitInstantiation ||
18947 Func->isConstexpr()) {
18948 if (isa<CXXRecordDecl>(Val: Func->getDeclContext()) &&
18949 cast<CXXRecordDecl>(Val: Func->getDeclContext())->isLocalClass() &&
18950 CodeSynthesisContexts.size())
18951 PendingLocalImplicitInstantiations.push_back(
18952 x: std::make_pair(x&: Func, y&: PointOfInstantiation));
18953 else if (Func->isConstexpr())
18954 // Do not defer instantiations of constexpr functions, to avoid the
18955 // expression evaluator needing to call back into Sema if it sees a
18956 // call to such a function.
18957 InstantiateFunctionDefinition(PointOfInstantiation, Function: Func);
18958 else {
18959 Func->setInstantiationIsPending(true);
18960 PendingInstantiations.push_back(
18961 x: std::make_pair(x&: Func, y&: PointOfInstantiation));
18962 if (llvm::isTimeTraceVerbose()) {
18963 llvm::timeTraceAddInstantEvent(Name: "DeferInstantiation", Detail: [&] {
18964 std::string Name;
18965 llvm::raw_string_ostream OS(Name);
18966 Func->getNameForDiagnostic(OS, Policy: getPrintingPolicy(),
18967 /*Qualified=*/true);
18968 return Name;
18969 });
18970 }
18971 // Notify the consumer that a function was implicitly instantiated.
18972 Consumer.HandleCXXImplicitFunctionInstantiation(D: Func);
18973 }
18974 }
18975 } else {
18976 // Walk redefinitions, as some of them may be instantiable.
18977 for (auto *i : Func->redecls()) {
18978 if (!i->isUsed(CheckUsedAttr: false) && i->isImplicitlyInstantiable())
18979 MarkFunctionReferenced(Loc, Func: i, MightBeOdrUse);
18980 }
18981 }
18982 });
18983 }
18984
18985 // If a constructor was defined in the context of a default parameter
18986 // or of another default member initializer (ie a PotentiallyEvaluatedIfUsed
18987 // context), its initializers may not be referenced yet.
18988 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Val: Func)) {
18989 EnterExpressionEvaluationContext EvalContext(
18990 *this,
18991 Constructor->isImmediateFunction()
18992 ? ExpressionEvaluationContext::ImmediateFunctionContext
18993 : ExpressionEvaluationContext::PotentiallyEvaluated,
18994 Constructor);
18995 for (CXXCtorInitializer *Init : Constructor->inits()) {
18996 if (Init->isInClassMemberInitializer())
18997 runWithSufficientStackSpace(Loc: Init->getSourceLocation(), Fn: [&]() {
18998 MarkDeclarationsReferencedInExpr(E: Init->getInit());
18999 });
19000 }
19001 }
19002
19003 // C++14 [except.spec]p17:
19004 // An exception-specification is considered to be needed when:
19005 // - the function is odr-used or, if it appears in an unevaluated operand,
19006 // would be odr-used if the expression were potentially-evaluated;
19007 //
19008 // Note, we do this even if MightBeOdrUse is false. That indicates that the
19009 // function is a pure virtual function we're calling, and in that case the
19010 // function was selected by overload resolution and we need to resolve its
19011 // exception specification for a different reason.
19012 const FunctionProtoType *FPT = Func->getType()->getAs<FunctionProtoType>();
19013 if (FPT && isUnresolvedExceptionSpec(ESpecType: FPT->getExceptionSpecType()))
19014 ResolveExceptionSpec(Loc, FPT);
19015
19016 // A callee could be called by a host function then by a device function.
19017 // If we only try recording once, we will miss recording the use on device
19018 // side. Therefore keep trying until it is recorded.
19019 if (LangOpts.OffloadImplicitHostDeviceTemplates && LangOpts.CUDAIsDevice &&
19020 !getASTContext().CUDAImplicitHostDeviceFunUsedByDevice.count(V: Func))
19021 CUDA().RecordImplicitHostDeviceFuncUsedByDevice(FD: Func);
19022
19023 // If this is the first "real" use, act on that.
19024 if (OdrUse == OdrUseContext::Used && !Func->isUsed(/*CheckUsedAttr=*/false)) {
19025 // Keep track of used but undefined functions.
19026 if (!Func->isDefined() && !Func->isInAnotherModuleUnit()) {
19027 if (mightHaveNonExternalLinkage(FD: Func))
19028 UndefinedButUsed.insert(KV: std::make_pair(x: Func->getCanonicalDecl(), y&: Loc));
19029 else if (Func->getMostRecentDecl()->isInlined() &&
19030 !LangOpts.GNUInline &&
19031 !Func->getMostRecentDecl()->hasAttr<GNUInlineAttr>())
19032 UndefinedButUsed.insert(KV: std::make_pair(x: Func->getCanonicalDecl(), y&: Loc));
19033 else if (isExternalWithNoLinkageType(VD: Func))
19034 UndefinedButUsed.insert(KV: std::make_pair(x: Func->getCanonicalDecl(), y&: Loc));
19035 }
19036
19037 // Some x86 Windows calling conventions mangle the size of the parameter
19038 // pack into the name. Computing the size of the parameters requires the
19039 // parameter types to be complete. Check that now.
19040 if (funcHasParameterSizeMangling(S&: *this, FD: Func))
19041 CheckCompleteParameterTypesForMangler(S&: *this, FD: Func, Loc);
19042
19043 // In the MS C++ ABI, the compiler emits destructor variants where they are
19044 // used. If the destructor is used here but defined elsewhere, mark the
19045 // virtual base destructors referenced. If those virtual base destructors
19046 // are inline, this will ensure they are defined when emitting the complete
19047 // destructor variant. This checking may be redundant if the destructor is
19048 // provided later in this TU.
19049 if (Context.getTargetInfo().getCXXABI().isMicrosoft()) {
19050 if (auto *Dtor = dyn_cast<CXXDestructorDecl>(Val: Func)) {
19051 CXXRecordDecl *Parent = Dtor->getParent();
19052 if (Parent->getNumVBases() > 0 && !Dtor->getBody())
19053 CheckCompleteDestructorVariant(CurrentLocation: Loc, Dtor);
19054 }
19055 }
19056
19057 Func->markUsed(C&: Context);
19058 }
19059}
19060
19061/// Directly mark a variable odr-used. Given a choice, prefer to use
19062/// MarkVariableReferenced since it does additional checks and then
19063/// calls MarkVarDeclODRUsed.
19064/// If the variable must be captured:
19065/// - if FunctionScopeIndexToStopAt is null, capture it in the CurContext
19066/// - else capture it in the DeclContext that maps to the
19067/// *FunctionScopeIndexToStopAt on the FunctionScopeInfo stack.
19068static void
19069MarkVarDeclODRUsed(ValueDecl *V, SourceLocation Loc, Sema &SemaRef,
19070 const unsigned *const FunctionScopeIndexToStopAt = nullptr) {
19071 // Keep track of used but undefined variables.
19072 // FIXME: We shouldn't suppress this warning for static data members.
19073 VarDecl *Var = V->getPotentiallyDecomposedVarDecl();
19074 assert(Var && "expected a capturable variable");
19075
19076 if (Var->hasDefinition(SemaRef.Context) == VarDecl::DeclarationOnly &&
19077 (!Var->isExternallyVisible() || Var->isInline() ||
19078 SemaRef.isExternalWithNoLinkageType(VD: Var)) &&
19079 !(Var->isStaticDataMember() && Var->hasInit())) {
19080 SourceLocation &old = SemaRef.UndefinedButUsed[Var->getCanonicalDecl()];
19081 if (old.isInvalid())
19082 old = Loc;
19083 }
19084 QualType CaptureType, DeclRefType;
19085 if (SemaRef.LangOpts.OpenMP)
19086 SemaRef.OpenMP().tryCaptureOpenMPLambdas(V);
19087 SemaRef.tryCaptureVariable(Var: V, Loc, Kind: TryCaptureKind::Implicit,
19088 /*EllipsisLoc*/ SourceLocation(),
19089 /*BuildAndDiagnose*/ true, CaptureType,
19090 DeclRefType, FunctionScopeIndexToStopAt);
19091
19092 if (SemaRef.LangOpts.CUDA && Var->hasGlobalStorage()) {
19093 auto *FD = dyn_cast_or_null<FunctionDecl>(Val: SemaRef.CurContext);
19094 auto VarTarget = SemaRef.CUDA().IdentifyTarget(D: Var);
19095 auto UserTarget = SemaRef.CUDA().IdentifyTarget(D: FD);
19096 if (VarTarget == SemaCUDA::CVT_Host &&
19097 (UserTarget == CUDAFunctionTarget::Device ||
19098 UserTarget == CUDAFunctionTarget::HostDevice ||
19099 UserTarget == CUDAFunctionTarget::Global)) {
19100 // Diagnose ODR-use of host global variables in device functions.
19101 // Reference of device global variables in host functions is allowed
19102 // through shadow variables therefore it is not diagnosed.
19103 if (SemaRef.LangOpts.CUDAIsDevice && !SemaRef.LangOpts.HIPStdPar) {
19104 SemaRef.targetDiag(Loc, DiagID: diag::err_ref_bad_target)
19105 << /*host*/ 2 << /*variable*/ 1 << Var << UserTarget;
19106 SemaRef.targetDiag(Loc: Var->getLocation(),
19107 DiagID: Var->getType().isConstQualified()
19108 ? diag::note_cuda_const_var_unpromoted
19109 : diag::note_cuda_host_var);
19110 }
19111 } else if ((VarTarget == SemaCUDA::CVT_Device ||
19112 // Also capture __device__ const variables, which are classified
19113 // as CVT_Both due to an implicit CUDAConstantAttr. We check for
19114 // an explicit CUDADeviceAttr to distinguish them from plain
19115 // const variables (no __device__), which also get CVT_Both but
19116 // only have an implicit CUDADeviceAttr.
19117 (VarTarget == SemaCUDA::CVT_Both &&
19118 Var->hasAttr<CUDADeviceAttr>() &&
19119 !Var->getAttr<CUDADeviceAttr>()->isImplicit())) &&
19120 !Var->hasAttr<CUDASharedAttr>() &&
19121 (UserTarget == CUDAFunctionTarget::Host ||
19122 UserTarget == CUDAFunctionTarget::HostDevice)) {
19123 // Record a CUDA/HIP device side variable if it is ODR-used
19124 // by host code. This is done conservatively, when the variable is
19125 // referenced in any of the following contexts:
19126 // - a non-function context
19127 // - a host function
19128 // - a host device function
19129 // This makes the ODR-use of the device side variable by host code to
19130 // be visible in the device compilation for the compiler to be able to
19131 // emit template variables instantiated by host code only and to
19132 // externalize the static device side variable ODR-used by host code.
19133 if (!Var->hasExternalStorage())
19134 SemaRef.getASTContext().CUDADeviceVarODRUsedByHost.insert(V: Var);
19135 else if (SemaRef.LangOpts.GPURelocatableDeviceCode &&
19136 (!FD || (!FD->getDescribedFunctionTemplate() &&
19137 SemaRef.getASTContext().GetGVALinkageForFunction(FD) ==
19138 GVA_StrongExternal)))
19139 SemaRef.getASTContext().CUDAExternalDeviceDeclODRUsedByHost.insert(X: Var);
19140 }
19141 }
19142
19143 V->markUsed(C&: SemaRef.Context);
19144}
19145
19146void Sema::MarkCaptureUsedInEnclosingContext(ValueDecl *Capture,
19147 SourceLocation Loc,
19148 unsigned CapturingScopeIndex) {
19149 MarkVarDeclODRUsed(V: Capture, Loc, SemaRef&: *this, FunctionScopeIndexToStopAt: &CapturingScopeIndex);
19150}
19151
19152static void diagnoseUncapturableValueReferenceOrBinding(Sema &S,
19153 SourceLocation loc,
19154 ValueDecl *var) {
19155 DeclContext *VarDC = var->getDeclContext();
19156
19157 // If the parameter still belongs to the translation unit, then
19158 // we're actually just using one parameter in the declaration of
19159 // the next.
19160 if (isa<ParmVarDecl>(Val: var) &&
19161 isa<TranslationUnitDecl>(Val: VarDC))
19162 return;
19163
19164 // For C code, don't diagnose about capture if we're not actually in code
19165 // right now; it's impossible to write a non-constant expression outside of
19166 // function context, so we'll get other (more useful) diagnostics later.
19167 //
19168 // For C++, things get a bit more nasty... it would be nice to suppress this
19169 // diagnostic for certain cases like using a local variable in an array bound
19170 // for a member of a local class, but the correct predicate is not obvious.
19171 if (!S.getLangOpts().CPlusPlus && !S.CurContext->isFunctionOrMethod())
19172 return;
19173
19174 unsigned ValueKind = isa<BindingDecl>(Val: var) ? 1 : 0;
19175 unsigned ContextKind = 3; // unknown
19176 if (isa<CXXMethodDecl>(Val: VarDC) &&
19177 cast<CXXRecordDecl>(Val: VarDC->getParent())->isLambda()) {
19178 ContextKind = 2;
19179 } else if (isa<FunctionDecl>(Val: VarDC)) {
19180 ContextKind = 0;
19181 } else if (isa<BlockDecl>(Val: VarDC)) {
19182 ContextKind = 1;
19183 }
19184
19185 S.Diag(Loc: loc, DiagID: diag::err_reference_to_local_in_enclosing_context)
19186 << var << ValueKind << ContextKind << VarDC;
19187 S.Diag(Loc: var->getLocation(), DiagID: diag::note_entity_declared_at)
19188 << var;
19189
19190 // FIXME: Add additional diagnostic info about class etc. which prevents
19191 // capture.
19192}
19193
19194static bool isVariableAlreadyCapturedInScopeInfo(CapturingScopeInfo *CSI,
19195 ValueDecl *Var,
19196 bool &SubCapturesAreNested,
19197 QualType &CaptureType,
19198 QualType &DeclRefType) {
19199 // Check whether we've already captured it.
19200 if (CSI->CaptureMap.count(Val: Var)) {
19201 // If we found a capture, any subcaptures are nested.
19202 SubCapturesAreNested = true;
19203
19204 // Retrieve the capture type for this variable.
19205 CaptureType = CSI->getCapture(Var).getCaptureType();
19206
19207 // Compute the type of an expression that refers to this variable.
19208 DeclRefType = CaptureType.getNonReferenceType();
19209
19210 // Similarly to mutable captures in lambda, all the OpenMP captures by copy
19211 // are mutable in the sense that user can change their value - they are
19212 // private instances of the captured declarations.
19213 const Capture &Cap = CSI->getCapture(Var);
19214 // C++ [expr.prim.lambda]p10:
19215 // The type of such a data member is [...] an lvalue reference to the
19216 // referenced function type if the entity is a reference to a function.
19217 // [...]
19218 if (Cap.isCopyCapture() && !DeclRefType->isFunctionType() &&
19219 !(isa<LambdaScopeInfo>(Val: CSI) &&
19220 !cast<LambdaScopeInfo>(Val: CSI)->lambdaCaptureShouldBeConst()) &&
19221 !(isa<CapturedRegionScopeInfo>(Val: CSI) &&
19222 cast<CapturedRegionScopeInfo>(Val: CSI)->CapRegionKind == CR_OpenMP))
19223 DeclRefType.addConst();
19224 return true;
19225 }
19226 return false;
19227}
19228
19229// Only block literals, captured statements, and lambda expressions can
19230// capture; other scopes don't work.
19231static DeclContext *getParentOfCapturingContextOrNull(DeclContext *DC,
19232 ValueDecl *Var,
19233 SourceLocation Loc,
19234 const bool Diagnose,
19235 Sema &S) {
19236 if (isa<BlockDecl>(Val: DC) || isa<CapturedDecl>(Val: DC) || isLambdaCallOperator(DC))
19237 return getLambdaAwareParentOfDeclContext(DC);
19238
19239 VarDecl *Underlying = Var->getPotentiallyDecomposedVarDecl();
19240 if (Underlying) {
19241 if (Underlying->hasLocalStorage() && Diagnose)
19242 diagnoseUncapturableValueReferenceOrBinding(S, loc: Loc, var: Var);
19243 }
19244 return nullptr;
19245}
19246
19247// Certain capturing entities (lambdas, blocks etc.) are not allowed to capture
19248// certain types of variables (unnamed, variably modified types etc.)
19249// so check for eligibility.
19250static bool isVariableCapturable(CapturingScopeInfo *CSI, ValueDecl *Var,
19251 SourceLocation Loc, const bool Diagnose,
19252 Sema &S) {
19253
19254 assert((isa<VarDecl, BindingDecl>(Var)) &&
19255 "Only variables and structured bindings can be captured");
19256
19257 bool IsBlock = isa<BlockScopeInfo>(Val: CSI);
19258 bool IsLambda = isa<LambdaScopeInfo>(Val: CSI);
19259
19260 // Lambdas are not allowed to capture unnamed variables
19261 // (e.g. anonymous unions).
19262 // FIXME: The C++11 rule don't actually state this explicitly, but I'm
19263 // assuming that's the intent.
19264 if (IsLambda && !Var->getDeclName()) {
19265 if (Diagnose) {
19266 S.Diag(Loc, DiagID: diag::err_lambda_capture_anonymous_var);
19267 S.Diag(Loc: Var->getLocation(), DiagID: diag::note_declared_at);
19268 }
19269 return false;
19270 }
19271
19272 // Prohibit variably-modified types in blocks; they're difficult to deal with.
19273 if (Var->getType()->isVariablyModifiedType() && IsBlock) {
19274 if (Diagnose) {
19275 S.Diag(Loc, DiagID: diag::err_ref_vm_type);
19276 S.Diag(Loc: Var->getLocation(), DiagID: diag::note_previous_decl) << Var;
19277 }
19278 return false;
19279 }
19280 // Prohibit structs with flexible array members too.
19281 // We cannot capture what is in the tail end of the struct.
19282 if (const auto *VTD = Var->getType()->getAsRecordDecl();
19283 VTD && VTD->hasFlexibleArrayMember()) {
19284 if (Diagnose) {
19285 if (IsBlock)
19286 S.Diag(Loc, DiagID: diag::err_ref_flexarray_type);
19287 else
19288 S.Diag(Loc, DiagID: diag::err_lambda_capture_flexarray_type) << Var;
19289 S.Diag(Loc: Var->getLocation(), DiagID: diag::note_previous_decl) << Var;
19290 }
19291 return false;
19292 }
19293 const bool HasBlocksAttr = Var->hasAttr<BlocksAttr>();
19294 // Lambdas and captured statements are not allowed to capture __block
19295 // variables; they don't support the expected semantics.
19296 if (HasBlocksAttr && (IsLambda || isa<CapturedRegionScopeInfo>(Val: CSI))) {
19297 if (Diagnose) {
19298 S.Diag(Loc, DiagID: diag::err_capture_block_variable) << Var << !IsLambda;
19299 S.Diag(Loc: Var->getLocation(), DiagID: diag::note_previous_decl) << Var;
19300 }
19301 return false;
19302 }
19303 // OpenCL v2.0 s6.12.5: Blocks cannot reference/capture other blocks
19304 if (S.getLangOpts().OpenCL && IsBlock &&
19305 Var->getType()->isBlockPointerType()) {
19306 if (Diagnose)
19307 S.Diag(Loc, DiagID: diag::err_opencl_block_ref_block);
19308 return false;
19309 }
19310
19311 if (isa<BindingDecl>(Val: Var)) {
19312 if (!IsLambda || !S.getLangOpts().CPlusPlus) {
19313 if (Diagnose)
19314 diagnoseUncapturableValueReferenceOrBinding(S, loc: Loc, var: Var);
19315 return false;
19316 } else if (Diagnose && S.getLangOpts().CPlusPlus) {
19317 S.Diag(Loc, DiagID: S.LangOpts.CPlusPlus20
19318 ? diag::warn_cxx17_compat_capture_binding
19319 : diag::ext_capture_binding)
19320 << Var;
19321 S.Diag(Loc: Var->getLocation(), DiagID: diag::note_entity_declared_at) << Var;
19322 }
19323 }
19324
19325 return true;
19326}
19327
19328// Returns true if the capture by block was successful.
19329static bool captureInBlock(BlockScopeInfo *BSI, ValueDecl *Var,
19330 SourceLocation Loc, const bool BuildAndDiagnose,
19331 QualType &CaptureType, QualType &DeclRefType,
19332 const bool Nested, Sema &S, bool Invalid) {
19333 bool ByRef = false;
19334
19335 // Blocks are not allowed to capture arrays, excepting OpenCL.
19336 // OpenCL v2.0 s1.12.5 (revision 40): arrays are captured by reference
19337 // (decayed to pointers).
19338 if (!Invalid && !S.getLangOpts().OpenCL && CaptureType->isArrayType()) {
19339 if (BuildAndDiagnose) {
19340 S.Diag(Loc, DiagID: diag::err_ref_array_type);
19341 S.Diag(Loc: Var->getLocation(), DiagID: diag::note_previous_decl) << Var;
19342 Invalid = true;
19343 } else {
19344 return false;
19345 }
19346 }
19347
19348 // Forbid the block-capture of autoreleasing variables.
19349 if (!Invalid &&
19350 CaptureType.getObjCLifetime() == Qualifiers::OCL_Autoreleasing) {
19351 if (BuildAndDiagnose) {
19352 S.Diag(Loc, DiagID: diag::err_arc_autoreleasing_capture)
19353 << /*block*/ 0;
19354 S.Diag(Loc: Var->getLocation(), DiagID: diag::note_previous_decl) << Var;
19355 Invalid = true;
19356 } else {
19357 return false;
19358 }
19359 }
19360
19361 // Warn about implicitly autoreleasing indirect parameters captured by blocks.
19362 if (const auto *PT = CaptureType->getAs<PointerType>()) {
19363 QualType PointeeTy = PT->getPointeeType();
19364
19365 if (!Invalid && PointeeTy->getAs<ObjCObjectPointerType>() &&
19366 PointeeTy.getObjCLifetime() == Qualifiers::OCL_Autoreleasing &&
19367 !S.Context.hasDirectOwnershipQualifier(Ty: PointeeTy)) {
19368 if (BuildAndDiagnose) {
19369 SourceLocation VarLoc = Var->getLocation();
19370 S.Diag(Loc, DiagID: diag::warn_block_capture_autoreleasing);
19371 S.Diag(Loc: VarLoc, DiagID: diag::note_declare_parameter_strong);
19372 }
19373 }
19374 }
19375
19376 const bool HasBlocksAttr = Var->hasAttr<BlocksAttr>();
19377 if (HasBlocksAttr || CaptureType->isReferenceType() ||
19378 (S.getLangOpts().OpenMP && S.OpenMP().isOpenMPCapturedDecl(D: Var))) {
19379 // Block capture by reference does not change the capture or
19380 // declaration reference types.
19381 ByRef = true;
19382 } else {
19383 // Block capture by copy introduces 'const'.
19384 CaptureType = CaptureType.getNonReferenceType().withConst();
19385 DeclRefType = CaptureType;
19386 }
19387
19388 // Actually capture the variable.
19389 if (BuildAndDiagnose)
19390 BSI->addCapture(Var, isBlock: HasBlocksAttr, isByref: ByRef, isNested: Nested, Loc, EllipsisLoc: SourceLocation(),
19391 CaptureType, Invalid);
19392
19393 return !Invalid;
19394}
19395
19396/// Capture the given variable in the captured region.
19397static bool captureInCapturedRegion(
19398 CapturedRegionScopeInfo *RSI, ValueDecl *Var, SourceLocation Loc,
19399 const bool BuildAndDiagnose, QualType &CaptureType, QualType &DeclRefType,
19400 const bool RefersToCapturedVariable, TryCaptureKind Kind, bool IsTopScope,
19401 Sema &S, bool Invalid) {
19402 // By default, capture variables by reference.
19403 bool ByRef = true;
19404 if (IsTopScope && Kind != TryCaptureKind::Implicit) {
19405 ByRef = (Kind == TryCaptureKind::ExplicitByRef);
19406 } else if (S.getLangOpts().OpenMP && RSI->CapRegionKind == CR_OpenMP) {
19407 // Using an LValue reference type is consistent with Lambdas (see below).
19408 if (S.OpenMP().isOpenMPCapturedDecl(D: Var)) {
19409 bool HasConst = DeclRefType.isConstQualified();
19410 DeclRefType = DeclRefType.getUnqualifiedType();
19411 // Don't lose diagnostics about assignments to const.
19412 if (HasConst)
19413 DeclRefType.addConst();
19414 }
19415 // Do not capture firstprivates in tasks.
19416 if (S.OpenMP().isOpenMPPrivateDecl(D: Var, Level: RSI->OpenMPLevel,
19417 CapLevel: RSI->OpenMPCaptureLevel) != OMPC_unknown)
19418 return true;
19419 ByRef = S.OpenMP().isOpenMPCapturedByRef(D: Var, Level: RSI->OpenMPLevel,
19420 OpenMPCaptureLevel: RSI->OpenMPCaptureLevel);
19421 }
19422
19423 if (ByRef)
19424 CaptureType = S.Context.getLValueReferenceType(T: DeclRefType);
19425 else
19426 CaptureType = DeclRefType;
19427
19428 // Actually capture the variable.
19429 if (BuildAndDiagnose)
19430 RSI->addCapture(Var, /*isBlock*/ false, isByref: ByRef, isNested: RefersToCapturedVariable,
19431 Loc, EllipsisLoc: SourceLocation(), CaptureType, Invalid);
19432
19433 return !Invalid;
19434}
19435
19436/// Capture the given variable in the lambda.
19437static bool captureInLambda(LambdaScopeInfo *LSI, ValueDecl *Var,
19438 SourceLocation Loc, const bool BuildAndDiagnose,
19439 QualType &CaptureType, QualType &DeclRefType,
19440 const bool RefersToCapturedVariable,
19441 const TryCaptureKind Kind,
19442 SourceLocation EllipsisLoc, const bool IsTopScope,
19443 Sema &S, bool Invalid) {
19444 // Determine whether we are capturing by reference or by value.
19445 bool ByRef = false;
19446 if (IsTopScope && Kind != TryCaptureKind::Implicit) {
19447 ByRef = (Kind == TryCaptureKind::ExplicitByRef);
19448 } else {
19449 ByRef = (LSI->ImpCaptureStyle == LambdaScopeInfo::ImpCap_LambdaByref);
19450 }
19451
19452 if (BuildAndDiagnose && S.Context.getTargetInfo().getTriple().isWasm() &&
19453 CaptureType.getNonReferenceType().isWebAssemblyReferenceType()) {
19454 S.Diag(Loc, DiagID: diag::err_wasm_ca_reference) << 0;
19455 Invalid = true;
19456 }
19457
19458 // Compute the type of the field that will capture this variable.
19459 if (ByRef) {
19460 // C++11 [expr.prim.lambda]p15:
19461 // An entity is captured by reference if it is implicitly or
19462 // explicitly captured but not captured by copy. It is
19463 // unspecified whether additional unnamed non-static data
19464 // members are declared in the closure type for entities
19465 // captured by reference.
19466 //
19467 // FIXME: It is not clear whether we want to build an lvalue reference
19468 // to the DeclRefType or to CaptureType.getNonReferenceType(). GCC appears
19469 // to do the former, while EDG does the latter. Core issue 1249 will
19470 // clarify, but for now we follow GCC because it's a more permissive and
19471 // easily defensible position.
19472 CaptureType = S.Context.getLValueReferenceType(T: DeclRefType);
19473 } else {
19474 // C++11 [expr.prim.lambda]p14:
19475 // For each entity captured by copy, an unnamed non-static
19476 // data member is declared in the closure type. The
19477 // declaration order of these members is unspecified. The type
19478 // of such a data member is the type of the corresponding
19479 // captured entity if the entity is not a reference to an
19480 // object, or the referenced type otherwise. [Note: If the
19481 // captured entity is a reference to a function, the
19482 // corresponding data member is also a reference to a
19483 // function. - end note ]
19484 if (const ReferenceType *RefType = CaptureType->getAs<ReferenceType>()){
19485 if (!RefType->getPointeeType()->isFunctionType())
19486 CaptureType = RefType->getPointeeType();
19487 }
19488
19489 // Forbid the lambda copy-capture of autoreleasing variables.
19490 if (!Invalid &&
19491 CaptureType.getObjCLifetime() == Qualifiers::OCL_Autoreleasing) {
19492 if (BuildAndDiagnose) {
19493 S.Diag(Loc, DiagID: diag::err_arc_autoreleasing_capture) << /*lambda*/ 1;
19494 S.Diag(Loc: Var->getLocation(), DiagID: diag::note_previous_decl)
19495 << Var->getDeclName();
19496 Invalid = true;
19497 } else {
19498 return false;
19499 }
19500 }
19501
19502 // Make sure that by-copy captures are of a complete and non-abstract type.
19503 if (!Invalid && BuildAndDiagnose) {
19504 if (!CaptureType->isDependentType() &&
19505 S.RequireCompleteSizedType(
19506 Loc, T: CaptureType,
19507 DiagID: diag::err_capture_of_incomplete_or_sizeless_type,
19508 Args: Var->getDeclName()))
19509 Invalid = true;
19510 else if (S.RequireNonAbstractType(Loc, T: CaptureType,
19511 DiagID: diag::err_capture_of_abstract_type))
19512 Invalid = true;
19513 }
19514 }
19515
19516 // Compute the type of a reference to this captured variable.
19517 if (ByRef)
19518 DeclRefType = CaptureType.getNonReferenceType();
19519 else {
19520 // C++ [expr.prim.lambda]p5:
19521 // The closure type for a lambda-expression has a public inline
19522 // function call operator [...]. This function call operator is
19523 // declared const (9.3.1) if and only if the lambda-expression's
19524 // parameter-declaration-clause is not followed by mutable.
19525 DeclRefType = CaptureType.getNonReferenceType();
19526 bool Const = LSI->lambdaCaptureShouldBeConst();
19527 // C++ [expr.prim.lambda]p10:
19528 // The type of such a data member is [...] an lvalue reference to the
19529 // referenced function type if the entity is a reference to a function.
19530 // [...]
19531 if (Const && !CaptureType->isReferenceType() &&
19532 !DeclRefType->isFunctionType())
19533 DeclRefType.addConst();
19534 }
19535
19536 // Add the capture.
19537 if (BuildAndDiagnose)
19538 LSI->addCapture(Var, /*isBlock=*/false, isByref: ByRef, isNested: RefersToCapturedVariable,
19539 Loc, EllipsisLoc, CaptureType, Invalid);
19540
19541 return !Invalid;
19542}
19543
19544static bool canCaptureVariableByCopy(ValueDecl *Var,
19545 const ASTContext &Context) {
19546 // Offer a Copy fix even if the type is dependent.
19547 if (Var->getType()->isDependentType())
19548 return true;
19549 QualType T = Var->getType().getNonReferenceType();
19550 if (T.isTriviallyCopyableType(Context))
19551 return true;
19552 if (CXXRecordDecl *RD = T->getAsCXXRecordDecl()) {
19553
19554 if (!(RD = RD->getDefinition()))
19555 return false;
19556 if (RD->hasSimpleCopyConstructor())
19557 return true;
19558 if (RD->hasUserDeclaredCopyConstructor())
19559 for (CXXConstructorDecl *Ctor : RD->ctors())
19560 if (Ctor->isCopyConstructor())
19561 return !Ctor->isDeleted();
19562 }
19563 return false;
19564}
19565
19566/// Create up to 4 fix-its for explicit reference and value capture of \p Var or
19567/// default capture. Fixes may be omitted if they aren't allowed by the
19568/// standard, for example we can't emit a default copy capture fix-it if we
19569/// already explicitly copy capture capture another variable.
19570static void buildLambdaCaptureFixit(Sema &Sema, LambdaScopeInfo *LSI,
19571 ValueDecl *Var) {
19572 assert(LSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_None);
19573 // Don't offer Capture by copy of default capture by copy fixes if Var is
19574 // known not to be copy constructible.
19575 bool ShouldOfferCopyFix = canCaptureVariableByCopy(Var, Context: Sema.getASTContext());
19576
19577 SmallString<32> FixBuffer;
19578 StringRef Separator = LSI->NumExplicitCaptures > 0 ? ", " : "";
19579 if (Var->getDeclName().isIdentifier() && !Var->getName().empty()) {
19580 SourceLocation VarInsertLoc = LSI->IntroducerRange.getEnd();
19581 if (ShouldOfferCopyFix) {
19582 // Offer fixes to insert an explicit capture for the variable.
19583 // [] -> [VarName]
19584 // [OtherCapture] -> [OtherCapture, VarName]
19585 FixBuffer.assign(Refs: {Separator, Var->getName()});
19586 Sema.Diag(Loc: VarInsertLoc, DiagID: diag::note_lambda_variable_capture_fixit)
19587 << Var << /*value*/ 0
19588 << FixItHint::CreateInsertion(InsertionLoc: VarInsertLoc, Code: FixBuffer);
19589 }
19590 // As above but capture by reference.
19591 FixBuffer.assign(Refs: {Separator, "&", Var->getName()});
19592 Sema.Diag(Loc: VarInsertLoc, DiagID: diag::note_lambda_variable_capture_fixit)
19593 << Var << /*reference*/ 1
19594 << FixItHint::CreateInsertion(InsertionLoc: VarInsertLoc, Code: FixBuffer);
19595 }
19596
19597 // Only try to offer default capture if there are no captures excluding this
19598 // and init captures.
19599 // [this]: OK.
19600 // [X = Y]: OK.
19601 // [&A, &B]: Don't offer.
19602 // [A, B]: Don't offer.
19603 if (llvm::any_of(Range&: LSI->Captures, P: [](Capture &C) {
19604 return !C.isThisCapture() && !C.isInitCapture();
19605 }))
19606 return;
19607
19608 // The default capture specifiers, '=' or '&', must appear first in the
19609 // capture body.
19610 SourceLocation DefaultInsertLoc =
19611 LSI->IntroducerRange.getBegin().getLocWithOffset(Offset: 1);
19612
19613 if (ShouldOfferCopyFix) {
19614 bool CanDefaultCopyCapture = true;
19615 // [=, *this] OK since c++17
19616 // [=, this] OK since c++20
19617 if (LSI->isCXXThisCaptured() && !Sema.getLangOpts().CPlusPlus20)
19618 CanDefaultCopyCapture = Sema.getLangOpts().CPlusPlus17
19619 ? LSI->getCXXThisCapture().isCopyCapture()
19620 : false;
19621 // We can't use default capture by copy if any captures already specified
19622 // capture by copy.
19623 if (CanDefaultCopyCapture && llvm::none_of(Range&: LSI->Captures, P: [](Capture &C) {
19624 return !C.isThisCapture() && !C.isInitCapture() && C.isCopyCapture();
19625 })) {
19626 FixBuffer.assign(Refs: {"=", Separator});
19627 Sema.Diag(Loc: DefaultInsertLoc, DiagID: diag::note_lambda_default_capture_fixit)
19628 << /*value*/ 0
19629 << FixItHint::CreateInsertion(InsertionLoc: DefaultInsertLoc, Code: FixBuffer);
19630 }
19631 }
19632
19633 // We can't use default capture by reference if any captures already specified
19634 // capture by reference.
19635 if (llvm::none_of(Range&: LSI->Captures, P: [](Capture &C) {
19636 return !C.isInitCapture() && C.isReferenceCapture() &&
19637 !C.isThisCapture();
19638 })) {
19639 FixBuffer.assign(Refs: {"&", Separator});
19640 Sema.Diag(Loc: DefaultInsertLoc, DiagID: diag::note_lambda_default_capture_fixit)
19641 << /*reference*/ 1
19642 << FixItHint::CreateInsertion(InsertionLoc: DefaultInsertLoc, Code: FixBuffer);
19643 }
19644}
19645
19646bool Sema::tryCaptureVariable(
19647 ValueDecl *Var, SourceLocation ExprLoc, TryCaptureKind Kind,
19648 SourceLocation EllipsisLoc, bool BuildAndDiagnose, QualType &CaptureType,
19649 QualType &DeclRefType, const unsigned *const FunctionScopeIndexToStopAt) {
19650 // An init-capture is notionally from the context surrounding its
19651 // declaration, but its parent DC is the lambda class.
19652 DeclContext *VarDC = Var->getDeclContext();
19653 DeclContext *DC = CurContext;
19654
19655 // Skip past RequiresExprBodys because they don't constitute function scopes.
19656 while (DC->isRequiresExprBody())
19657 DC = DC->getParent();
19658
19659 // tryCaptureVariable is called every time a DeclRef is formed,
19660 // it can therefore have non-negigible impact on performances.
19661 // For local variables and when there is no capturing scope,
19662 // we can bailout early.
19663 if (CapturingFunctionScopes == 0 && (!BuildAndDiagnose || VarDC == DC))
19664 return true;
19665
19666 // Exception: Function parameters are not tied to the function's DeclContext
19667 // until we enter the function definition. Capturing them anyway would result
19668 // in an out-of-bounds error while traversing DC and its parents.
19669 if (isa<ParmVarDecl>(Val: Var) && !VarDC->isFunctionOrMethod())
19670 return true;
19671
19672 const auto *VD = dyn_cast<VarDecl>(Val: Var);
19673 if (VD) {
19674 if (VD->isInitCapture())
19675 VarDC = VarDC->getParent();
19676 } else {
19677 VD = Var->getPotentiallyDecomposedVarDecl();
19678 }
19679 assert(VD && "Cannot capture a null variable");
19680
19681 const unsigned MaxFunctionScopesIndex = FunctionScopeIndexToStopAt
19682 ? *FunctionScopeIndexToStopAt : FunctionScopes.size() - 1;
19683 // We need to sync up the Declaration Context with the
19684 // FunctionScopeIndexToStopAt
19685 if (FunctionScopeIndexToStopAt) {
19686 assert(!FunctionScopes.empty() && "No function scopes to stop at?");
19687 unsigned FSIndex = FunctionScopes.size() - 1;
19688 // When we're parsing the lambda parameter list, the current DeclContext is
19689 // NOT the lambda but its parent. So move away the current LSI before
19690 // aligning DC and FunctionScopeIndexToStopAt.
19691 if (auto *LSI = dyn_cast<LambdaScopeInfo>(Val: FunctionScopes[FSIndex]);
19692 FSIndex && LSI && !LSI->AfterParameterList)
19693 --FSIndex;
19694 assert(MaxFunctionScopesIndex <= FSIndex &&
19695 "FunctionScopeIndexToStopAt should be no greater than FSIndex into "
19696 "FunctionScopes.");
19697 while (FSIndex != MaxFunctionScopesIndex) {
19698 DC = getLambdaAwareParentOfDeclContext(DC);
19699 --FSIndex;
19700 }
19701 }
19702
19703 // Capture global variables if it is required to use private copy of this
19704 // variable.
19705 bool IsGlobal = !VD->hasLocalStorage();
19706 if (IsGlobal && !(LangOpts.OpenMP &&
19707 OpenMP().isOpenMPCapturedDecl(D: Var, /*CheckScopeInfo=*/true,
19708 StopAt: MaxFunctionScopesIndex)))
19709 return true;
19710
19711 if (isa<VarDecl>(Val: Var))
19712 Var = cast<VarDecl>(Val: Var->getCanonicalDecl());
19713
19714 // Walk up the stack to determine whether we can capture the variable,
19715 // performing the "simple" checks that don't depend on type. We stop when
19716 // we've either hit the declared scope of the variable or find an existing
19717 // capture of that variable. We start from the innermost capturing-entity
19718 // (the DC) and ensure that all intervening capturing-entities
19719 // (blocks/lambdas etc.) between the innermost capturer and the variable`s
19720 // declcontext can either capture the variable or have already captured
19721 // the variable.
19722 CaptureType = Var->getType();
19723 DeclRefType = CaptureType.getNonReferenceType();
19724 bool Nested = false;
19725 bool Explicit = (Kind != TryCaptureKind::Implicit);
19726 unsigned FunctionScopesIndex = MaxFunctionScopesIndex;
19727 do {
19728
19729 LambdaScopeInfo *LSI = nullptr;
19730 if (!FunctionScopes.empty())
19731 LSI = dyn_cast_or_null<LambdaScopeInfo>(
19732 Val: FunctionScopes[FunctionScopesIndex]);
19733
19734 bool IsInScopeDeclarationContext =
19735 !LSI || LSI->AfterParameterList || CurContext == LSI->CallOperator;
19736
19737 if (LSI && !LSI->AfterParameterList) {
19738 // This allows capturing parameters from a default value which does not
19739 // seems correct
19740 if (isa<ParmVarDecl>(Val: Var) && !Var->getDeclContext()->isFunctionOrMethod())
19741 return true;
19742 }
19743 // If the variable is declared in the current context, there is no need to
19744 // capture it.
19745 if (IsInScopeDeclarationContext &&
19746 FunctionScopesIndex == MaxFunctionScopesIndex && VarDC == DC)
19747 return true;
19748
19749 // Only block literals, captured statements, and lambda expressions can
19750 // capture; other scopes don't work.
19751 DeclContext *ParentDC =
19752 !IsInScopeDeclarationContext
19753 ? DC->getParent()
19754 : getParentOfCapturingContextOrNull(DC, Var, Loc: ExprLoc,
19755 Diagnose: BuildAndDiagnose, S&: *this);
19756 // We need to check for the parent *first* because, if we *have*
19757 // private-captured a global variable, we need to recursively capture it in
19758 // intermediate blocks, lambdas, etc.
19759 if (!ParentDC) {
19760 if (IsGlobal) {
19761 FunctionScopesIndex = MaxFunctionScopesIndex - 1;
19762 break;
19763 }
19764 return true;
19765 }
19766
19767 FunctionScopeInfo *FSI = FunctionScopes[FunctionScopesIndex];
19768 CapturingScopeInfo *CSI = cast<CapturingScopeInfo>(Val: FSI);
19769
19770 // Check whether we've already captured it.
19771 if (isVariableAlreadyCapturedInScopeInfo(CSI, Var, SubCapturesAreNested&: Nested, CaptureType,
19772 DeclRefType)) {
19773 CSI->getCapture(Var).markUsed(IsODRUse: BuildAndDiagnose);
19774 break;
19775 }
19776
19777 // When evaluating some attributes (like enable_if) we might refer to a
19778 // function parameter appertaining to the same declaration as that
19779 // attribute.
19780 if (const auto *Parm = dyn_cast<ParmVarDecl>(Val: Var);
19781 Parm && Parm->getDeclContext() == DC)
19782 return true;
19783
19784 // If we are instantiating a generic lambda call operator body,
19785 // we do not want to capture new variables. What was captured
19786 // during either a lambdas transformation or initial parsing
19787 // should be used.
19788 if (isGenericLambdaCallOperatorSpecialization(DC)) {
19789 if (BuildAndDiagnose) {
19790 LambdaScopeInfo *LSI = cast<LambdaScopeInfo>(Val: CSI);
19791 if (LSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_None) {
19792 Diag(Loc: ExprLoc, DiagID: diag::err_lambda_impcap) << Var;
19793 Diag(Loc: Var->getLocation(), DiagID: diag::note_previous_decl) << Var;
19794 Diag(Loc: LSI->Lambda->getBeginLoc(), DiagID: diag::note_lambda_decl);
19795 buildLambdaCaptureFixit(Sema&: *this, LSI, Var);
19796 } else
19797 diagnoseUncapturableValueReferenceOrBinding(S&: *this, loc: ExprLoc, var: Var);
19798 }
19799 return true;
19800 }
19801
19802 // Try to capture variable-length arrays types.
19803 if (Var->getType()->isVariablyModifiedType()) {
19804 // We're going to walk down into the type and look for VLA
19805 // expressions.
19806 QualType QTy = Var->getType();
19807 if (ParmVarDecl *PVD = dyn_cast_or_null<ParmVarDecl>(Val: Var))
19808 QTy = PVD->getOriginalType();
19809 captureVariablyModifiedType(Context, T: QTy, CSI);
19810 }
19811
19812 if (getLangOpts().OpenMP) {
19813 if (auto *RSI = dyn_cast<CapturedRegionScopeInfo>(Val: CSI)) {
19814 // OpenMP private variables should not be captured in outer scope, so
19815 // just break here. Similarly, global variables that are captured in a
19816 // target region should not be captured outside the scope of the region.
19817 if (RSI->CapRegionKind == CR_OpenMP) {
19818 // FIXME: We should support capturing structured bindings in OpenMP.
19819 if (isa<BindingDecl>(Val: Var)) {
19820 if (BuildAndDiagnose) {
19821 Diag(Loc: ExprLoc, DiagID: diag::err_capture_binding_openmp) << Var;
19822 Diag(Loc: Var->getLocation(), DiagID: diag::note_entity_declared_at) << Var;
19823 }
19824 return true;
19825 }
19826 OpenMPClauseKind IsOpenMPPrivateDecl = OpenMP().isOpenMPPrivateDecl(
19827 D: Var, Level: RSI->OpenMPLevel, CapLevel: RSI->OpenMPCaptureLevel);
19828 // If the variable is private (i.e. not captured) and has variably
19829 // modified type, we still need to capture the type for correct
19830 // codegen in all regions, associated with the construct. Currently,
19831 // it is captured in the innermost captured region only.
19832 if (IsOpenMPPrivateDecl != OMPC_unknown &&
19833 Var->getType()->isVariablyModifiedType()) {
19834 QualType QTy = Var->getType();
19835 if (ParmVarDecl *PVD = dyn_cast_or_null<ParmVarDecl>(Val: Var))
19836 QTy = PVD->getOriginalType();
19837 for (int I = 1,
19838 E = OpenMP().getNumberOfConstructScopes(Level: RSI->OpenMPLevel);
19839 I < E; ++I) {
19840 auto *OuterRSI = cast<CapturedRegionScopeInfo>(
19841 Val: FunctionScopes[FunctionScopesIndex - I]);
19842 assert(RSI->OpenMPLevel == OuterRSI->OpenMPLevel &&
19843 "Wrong number of captured regions associated with the "
19844 "OpenMP construct.");
19845 captureVariablyModifiedType(Context, T: QTy, CSI: OuterRSI);
19846 }
19847 }
19848 bool IsTargetCap =
19849 IsOpenMPPrivateDecl != OMPC_private &&
19850 OpenMP().isOpenMPTargetCapturedDecl(D: Var, Level: RSI->OpenMPLevel,
19851 CaptureLevel: RSI->OpenMPCaptureLevel);
19852 // Do not capture global if it is not privatized in outer regions.
19853 bool IsGlobalCap =
19854 IsGlobal && OpenMP().isOpenMPGlobalCapturedDecl(
19855 D: Var, Level: RSI->OpenMPLevel, CaptureLevel: RSI->OpenMPCaptureLevel);
19856
19857 // When we detect target captures we are looking from inside the
19858 // target region, therefore we need to propagate the capture from the
19859 // enclosing region. Therefore, the capture is not initially nested.
19860 if (IsTargetCap)
19861 OpenMP().adjustOpenMPTargetScopeIndex(FunctionScopesIndex,
19862 Level: RSI->OpenMPLevel);
19863
19864 if (IsTargetCap || IsOpenMPPrivateDecl == OMPC_private ||
19865 (IsGlobal && !IsGlobalCap)) {
19866 Nested = !IsTargetCap;
19867 bool HasConst = DeclRefType.isConstQualified();
19868 DeclRefType = DeclRefType.getUnqualifiedType();
19869 // Don't lose diagnostics about assignments to const.
19870 if (HasConst)
19871 DeclRefType.addConst();
19872 CaptureType = Context.getLValueReferenceType(T: DeclRefType);
19873 break;
19874 }
19875 }
19876 }
19877 }
19878 if (CSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_None && !Explicit) {
19879 // No capture-default, and this is not an explicit capture
19880 // so cannot capture this variable.
19881 if (BuildAndDiagnose) {
19882 Diag(Loc: ExprLoc, DiagID: diag::err_lambda_impcap) << Var;
19883 Diag(Loc: Var->getLocation(), DiagID: diag::note_previous_decl) << Var;
19884 auto *LSI = cast<LambdaScopeInfo>(Val: CSI);
19885 if (LSI->Lambda) {
19886 Diag(Loc: LSI->Lambda->getBeginLoc(), DiagID: diag::note_lambda_decl);
19887 buildLambdaCaptureFixit(Sema&: *this, LSI, Var);
19888 }
19889 // FIXME: If we error out because an outer lambda can not implicitly
19890 // capture a variable that an inner lambda explicitly captures, we
19891 // should have the inner lambda do the explicit capture - because
19892 // it makes for cleaner diagnostics later. This would purely be done
19893 // so that the diagnostic does not misleadingly claim that a variable
19894 // can not be captured by a lambda implicitly even though it is captured
19895 // explicitly. Suggestion:
19896 // - create const bool VariableCaptureWasInitiallyExplicit = Explicit
19897 // at the function head
19898 // - cache the StartingDeclContext - this must be a lambda
19899 // - captureInLambda in the innermost lambda the variable.
19900 }
19901 return true;
19902 }
19903 Explicit = false;
19904 FunctionScopesIndex--;
19905 if (IsInScopeDeclarationContext)
19906 DC = ParentDC;
19907 } while (!VarDC->Equals(DC));
19908
19909 // Walk back down the scope stack, (e.g. from outer lambda to inner lambda)
19910 // computing the type of the capture at each step, checking type-specific
19911 // requirements, and adding captures if requested.
19912 // If the variable had already been captured previously, we start capturing
19913 // at the lambda nested within that one.
19914 bool Invalid = false;
19915 for (unsigned I = ++FunctionScopesIndex, N = MaxFunctionScopesIndex + 1; I != N;
19916 ++I) {
19917 CapturingScopeInfo *CSI = cast<CapturingScopeInfo>(Val: FunctionScopes[I]);
19918
19919 // Certain capturing entities (lambdas, blocks etc.) are not allowed to capture
19920 // certain types of variables (unnamed, variably modified types etc.)
19921 // so check for eligibility.
19922 if (!Invalid)
19923 Invalid =
19924 !isVariableCapturable(CSI, Var, Loc: ExprLoc, Diagnose: BuildAndDiagnose, S&: *this);
19925
19926 // After encountering an error, if we're actually supposed to capture, keep
19927 // capturing in nested contexts to suppress any follow-on diagnostics.
19928 if (Invalid && !BuildAndDiagnose)
19929 return true;
19930
19931 if (BlockScopeInfo *BSI = dyn_cast<BlockScopeInfo>(Val: CSI)) {
19932 Invalid = !captureInBlock(BSI, Var, Loc: ExprLoc, BuildAndDiagnose, CaptureType,
19933 DeclRefType, Nested, S&: *this, Invalid);
19934 Nested = true;
19935 } else if (CapturedRegionScopeInfo *RSI = dyn_cast<CapturedRegionScopeInfo>(Val: CSI)) {
19936 Invalid = !captureInCapturedRegion(
19937 RSI, Var, Loc: ExprLoc, BuildAndDiagnose, CaptureType, DeclRefType, RefersToCapturedVariable: Nested,
19938 Kind, /*IsTopScope*/ I == N - 1, S&: *this, Invalid);
19939 Nested = true;
19940 } else {
19941 LambdaScopeInfo *LSI = cast<LambdaScopeInfo>(Val: CSI);
19942 Invalid =
19943 !captureInLambda(LSI, Var, Loc: ExprLoc, BuildAndDiagnose, CaptureType,
19944 DeclRefType, RefersToCapturedVariable: Nested, Kind, EllipsisLoc,
19945 /*IsTopScope*/ I == N - 1, S&: *this, Invalid);
19946 Nested = true;
19947 }
19948
19949 if (Invalid && !BuildAndDiagnose)
19950 return true;
19951 }
19952 return Invalid;
19953}
19954
19955bool Sema::tryCaptureVariable(ValueDecl *Var, SourceLocation Loc,
19956 TryCaptureKind Kind, SourceLocation EllipsisLoc) {
19957 QualType CaptureType;
19958 QualType DeclRefType;
19959 return tryCaptureVariable(Var, ExprLoc: Loc, Kind, EllipsisLoc,
19960 /*BuildAndDiagnose=*/true, CaptureType,
19961 DeclRefType, FunctionScopeIndexToStopAt: nullptr);
19962}
19963
19964bool Sema::NeedToCaptureVariable(ValueDecl *Var, SourceLocation Loc) {
19965 QualType CaptureType;
19966 QualType DeclRefType;
19967 return !tryCaptureVariable(
19968 Var, ExprLoc: Loc, Kind: TryCaptureKind::Implicit, EllipsisLoc: SourceLocation(),
19969 /*BuildAndDiagnose=*/false, CaptureType, DeclRefType, FunctionScopeIndexToStopAt: nullptr);
19970}
19971
19972QualType Sema::getCapturedDeclRefType(ValueDecl *Var, SourceLocation Loc) {
19973 assert(Var && "Null value cannot be captured");
19974
19975 QualType CaptureType;
19976 QualType DeclRefType;
19977
19978 // Determine whether we can capture this variable.
19979 if (tryCaptureVariable(Var, ExprLoc: Loc, Kind: TryCaptureKind::Implicit, EllipsisLoc: SourceLocation(),
19980 /*BuildAndDiagnose=*/false, CaptureType, DeclRefType,
19981 FunctionScopeIndexToStopAt: nullptr))
19982 return QualType();
19983
19984 return DeclRefType;
19985}
19986
19987namespace {
19988// Helper to copy the template arguments from a DeclRefExpr or MemberExpr.
19989// The produced TemplateArgumentListInfo* points to data stored within this
19990// object, so should only be used in contexts where the pointer will not be
19991// used after the CopiedTemplateArgs object is destroyed.
19992class CopiedTemplateArgs {
19993 bool HasArgs;
19994 TemplateArgumentListInfo TemplateArgStorage;
19995public:
19996 template<typename RefExpr>
19997 CopiedTemplateArgs(RefExpr *E) : HasArgs(E->hasExplicitTemplateArgs()) {
19998 if (HasArgs)
19999 E->copyTemplateArgumentsInto(TemplateArgStorage);
20000 }
20001 operator TemplateArgumentListInfo*()
20002#ifdef __has_cpp_attribute
20003#if __has_cpp_attribute(clang::lifetimebound)
20004 [[clang::lifetimebound]]
20005#endif
20006#endif
20007 {
20008 return HasArgs ? &TemplateArgStorage : nullptr;
20009 }
20010};
20011}
20012
20013/// Walk the set of potential results of an expression and mark them all as
20014/// non-odr-uses if they satisfy the side-conditions of the NonOdrUseReason.
20015///
20016/// \return A new expression if we found any potential results, ExprEmpty() if
20017/// not, and ExprError() if we diagnosed an error.
20018static ExprResult rebuildPotentialResultsAsNonOdrUsed(Sema &S, Expr *E,
20019 NonOdrUseReason NOUR) {
20020 // Per C++11 [basic.def.odr], a variable is odr-used "unless it is
20021 // an object that satisfies the requirements for appearing in a
20022 // constant expression (5.19) and the lvalue-to-rvalue conversion (4.1)
20023 // is immediately applied." This function handles the lvalue-to-rvalue
20024 // conversion part.
20025 //
20026 // If we encounter a node that claims to be an odr-use but shouldn't be, we
20027 // transform it into the relevant kind of non-odr-use node and rebuild the
20028 // tree of nodes leading to it.
20029 //
20030 // This is a mini-TreeTransform that only transforms a restricted subset of
20031 // nodes (and only certain operands of them).
20032
20033 // Rebuild a subexpression.
20034 auto Rebuild = [&](Expr *Sub) {
20035 return rebuildPotentialResultsAsNonOdrUsed(S, E: Sub, NOUR);
20036 };
20037
20038 // Check whether a potential result satisfies the requirements of NOUR.
20039 auto IsPotentialResultOdrUsed = [&](NamedDecl *D) {
20040 // Any entity other than a VarDecl is always odr-used whenever it's named
20041 // in a potentially-evaluated expression.
20042 auto *VD = dyn_cast<VarDecl>(Val: D);
20043 if (!VD)
20044 return true;
20045
20046 // C++2a [basic.def.odr]p4:
20047 // A variable x whose name appears as a potentially-evalauted expression
20048 // e is odr-used by e unless
20049 // -- x is a reference that is usable in constant expressions, or
20050 // -- x is a variable of non-reference type that is usable in constant
20051 // expressions and has no mutable subobjects, and e is an element of
20052 // the set of potential results of an expression of
20053 // non-volatile-qualified non-class type to which the lvalue-to-rvalue
20054 // conversion is applied, or
20055 // -- x is a variable of non-reference type, and e is an element of the
20056 // set of potential results of a discarded-value expression to which
20057 // the lvalue-to-rvalue conversion is not applied
20058 //
20059 // We check the first bullet and the "potentially-evaluated" condition in
20060 // BuildDeclRefExpr. We check the type requirements in the second bullet
20061 // in CheckLValueToRValueConversionOperand below.
20062 switch (NOUR) {
20063 case NOUR_None:
20064 case NOUR_Unevaluated:
20065 llvm_unreachable("unexpected non-odr-use-reason");
20066
20067 case NOUR_Constant:
20068 // Constant references were handled when they were built.
20069 if (VD->getType()->isReferenceType())
20070 return true;
20071 if (auto *RD = VD->getType()->getAsCXXRecordDecl())
20072 if (RD->hasDefinition() && RD->hasMutableFields())
20073 return true;
20074 if (!VD->isUsableInConstantExpressions(C: S.Context))
20075 return true;
20076 break;
20077
20078 case NOUR_Discarded:
20079 if (VD->getType()->isReferenceType())
20080 return true;
20081 break;
20082 }
20083 return false;
20084 };
20085
20086 // Check whether this expression may be odr-used in CUDA/HIP.
20087 auto MaybeCUDAODRUsed = [&]() -> bool {
20088 if (!S.LangOpts.CUDA)
20089 return false;
20090 LambdaScopeInfo *LSI = S.getCurLambda();
20091 if (!LSI)
20092 return false;
20093 auto *DRE = dyn_cast<DeclRefExpr>(Val: E);
20094 if (!DRE)
20095 return false;
20096 auto *VD = dyn_cast<VarDecl>(Val: DRE->getDecl());
20097 if (!VD)
20098 return false;
20099 return LSI->CUDAPotentialODRUsedVars.count(Ptr: VD);
20100 };
20101
20102 // Mark that this expression does not constitute an odr-use.
20103 auto MarkNotOdrUsed = [&] {
20104 if (!MaybeCUDAODRUsed()) {
20105 S.MaybeODRUseExprs.remove(X: E);
20106 if (LambdaScopeInfo *LSI = S.getCurLambda())
20107 LSI->markVariableExprAsNonODRUsed(CapturingVarExpr: E);
20108 }
20109 };
20110
20111 // C++2a [basic.def.odr]p2:
20112 // The set of potential results of an expression e is defined as follows:
20113 switch (E->getStmtClass()) {
20114 // -- If e is an id-expression, ...
20115 case Expr::DeclRefExprClass: {
20116 auto *DRE = cast<DeclRefExpr>(Val: E);
20117 if (DRE->isNonOdrUse() || IsPotentialResultOdrUsed(DRE->getDecl()))
20118 break;
20119
20120 // Rebuild as a non-odr-use DeclRefExpr.
20121 MarkNotOdrUsed();
20122 return DeclRefExpr::Create(
20123 Context: S.Context, QualifierLoc: DRE->getQualifierLoc(), TemplateKWLoc: DRE->getTemplateKeywordLoc(),
20124 D: DRE->getDecl(), RefersToEnclosingVariableOrCapture: DRE->refersToEnclosingVariableOrCapture(),
20125 NameInfo: DRE->getNameInfo(), T: DRE->getType(), VK: DRE->getValueKind(),
20126 FoundD: DRE->getFoundDecl(), TemplateArgs: CopiedTemplateArgs(DRE), NOUR);
20127 }
20128
20129 case Expr::FunctionParmPackExprClass: {
20130 auto *FPPE = cast<FunctionParmPackExpr>(Val: E);
20131 // If any of the declarations in the pack is odr-used, then the expression
20132 // as a whole constitutes an odr-use.
20133 for (ValueDecl *D : *FPPE)
20134 if (IsPotentialResultOdrUsed(D))
20135 return ExprEmpty();
20136
20137 // FIXME: Rebuild as a non-odr-use FunctionParmPackExpr? In practice,
20138 // nothing cares about whether we marked this as an odr-use, but it might
20139 // be useful for non-compiler tools.
20140 MarkNotOdrUsed();
20141 break;
20142 }
20143
20144 // -- If e is a subscripting operation with an array operand...
20145 case Expr::ArraySubscriptExprClass: {
20146 auto *ASE = cast<ArraySubscriptExpr>(Val: E);
20147 Expr *OldBase = ASE->getBase()->IgnoreImplicit();
20148 if (!OldBase->getType()->isArrayType())
20149 break;
20150 ExprResult Base = Rebuild(OldBase);
20151 if (!Base.isUsable())
20152 return Base;
20153 Expr *LHS = ASE->getBase() == ASE->getLHS() ? Base.get() : ASE->getLHS();
20154 Expr *RHS = ASE->getBase() == ASE->getRHS() ? Base.get() : ASE->getRHS();
20155 SourceLocation LBracketLoc = ASE->getBeginLoc(); // FIXME: Not stored.
20156 return S.ActOnArraySubscriptExpr(S: nullptr, base: LHS, lbLoc: LBracketLoc, ArgExprs: RHS,
20157 rbLoc: ASE->getRBracketLoc());
20158 }
20159
20160 case Expr::MemberExprClass: {
20161 auto *ME = cast<MemberExpr>(Val: E);
20162 // -- If e is a class member access expression [...] naming a non-static
20163 // data member...
20164 if (isa<FieldDecl>(Val: ME->getMemberDecl())) {
20165 ExprResult Base = Rebuild(ME->getBase());
20166 if (!Base.isUsable())
20167 return Base;
20168 return MemberExpr::Create(
20169 C: S.Context, Base: Base.get(), IsArrow: ME->isArrow(), OperatorLoc: ME->getOperatorLoc(),
20170 QualifierLoc: ME->getQualifierLoc(), TemplateKWLoc: ME->getTemplateKeywordLoc(),
20171 MemberDecl: ME->getMemberDecl(), FoundDecl: ME->getFoundDecl(), MemberNameInfo: ME->getMemberNameInfo(),
20172 TemplateArgs: CopiedTemplateArgs(ME), T: ME->getType(), VK: ME->getValueKind(),
20173 OK: ME->getObjectKind(), NOUR: ME->isNonOdrUse());
20174 }
20175
20176 if (ME->getMemberDecl()->isCXXInstanceMember())
20177 break;
20178
20179 // -- If e is a class member access expression naming a static data member,
20180 // ...
20181 if (ME->isNonOdrUse() || IsPotentialResultOdrUsed(ME->getMemberDecl()))
20182 break;
20183
20184 // Rebuild as a non-odr-use MemberExpr.
20185 MarkNotOdrUsed();
20186 return MemberExpr::Create(
20187 C: S.Context, Base: ME->getBase(), IsArrow: ME->isArrow(), OperatorLoc: ME->getOperatorLoc(),
20188 QualifierLoc: ME->getQualifierLoc(), TemplateKWLoc: ME->getTemplateKeywordLoc(), MemberDecl: ME->getMemberDecl(),
20189 FoundDecl: ME->getFoundDecl(), MemberNameInfo: ME->getMemberNameInfo(), TemplateArgs: CopiedTemplateArgs(ME),
20190 T: ME->getType(), VK: ME->getValueKind(), OK: ME->getObjectKind(), NOUR);
20191 }
20192
20193 case Expr::BinaryOperatorClass: {
20194 auto *BO = cast<BinaryOperator>(Val: E);
20195 Expr *LHS = BO->getLHS();
20196 Expr *RHS = BO->getRHS();
20197 // -- If e is a pointer-to-member expression of the form e1 .* e2 ...
20198 if (BO->getOpcode() == BO_PtrMemD) {
20199 ExprResult Sub = Rebuild(LHS);
20200 if (!Sub.isUsable())
20201 return Sub;
20202 BO->setLHS(Sub.get());
20203 // -- If e is a comma expression, ...
20204 } else if (BO->getOpcode() == BO_Comma) {
20205 ExprResult Sub = Rebuild(RHS);
20206 if (!Sub.isUsable())
20207 return Sub;
20208 BO->setRHS(Sub.get());
20209 } else {
20210 break;
20211 }
20212 return ExprResult(BO);
20213 }
20214
20215 // -- If e has the form (e1)...
20216 case Expr::ParenExprClass: {
20217 auto *PE = cast<ParenExpr>(Val: E);
20218 ExprResult Sub = Rebuild(PE->getSubExpr());
20219 if (!Sub.isUsable())
20220 return Sub;
20221 return S.ActOnParenExpr(L: PE->getLParen(), R: PE->getRParen(), E: Sub.get());
20222 }
20223
20224 // -- If e is a glvalue conditional expression, ...
20225 // We don't apply this to a binary conditional operator. FIXME: Should we?
20226 case Expr::ConditionalOperatorClass: {
20227 auto *CO = cast<ConditionalOperator>(Val: E);
20228 ExprResult LHS = Rebuild(CO->getLHS());
20229 if (LHS.isInvalid())
20230 return ExprError();
20231 ExprResult RHS = Rebuild(CO->getRHS());
20232 if (RHS.isInvalid())
20233 return ExprError();
20234 if (!LHS.isUsable() && !RHS.isUsable())
20235 return ExprEmpty();
20236 if (!LHS.isUsable())
20237 LHS = CO->getLHS();
20238 if (!RHS.isUsable())
20239 RHS = CO->getRHS();
20240 return S.ActOnConditionalOp(QuestionLoc: CO->getQuestionLoc(), ColonLoc: CO->getColonLoc(),
20241 CondExpr: CO->getCond(), LHSExpr: LHS.get(), RHSExpr: RHS.get());
20242 }
20243
20244 // [Clang extension]
20245 // -- If e has the form __extension__ e1...
20246 case Expr::UnaryOperatorClass: {
20247 auto *UO = cast<UnaryOperator>(Val: E);
20248 if (UO->getOpcode() != UO_Extension)
20249 break;
20250 ExprResult Sub = Rebuild(UO->getSubExpr());
20251 if (!Sub.isUsable())
20252 return Sub;
20253 return S.BuildUnaryOp(S: nullptr, OpLoc: UO->getOperatorLoc(), Opc: UO_Extension,
20254 Input: Sub.get());
20255 }
20256
20257 // [Clang extension]
20258 // -- If e has the form _Generic(...), the set of potential results is the
20259 // union of the sets of potential results of the associated expressions.
20260 case Expr::GenericSelectionExprClass: {
20261 auto *GSE = cast<GenericSelectionExpr>(Val: E);
20262
20263 SmallVector<Expr *, 4> AssocExprs;
20264 bool AnyChanged = false;
20265 for (Expr *OrigAssocExpr : GSE->getAssocExprs()) {
20266 ExprResult AssocExpr = Rebuild(OrigAssocExpr);
20267 if (AssocExpr.isInvalid())
20268 return ExprError();
20269 if (AssocExpr.isUsable()) {
20270 AssocExprs.push_back(Elt: AssocExpr.get());
20271 AnyChanged = true;
20272 } else {
20273 AssocExprs.push_back(Elt: OrigAssocExpr);
20274 }
20275 }
20276
20277 void *ExOrTy = nullptr;
20278 bool IsExpr = GSE->isExprPredicate();
20279 if (IsExpr)
20280 ExOrTy = GSE->getControllingExpr();
20281 else
20282 ExOrTy = GSE->getControllingType();
20283 return AnyChanged ? S.CreateGenericSelectionExpr(
20284 KeyLoc: GSE->getGenericLoc(), DefaultLoc: GSE->getDefaultLoc(),
20285 RParenLoc: GSE->getRParenLoc(), PredicateIsExpr: IsExpr, ControllingExprOrType: ExOrTy,
20286 Types: GSE->getAssocTypeSourceInfos(), Exprs: AssocExprs)
20287 : ExprEmpty();
20288 }
20289
20290 // [Clang extension]
20291 // -- If e has the form __builtin_choose_expr(...), the set of potential
20292 // results is the union of the sets of potential results of the
20293 // second and third subexpressions.
20294 case Expr::ChooseExprClass: {
20295 auto *CE = cast<ChooseExpr>(Val: E);
20296
20297 ExprResult LHS = Rebuild(CE->getLHS());
20298 if (LHS.isInvalid())
20299 return ExprError();
20300
20301 ExprResult RHS = Rebuild(CE->getLHS());
20302 if (RHS.isInvalid())
20303 return ExprError();
20304
20305 if (!LHS.get() && !RHS.get())
20306 return ExprEmpty();
20307 if (!LHS.isUsable())
20308 LHS = CE->getLHS();
20309 if (!RHS.isUsable())
20310 RHS = CE->getRHS();
20311
20312 return S.ActOnChooseExpr(BuiltinLoc: CE->getBuiltinLoc(), CondExpr: CE->getCond(), LHSExpr: LHS.get(),
20313 RHSExpr: RHS.get(), RPLoc: CE->getRParenLoc());
20314 }
20315
20316 // Step through non-syntactic nodes.
20317 case Expr::ConstantExprClass: {
20318 auto *CE = cast<ConstantExpr>(Val: E);
20319 ExprResult Sub = Rebuild(CE->getSubExpr());
20320 if (!Sub.isUsable())
20321 return Sub;
20322 return ConstantExpr::Create(Context: S.Context, E: Sub.get());
20323 }
20324
20325 // We could mostly rely on the recursive rebuilding to rebuild implicit
20326 // casts, but not at the top level, so rebuild them here.
20327 case Expr::ImplicitCastExprClass: {
20328 auto *ICE = cast<ImplicitCastExpr>(Val: E);
20329 // Only step through the narrow set of cast kinds we expect to encounter.
20330 // Anything else suggests we've left the region in which potential results
20331 // can be found.
20332 switch (ICE->getCastKind()) {
20333 case CK_NoOp:
20334 case CK_DerivedToBase:
20335 case CK_UncheckedDerivedToBase: {
20336 ExprResult Sub = Rebuild(ICE->getSubExpr());
20337 if (!Sub.isUsable())
20338 return Sub;
20339 CXXCastPath Path(ICE->path());
20340 return S.ImpCastExprToType(E: Sub.get(), Type: ICE->getType(), CK: ICE->getCastKind(),
20341 VK: ICE->getValueKind(), BasePath: &Path);
20342 }
20343
20344 default:
20345 break;
20346 }
20347 break;
20348 }
20349
20350 default:
20351 break;
20352 }
20353
20354 // Can't traverse through this node. Nothing to do.
20355 return ExprEmpty();
20356}
20357
20358ExprResult Sema::CheckLValueToRValueConversionOperand(Expr *E) {
20359 // Check whether the operand is or contains an object of non-trivial C union
20360 // type.
20361 if (E->getType().isVolatileQualified() &&
20362 (E->getType().hasNonTrivialToPrimitiveDestructCUnion() ||
20363 E->getType().hasNonTrivialToPrimitiveCopyCUnion()))
20364 checkNonTrivialCUnion(QT: E->getType(), Loc: E->getExprLoc(),
20365 UseContext: NonTrivialCUnionContext::LValueToRValueVolatile,
20366 NonTrivialKind: NTCUK_Destruct | NTCUK_Copy);
20367
20368 // C++2a [basic.def.odr]p4:
20369 // [...] an expression of non-volatile-qualified non-class type to which
20370 // the lvalue-to-rvalue conversion is applied [...]
20371 if (E->getType().isVolatileQualified() || E->getType()->isRecordType())
20372 return E;
20373
20374 ExprResult Result =
20375 rebuildPotentialResultsAsNonOdrUsed(S&: *this, E, NOUR: NOUR_Constant);
20376 if (Result.isInvalid())
20377 return ExprError();
20378 return Result.get() ? Result : E;
20379}
20380
20381ExprResult Sema::ActOnConstantExpression(ExprResult Res) {
20382 if (!Res.isUsable())
20383 return Res;
20384
20385 // If a constant-expression is a reference to a variable where we delay
20386 // deciding whether it is an odr-use, just assume we will apply the
20387 // lvalue-to-rvalue conversion. In the one case where this doesn't happen
20388 // (a non-type template argument), we have special handling anyway.
20389 return CheckLValueToRValueConversionOperand(E: Res.get());
20390}
20391
20392void Sema::CleanupVarDeclMarking() {
20393 // Iterate through a local copy in case MarkVarDeclODRUsed makes a recursive
20394 // call.
20395 MaybeODRUseExprSet LocalMaybeODRUseExprs;
20396 std::swap(LHS&: LocalMaybeODRUseExprs, RHS&: MaybeODRUseExprs);
20397
20398 for (Expr *E : LocalMaybeODRUseExprs) {
20399 if (auto *DRE = dyn_cast<DeclRefExpr>(Val: E)) {
20400 MarkVarDeclODRUsed(V: cast<VarDecl>(Val: DRE->getDecl()),
20401 Loc: DRE->getLocation(), SemaRef&: *this);
20402 } else if (auto *ME = dyn_cast<MemberExpr>(Val: E)) {
20403 MarkVarDeclODRUsed(V: cast<VarDecl>(Val: ME->getMemberDecl()), Loc: ME->getMemberLoc(),
20404 SemaRef&: *this);
20405 } else if (auto *FP = dyn_cast<FunctionParmPackExpr>(Val: E)) {
20406 for (ValueDecl *VD : *FP)
20407 MarkVarDeclODRUsed(V: VD, Loc: FP->getParameterPackLocation(), SemaRef&: *this);
20408 } else {
20409 llvm_unreachable("Unexpected expression");
20410 }
20411 }
20412
20413 assert(MaybeODRUseExprs.empty() &&
20414 "MarkVarDeclODRUsed failed to cleanup MaybeODRUseExprs?");
20415}
20416
20417static void DoMarkPotentialCapture(Sema &SemaRef, SourceLocation Loc,
20418 ValueDecl *Var, Expr *E) {
20419 VarDecl *VD = Var->getPotentiallyDecomposedVarDecl();
20420 if (!VD)
20421 return;
20422
20423 const bool RefersToEnclosingScope =
20424 (SemaRef.CurContext != VD->getDeclContext() &&
20425 VD->getDeclContext()->isFunctionOrMethod() && VD->hasLocalStorage());
20426 if (RefersToEnclosingScope) {
20427 LambdaScopeInfo *const LSI =
20428 SemaRef.getCurLambda(/*IgnoreNonLambdaCapturingScope=*/true);
20429 if (LSI && (!LSI->CallOperator ||
20430 !LSI->CallOperator->Encloses(DC: Var->getDeclContext()))) {
20431 // If a variable could potentially be odr-used, defer marking it so
20432 // until we finish analyzing the full expression for any
20433 // lvalue-to-rvalue
20434 // or discarded value conversions that would obviate odr-use.
20435 // Add it to the list of potential captures that will be analyzed
20436 // later (ActOnFinishFullExpr) for eventual capture and odr-use marking
20437 // unless the variable is a reference that was initialized by a constant
20438 // expression (this will never need to be captured or odr-used).
20439 //
20440 // FIXME: We can simplify this a lot after implementing P0588R1.
20441 assert(E && "Capture variable should be used in an expression.");
20442 if (!Var->getType()->isReferenceType() ||
20443 !VD->isUsableInConstantExpressions(C: SemaRef.Context))
20444 LSI->addPotentialCapture(VarExpr: E->IgnoreParens());
20445 }
20446 }
20447}
20448
20449static void DoMarkVarDeclReferenced(
20450 Sema &SemaRef, SourceLocation Loc, VarDecl *Var, Expr *E,
20451 llvm::DenseMap<const VarDecl *, int> &RefsMinusAssignments) {
20452 assert((!E || isa<DeclRefExpr>(E) || isa<MemberExpr>(E) ||
20453 isa<FunctionParmPackExpr>(E)) &&
20454 "Invalid Expr argument to DoMarkVarDeclReferenced");
20455 Var->setReferenced();
20456
20457 if (Var->isInvalidDecl())
20458 return;
20459
20460 auto *MSI = Var->getMemberSpecializationInfo();
20461 TemplateSpecializationKind TSK = MSI ? MSI->getTemplateSpecializationKind()
20462 : Var->getTemplateSpecializationKind();
20463
20464 OdrUseContext OdrUse = isOdrUseContext(SemaRef);
20465 bool UsableInConstantExpr =
20466 Var->mightBeUsableInConstantExpressions(C: SemaRef.Context);
20467
20468 if (Var->isLocalVarDeclOrParm() && !Var->hasExternalStorage()) {
20469 RefsMinusAssignments.insert(KV: {Var, 0}).first->getSecond()++;
20470 }
20471
20472 // C++20 [expr.const]p12:
20473 // A variable [...] is needed for constant evaluation if it is [...] a
20474 // variable whose name appears as a potentially constant evaluated
20475 // expression that is either a contexpr variable or is of non-volatile
20476 // const-qualified integral type or of reference type
20477 bool NeededForConstantEvaluation =
20478 isPotentiallyConstantEvaluatedContext(SemaRef) && UsableInConstantExpr;
20479
20480 bool NeedDefinition =
20481 OdrUse == OdrUseContext::Used || NeededForConstantEvaluation ||
20482 (TSK != clang::TSK_Undeclared && !UsableInConstantExpr &&
20483 Var->getType()->isUndeducedType());
20484
20485 assert(!isa<VarTemplatePartialSpecializationDecl>(Var) &&
20486 "Can't instantiate a partial template specialization.");
20487
20488 // If this might be a member specialization of a static data member, check
20489 // the specialization is visible. We already did the checks for variable
20490 // template specializations when we created them.
20491 if (NeedDefinition && TSK != TSK_Undeclared &&
20492 !isa<VarTemplateSpecializationDecl>(Val: Var))
20493 SemaRef.checkSpecializationVisibility(Loc, Spec: Var);
20494
20495 // Perform implicit instantiation of static data members, static data member
20496 // templates of class templates, and variable template specializations. Delay
20497 // instantiations of variable templates, except for those that could be used
20498 // in a constant expression.
20499 if (NeedDefinition && isTemplateInstantiation(Kind: TSK)) {
20500 // Per C++17 [temp.explicit]p10, we may instantiate despite an explicit
20501 // instantiation declaration if a variable is usable in a constant
20502 // expression (among other cases).
20503 bool TryInstantiating =
20504 TSK == TSK_ImplicitInstantiation ||
20505 (TSK == TSK_ExplicitInstantiationDeclaration && UsableInConstantExpr);
20506
20507 if (TryInstantiating) {
20508 SourceLocation PointOfInstantiation =
20509 MSI ? MSI->getPointOfInstantiation() : Var->getPointOfInstantiation();
20510 bool FirstInstantiation = PointOfInstantiation.isInvalid();
20511 if (FirstInstantiation) {
20512 PointOfInstantiation = Loc;
20513 if (MSI)
20514 MSI->setPointOfInstantiation(PointOfInstantiation);
20515 // FIXME: Notify listener.
20516 else
20517 Var->setTemplateSpecializationKind(TSK, PointOfInstantiation);
20518 }
20519
20520 if (UsableInConstantExpr || Var->getType()->isUndeducedType()) {
20521 // Do not defer instantiations of variables that could be used in a
20522 // constant expression.
20523 // The type deduction also needs a complete initializer.
20524 SemaRef.runWithSufficientStackSpace(Loc: PointOfInstantiation, Fn: [&] {
20525 SemaRef.InstantiateVariableDefinition(PointOfInstantiation, Var);
20526 });
20527
20528 // The size of an incomplete array type can be updated by
20529 // instantiating the initializer. The DeclRefExpr's type should be
20530 // updated accordingly too, or users of it would be confused!
20531 if (E)
20532 SemaRef.getCompletedType(E);
20533
20534 // Re-set the member to trigger a recomputation of the dependence bits
20535 // for the expression.
20536 if (auto *DRE = dyn_cast_or_null<DeclRefExpr>(Val: E))
20537 DRE->setDecl(DRE->getDecl());
20538 else if (auto *ME = dyn_cast_or_null<MemberExpr>(Val: E))
20539 ME->setMemberDecl(ME->getMemberDecl());
20540 } else if (FirstInstantiation) {
20541 SemaRef.PendingInstantiations
20542 .push_back(x: std::make_pair(x&: Var, y&: PointOfInstantiation));
20543 } else {
20544 bool Inserted = false;
20545 for (auto &I : SemaRef.SavedPendingInstantiations) {
20546 auto Iter = llvm::find_if(
20547 Range&: I, P: [Var](const Sema::PendingImplicitInstantiation &P) {
20548 return P.first == Var;
20549 });
20550 if (Iter != I.end()) {
20551 SemaRef.PendingInstantiations.push_back(x: *Iter);
20552 I.erase(position: Iter);
20553 Inserted = true;
20554 break;
20555 }
20556 }
20557
20558 // FIXME: For a specialization of a variable template, we don't
20559 // distinguish between "declaration and type implicitly instantiated"
20560 // and "implicit instantiation of definition requested", so we have
20561 // no direct way to avoid enqueueing the pending instantiation
20562 // multiple times.
20563 if (isa<VarTemplateSpecializationDecl>(Val: Var) && !Inserted)
20564 SemaRef.PendingInstantiations
20565 .push_back(x: std::make_pair(x&: Var, y&: PointOfInstantiation));
20566 }
20567 }
20568 }
20569
20570 // C++2a [basic.def.odr]p4:
20571 // A variable x whose name appears as a potentially-evaluated expression e
20572 // is odr-used by e unless
20573 // -- x is a reference that is usable in constant expressions
20574 // -- x is a variable of non-reference type that is usable in constant
20575 // expressions and has no mutable subobjects [FIXME], and e is an
20576 // element of the set of potential results of an expression of
20577 // non-volatile-qualified non-class type to which the lvalue-to-rvalue
20578 // conversion is applied
20579 // -- x is a variable of non-reference type, and e is an element of the set
20580 // of potential results of a discarded-value expression to which the
20581 // lvalue-to-rvalue conversion is not applied [FIXME]
20582 //
20583 // We check the first part of the second bullet here, and
20584 // Sema::CheckLValueToRValueConversionOperand deals with the second part.
20585 // FIXME: To get the third bullet right, we need to delay this even for
20586 // variables that are not usable in constant expressions.
20587
20588 // If we already know this isn't an odr-use, there's nothing more to do.
20589 if (DeclRefExpr *DRE = dyn_cast_or_null<DeclRefExpr>(Val: E))
20590 if (DRE->isNonOdrUse())
20591 return;
20592 if (MemberExpr *ME = dyn_cast_or_null<MemberExpr>(Val: E))
20593 if (ME->isNonOdrUse())
20594 return;
20595
20596 switch (OdrUse) {
20597 case OdrUseContext::None:
20598 // In some cases, a variable may not have been marked unevaluated, if it
20599 // appears in a defaukt initializer.
20600 assert((!E || isa<FunctionParmPackExpr>(E) ||
20601 SemaRef.isUnevaluatedContext()) &&
20602 "missing non-odr-use marking for unevaluated decl ref");
20603 break;
20604
20605 case OdrUseContext::FormallyOdrUsed:
20606 // FIXME: Ignoring formal odr-uses results in incorrect lambda capture
20607 // behavior.
20608 break;
20609
20610 case OdrUseContext::Used:
20611 // If we might later find that this expression isn't actually an odr-use,
20612 // delay the marking.
20613 if (E && Var->isUsableInConstantExpressions(C: SemaRef.Context))
20614 SemaRef.MaybeODRUseExprs.insert(X: E);
20615 else
20616 MarkVarDeclODRUsed(V: Var, Loc, SemaRef);
20617 break;
20618
20619 case OdrUseContext::Dependent:
20620 // If this is a dependent context, we don't need to mark variables as
20621 // odr-used, but we may still need to track them for lambda capture.
20622 // FIXME: Do we also need to do this inside dependent typeid expressions
20623 // (which are modeled as unevaluated at this point)?
20624 DoMarkPotentialCapture(SemaRef, Loc, Var, E);
20625 break;
20626 }
20627}
20628
20629static void DoMarkBindingDeclReferenced(Sema &SemaRef, SourceLocation Loc,
20630 BindingDecl *BD, Expr *E) {
20631 BD->setReferenced();
20632
20633 if (BD->isInvalidDecl())
20634 return;
20635
20636 OdrUseContext OdrUse = isOdrUseContext(SemaRef);
20637 if (OdrUse == OdrUseContext::Used) {
20638 QualType CaptureType, DeclRefType;
20639 SemaRef.tryCaptureVariable(Var: BD, ExprLoc: Loc, Kind: TryCaptureKind::Implicit,
20640 /*EllipsisLoc*/ SourceLocation(),
20641 /*BuildAndDiagnose*/ true, CaptureType,
20642 DeclRefType,
20643 /*FunctionScopeIndexToStopAt*/ nullptr);
20644 } else if (OdrUse == OdrUseContext::Dependent) {
20645 DoMarkPotentialCapture(SemaRef, Loc, Var: BD, E);
20646 }
20647}
20648
20649void Sema::MarkVariableReferenced(SourceLocation Loc, VarDecl *Var) {
20650 DoMarkVarDeclReferenced(SemaRef&: *this, Loc, Var, E: nullptr, RefsMinusAssignments);
20651}
20652
20653// C++ [temp.dep.expr]p3:
20654// An id-expression is type-dependent if it contains:
20655// - an identifier associated by name lookup with an entity captured by copy
20656// in a lambda-expression that has an explicit object parameter whose type
20657// is dependent ([dcl.fct]),
20658static void FixDependencyOfIdExpressionsInLambdaWithDependentObjectParameter(
20659 Sema &SemaRef, ValueDecl *D, Expr *E) {
20660 auto *ID = dyn_cast<DeclRefExpr>(Val: E);
20661 if (!ID || ID->isTypeDependent() || !ID->refersToEnclosingVariableOrCapture())
20662 return;
20663
20664 // If any enclosing lambda with a dependent explicit object parameter either
20665 // explicitly captures the variable by value, or has a capture default of '='
20666 // and does not capture the variable by reference, then the type of the DRE
20667 // is dependent on the type of that lambda's explicit object parameter.
20668 auto IsDependent = [&]() {
20669 for (auto *Scope : llvm::reverse(C&: SemaRef.FunctionScopes)) {
20670 auto *LSI = dyn_cast<sema::LambdaScopeInfo>(Val: Scope);
20671 if (!LSI)
20672 continue;
20673
20674 if (LSI->Lambda && !LSI->Lambda->Encloses(DC: SemaRef.CurContext) &&
20675 LSI->AfterParameterList)
20676 return false;
20677
20678 const auto *MD = LSI->CallOperator;
20679 if (MD->getType().isNull())
20680 continue;
20681
20682 const auto *Ty = MD->getType()->getAs<FunctionProtoType>();
20683 if (!Ty || !MD->isExplicitObjectMemberFunction() ||
20684 !Ty->getParamType(i: 0)->isDependentType())
20685 continue;
20686
20687 if (auto *C = LSI->CaptureMap.count(Val: D) ? &LSI->getCapture(Var: D) : nullptr) {
20688 if (C->isCopyCapture())
20689 return true;
20690 continue;
20691 }
20692
20693 if (LSI->ImpCaptureStyle == LambdaScopeInfo::ImpCap_LambdaByval)
20694 return true;
20695 }
20696 return false;
20697 }();
20698
20699 ID->setCapturedByCopyInLambdaWithExplicitObjectParameter(
20700 Set: IsDependent, Context: SemaRef.getASTContext());
20701}
20702
20703static void
20704MarkExprReferenced(Sema &SemaRef, SourceLocation Loc, Decl *D, Expr *E,
20705 bool MightBeOdrUse,
20706 llvm::DenseMap<const VarDecl *, int> &RefsMinusAssignments) {
20707 if (SemaRef.OpenMP().isInOpenMPDeclareTargetContext())
20708 SemaRef.OpenMP().checkDeclIsAllowedInOpenMPTarget(E, D);
20709
20710 if (SemaRef.getLangOpts().OpenACC)
20711 SemaRef.OpenACC().CheckDeclReference(Loc, E, D);
20712
20713 if (VarDecl *Var = dyn_cast<VarDecl>(Val: D)) {
20714 DoMarkVarDeclReferenced(SemaRef, Loc, Var, E, RefsMinusAssignments);
20715 if (SemaRef.getLangOpts().CPlusPlus)
20716 FixDependencyOfIdExpressionsInLambdaWithDependentObjectParameter(SemaRef,
20717 D: Var, E);
20718 return;
20719 }
20720
20721 if (BindingDecl *Decl = dyn_cast<BindingDecl>(Val: D)) {
20722 DoMarkBindingDeclReferenced(SemaRef, Loc, BD: Decl, E);
20723 if (SemaRef.getLangOpts().CPlusPlus)
20724 FixDependencyOfIdExpressionsInLambdaWithDependentObjectParameter(SemaRef,
20725 D: Decl, E);
20726 return;
20727 }
20728 SemaRef.MarkAnyDeclReferenced(Loc, D, MightBeOdrUse);
20729
20730 // If this is a call to a method via a cast, also mark the method in the
20731 // derived class used in case codegen can devirtualize the call.
20732 const MemberExpr *ME = dyn_cast<MemberExpr>(Val: E);
20733 if (!ME)
20734 return;
20735 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Val: ME->getMemberDecl());
20736 if (!MD)
20737 return;
20738 // Only attempt to devirtualize if this is truly a virtual call.
20739 bool IsVirtualCall = MD->isVirtual() &&
20740 ME->performsVirtualDispatch(LO: SemaRef.getLangOpts());
20741 if (!IsVirtualCall)
20742 return;
20743
20744 // If it's possible to devirtualize the call, mark the called function
20745 // referenced.
20746 CXXMethodDecl *DM = MD->getDevirtualizedMethod(
20747 Base: ME->getBase(), IsAppleKext: SemaRef.getLangOpts().AppleKext);
20748 if (DM)
20749 SemaRef.MarkAnyDeclReferenced(Loc, D: DM, MightBeOdrUse);
20750}
20751
20752void Sema::MarkDeclRefReferenced(DeclRefExpr *E, const Expr *Base) {
20753 // [basic.def.odr] (CWG 1614)
20754 // A function is named by an expression or conversion [...]
20755 // unless it is a pure virtual function and either the expression is not an
20756 // id-expression naming the function with an explicitly qualified name or
20757 // the expression forms a pointer to member
20758 bool OdrUse = true;
20759 if (const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Val: E->getDecl()))
20760 if (Method->isVirtual() &&
20761 !Method->getDevirtualizedMethod(Base, IsAppleKext: getLangOpts().AppleKext))
20762 OdrUse = false;
20763
20764 if (auto *FD = dyn_cast<FunctionDecl>(Val: E->getDecl())) {
20765 if (!isUnevaluatedContext() && !isConstantEvaluatedContext() &&
20766 !isImmediateFunctionContext() &&
20767 !isCheckingDefaultArgumentOrInitializer() &&
20768 FD->isImmediateFunction() && !RebuildingImmediateInvocation &&
20769 !FD->isDependentContext())
20770 ExprEvalContexts.back().ReferenceToConsteval.insert(Ptr: E);
20771 }
20772 MarkExprReferenced(SemaRef&: *this, Loc: E->getLocation(), D: E->getDecl(), E, MightBeOdrUse: OdrUse,
20773 RefsMinusAssignments);
20774}
20775
20776void Sema::MarkMemberReferenced(MemberExpr *E) {
20777 // C++11 [basic.def.odr]p2:
20778 // A non-overloaded function whose name appears as a potentially-evaluated
20779 // expression or a member of a set of candidate functions, if selected by
20780 // overload resolution when referred to from a potentially-evaluated
20781 // expression, is odr-used, unless it is a pure virtual function and its
20782 // name is not explicitly qualified.
20783 bool MightBeOdrUse = true;
20784 if (E->performsVirtualDispatch(LO: getLangOpts())) {
20785 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Val: E->getMemberDecl()))
20786 if (Method->isPureVirtual())
20787 MightBeOdrUse = false;
20788 }
20789 SourceLocation Loc =
20790 E->getMemberLoc().isValid() ? E->getMemberLoc() : E->getBeginLoc();
20791 MarkExprReferenced(SemaRef&: *this, Loc, D: E->getMemberDecl(), E, MightBeOdrUse,
20792 RefsMinusAssignments);
20793}
20794
20795void Sema::MarkFunctionParmPackReferenced(FunctionParmPackExpr *E) {
20796 for (ValueDecl *VD : *E)
20797 MarkExprReferenced(SemaRef&: *this, Loc: E->getParameterPackLocation(), D: VD, E, MightBeOdrUse: true,
20798 RefsMinusAssignments);
20799}
20800
20801/// Perform marking for a reference to an arbitrary declaration. It
20802/// marks the declaration referenced, and performs odr-use checking for
20803/// functions and variables. This method should not be used when building a
20804/// normal expression which refers to a variable.
20805void Sema::MarkAnyDeclReferenced(SourceLocation Loc, Decl *D,
20806 bool MightBeOdrUse) {
20807 if (MightBeOdrUse) {
20808 if (auto *VD = dyn_cast<VarDecl>(Val: D)) {
20809 MarkVariableReferenced(Loc, Var: VD);
20810 return;
20811 }
20812 }
20813 if (auto *FD = dyn_cast<FunctionDecl>(Val: D)) {
20814 MarkFunctionReferenced(Loc, Func: FD, MightBeOdrUse);
20815 return;
20816 }
20817 D->setReferenced();
20818}
20819
20820namespace {
20821 // Mark all of the declarations used by a type as referenced.
20822 // FIXME: Not fully implemented yet! We need to have a better understanding
20823 // of when we're entering a context we should not recurse into.
20824 // FIXME: This is and EvaluatedExprMarker are more-or-less equivalent to
20825 // TreeTransforms rebuilding the type in a new context. Rather than
20826 // duplicating the TreeTransform logic, we should consider reusing it here.
20827 // Currently that causes problems when rebuilding LambdaExprs.
20828class MarkReferencedDecls : public DynamicRecursiveASTVisitor {
20829 Sema &S;
20830 SourceLocation Loc;
20831
20832public:
20833 MarkReferencedDecls(Sema &S, SourceLocation Loc) : S(S), Loc(Loc) {}
20834
20835 bool TraverseTemplateArgument(const TemplateArgument &Arg) override;
20836};
20837}
20838
20839bool MarkReferencedDecls::TraverseTemplateArgument(
20840 const TemplateArgument &Arg) {
20841 {
20842 // A non-type template argument is a constant-evaluated context.
20843 EnterExpressionEvaluationContext Evaluated(
20844 S, Sema::ExpressionEvaluationContext::ConstantEvaluated);
20845 if (Arg.getKind() == TemplateArgument::Declaration) {
20846 if (Decl *D = Arg.getAsDecl())
20847 S.MarkAnyDeclReferenced(Loc, D, MightBeOdrUse: true);
20848 } else if (Arg.getKind() == TemplateArgument::Expression) {
20849 S.MarkDeclarationsReferencedInExpr(E: Arg.getAsExpr(), SkipLocalVariables: false);
20850 }
20851 }
20852
20853 return DynamicRecursiveASTVisitor::TraverseTemplateArgument(Arg);
20854}
20855
20856void Sema::MarkDeclarationsReferencedInType(SourceLocation Loc, QualType T) {
20857 MarkReferencedDecls Marker(*this, Loc);
20858 Marker.TraverseType(T);
20859}
20860
20861namespace {
20862/// Helper class that marks all of the declarations referenced by
20863/// potentially-evaluated subexpressions as "referenced".
20864class EvaluatedExprMarker : public UsedDeclVisitor<EvaluatedExprMarker> {
20865public:
20866 typedef UsedDeclVisitor<EvaluatedExprMarker> Inherited;
20867 bool SkipLocalVariables;
20868 ArrayRef<const Expr *> StopAt;
20869
20870 EvaluatedExprMarker(Sema &S, bool SkipLocalVariables,
20871 ArrayRef<const Expr *> StopAt)
20872 : Inherited(S), SkipLocalVariables(SkipLocalVariables), StopAt(StopAt) {}
20873
20874 void visitUsedDecl(SourceLocation Loc, Decl *D) {
20875 S.MarkFunctionReferenced(Loc, Func: cast<FunctionDecl>(Val: D));
20876 }
20877
20878 void Visit(Expr *E) {
20879 if (llvm::is_contained(Range&: StopAt, Element: E))
20880 return;
20881 Inherited::Visit(S: E);
20882 }
20883
20884 void VisitConstantExpr(ConstantExpr *E) {
20885 // Don't mark declarations within a ConstantExpression, as this expression
20886 // will be evaluated and folded to a value.
20887 }
20888
20889 void VisitDeclRefExpr(DeclRefExpr *E) {
20890 // If we were asked not to visit local variables, don't.
20891 if (SkipLocalVariables) {
20892 if (VarDecl *VD = dyn_cast<VarDecl>(Val: E->getDecl()))
20893 if (VD->hasLocalStorage())
20894 return;
20895 }
20896
20897 // FIXME: This can trigger the instantiation of the initializer of a
20898 // variable, which can cause the expression to become value-dependent
20899 // or error-dependent. Do we need to propagate the new dependence bits?
20900 S.MarkDeclRefReferenced(E);
20901 }
20902
20903 void VisitMemberExpr(MemberExpr *E) {
20904 S.MarkMemberReferenced(E);
20905 Visit(E: E->getBase());
20906 }
20907};
20908} // namespace
20909
20910void Sema::MarkDeclarationsReferencedInExpr(Expr *E,
20911 bool SkipLocalVariables,
20912 ArrayRef<const Expr*> StopAt) {
20913 EvaluatedExprMarker(*this, SkipLocalVariables, StopAt).Visit(E);
20914}
20915
20916/// Emit a diagnostic when statements are reachable.
20917bool Sema::DiagIfReachable(SourceLocation Loc, ArrayRef<const Stmt *> Stmts,
20918 const PartialDiagnostic &PD) {
20919 VarDecl *Decl = ExprEvalContexts.back().DeclForInitializer;
20920 // The initializer of a constexpr variable or of the first declaration of a
20921 // static data member is not syntactically a constant evaluated constant,
20922 // but nonetheless is always required to be a constant expression, so we
20923 // can skip diagnosing.
20924 if (Decl &&
20925 (Decl->isConstexpr() || (Decl->isStaticDataMember() &&
20926 Decl->isFirstDecl() && !Decl->isInline())))
20927 return false;
20928
20929 if (Stmts.empty()) {
20930 Diag(Loc, PD);
20931 return true;
20932 }
20933
20934 if (getCurFunction()) {
20935 FunctionScopes.back()->PossiblyUnreachableDiags.push_back(
20936 Elt: sema::PossiblyUnreachableDiag(PD, Loc, Stmts));
20937 return true;
20938 }
20939
20940 // For non-constexpr file-scope variables with reachability context (non-empty
20941 // Stmts), build a CFG for the initializer and check whether the context in
20942 // question is reachable.
20943 if (Decl && Decl->isFileVarDecl()) {
20944 AnalysisWarnings.registerVarDeclWarning(
20945 VD: Decl, PUD: sema::PossiblyUnreachableDiag(PD, Loc, Stmts));
20946 return true;
20947 }
20948
20949 Diag(Loc, PD);
20950 return true;
20951}
20952
20953/// Emit a diagnostic that describes an effect on the run-time behavior
20954/// of the program being compiled.
20955///
20956/// This routine emits the given diagnostic when the code currently being
20957/// type-checked is "potentially evaluated", meaning that there is a
20958/// possibility that the code will actually be executable. Code in sizeof()
20959/// expressions, code used only during overload resolution, etc., are not
20960/// potentially evaluated. This routine will suppress such diagnostics or,
20961/// in the absolutely nutty case of potentially potentially evaluated
20962/// expressions (C++ typeid), queue the diagnostic to potentially emit it
20963/// later.
20964///
20965/// This routine should be used for all diagnostics that describe the run-time
20966/// behavior of a program, such as passing a non-POD value through an ellipsis.
20967/// Failure to do so will likely result in spurious diagnostics or failures
20968/// during overload resolution or within sizeof/alignof/typeof/typeid.
20969bool Sema::DiagRuntimeBehavior(SourceLocation Loc, ArrayRef<const Stmt*> Stmts,
20970 const PartialDiagnostic &PD) {
20971
20972 if (ExprEvalContexts.back().isDiscardedStatementContext())
20973 return false;
20974
20975 switch (ExprEvalContexts.back().Context) {
20976 case ExpressionEvaluationContext::Unevaluated:
20977 case ExpressionEvaluationContext::UnevaluatedList:
20978 case ExpressionEvaluationContext::UnevaluatedAbstract:
20979 case ExpressionEvaluationContext::DiscardedStatement:
20980 // The argument will never be evaluated, so don't complain.
20981 break;
20982
20983 case ExpressionEvaluationContext::ConstantEvaluated:
20984 case ExpressionEvaluationContext::ImmediateFunctionContext:
20985 // Relevant diagnostics should be produced by constant evaluation.
20986 break;
20987
20988 case ExpressionEvaluationContext::PotentiallyEvaluated:
20989 case ExpressionEvaluationContext::PotentiallyEvaluatedIfUsed:
20990 return DiagIfReachable(Loc, Stmts, PD);
20991 }
20992
20993 return false;
20994}
20995
20996bool Sema::DiagRuntimeBehavior(SourceLocation Loc, const Stmt *Statement,
20997 const PartialDiagnostic &PD) {
20998 return DiagRuntimeBehavior(
20999 Loc, Stmts: Statement ? llvm::ArrayRef(Statement) : llvm::ArrayRef<Stmt *>(),
21000 PD);
21001}
21002
21003bool Sema::CheckCallReturnType(QualType ReturnType, SourceLocation Loc,
21004 CallExpr *CE, FunctionDecl *FD) {
21005 if (ReturnType->isVoidType() || !ReturnType->isIncompleteType())
21006 return false;
21007
21008 // If we're inside a decltype's expression, don't check for a valid return
21009 // type or construct temporaries until we know whether this is the last call.
21010 if (ExprEvalContexts.back().ExprContext ==
21011 ExpressionEvaluationContextRecord::EK_Decltype) {
21012 ExprEvalContexts.back().DelayedDecltypeCalls.push_back(Elt: CE);
21013 return false;
21014 }
21015
21016 class CallReturnIncompleteDiagnoser : public TypeDiagnoser {
21017 FunctionDecl *FD;
21018 CallExpr *CE;
21019
21020 public:
21021 CallReturnIncompleteDiagnoser(FunctionDecl *FD, CallExpr *CE)
21022 : FD(FD), CE(CE) { }
21023
21024 void diagnose(Sema &S, SourceLocation Loc, QualType T) override {
21025 if (!FD) {
21026 S.Diag(Loc, DiagID: diag::err_call_incomplete_return)
21027 << T << CE->getSourceRange();
21028 return;
21029 }
21030
21031 S.Diag(Loc, DiagID: diag::err_call_function_incomplete_return)
21032 << CE->getSourceRange() << FD << T;
21033 S.Diag(Loc: FD->getLocation(), DiagID: diag::note_entity_declared_at)
21034 << FD->getDeclName();
21035 }
21036 } Diagnoser(FD, CE);
21037
21038 if (RequireCompleteType(Loc, T: ReturnType, Diagnoser))
21039 return true;
21040
21041 return false;
21042}
21043
21044// Diagnose the s/=/==/ and s/\|=/!=/ typos. Note that adding parentheses
21045// will prevent this condition from triggering, which is what we want.
21046void Sema::DiagnoseAssignmentAsCondition(Expr *E) {
21047 SourceLocation Loc;
21048
21049 unsigned diagnostic = diag::warn_condition_is_assignment;
21050 bool IsOrAssign = false;
21051
21052 if (BinaryOperator *Op = dyn_cast<BinaryOperator>(Val: E)) {
21053 if (Op->getOpcode() != BO_Assign && Op->getOpcode() != BO_OrAssign)
21054 return;
21055
21056 IsOrAssign = Op->getOpcode() == BO_OrAssign;
21057
21058 // Greylist some idioms by putting them into a warning subcategory.
21059 if (ObjCMessageExpr *ME
21060 = dyn_cast<ObjCMessageExpr>(Val: Op->getRHS()->IgnoreParenCasts())) {
21061 Selector Sel = ME->getSelector();
21062
21063 // self = [<foo> init...]
21064 if (ObjC().isSelfExpr(RExpr: Op->getLHS()) && ME->getMethodFamily() == OMF_init)
21065 diagnostic = diag::warn_condition_is_idiomatic_assignment;
21066
21067 // <foo> = [<bar> nextObject]
21068 else if (Sel.isUnarySelector() && Sel.getNameForSlot(argIndex: 0) == "nextObject")
21069 diagnostic = diag::warn_condition_is_idiomatic_assignment;
21070 }
21071
21072 Loc = Op->getOperatorLoc();
21073 } else if (CXXOperatorCallExpr *Op = dyn_cast<CXXOperatorCallExpr>(Val: E)) {
21074 if (Op->getOperator() != OO_Equal && Op->getOperator() != OO_PipeEqual)
21075 return;
21076
21077 IsOrAssign = Op->getOperator() == OO_PipeEqual;
21078 Loc = Op->getOperatorLoc();
21079 } else if (PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(Val: E))
21080 return DiagnoseAssignmentAsCondition(E: POE->getSyntacticForm());
21081 else {
21082 // Not an assignment.
21083 return;
21084 }
21085
21086 Diag(Loc, DiagID: diagnostic) << E->getSourceRange();
21087
21088 SourceLocation Open = E->getBeginLoc();
21089 SourceLocation Close = getLocForEndOfToken(Loc: E->getSourceRange().getEnd());
21090 Diag(Loc, DiagID: diag::note_condition_assign_silence)
21091 << FixItHint::CreateInsertion(InsertionLoc: Open, Code: "(")
21092 << FixItHint::CreateInsertion(InsertionLoc: Close, Code: ")");
21093
21094 if (IsOrAssign)
21095 Diag(Loc, DiagID: diag::note_condition_or_assign_to_comparison)
21096 << FixItHint::CreateReplacement(RemoveRange: Loc, Code: "!=");
21097 else
21098 Diag(Loc, DiagID: diag::note_condition_assign_to_comparison)
21099 << FixItHint::CreateReplacement(RemoveRange: Loc, Code: "==");
21100}
21101
21102void Sema::DiagnoseEqualityWithExtraParens(ParenExpr *ParenE) {
21103 // Don't warn if the parens came from a macro.
21104 SourceLocation parenLoc = ParenE->getBeginLoc();
21105 if (parenLoc.isInvalid() || parenLoc.isMacroID())
21106 return;
21107 // Don't warn for dependent expressions.
21108 if (ParenE->isTypeDependent())
21109 return;
21110
21111 Expr *E = ParenE->IgnoreParens();
21112 if (ParenE->isProducedByFoldExpansion() && ParenE->getSubExpr() == E)
21113 return;
21114
21115 if (BinaryOperator *opE = dyn_cast<BinaryOperator>(Val: E))
21116 if (opE->getOpcode() == BO_EQ &&
21117 opE->getLHS()->IgnoreParenImpCasts()->isModifiableLvalue(Ctx&: Context)
21118 == Expr::MLV_Valid) {
21119 SourceLocation Loc = opE->getOperatorLoc();
21120
21121 Diag(Loc, DiagID: diag::warn_equality_with_extra_parens) << E->getSourceRange();
21122 SourceRange ParenERange = ParenE->getSourceRange();
21123 Diag(Loc, DiagID: diag::note_equality_comparison_silence)
21124 << FixItHint::CreateRemoval(RemoveRange: ParenERange.getBegin())
21125 << FixItHint::CreateRemoval(RemoveRange: ParenERange.getEnd());
21126 Diag(Loc, DiagID: diag::note_equality_comparison_to_assign)
21127 << FixItHint::CreateReplacement(RemoveRange: Loc, Code: "=");
21128 }
21129}
21130
21131ExprResult Sema::CheckBooleanCondition(SourceLocation Loc, Expr *E,
21132 bool IsConstexpr) {
21133 DiagnoseAssignmentAsCondition(E);
21134 if (ParenExpr *parenE = dyn_cast<ParenExpr>(Val: E))
21135 DiagnoseEqualityWithExtraParens(ParenE: parenE);
21136
21137 ExprResult result = CheckPlaceholderExpr(E);
21138 if (result.isInvalid()) return ExprError();
21139 E = result.get();
21140
21141 if (!E->isTypeDependent()) {
21142 if (getLangOpts().CPlusPlus)
21143 return CheckCXXBooleanCondition(CondExpr: E, IsConstexpr); // C++ 6.4p4
21144
21145 ExprResult ERes = DefaultFunctionArrayLvalueConversion(E);
21146 if (ERes.isInvalid())
21147 return ExprError();
21148 E = ERes.get();
21149
21150 QualType T = E->getType();
21151 if (!T->isScalarType()) { // C99 6.8.4.1p1
21152 Diag(Loc, DiagID: diag::err_typecheck_statement_requires_scalar)
21153 << T << E->getSourceRange();
21154 return ExprError();
21155 }
21156 CheckBoolLikeConversion(E, CC: Loc);
21157 }
21158
21159 return E;
21160}
21161
21162Sema::ConditionResult Sema::ActOnCondition(Scope *S, SourceLocation Loc,
21163 Expr *SubExpr, ConditionKind CK,
21164 bool MissingOK) {
21165 // MissingOK indicates whether having no condition expression is valid
21166 // (for loop) or invalid (e.g. while loop).
21167 if (!SubExpr)
21168 return MissingOK ? ConditionResult() : ConditionError();
21169
21170 ExprResult Cond;
21171 switch (CK) {
21172 case ConditionKind::Boolean:
21173 Cond = CheckBooleanCondition(Loc, E: SubExpr);
21174 break;
21175
21176 case ConditionKind::ConstexprIf:
21177 // Note: this might produce a FullExpr
21178 Cond = CheckBooleanCondition(Loc, E: SubExpr, IsConstexpr: true);
21179 break;
21180
21181 case ConditionKind::Switch:
21182 Cond = CheckSwitchCondition(SwitchLoc: Loc, Cond: SubExpr);
21183 break;
21184 }
21185 if (Cond.isInvalid()) {
21186 Cond = CreateRecoveryExpr(Begin: SubExpr->getBeginLoc(), End: SubExpr->getEndLoc(),
21187 SubExprs: {SubExpr}, T: PreferredConditionType(K: CK));
21188 if (!Cond.get())
21189 return ConditionError();
21190 } else if (Cond.isUsable() && !isa<FullExpr>(Val: Cond.get()))
21191 Cond = ActOnFinishFullExpr(Expr: Cond.get(), CC: Loc, /*DiscardedValue*/ false);
21192
21193 if (!Cond.isUsable())
21194 return ConditionError();
21195
21196 return ConditionResult(*this, nullptr, Cond,
21197 CK == ConditionKind::ConstexprIf);
21198}
21199
21200namespace {
21201 /// A visitor for rebuilding a call to an __unknown_any expression
21202 /// to have an appropriate type.
21203 struct RebuildUnknownAnyFunction
21204 : StmtVisitor<RebuildUnknownAnyFunction, ExprResult> {
21205
21206 Sema &S;
21207
21208 RebuildUnknownAnyFunction(Sema &S) : S(S) {}
21209
21210 ExprResult VisitStmt(Stmt *S) {
21211 llvm_unreachable("unexpected statement!");
21212 }
21213
21214 ExprResult VisitExpr(Expr *E) {
21215 S.Diag(Loc: E->getExprLoc(), DiagID: diag::err_unsupported_unknown_any_call)
21216 << E->getSourceRange();
21217 return ExprError();
21218 }
21219
21220 /// Rebuild an expression which simply semantically wraps another
21221 /// expression which it shares the type and value kind of.
21222 template <class T> ExprResult rebuildSugarExpr(T *E) {
21223 ExprResult SubResult = Visit(S: E->getSubExpr());
21224 if (SubResult.isInvalid()) return ExprError();
21225
21226 Expr *SubExpr = SubResult.get();
21227 E->setSubExpr(SubExpr);
21228 E->setType(SubExpr->getType());
21229 E->setValueKind(SubExpr->getValueKind());
21230 assert(E->getObjectKind() == OK_Ordinary);
21231 return E;
21232 }
21233
21234 ExprResult VisitParenExpr(ParenExpr *E) {
21235 return rebuildSugarExpr(E);
21236 }
21237
21238 ExprResult VisitUnaryExtension(UnaryOperator *E) {
21239 return rebuildSugarExpr(E);
21240 }
21241
21242 ExprResult VisitUnaryAddrOf(UnaryOperator *E) {
21243 ExprResult SubResult = Visit(S: E->getSubExpr());
21244 if (SubResult.isInvalid()) return ExprError();
21245
21246 Expr *SubExpr = SubResult.get();
21247 E->setSubExpr(SubExpr);
21248 E->setType(S.Context.getPointerType(T: SubExpr->getType()));
21249 assert(E->isPRValue());
21250 assert(E->getObjectKind() == OK_Ordinary);
21251 return E;
21252 }
21253
21254 ExprResult resolveDecl(Expr *E, ValueDecl *VD) {
21255 if (!isa<FunctionDecl>(Val: VD)) return VisitExpr(E);
21256
21257 E->setType(VD->getType());
21258
21259 assert(E->isPRValue());
21260 if (S.getLangOpts().CPlusPlus &&
21261 !(isa<CXXMethodDecl>(Val: VD) &&
21262 cast<CXXMethodDecl>(Val: VD)->isInstance()))
21263 E->setValueKind(VK_LValue);
21264
21265 return E;
21266 }
21267
21268 ExprResult VisitMemberExpr(MemberExpr *E) {
21269 return resolveDecl(E, VD: E->getMemberDecl());
21270 }
21271
21272 ExprResult VisitDeclRefExpr(DeclRefExpr *E) {
21273 return resolveDecl(E, VD: E->getDecl());
21274 }
21275 };
21276}
21277
21278/// Given a function expression of unknown-any type, try to rebuild it
21279/// to have a function type.
21280static ExprResult rebuildUnknownAnyFunction(Sema &S, Expr *FunctionExpr) {
21281 ExprResult Result = RebuildUnknownAnyFunction(S).Visit(S: FunctionExpr);
21282 if (Result.isInvalid()) return ExprError();
21283 return S.DefaultFunctionArrayConversion(E: Result.get());
21284}
21285
21286namespace {
21287 /// A visitor for rebuilding an expression of type __unknown_anytype
21288 /// into one which resolves the type directly on the referring
21289 /// expression. Strict preservation of the original source
21290 /// structure is not a goal.
21291 struct RebuildUnknownAnyExpr
21292 : StmtVisitor<RebuildUnknownAnyExpr, ExprResult> {
21293
21294 Sema &S;
21295
21296 /// The current destination type.
21297 QualType DestType;
21298
21299 RebuildUnknownAnyExpr(Sema &S, QualType CastType)
21300 : S(S), DestType(CastType) {}
21301
21302 ExprResult VisitStmt(Stmt *S) {
21303 llvm_unreachable("unexpected statement!");
21304 }
21305
21306 ExprResult VisitExpr(Expr *E) {
21307 S.Diag(Loc: E->getExprLoc(), DiagID: diag::err_unsupported_unknown_any_expr)
21308 << E->getSourceRange();
21309 return ExprError();
21310 }
21311
21312 ExprResult VisitCallExpr(CallExpr *E);
21313 ExprResult VisitObjCMessageExpr(ObjCMessageExpr *E);
21314
21315 /// Rebuild an expression which simply semantically wraps another
21316 /// expression which it shares the type and value kind of.
21317 template <class T> ExprResult rebuildSugarExpr(T *E) {
21318 ExprResult SubResult = Visit(S: E->getSubExpr());
21319 if (SubResult.isInvalid()) return ExprError();
21320 Expr *SubExpr = SubResult.get();
21321 E->setSubExpr(SubExpr);
21322 E->setType(SubExpr->getType());
21323 E->setValueKind(SubExpr->getValueKind());
21324 assert(E->getObjectKind() == OK_Ordinary);
21325 return E;
21326 }
21327
21328 ExprResult VisitParenExpr(ParenExpr *E) {
21329 return rebuildSugarExpr(E);
21330 }
21331
21332 ExprResult VisitUnaryExtension(UnaryOperator *E) {
21333 return rebuildSugarExpr(E);
21334 }
21335
21336 ExprResult VisitUnaryAddrOf(UnaryOperator *E) {
21337 const PointerType *Ptr = DestType->getAs<PointerType>();
21338 if (!Ptr) {
21339 S.Diag(Loc: E->getOperatorLoc(), DiagID: diag::err_unknown_any_addrof)
21340 << E->getSourceRange();
21341 return ExprError();
21342 }
21343
21344 if (isa<CallExpr>(Val: E->getSubExpr())) {
21345 S.Diag(Loc: E->getOperatorLoc(), DiagID: diag::err_unknown_any_addrof_call)
21346 << E->getSourceRange();
21347 return ExprError();
21348 }
21349
21350 assert(E->isPRValue());
21351 assert(E->getObjectKind() == OK_Ordinary);
21352 E->setType(DestType);
21353
21354 // Build the sub-expression as if it were an object of the pointee type.
21355 DestType = Ptr->getPointeeType();
21356 ExprResult SubResult = Visit(S: E->getSubExpr());
21357 if (SubResult.isInvalid()) return ExprError();
21358 E->setSubExpr(SubResult.get());
21359 return E;
21360 }
21361
21362 ExprResult VisitImplicitCastExpr(ImplicitCastExpr *E);
21363
21364 ExprResult resolveDecl(Expr *E, ValueDecl *VD);
21365
21366 ExprResult VisitMemberExpr(MemberExpr *E) {
21367 return resolveDecl(E, VD: E->getMemberDecl());
21368 }
21369
21370 ExprResult VisitDeclRefExpr(DeclRefExpr *E) {
21371 return resolveDecl(E, VD: E->getDecl());
21372 }
21373 };
21374}
21375
21376/// Rebuilds a call expression which yielded __unknown_anytype.
21377ExprResult RebuildUnknownAnyExpr::VisitCallExpr(CallExpr *E) {
21378 Expr *CalleeExpr = E->getCallee();
21379
21380 enum FnKind {
21381 FK_MemberFunction,
21382 FK_FunctionPointer,
21383 FK_BlockPointer
21384 };
21385
21386 FnKind Kind;
21387 QualType CalleeType = CalleeExpr->getType();
21388 if (CalleeType == S.Context.BoundMemberTy) {
21389 assert(isa<CXXMemberCallExpr>(E) || isa<CXXOperatorCallExpr>(E));
21390 Kind = FK_MemberFunction;
21391 CalleeType = Expr::findBoundMemberType(expr: CalleeExpr);
21392 } else if (const PointerType *Ptr = CalleeType->getAs<PointerType>()) {
21393 CalleeType = Ptr->getPointeeType();
21394 Kind = FK_FunctionPointer;
21395 } else {
21396 CalleeType = CalleeType->castAs<BlockPointerType>()->getPointeeType();
21397 Kind = FK_BlockPointer;
21398 }
21399 const FunctionType *FnType = CalleeType->castAs<FunctionType>();
21400
21401 // Verify that this is a legal result type of a function.
21402 if ((DestType->isArrayType() && !S.getLangOpts().allowArrayReturnTypes()) ||
21403 DestType->isFunctionType()) {
21404 unsigned diagID = diag::err_func_returning_array_function;
21405 if (Kind == FK_BlockPointer)
21406 diagID = diag::err_block_returning_array_function;
21407
21408 S.Diag(Loc: E->getExprLoc(), DiagID: diagID)
21409 << DestType->isFunctionType() << DestType;
21410 return ExprError();
21411 }
21412
21413 // Otherwise, go ahead and set DestType as the call's result.
21414 E->setType(DestType.getNonLValueExprType(Context: S.Context));
21415 E->setValueKind(Expr::getValueKindForType(T: DestType));
21416 assert(E->getObjectKind() == OK_Ordinary);
21417
21418 // Rebuild the function type, replacing the result type with DestType.
21419 const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(Val: FnType);
21420 if (Proto) {
21421 // __unknown_anytype(...) is a special case used by the debugger when
21422 // it has no idea what a function's signature is.
21423 //
21424 // We want to build this call essentially under the K&R
21425 // unprototyped rules, but making a FunctionNoProtoType in C++
21426 // would foul up all sorts of assumptions. However, we cannot
21427 // simply pass all arguments as variadic arguments, nor can we
21428 // portably just call the function under a non-variadic type; see
21429 // the comment on IR-gen's TargetInfo::isNoProtoCallVariadic.
21430 // However, it turns out that in practice it is generally safe to
21431 // call a function declared as "A foo(B,C,D);" under the prototype
21432 // "A foo(B,C,D,...);". The only known exception is with the
21433 // Windows ABI, where any variadic function is implicitly cdecl
21434 // regardless of its normal CC. Therefore we change the parameter
21435 // types to match the types of the arguments.
21436 //
21437 // This is a hack, but it is far superior to moving the
21438 // corresponding target-specific code from IR-gen to Sema/AST.
21439
21440 ArrayRef<QualType> ParamTypes = Proto->getParamTypes();
21441 SmallVector<QualType, 8> ArgTypes;
21442 if (ParamTypes.empty() && Proto->isVariadic()) { // the special case
21443 ArgTypes.reserve(N: E->getNumArgs());
21444 for (unsigned i = 0, e = E->getNumArgs(); i != e; ++i) {
21445 ArgTypes.push_back(Elt: S.Context.getReferenceQualifiedType(e: E->getArg(Arg: i)));
21446 }
21447 ParamTypes = ArgTypes;
21448 }
21449 DestType = S.Context.getFunctionType(ResultTy: DestType, Args: ParamTypes,
21450 EPI: Proto->getExtProtoInfo());
21451 } else {
21452 DestType = S.Context.getFunctionNoProtoType(ResultTy: DestType,
21453 Info: FnType->getExtInfo());
21454 }
21455
21456 // Rebuild the appropriate pointer-to-function type.
21457 switch (Kind) {
21458 case FK_MemberFunction:
21459 // Nothing to do.
21460 break;
21461
21462 case FK_FunctionPointer:
21463 DestType = S.Context.getPointerType(T: DestType);
21464 break;
21465
21466 case FK_BlockPointer:
21467 DestType = S.Context.getBlockPointerType(T: DestType);
21468 break;
21469 }
21470
21471 // Finally, we can recurse.
21472 ExprResult CalleeResult = Visit(S: CalleeExpr);
21473 if (!CalleeResult.isUsable()) return ExprError();
21474 E->setCallee(CalleeResult.get());
21475
21476 // Bind a temporary if necessary.
21477 return S.MaybeBindToTemporary(E);
21478}
21479
21480ExprResult RebuildUnknownAnyExpr::VisitObjCMessageExpr(ObjCMessageExpr *E) {
21481 // Verify that this is a legal result type of a call.
21482 if (DestType->isArrayType() || DestType->isFunctionType()) {
21483 S.Diag(Loc: E->getExprLoc(), DiagID: diag::err_func_returning_array_function)
21484 << DestType->isFunctionType() << DestType;
21485 return ExprError();
21486 }
21487
21488 // Rewrite the method result type if available.
21489 if (ObjCMethodDecl *Method = E->getMethodDecl()) {
21490 assert(Method->getReturnType() == S.Context.UnknownAnyTy);
21491 Method->setReturnType(DestType);
21492 }
21493
21494 // Change the type of the message.
21495 E->setType(DestType.getNonReferenceType());
21496 E->setValueKind(Expr::getValueKindForType(T: DestType));
21497
21498 return S.MaybeBindToTemporary(E);
21499}
21500
21501ExprResult RebuildUnknownAnyExpr::VisitImplicitCastExpr(ImplicitCastExpr *E) {
21502 // The only case we should ever see here is a function-to-pointer decay.
21503 if (E->getCastKind() == CK_FunctionToPointerDecay) {
21504 assert(E->isPRValue());
21505 assert(E->getObjectKind() == OK_Ordinary);
21506
21507 E->setType(DestType);
21508
21509 // Rebuild the sub-expression as the pointee (function) type.
21510 DestType = DestType->castAs<PointerType>()->getPointeeType();
21511
21512 ExprResult Result = Visit(S: E->getSubExpr());
21513 if (!Result.isUsable()) return ExprError();
21514
21515 E->setSubExpr(Result.get());
21516 return E;
21517 } else if (E->getCastKind() == CK_LValueToRValue) {
21518 assert(E->isPRValue());
21519 assert(E->getObjectKind() == OK_Ordinary);
21520
21521 assert(isa<BlockPointerType>(E->getType()));
21522
21523 E->setType(DestType);
21524
21525 // The sub-expression has to be a lvalue reference, so rebuild it as such.
21526 DestType = S.Context.getLValueReferenceType(T: DestType);
21527
21528 ExprResult Result = Visit(S: E->getSubExpr());
21529 if (!Result.isUsable()) return ExprError();
21530
21531 E->setSubExpr(Result.get());
21532 return E;
21533 } else {
21534 llvm_unreachable("Unhandled cast type!");
21535 }
21536}
21537
21538ExprResult RebuildUnknownAnyExpr::resolveDecl(Expr *E, ValueDecl *VD) {
21539 ExprValueKind ValueKind = VK_LValue;
21540 QualType Type = DestType;
21541
21542 // We know how to make this work for certain kinds of decls:
21543
21544 // - functions
21545 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Val: VD)) {
21546 if (const PointerType *Ptr = Type->getAs<PointerType>()) {
21547 DestType = Ptr->getPointeeType();
21548 ExprResult Result = resolveDecl(E, VD);
21549 if (Result.isInvalid()) return ExprError();
21550 return S.ImpCastExprToType(E: Result.get(), Type, CK: CK_FunctionToPointerDecay,
21551 VK: VK_PRValue);
21552 }
21553
21554 if (!Type->isFunctionType()) {
21555 S.Diag(Loc: E->getExprLoc(), DiagID: diag::err_unknown_any_function)
21556 << VD << E->getSourceRange();
21557 return ExprError();
21558 }
21559 if (const FunctionProtoType *FT = Type->getAs<FunctionProtoType>()) {
21560 // We must match the FunctionDecl's type to the hack introduced in
21561 // RebuildUnknownAnyExpr::VisitCallExpr to vararg functions of unknown
21562 // type. See the lengthy commentary in that routine.
21563 QualType FDT = FD->getType();
21564 const FunctionType *FnType = FDT->castAs<FunctionType>();
21565 const FunctionProtoType *Proto = dyn_cast_or_null<FunctionProtoType>(Val: FnType);
21566 DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Val: E);
21567 if (DRE && Proto && Proto->getParamTypes().empty() && Proto->isVariadic()) {
21568 SourceLocation Loc = FD->getLocation();
21569 FunctionDecl *NewFD = FunctionDecl::Create(
21570 C&: S.Context, DC: FD->getDeclContext(), StartLoc: Loc, NLoc: Loc,
21571 N: FD->getNameInfo().getName(), T: DestType, TInfo: FD->getTypeSourceInfo(),
21572 SC: SC_None, UsesFPIntrin: S.getCurFPFeatures().isFPConstrained(),
21573 isInlineSpecified: false /*isInlineSpecified*/, hasWrittenPrototype: FD->hasPrototype(),
21574 /*ConstexprKind*/ ConstexprSpecKind::Unspecified);
21575
21576 if (FD->getQualifier())
21577 NewFD->setQualifierInfo(FD->getQualifierLoc());
21578
21579 SmallVector<ParmVarDecl*, 16> Params;
21580 for (const auto &AI : FT->param_types()) {
21581 ParmVarDecl *Param =
21582 S.BuildParmVarDeclForTypedef(DC: FD, Loc, T: AI);
21583 Param->setScopeInfo(scopeDepth: 0, parameterIndex: Params.size());
21584 Params.push_back(Elt: Param);
21585 }
21586 NewFD->setParams(Params);
21587 DRE->setDecl(NewFD);
21588 VD = DRE->getDecl();
21589 }
21590 }
21591
21592 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Val: FD))
21593 if (MD->isInstance()) {
21594 ValueKind = VK_PRValue;
21595 Type = S.Context.BoundMemberTy;
21596 }
21597
21598 // Function references aren't l-values in C.
21599 if (!S.getLangOpts().CPlusPlus)
21600 ValueKind = VK_PRValue;
21601
21602 // - variables
21603 } else if (isa<VarDecl>(Val: VD)) {
21604 if (const ReferenceType *RefTy = Type->getAs<ReferenceType>()) {
21605 Type = RefTy->getPointeeType();
21606 } else if (Type->isFunctionType()) {
21607 S.Diag(Loc: E->getExprLoc(), DiagID: diag::err_unknown_any_var_function_type)
21608 << VD << E->getSourceRange();
21609 return ExprError();
21610 }
21611
21612 // - nothing else
21613 } else {
21614 S.Diag(Loc: E->getExprLoc(), DiagID: diag::err_unsupported_unknown_any_decl)
21615 << VD << E->getSourceRange();
21616 return ExprError();
21617 }
21618
21619 // Modifying the declaration like this is friendly to IR-gen but
21620 // also really dangerous.
21621 VD->setType(DestType);
21622 E->setType(Type);
21623 E->setValueKind(ValueKind);
21624 return E;
21625}
21626
21627ExprResult Sema::checkUnknownAnyCast(SourceRange TypeRange, QualType CastType,
21628 Expr *CastExpr, CastKind &CastKind,
21629 ExprValueKind &VK, CXXCastPath &Path) {
21630 // The type we're casting to must be either void or complete.
21631 if (!CastType->isVoidType() &&
21632 RequireCompleteType(Loc: TypeRange.getBegin(), T: CastType,
21633 DiagID: diag::err_typecheck_cast_to_incomplete))
21634 return ExprError();
21635
21636 // Rewrite the casted expression from scratch.
21637 ExprResult result = RebuildUnknownAnyExpr(*this, CastType).Visit(S: CastExpr);
21638 if (!result.isUsable()) return ExprError();
21639
21640 CastExpr = result.get();
21641 VK = CastExpr->getValueKind();
21642 CastKind = CK_NoOp;
21643
21644 return CastExpr;
21645}
21646
21647ExprResult Sema::forceUnknownAnyToType(Expr *E, QualType ToType) {
21648 return RebuildUnknownAnyExpr(*this, ToType).Visit(S: E);
21649}
21650
21651ExprResult Sema::checkUnknownAnyArg(SourceLocation callLoc,
21652 Expr *arg, QualType &paramType) {
21653 // If the syntactic form of the argument is not an explicit cast of
21654 // any sort, just do default argument promotion.
21655 ExplicitCastExpr *castArg = dyn_cast<ExplicitCastExpr>(Val: arg->IgnoreParens());
21656 if (!castArg) {
21657 ExprResult result = DefaultArgumentPromotion(E: arg);
21658 if (result.isInvalid()) return ExprError();
21659 paramType = result.get()->getType();
21660 return result;
21661 }
21662
21663 // Otherwise, use the type that was written in the explicit cast.
21664 assert(!arg->hasPlaceholderType());
21665 paramType = castArg->getTypeAsWritten();
21666
21667 // Copy-initialize a parameter of that type.
21668 InitializedEntity entity =
21669 InitializedEntity::InitializeParameter(Context, Type: paramType,
21670 /*consumed*/ Consumed: false);
21671 return PerformCopyInitialization(Entity: entity, EqualLoc: callLoc, Init: arg);
21672}
21673
21674static ExprResult diagnoseUnknownAnyExpr(Sema &S, Expr *E) {
21675 Expr *orig = E;
21676 unsigned diagID = diag::err_uncasted_use_of_unknown_any;
21677 while (true) {
21678 E = E->IgnoreParenImpCasts();
21679 if (CallExpr *call = dyn_cast<CallExpr>(Val: E)) {
21680 E = call->getCallee();
21681 diagID = diag::err_uncasted_call_of_unknown_any;
21682 } else {
21683 break;
21684 }
21685 }
21686
21687 SourceLocation loc;
21688 NamedDecl *d;
21689 if (DeclRefExpr *ref = dyn_cast<DeclRefExpr>(Val: E)) {
21690 loc = ref->getLocation();
21691 d = ref->getDecl();
21692 } else if (MemberExpr *mem = dyn_cast<MemberExpr>(Val: E)) {
21693 loc = mem->getMemberLoc();
21694 d = mem->getMemberDecl();
21695 } else if (ObjCMessageExpr *msg = dyn_cast<ObjCMessageExpr>(Val: E)) {
21696 diagID = diag::err_uncasted_call_of_unknown_any;
21697 loc = msg->getSelectorStartLoc();
21698 d = msg->getMethodDecl();
21699 if (!d) {
21700 S.Diag(Loc: loc, DiagID: diag::err_uncasted_send_to_unknown_any_method)
21701 << static_cast<unsigned>(msg->isClassMessage()) << msg->getSelector()
21702 << orig->getSourceRange();
21703 return ExprError();
21704 }
21705 } else {
21706 S.Diag(Loc: E->getExprLoc(), DiagID: diag::err_unsupported_unknown_any_expr)
21707 << E->getSourceRange();
21708 return ExprError();
21709 }
21710
21711 S.Diag(Loc: loc, DiagID: diagID) << d << orig->getSourceRange();
21712
21713 // Never recoverable.
21714 return ExprError();
21715}
21716
21717ExprResult Sema::CheckPlaceholderExpr(Expr *E) {
21718 const BuiltinType *placeholderType = E->getType()->getAsPlaceholderType();
21719 if (!placeholderType) return E;
21720
21721 switch (placeholderType->getKind()) {
21722 case BuiltinType::UnresolvedTemplate: {
21723 auto *ULE = cast<UnresolvedLookupExpr>(Val: E);
21724 const DeclarationNameInfo &NameInfo = ULE->getNameInfo();
21725 // There's only one FoundDecl for UnresolvedTemplate type. See
21726 // BuildTemplateIdExpr.
21727 NamedDecl *Temp = *ULE->decls_begin();
21728 const bool IsTypeAliasTemplateDecl = isa<TypeAliasTemplateDecl>(Val: Temp);
21729
21730 NestedNameSpecifier NNS = ULE->getQualifierLoc().getNestedNameSpecifier();
21731 // FIXME: AssumedTemplate is not very appropriate for error recovery here,
21732 // as it models only the unqualified-id case, where this case can clearly be
21733 // qualified. Thus we can't just qualify an assumed template.
21734 TemplateName TN;
21735 if (auto *TD = dyn_cast<TemplateDecl>(Val: Temp))
21736 TN = Context.getQualifiedTemplateName(Qualifier: NNS, TemplateKeyword: ULE->hasTemplateKeyword(),
21737 Template: TemplateName(TD));
21738 else
21739 TN = Context.getAssumedTemplateName(Name: NameInfo.getName());
21740
21741 Diag(Loc: NameInfo.getLoc(), DiagID: diag::err_template_kw_refers_to_type_template)
21742 << TN << ULE->getSourceRange() << IsTypeAliasTemplateDecl;
21743 Diag(Loc: Temp->getLocation(), DiagID: diag::note_referenced_type_template)
21744 << IsTypeAliasTemplateDecl;
21745
21746 TemplateArgumentListInfo TAL(ULE->getLAngleLoc(), ULE->getRAngleLoc());
21747 bool HasAnyDependentTA = false;
21748 for (const TemplateArgumentLoc &Arg : ULE->template_arguments()) {
21749 HasAnyDependentTA |= Arg.getArgument().isDependent();
21750 TAL.addArgument(Loc: Arg);
21751 }
21752
21753 QualType TST;
21754 {
21755 SFINAETrap Trap(*this);
21756 TST = CheckTemplateIdType(
21757 Keyword: ElaboratedTypeKeyword::None, Template: TN, TemplateLoc: NameInfo.getBeginLoc(), TemplateArgs&: TAL,
21758 /*Scope=*/nullptr, /*ForNestedNameSpecifier=*/false);
21759 }
21760 if (TST.isNull())
21761 TST = Context.getTemplateSpecializationType(
21762 Keyword: ElaboratedTypeKeyword::None, T: TN, SpecifiedArgs: ULE->template_arguments(),
21763 /*CanonicalArgs=*/{},
21764 Canon: HasAnyDependentTA ? Context.DependentTy : Context.IntTy);
21765 return CreateRecoveryExpr(Begin: NameInfo.getBeginLoc(), End: NameInfo.getEndLoc(), SubExprs: {},
21766 T: TST);
21767 }
21768
21769 // Overloaded expressions.
21770 case BuiltinType::Overload: {
21771 // Try to resolve a single function template specialization.
21772 // This is obligatory.
21773 ExprResult Result = E;
21774 if (ResolveAndFixSingleFunctionTemplateSpecialization(SrcExpr&: Result, DoFunctionPointerConversion: false))
21775 return Result;
21776
21777 // No guarantees that ResolveAndFixSingleFunctionTemplateSpecialization
21778 // leaves Result unchanged on failure.
21779 Result = E;
21780 if (resolveAndFixAddressOfSingleOverloadCandidate(SrcExpr&: Result))
21781 return Result;
21782
21783 // If that failed, try to recover with a call.
21784 tryToRecoverWithCall(E&: Result, PD: PDiag(DiagID: diag::err_ovl_unresolvable),
21785 /*complain*/ ForceComplain: true);
21786 return Result;
21787 }
21788
21789 // Bound member functions.
21790 case BuiltinType::BoundMember: {
21791 ExprResult result = E;
21792 const Expr *BME = E->IgnoreParens();
21793 PartialDiagnostic PD = PDiag(DiagID: diag::err_bound_member_function);
21794 // Try to give a nicer diagnostic if it is a bound member that we recognize.
21795 if (isa<CXXPseudoDestructorExpr>(Val: BME)) {
21796 PD = PDiag(DiagID: diag::err_dtor_expr_without_call) << /*pseudo-destructor*/ 1;
21797 } else if (const auto *ME = dyn_cast<MemberExpr>(Val: BME)) {
21798 if (ME->getMemberNameInfo().getName().getNameKind() ==
21799 DeclarationName::CXXDestructorName)
21800 PD = PDiag(DiagID: diag::err_dtor_expr_without_call) << /*destructor*/ 0;
21801 }
21802 tryToRecoverWithCall(E&: result, PD,
21803 /*complain*/ ForceComplain: true);
21804 return result;
21805 }
21806
21807 // ARC unbridged casts.
21808 case BuiltinType::ARCUnbridgedCast: {
21809 Expr *realCast = ObjC().stripARCUnbridgedCast(e: E);
21810 ObjC().diagnoseARCUnbridgedCast(e: realCast);
21811 return realCast;
21812 }
21813
21814 // Expressions of unknown type.
21815 case BuiltinType::UnknownAny:
21816 return diagnoseUnknownAnyExpr(S&: *this, E);
21817
21818 // Pseudo-objects.
21819 case BuiltinType::PseudoObject:
21820 return PseudoObject().checkRValue(E);
21821
21822 case BuiltinType::BuiltinFn: {
21823 // Accept __noop without parens by implicitly converting it to a call expr.
21824 auto *DRE = dyn_cast<DeclRefExpr>(Val: E->IgnoreParenImpCasts());
21825 if (DRE) {
21826 auto *FD = cast<FunctionDecl>(Val: DRE->getDecl());
21827 unsigned BuiltinID = FD->getBuiltinID();
21828 if (BuiltinID == Builtin::BI__noop) {
21829 E = ImpCastExprToType(E, Type: Context.getPointerType(T: FD->getType()),
21830 CK: CK_BuiltinFnToFnPtr)
21831 .get();
21832 return CallExpr::Create(Ctx: Context, Fn: E, /*Args=*/{}, Ty: Context.IntTy,
21833 VK: VK_PRValue, RParenLoc: SourceLocation(),
21834 FPFeatures: FPOptionsOverride());
21835 }
21836
21837 if (Context.BuiltinInfo.isInStdNamespace(ID: BuiltinID)) {
21838 // Any use of these other than a direct call is ill-formed as of C++20,
21839 // because they are not addressable functions. In earlier language
21840 // modes, warn and force an instantiation of the real body.
21841 Diag(Loc: E->getBeginLoc(),
21842 DiagID: getLangOpts().CPlusPlus20
21843 ? diag::err_use_of_unaddressable_function
21844 : diag::warn_cxx20_compat_use_of_unaddressable_function);
21845 if (FD->isImplicitlyInstantiable()) {
21846 // Require a definition here because a normal attempt at
21847 // instantiation for a builtin will be ignored, and we won't try
21848 // again later. We assume that the definition of the template
21849 // precedes this use.
21850 InstantiateFunctionDefinition(PointOfInstantiation: E->getBeginLoc(), Function: FD,
21851 /*Recursive=*/false,
21852 /*DefinitionRequired=*/true,
21853 /*AtEndOfTU=*/false);
21854 }
21855 // Produce a properly-typed reference to the function.
21856 CXXScopeSpec SS;
21857 SS.Adopt(Other: DRE->getQualifierLoc());
21858 TemplateArgumentListInfo TemplateArgs;
21859 DRE->copyTemplateArgumentsInto(List&: TemplateArgs);
21860 return BuildDeclRefExpr(
21861 D: FD, Ty: FD->getType(), VK: VK_LValue, NameInfo: DRE->getNameInfo(),
21862 SS: DRE->hasQualifier() ? &SS : nullptr, FoundD: DRE->getFoundDecl(),
21863 TemplateKWLoc: DRE->getTemplateKeywordLoc(),
21864 TemplateArgs: DRE->hasExplicitTemplateArgs() ? &TemplateArgs : nullptr);
21865 }
21866 }
21867
21868 Diag(Loc: E->getBeginLoc(), DiagID: diag::err_builtin_fn_use);
21869 return ExprError();
21870 }
21871
21872 case BuiltinType::IncompleteMatrixIdx: {
21873 auto *MS = cast<MatrixSubscriptExpr>(Val: E->IgnoreParens());
21874 // At this point, we know there was no second [] to complete the operator.
21875 // In HLSL, treat "m[row]" as selecting a row lane of column sized vector.
21876 if (getLangOpts().HLSL) {
21877 return CreateBuiltinMatrixSingleSubscriptExpr(
21878 Base: MS->getBase(), RowIdx: MS->getRowIdx(), RBLoc: E->getExprLoc());
21879 }
21880 Diag(Loc: MS->getRowIdx()->getBeginLoc(), DiagID: diag::err_matrix_incomplete_index);
21881 return ExprError();
21882 }
21883
21884 // Expressions of unknown type.
21885 case BuiltinType::ArraySection:
21886 // If we've already diagnosed something on the array section type, we
21887 // shouldn't need to do any further diagnostic here.
21888 if (!E->containsErrors())
21889 Diag(Loc: E->getBeginLoc(), DiagID: diag::err_array_section_use)
21890 << cast<ArraySectionExpr>(Val: E)->isOMPArraySection();
21891 return ExprError();
21892
21893 // Expressions of unknown type.
21894 case BuiltinType::OMPArrayShaping:
21895 return ExprError(Diag(Loc: E->getBeginLoc(), DiagID: diag::err_omp_array_shaping_use));
21896
21897 case BuiltinType::OMPIterator:
21898 return ExprError(Diag(Loc: E->getBeginLoc(), DiagID: diag::err_omp_iterator_use));
21899
21900 // Everything else should be impossible.
21901#define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
21902 case BuiltinType::Id:
21903#include "clang/Basic/OpenCLImageTypes.def"
21904#define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \
21905 case BuiltinType::Id:
21906#include "clang/Basic/OpenCLExtensionTypes.def"
21907#define SVE_TYPE(Name, Id, SingletonId) \
21908 case BuiltinType::Id:
21909#include "clang/Basic/AArch64ACLETypes.def"
21910#define PPC_VECTOR_TYPE(Name, Id, Size) \
21911 case BuiltinType::Id:
21912#include "clang/Basic/PPCTypes.def"
21913#define RVV_TYPE(Name, Id, SingletonId) case BuiltinType::Id:
21914#include "clang/Basic/RISCVVTypes.def"
21915#define WASM_TYPE(Name, Id, SingletonId) case BuiltinType::Id:
21916#include "clang/Basic/WebAssemblyReferenceTypes.def"
21917#define AMDGPU_TYPE(Name, Id, SingletonId, Width, Align) case BuiltinType::Id:
21918#include "clang/Basic/AMDGPUTypes.def"
21919#define HLSL_INTANGIBLE_TYPE(Name, Id, SingletonId) case BuiltinType::Id:
21920#include "clang/Basic/HLSLIntangibleTypes.def"
21921#define BUILTIN_TYPE(Id, SingletonId) case BuiltinType::Id:
21922#define PLACEHOLDER_TYPE(Id, SingletonId)
21923#include "clang/AST/BuiltinTypes.def"
21924 break;
21925 }
21926
21927 llvm_unreachable("invalid placeholder type!");
21928}
21929
21930bool Sema::CheckCaseExpression(Expr *E) {
21931 if (E->isTypeDependent())
21932 return true;
21933 if (E->isValueDependent() || E->isIntegerConstantExpr(Ctx: Context))
21934 return E->getType()->isIntegralOrEnumerationType();
21935 return false;
21936}
21937
21938ExprResult Sema::CreateRecoveryExpr(SourceLocation Begin, SourceLocation End,
21939 ArrayRef<Expr *> SubExprs, QualType T) {
21940 if (!Context.getLangOpts().RecoveryAST)
21941 return ExprError();
21942
21943 if (isSFINAEContext())
21944 return ExprError();
21945
21946 if (T.isNull() || T->isUndeducedType() ||
21947 !Context.getLangOpts().RecoveryASTType)
21948 // We don't know the concrete type, fallback to dependent type.
21949 T = Context.DependentTy;
21950
21951 return RecoveryExpr::Create(Ctx&: Context, T, BeginLoc: Begin, EndLoc: End, SubExprs);
21952}
21953