1//===--- SemaExpr.cpp - Semantic Analysis for Expressions -----------------===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8//
9// This file implements semantic analysis for expressions.
10//
11//===----------------------------------------------------------------------===//
12
13#include "CheckExprLifetime.h"
14#include "TreeTransform.h"
15#include "UsedDeclVisitor.h"
16#include "clang/AST/ASTConsumer.h"
17#include "clang/AST/ASTContext.h"
18#include "clang/AST/ASTDiagnostic.h"
19#include "clang/AST/ASTLambda.h"
20#include "clang/AST/ASTMutationListener.h"
21#include "clang/AST/Attr.h"
22#include "clang/AST/CXXInheritance.h"
23#include "clang/AST/Decl.h"
24#include "clang/AST/DeclObjC.h"
25#include "clang/AST/DeclTemplate.h"
26#include "clang/AST/DynamicRecursiveASTVisitor.h"
27#include "clang/AST/EvaluatedExprVisitor.h"
28#include "clang/AST/Expr.h"
29#include "clang/AST/ExprCXX.h"
30#include "clang/AST/ExprObjC.h"
31#include "clang/AST/MangleNumberingContext.h"
32#include "clang/AST/OperationKinds.h"
33#include "clang/AST/StmtVisitor.h"
34#include "clang/AST/Type.h"
35#include "clang/AST/TypeLoc.h"
36#include "clang/Basic/Builtins.h"
37#include "clang/Basic/DiagnosticSema.h"
38#include "clang/Basic/PartialDiagnostic.h"
39#include "clang/Basic/SourceManager.h"
40#include "clang/Basic/Specifiers.h"
41#include "clang/Basic/TargetInfo.h"
42#include "clang/Basic/TypeTraits.h"
43#include "clang/Lex/LiteralSupport.h"
44#include "clang/Lex/Preprocessor.h"
45#include "clang/Sema/AnalysisBasedWarnings.h"
46#include "clang/Sema/DeclSpec.h"
47#include "clang/Sema/DelayedDiagnostic.h"
48#include "clang/Sema/Designator.h"
49#include "clang/Sema/EnterExpressionEvaluationContext.h"
50#include "clang/Sema/Initialization.h"
51#include "clang/Sema/Lookup.h"
52#include "clang/Sema/Overload.h"
53#include "clang/Sema/ParsedTemplate.h"
54#include "clang/Sema/Scope.h"
55#include "clang/Sema/ScopeInfo.h"
56#include "clang/Sema/SemaAMDGPU.h"
57#include "clang/Sema/SemaARM.h"
58#include "clang/Sema/SemaCUDA.h"
59#include "clang/Sema/SemaFixItUtils.h"
60#include "clang/Sema/SemaHLSL.h"
61#include "clang/Sema/SemaObjC.h"
62#include "clang/Sema/SemaOpenCL.h"
63#include "clang/Sema/SemaOpenMP.h"
64#include "clang/Sema/SemaPseudoObject.h"
65#include "clang/Sema/Template.h"
66#include "llvm/ADT/STLExtras.h"
67#include "llvm/ADT/StringExtras.h"
68#include "llvm/Support/ConvertUTF.h"
69#include "llvm/Support/SaveAndRestore.h"
70#include "llvm/Support/TimeProfiler.h"
71#include "llvm/Support/TypeSize.h"
72#include <limits>
73#include <optional>
74
75using namespace clang;
76using namespace sema;
77
78bool Sema::CanUseDecl(NamedDecl *D, bool TreatUnavailableAsInvalid) {
79 // See if this is an auto-typed variable whose initializer we are parsing.
80 if (ParsingInitForAutoVars.count(Ptr: D))
81 return false;
82
83 // See if this is a deleted function.
84 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Val: D)) {
85 if (FD->isDeleted())
86 return false;
87
88 // If the function has a deduced return type, and we can't deduce it,
89 // then we can't use it either.
90 if (getLangOpts().CPlusPlus14 && FD->getReturnType()->isUndeducedType() &&
91 DeduceReturnType(FD, Loc: SourceLocation(), /*Diagnose*/ false))
92 return false;
93
94 // See if this is an aligned allocation/deallocation function that is
95 // unavailable.
96 if (TreatUnavailableAsInvalid &&
97 isUnavailableAlignedAllocationFunction(FD: *FD))
98 return false;
99 }
100
101 // See if this function is unavailable.
102 if (TreatUnavailableAsInvalid && D->getAvailability() == AR_Unavailable &&
103 cast<Decl>(Val: CurContext)->getAvailability() != AR_Unavailable)
104 return false;
105
106 if (isa<UnresolvedUsingIfExistsDecl>(Val: D))
107 return false;
108
109 return true;
110}
111
112static void DiagnoseUnusedOfDecl(Sema &S, NamedDecl *D, SourceLocation Loc) {
113 // Warn if this is used but marked unused.
114 if (const auto *A = D->getAttr<UnusedAttr>()) {
115 // [[maybe_unused]] should not diagnose uses, but __attribute__((unused))
116 // should diagnose them.
117 if (A->getSemanticSpelling() != UnusedAttr::CXX11_maybe_unused &&
118 A->getSemanticSpelling() != UnusedAttr::C23_maybe_unused) {
119 const Decl *DC = cast_or_null<Decl>(Val: S.ObjC().getCurObjCLexicalContext());
120 if (DC && !DC->hasAttr<UnusedAttr>())
121 S.Diag(Loc, DiagID: diag::warn_used_but_marked_unused) << D;
122 }
123 }
124}
125
126void Sema::NoteDeletedFunction(FunctionDecl *Decl) {
127 assert(Decl && Decl->isDeleted());
128
129 if (Decl->isDefaulted()) {
130 // If the method was explicitly defaulted, point at that declaration.
131 if (!Decl->isImplicit())
132 Diag(Loc: Decl->getLocation(), DiagID: diag::note_implicitly_deleted);
133
134 // Try to diagnose why this special member function was implicitly
135 // deleted. This might fail, if that reason no longer applies.
136 DiagnoseDeletedDefaultedFunction(FD: Decl);
137 return;
138 }
139
140 auto *Ctor = dyn_cast<CXXConstructorDecl>(Val: Decl);
141 if (Ctor && Ctor->isInheritingConstructor())
142 return NoteDeletedInheritingConstructor(CD: Ctor);
143
144 Diag(Loc: Decl->getLocation(), DiagID: diag::note_availability_specified_here)
145 << Decl << 1;
146}
147
148/// Determine whether a FunctionDecl was ever declared with an
149/// explicit storage class.
150static bool hasAnyExplicitStorageClass(const FunctionDecl *D) {
151 for (auto *I : D->redecls()) {
152 if (I->getStorageClass() != SC_None)
153 return true;
154 }
155 return false;
156}
157
158/// Check whether we're in an extern inline function and referring to a
159/// variable or function with internal linkage (C11 6.7.4p3).
160///
161/// This is only a warning because we used to silently accept this code, but
162/// in many cases it will not behave correctly. This is not enabled in C++ mode
163/// because the restriction language is a bit weaker (C++11 [basic.def.odr]p6)
164/// and so while there may still be user mistakes, most of the time we can't
165/// prove that there are errors.
166static void diagnoseUseOfInternalDeclInInlineFunction(Sema &S,
167 const NamedDecl *D,
168 SourceLocation Loc) {
169 // This is disabled under C++; there are too many ways for this to fire in
170 // contexts where the warning is a false positive, or where it is technically
171 // correct but benign.
172 //
173 // WG14 N3622 which removed the constraint entirely in C2y. It is left
174 // enabled in earlier language modes because this is a constraint in those
175 // language modes. But in C2y mode, we still want to issue the "incompatible
176 // with previous standards" diagnostic, too.
177 if (S.getLangOpts().CPlusPlus)
178 return;
179
180 // Check if this is an inlined function or method.
181 FunctionDecl *Current = S.getCurFunctionDecl();
182 if (!Current)
183 return;
184 if (!Current->isInlined())
185 return;
186 if (!Current->isExternallyVisible())
187 return;
188
189 // Check if the decl has internal linkage.
190 if (D->getFormalLinkage() != Linkage::Internal)
191 return;
192
193 // Downgrade from ExtWarn to Extension if
194 // (1) the supposedly external inline function is in the main file,
195 // and probably won't be included anywhere else.
196 // (2) the thing we're referencing is a pure function.
197 // (3) the thing we're referencing is another inline function.
198 // This last can give us false negatives, but it's better than warning on
199 // wrappers for simple C library functions.
200 const FunctionDecl *UsedFn = dyn_cast<FunctionDecl>(Val: D);
201 unsigned DiagID;
202 if (S.getLangOpts().C2y)
203 DiagID = diag::warn_c2y_compat_internal_in_extern_inline;
204 else if ((UsedFn && (UsedFn->isInlined() || UsedFn->hasAttr<ConstAttr>())) ||
205 S.getSourceManager().isInMainFile(Loc))
206 DiagID = diag::ext_internal_in_extern_inline_quiet;
207 else
208 DiagID = diag::ext_internal_in_extern_inline;
209
210 S.Diag(Loc, DiagID) << /*IsVar=*/!UsedFn << D;
211 S.MaybeSuggestAddingStaticToDecl(D: Current);
212 S.Diag(Loc: D->getCanonicalDecl()->getLocation(), DiagID: diag::note_entity_declared_at)
213 << D;
214}
215
216void Sema::MaybeSuggestAddingStaticToDecl(const FunctionDecl *Cur) {
217 const FunctionDecl *First = Cur->getFirstDecl();
218
219 // Suggest "static" on the function, if possible.
220 if (!hasAnyExplicitStorageClass(D: First)) {
221 SourceLocation DeclBegin = First->getSourceRange().getBegin();
222 Diag(Loc: DeclBegin, DiagID: diag::note_convert_inline_to_static)
223 << Cur << FixItHint::CreateInsertion(InsertionLoc: DeclBegin, Code: "static ");
224 }
225}
226
227bool Sema::DiagnoseUseOfDecl(NamedDecl *D, ArrayRef<SourceLocation> Locs,
228 const ObjCInterfaceDecl *UnknownObjCClass,
229 bool ObjCPropertyAccess,
230 bool AvoidPartialAvailabilityChecks,
231 ObjCInterfaceDecl *ClassReceiver,
232 bool SkipTrailingRequiresClause) {
233 SourceLocation Loc = Locs.front();
234 if (getLangOpts().CPlusPlus && isa<FunctionDecl>(Val: D)) {
235 // If there were any diagnostics suppressed by template argument deduction,
236 // emit them now.
237 auto Pos = SuppressedDiagnostics.find(Val: D->getCanonicalDecl());
238 if (Pos != SuppressedDiagnostics.end()) {
239 for (const auto &[DiagLoc, PD] : Pos->second) {
240 DiagnosticBuilder Builder(Diags.Report(Loc: DiagLoc, DiagID: PD.getDiagID()));
241 PD.Emit(DB: Builder);
242 }
243 // Clear out the list of suppressed diagnostics, so that we don't emit
244 // them again for this specialization. However, we don't obsolete this
245 // entry from the table, because we want to avoid ever emitting these
246 // diagnostics again.
247 Pos->second.clear();
248 }
249
250 // C++ [basic.start.main]p3:
251 // The function 'main' shall not be used within a program.
252 if (cast<FunctionDecl>(Val: D)->isMain())
253 Diag(Loc, DiagID: diag::ext_main_used);
254
255 diagnoseUnavailableAlignedAllocation(FD: *cast<FunctionDecl>(Val: D), Loc);
256 }
257
258 // See if this is an auto-typed variable whose initializer we are parsing.
259 if (ParsingInitForAutoVars.count(Ptr: D)) {
260 if (isa<BindingDecl>(Val: D)) {
261 Diag(Loc, DiagID: diag::err_binding_cannot_appear_in_own_initializer)
262 << D->getDeclName();
263 } else {
264 Diag(Loc, DiagID: diag::err_auto_variable_cannot_appear_in_own_initializer)
265 << diag::ParsingInitFor::Var << D->getDeclName()
266 << cast<VarDecl>(Val: D)->getType();
267 }
268 return true;
269 }
270
271 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Val: D)) {
272 // See if this is a deleted function.
273 if (FD->isDeleted()) {
274 auto *Ctor = dyn_cast<CXXConstructorDecl>(Val: FD);
275 if (Ctor && Ctor->isInheritingConstructor())
276 Diag(Loc, DiagID: diag::err_deleted_inherited_ctor_use)
277 << Ctor->getParent()
278 << Ctor->getInheritedConstructor().getConstructor()->getParent();
279 else {
280 StringLiteral *Msg = FD->getDeletedMessage();
281 Diag(Loc, DiagID: diag::err_deleted_function_use)
282 << (Msg != nullptr) << (Msg ? Msg->getString() : StringRef());
283 }
284 NoteDeletedFunction(Decl: FD);
285 return true;
286 }
287
288 // [expr.prim.id]p4
289 // A program that refers explicitly or implicitly to a function with a
290 // trailing requires-clause whose constraint-expression is not satisfied,
291 // other than to declare it, is ill-formed. [...]
292 //
293 // See if this is a function with constraints that need to be satisfied.
294 // Check this before deducing the return type, as it might instantiate the
295 // definition.
296 if (!SkipTrailingRequiresClause && FD->getTrailingRequiresClause()) {
297 ConstraintSatisfaction Satisfaction;
298 if (CheckFunctionConstraints(FD, Satisfaction, UsageLoc: Loc,
299 /*ForOverloadResolution*/ true))
300 // A diagnostic will have already been generated (non-constant
301 // constraint expression, for example)
302 return true;
303 if (!Satisfaction.IsSatisfied) {
304 Diag(Loc,
305 DiagID: diag::err_reference_to_function_with_unsatisfied_constraints)
306 << D;
307 DiagnoseUnsatisfiedConstraint(Satisfaction);
308 return true;
309 }
310 }
311
312 // If the function has a deduced return type, and we can't deduce it,
313 // then we can't use it either.
314 if (getLangOpts().CPlusPlus14 && FD->getReturnType()->isUndeducedType() &&
315 DeduceReturnType(FD, Loc))
316 return true;
317
318 if (getLangOpts().CUDA && !CUDA().CheckCall(Loc, Callee: FD))
319 return true;
320
321 }
322
323 if (auto *Concept = dyn_cast<ConceptDecl>(Val: D);
324 Concept && CheckConceptUseInDefinition(Concept, Loc))
325 return true;
326
327 if (auto *MD = dyn_cast<CXXMethodDecl>(Val: D)) {
328 // Lambdas are only default-constructible or assignable in C++2a onwards.
329 if (MD->getParent()->isLambda() &&
330 ((isa<CXXConstructorDecl>(Val: MD) &&
331 cast<CXXConstructorDecl>(Val: MD)->isDefaultConstructor()) ||
332 MD->isCopyAssignmentOperator() || MD->isMoveAssignmentOperator())) {
333 Diag(Loc, DiagID: diag::warn_cxx17_compat_lambda_def_ctor_assign)
334 << !isa<CXXConstructorDecl>(Val: MD);
335 }
336 }
337
338 auto getReferencedObjCProp = [](const NamedDecl *D) ->
339 const ObjCPropertyDecl * {
340 if (const auto *MD = dyn_cast<ObjCMethodDecl>(Val: D))
341 return MD->findPropertyDecl();
342 return nullptr;
343 };
344 if (const ObjCPropertyDecl *ObjCPDecl = getReferencedObjCProp(D)) {
345 if (diagnoseArgIndependentDiagnoseIfAttrs(ND: ObjCPDecl, Loc))
346 return true;
347 } else if (diagnoseArgIndependentDiagnoseIfAttrs(ND: D, Loc)) {
348 return true;
349 }
350
351 // [OpenMP 4.0], 2.15 declare reduction Directive, Restrictions
352 // Only the variables omp_in and omp_out are allowed in the combiner.
353 // Only the variables omp_priv and omp_orig are allowed in the
354 // initializer-clause.
355 auto *DRD = dyn_cast<OMPDeclareReductionDecl>(Val: CurContext);
356 if (LangOpts.OpenMP && DRD && !CurContext->containsDecl(D) &&
357 isa<VarDecl>(Val: D)) {
358 Diag(Loc, DiagID: diag::err_omp_wrong_var_in_declare_reduction)
359 << getCurFunction()->HasOMPDeclareReductionCombiner;
360 Diag(Loc: D->getLocation(), DiagID: diag::note_entity_declared_at) << D;
361 return true;
362 }
363
364 // [OpenMP 5.0], 2.19.7.3. declare mapper Directive, Restrictions
365 // List-items in map clauses on this construct may only refer to the declared
366 // variable var and entities that could be referenced by a procedure defined
367 // at the same location.
368 // [OpenMP 5.2] Also allow iterator declared variables.
369 if (LangOpts.OpenMP && isa<VarDecl>(Val: D) &&
370 !OpenMP().isOpenMPDeclareMapperVarDeclAllowed(VD: cast<VarDecl>(Val: D))) {
371 Diag(Loc, DiagID: diag::err_omp_declare_mapper_wrong_var)
372 << OpenMP().getOpenMPDeclareMapperVarName();
373 Diag(Loc: D->getLocation(), DiagID: diag::note_entity_declared_at) << D;
374 return true;
375 }
376
377 if (const auto *EmptyD = dyn_cast<UnresolvedUsingIfExistsDecl>(Val: D)) {
378 Diag(Loc, DiagID: diag::err_use_of_empty_using_if_exists);
379 Diag(Loc: EmptyD->getLocation(), DiagID: diag::note_empty_using_if_exists_here);
380 return true;
381 }
382
383 DiagnoseAvailabilityOfDecl(D, Locs, UnknownObjCClass, ObjCPropertyAccess,
384 AvoidPartialAvailabilityChecks, ClassReceiver);
385
386 DiagnoseUnusedOfDecl(S&: *this, D, Loc);
387
388 diagnoseUseOfInternalDeclInInlineFunction(S&: *this, D, Loc);
389
390 if (D->hasAttr<AvailableOnlyInDefaultEvalMethodAttr>()) {
391 if (getLangOpts().getFPEvalMethod() !=
392 LangOptions::FPEvalMethodKind::FEM_UnsetOnCommandLine &&
393 PP.getLastFPEvalPragmaLocation().isValid() &&
394 PP.getCurrentFPEvalMethod() != getLangOpts().getFPEvalMethod())
395 Diag(Loc: D->getLocation(),
396 DiagID: diag::err_type_available_only_in_default_eval_method)
397 << D->getName();
398 }
399
400 if (auto *VD = dyn_cast<ValueDecl>(Val: D))
401 checkTypeSupport(Ty: VD->getType(), Loc, D: VD);
402
403 if (LangOpts.SYCLIsDevice ||
404 (LangOpts.OpenMP && LangOpts.OpenMPIsTargetDevice)) {
405 if (!Context.getTargetInfo().isTLSSupported())
406 if (const auto *VD = dyn_cast<VarDecl>(Val: D))
407 if (VD->getTLSKind() != VarDecl::TLS_None)
408 targetDiag(Loc: *Locs.begin(), DiagID: diag::err_thread_unsupported);
409 }
410
411 if (LangOpts.SYCLIsDevice && isa<FunctionDecl>(Val: D))
412 SYCL().CheckDeviceUseOfDecl(ND: D, Loc);
413
414 return false;
415}
416
417void Sema::DiagnoseSentinelCalls(const NamedDecl *D, SourceLocation Loc,
418 ArrayRef<Expr *> Args) {
419 const SentinelAttr *Attr = D->getAttr<SentinelAttr>();
420 if (!Attr)
421 return;
422
423 // The number of formal parameters of the declaration.
424 unsigned NumFormalParams;
425
426 // The kind of declaration. This is also an index into a %select in
427 // the diagnostic.
428 enum { CK_Function, CK_Method, CK_Block } CalleeKind;
429
430 if (const auto *MD = dyn_cast<ObjCMethodDecl>(Val: D)) {
431 NumFormalParams = MD->param_size();
432 CalleeKind = CK_Method;
433 } else if (const auto *FD = dyn_cast<FunctionDecl>(Val: D)) {
434 NumFormalParams = FD->param_size();
435 CalleeKind = CK_Function;
436 } else if (const auto *VD = dyn_cast<VarDecl>(Val: D)) {
437 QualType Ty = VD->getType();
438 const FunctionType *Fn = nullptr;
439 if (const auto *PtrTy = Ty->getAs<PointerType>()) {
440 Fn = PtrTy->getPointeeType()->getAs<FunctionType>();
441 if (!Fn)
442 return;
443 CalleeKind = CK_Function;
444 } else if (const auto *PtrTy = Ty->getAs<BlockPointerType>()) {
445 Fn = PtrTy->getPointeeType()->castAs<FunctionType>();
446 CalleeKind = CK_Block;
447 } else {
448 return;
449 }
450
451 if (const auto *proto = dyn_cast<FunctionProtoType>(Val: Fn))
452 NumFormalParams = proto->getNumParams();
453 else
454 NumFormalParams = 0;
455 } else {
456 return;
457 }
458
459 // "NullPos" is the number of formal parameters at the end which
460 // effectively count as part of the variadic arguments. This is
461 // useful if you would prefer to not have *any* formal parameters,
462 // but the language forces you to have at least one.
463 unsigned NullPos = Attr->getNullPos();
464 assert((NullPos == 0 || NullPos == 1) && "invalid null position on sentinel");
465 NumFormalParams = (NullPos > NumFormalParams ? 0 : NumFormalParams - NullPos);
466
467 // The number of arguments which should follow the sentinel.
468 unsigned NumArgsAfterSentinel = Attr->getSentinel();
469
470 // If there aren't enough arguments for all the formal parameters,
471 // the sentinel, and the args after the sentinel, complain.
472 if (Args.size() < NumFormalParams + NumArgsAfterSentinel + 1) {
473 Diag(Loc, DiagID: diag::warn_not_enough_argument) << D->getDeclName();
474 Diag(Loc: D->getLocation(), DiagID: diag::note_sentinel_here) << int(CalleeKind);
475 return;
476 }
477
478 // Otherwise, find the sentinel expression.
479 const Expr *SentinelExpr = Args[Args.size() - NumArgsAfterSentinel - 1];
480 if (!SentinelExpr)
481 return;
482 if (SentinelExpr->isValueDependent())
483 return;
484 if (Context.isSentinelNullExpr(E: SentinelExpr))
485 return;
486
487 // Pick a reasonable string to insert. Optimistically use 'nil', 'nullptr',
488 // or 'NULL' if those are actually defined in the context. Only use
489 // 'nil' for ObjC methods, where it's much more likely that the
490 // variadic arguments form a list of object pointers.
491 SourceLocation MissingNilLoc = getLocForEndOfToken(Loc: SentinelExpr->getEndLoc());
492 std::string NullValue;
493 if (CalleeKind == CK_Method && PP.isMacroDefined(Id: "nil"))
494 NullValue = "nil";
495 else if (getLangOpts().CPlusPlus11)
496 NullValue = "nullptr";
497 else if (PP.isMacroDefined(Id: "NULL"))
498 NullValue = "NULL";
499 else
500 NullValue = "(void*) 0";
501
502 if (MissingNilLoc.isInvalid())
503 Diag(Loc, DiagID: diag::warn_missing_sentinel) << int(CalleeKind);
504 else
505 Diag(Loc: MissingNilLoc, DiagID: diag::warn_missing_sentinel)
506 << int(CalleeKind)
507 << FixItHint::CreateInsertion(InsertionLoc: MissingNilLoc, Code: ", " + NullValue);
508 Diag(Loc: D->getLocation(), DiagID: diag::note_sentinel_here)
509 << int(CalleeKind) << Attr->getRange();
510}
511
512SourceRange Sema::getExprRange(Expr *E) const {
513 return E ? E->getSourceRange() : SourceRange();
514}
515
516//===----------------------------------------------------------------------===//
517// Standard Promotions and Conversions
518//===----------------------------------------------------------------------===//
519
520/// DefaultFunctionArrayConversion (C99 6.3.2.1p3, C99 6.3.2.1p4).
521ExprResult Sema::DefaultFunctionArrayConversion(Expr *E, bool Diagnose) {
522 // Handle any placeholder expressions which made it here.
523 if (E->hasPlaceholderType()) {
524 ExprResult result = CheckPlaceholderExpr(E);
525 if (result.isInvalid()) return ExprError();
526 E = result.get();
527 }
528
529 QualType Ty = E->getType();
530 assert(!Ty.isNull() && "DefaultFunctionArrayConversion - missing type");
531
532 if (Ty->isFunctionType()) {
533 if (auto *DRE = dyn_cast<DeclRefExpr>(Val: E->IgnoreParenCasts()))
534 if (auto *FD = dyn_cast<FunctionDecl>(Val: DRE->getDecl()))
535 if (!checkAddressOfFunctionIsAvailable(Function: FD, Complain: Diagnose, Loc: E->getExprLoc()))
536 return ExprError();
537
538 E = ImpCastExprToType(E, Type: Context.getPointerType(T: Ty),
539 CK: CK_FunctionToPointerDecay).get();
540 } else if (Ty->isArrayType()) {
541 // In C90 mode, arrays only promote to pointers if the array expression is
542 // an lvalue. The relevant legalese is C90 6.2.2.1p3: "an lvalue that has
543 // type 'array of type' is converted to an expression that has type 'pointer
544 // to type'...". In C99 this was changed to: C99 6.3.2.1p3: "an expression
545 // that has type 'array of type' ...". The relevant change is "an lvalue"
546 // (C90) to "an expression" (C99).
547 //
548 // C++ 4.2p1:
549 // An lvalue or rvalue of type "array of N T" or "array of unknown bound of
550 // T" can be converted to an rvalue of type "pointer to T".
551 //
552 if (getLangOpts().C99 || getLangOpts().CPlusPlus || E->isLValue()) {
553 ExprResult Res = ImpCastExprToType(E, Type: Context.getArrayDecayedType(T: Ty),
554 CK: CK_ArrayToPointerDecay);
555 if (Res.isInvalid())
556 return ExprError();
557 E = Res.get();
558 }
559 }
560 return E;
561}
562
563static void CheckForNullPointerDereference(Sema &S, Expr *E) {
564 // Check to see if we are dereferencing a null pointer. If so,
565 // and if not volatile-qualified, this is undefined behavior that the
566 // optimizer will delete, so warn about it. People sometimes try to use this
567 // to get a deterministic trap and are surprised by clang's behavior. This
568 // only handles the pattern "*null", which is a very syntactic check.
569 const auto *UO = dyn_cast<UnaryOperator>(Val: E->IgnoreParenCasts());
570 if (UO && UO->getOpcode() == UO_Deref &&
571 UO->getSubExpr()->getType()->isPointerType()) {
572 const LangAS AS =
573 UO->getSubExpr()->getType()->getPointeeType().getAddressSpace();
574 if ((!isTargetAddressSpace(AS) ||
575 (isTargetAddressSpace(AS) && toTargetAddressSpace(AS) == 0)) &&
576 UO->getSubExpr()->IgnoreParenCasts()->isNullPointerConstant(
577 Ctx&: S.Context, NPC: Expr::NPC_ValueDependentIsNotNull) &&
578 !UO->getType().isVolatileQualified()) {
579 S.DiagRuntimeBehavior(Loc: UO->getOperatorLoc(), Statement: UO,
580 PD: S.PDiag(DiagID: diag::warn_indirection_through_null)
581 << UO->getSubExpr()->getSourceRange());
582 S.DiagRuntimeBehavior(Loc: UO->getOperatorLoc(), Statement: UO,
583 PD: S.PDiag(DiagID: diag::note_indirection_through_null));
584 }
585 }
586}
587
588static void DiagnoseDirectIsaAccess(Sema &S, const ObjCIvarRefExpr *OIRE,
589 SourceLocation AssignLoc,
590 const Expr* RHS) {
591 const ObjCIvarDecl *IV = OIRE->getDecl();
592 if (!IV)
593 return;
594
595 DeclarationName MemberName = IV->getDeclName();
596 IdentifierInfo *Member = MemberName.getAsIdentifierInfo();
597 if (!Member || !Member->isStr(Str: "isa"))
598 return;
599
600 const Expr *Base = OIRE->getBase();
601 QualType BaseType = Base->getType();
602 if (OIRE->isArrow())
603 BaseType = BaseType->getPointeeType();
604 if (const ObjCObjectType *OTy = BaseType->getAs<ObjCObjectType>())
605 if (ObjCInterfaceDecl *IDecl = OTy->getInterface()) {
606 ObjCInterfaceDecl *ClassDeclared = nullptr;
607 ObjCIvarDecl *IV = IDecl->lookupInstanceVariable(IVarName: Member, ClassDeclared);
608 if (!ClassDeclared->getSuperClass()
609 && (*ClassDeclared->ivar_begin()) == IV) {
610 if (RHS) {
611 NamedDecl *ObjectSetClass =
612 S.LookupSingleName(S: S.TUScope,
613 Name: &S.Context.Idents.get(Name: "object_setClass"),
614 Loc: SourceLocation(), NameKind: S.LookupOrdinaryName);
615 if (ObjectSetClass) {
616 SourceLocation RHSLocEnd = S.getLocForEndOfToken(Loc: RHS->getEndLoc());
617 S.Diag(Loc: OIRE->getExprLoc(), DiagID: diag::warn_objc_isa_assign)
618 << FixItHint::CreateInsertion(InsertionLoc: OIRE->getBeginLoc(),
619 Code: "object_setClass(")
620 << FixItHint::CreateReplacement(
621 RemoveRange: SourceRange(OIRE->getOpLoc(), AssignLoc), Code: ",")
622 << FixItHint::CreateInsertion(InsertionLoc: RHSLocEnd, Code: ")");
623 }
624 else
625 S.Diag(Loc: OIRE->getLocation(), DiagID: diag::warn_objc_isa_assign);
626 } else {
627 NamedDecl *ObjectGetClass =
628 S.LookupSingleName(S: S.TUScope,
629 Name: &S.Context.Idents.get(Name: "object_getClass"),
630 Loc: SourceLocation(), NameKind: S.LookupOrdinaryName);
631 if (ObjectGetClass)
632 S.Diag(Loc: OIRE->getExprLoc(), DiagID: diag::warn_objc_isa_use)
633 << FixItHint::CreateInsertion(InsertionLoc: OIRE->getBeginLoc(),
634 Code: "object_getClass(")
635 << FixItHint::CreateReplacement(
636 RemoveRange: SourceRange(OIRE->getOpLoc(), OIRE->getEndLoc()), Code: ")");
637 else
638 S.Diag(Loc: OIRE->getLocation(), DiagID: diag::warn_objc_isa_use);
639 }
640 S.Diag(Loc: IV->getLocation(), DiagID: diag::note_ivar_decl);
641 }
642 }
643}
644
645ExprResult Sema::DefaultLvalueConversion(Expr *E) {
646 // Handle any placeholder expressions which made it here.
647 if (E->hasPlaceholderType()) {
648 ExprResult result = CheckPlaceholderExpr(E);
649 if (result.isInvalid()) return ExprError();
650 E = result.get();
651 }
652
653 // C++ [conv.lval]p1:
654 // A glvalue of a non-function, non-array type T can be
655 // converted to a prvalue.
656 if (!E->isGLValue()) return E;
657
658 QualType T = E->getType();
659 assert(!T.isNull() && "r-value conversion on typeless expression?");
660
661 // lvalue-to-rvalue conversion cannot be applied to types that decay to
662 // pointers (i.e. function or array types).
663 if (T->canDecayToPointerType())
664 return E;
665
666 // We don't want to throw lvalue-to-rvalue casts on top of
667 // expressions of certain types in C++.
668 // In HLSL LvaluetoRvalue conversion is allowed on records.
669 if (getLangOpts().CPlusPlus) {
670 if (T == Context.OverloadTy || (T->isRecordType() && !getLangOpts().HLSL) ||
671 (T->isDependentType() && !T->isAnyPointerType() &&
672 !T->isMemberPointerType()))
673 return E;
674 }
675
676 // The C standard is actually really unclear on this point, and
677 // DR106 tells us what the result should be but not why. It's
678 // generally best to say that void types just doesn't undergo
679 // lvalue-to-rvalue at all. Note that expressions of unqualified
680 // 'void' type are never l-values, but qualified void can be.
681 if (T->isVoidType())
682 return E;
683
684 // OpenCL usually rejects direct accesses to values of 'half' type.
685 if (getLangOpts().OpenCL &&
686 !getOpenCLOptions().isAvailableOption(Ext: "cl_khr_fp16", LO: getLangOpts()) &&
687 T->isHalfType()) {
688 Diag(Loc: E->getExprLoc(), DiagID: diag::err_opencl_half_load_store)
689 << 0 << T;
690 return ExprError();
691 }
692
693 CheckForNullPointerDereference(S&: *this, E);
694 if (const ObjCIsaExpr *OISA = dyn_cast<ObjCIsaExpr>(Val: E->IgnoreParenCasts())) {
695 NamedDecl *ObjectGetClass = LookupSingleName(S: TUScope,
696 Name: &Context.Idents.get(Name: "object_getClass"),
697 Loc: SourceLocation(), NameKind: LookupOrdinaryName);
698 if (ObjectGetClass)
699 Diag(Loc: E->getExprLoc(), DiagID: diag::warn_objc_isa_use)
700 << FixItHint::CreateInsertion(InsertionLoc: OISA->getBeginLoc(), Code: "object_getClass(")
701 << FixItHint::CreateReplacement(
702 RemoveRange: SourceRange(OISA->getOpLoc(), OISA->getIsaMemberLoc()), Code: ")");
703 else
704 Diag(Loc: E->getExprLoc(), DiagID: diag::warn_objc_isa_use);
705 }
706 else if (const ObjCIvarRefExpr *OIRE =
707 dyn_cast<ObjCIvarRefExpr>(Val: E->IgnoreParenCasts()))
708 DiagnoseDirectIsaAccess(S&: *this, OIRE, AssignLoc: SourceLocation(), /* Expr*/RHS: nullptr);
709
710 // C++ [conv.lval]p1:
711 // [...] If T is a non-class type, the type of the prvalue is the
712 // cv-unqualified version of T. Otherwise, the type of the
713 // rvalue is T.
714 //
715 // C99 6.3.2.1p2:
716 // If the lvalue has qualified type, the value has the unqualified
717 // version of the type of the lvalue; otherwise, the value has the
718 // type of the lvalue.
719 if (T.hasQualifiers())
720 T = T.getUnqualifiedType();
721
722 // Under the MS ABI, lock down the inheritance model now.
723 if (T->isMemberPointerType() &&
724 Context.getTargetInfo().getCXXABI().isMicrosoft())
725 (void)isCompleteType(Loc: E->getExprLoc(), T);
726
727 ExprResult Res = CheckLValueToRValueConversionOperand(E);
728 if (Res.isInvalid())
729 return Res;
730 E = Res.get();
731
732 // Loading a __weak object implicitly retains the value, so we need a cleanup to
733 // balance that.
734 if (E->getType().getObjCLifetime() == Qualifiers::OCL_Weak)
735 Cleanup.setExprNeedsCleanups(true);
736
737 if (E->getType().isDestructedType() == QualType::DK_nontrivial_c_struct)
738 Cleanup.setExprNeedsCleanups(true);
739
740 if (!BoundsSafetyCheckUseOfCountAttrPtr(E: Res.get()))
741 return ExprError();
742
743 // C++ [conv.lval]p3:
744 // If T is cv std::nullptr_t, the result is a null pointer constant.
745 CastKind CK = T->isNullPtrType() ? CK_NullToPointer : CK_LValueToRValue;
746 Res = ImplicitCastExpr::Create(Context, T, Kind: CK, Operand: E, BasePath: nullptr, Cat: VK_PRValue,
747 FPO: CurFPFeatureOverrides());
748
749 // C11 6.3.2.1p2:
750 // ... if the lvalue has atomic type, the value has the non-atomic version
751 // of the type of the lvalue ...
752 if (const AtomicType *Atomic = T->getAs<AtomicType>()) {
753 T = Atomic->getValueType().getUnqualifiedType();
754 Res = ImplicitCastExpr::Create(Context, T, Kind: CK_AtomicToNonAtomic, Operand: Res.get(),
755 BasePath: nullptr, Cat: VK_PRValue, FPO: FPOptionsOverride());
756 }
757
758 return Res;
759}
760
761ExprResult Sema::DefaultFunctionArrayLvalueConversion(Expr *E, bool Diagnose) {
762 ExprResult Res = DefaultFunctionArrayConversion(E, Diagnose);
763 if (Res.isInvalid())
764 return ExprError();
765 Res = DefaultLvalueConversion(E: Res.get());
766 if (Res.isInvalid())
767 return ExprError();
768 return Res;
769}
770
771ExprResult Sema::CallExprUnaryConversions(Expr *E) {
772 QualType Ty = E->getType();
773 ExprResult Res = E;
774 // Only do implicit cast for a function type, but not for a pointer
775 // to function type.
776 if (Ty->isFunctionType()) {
777 Res = ImpCastExprToType(E, Type: Context.getPointerType(T: Ty),
778 CK: CK_FunctionToPointerDecay);
779 if (Res.isInvalid())
780 return ExprError();
781 }
782 Res = DefaultLvalueConversion(E: Res.get());
783 if (Res.isInvalid())
784 return ExprError();
785 return Res.get();
786}
787
788/// UsualUnaryFPConversions - Promotes floating-point types according to the
789/// current language semantics.
790ExprResult Sema::UsualUnaryFPConversions(Expr *E) {
791 QualType Ty = E->getType();
792 assert(!Ty.isNull() && "UsualUnaryFPConversions - missing type");
793
794 LangOptions::FPEvalMethodKind EvalMethod = CurFPFeatures.getFPEvalMethod();
795 if (EvalMethod != LangOptions::FEM_Source && Ty->isFloatingType() &&
796 (getLangOpts().getFPEvalMethod() !=
797 LangOptions::FPEvalMethodKind::FEM_UnsetOnCommandLine ||
798 PP.getLastFPEvalPragmaLocation().isValid())) {
799 switch (EvalMethod) {
800 default:
801 llvm_unreachable("Unrecognized float evaluation method");
802 break;
803 case LangOptions::FEM_UnsetOnCommandLine:
804 llvm_unreachable("Float evaluation method should be set by now");
805 break;
806 case LangOptions::FEM_Double:
807 if (Context.getFloatingTypeOrder(LHS: Context.DoubleTy, RHS: Ty) > 0)
808 // Widen the expression to double.
809 return Ty->isComplexType()
810 ? ImpCastExprToType(E,
811 Type: Context.getComplexType(T: Context.DoubleTy),
812 CK: CK_FloatingComplexCast)
813 : ImpCastExprToType(E, Type: Context.DoubleTy, CK: CK_FloatingCast);
814 break;
815 case LangOptions::FEM_Extended:
816 if (Context.getFloatingTypeOrder(LHS: Context.LongDoubleTy, RHS: Ty) > 0)
817 // Widen the expression to long double.
818 return Ty->isComplexType()
819 ? ImpCastExprToType(
820 E, Type: Context.getComplexType(T: Context.LongDoubleTy),
821 CK: CK_FloatingComplexCast)
822 : ImpCastExprToType(E, Type: Context.LongDoubleTy,
823 CK: CK_FloatingCast);
824 break;
825 }
826 }
827
828 // Half FP have to be promoted to float unless it is natively supported
829 if (Ty->isHalfType() && !getLangOpts().NativeHalfType)
830 return ImpCastExprToType(E, Type: Context.FloatTy, CK: CK_FloatingCast);
831
832 return E;
833}
834
835/// UsualUnaryConversions - Performs various conversions that are common to most
836/// operators (C99 6.3). The conversions of array and function types are
837/// sometimes suppressed. For example, the array->pointer conversion doesn't
838/// apply if the array is an argument to the sizeof or address (&) operators.
839/// In these instances, this routine should *not* be called.
840ExprResult Sema::UsualUnaryConversions(Expr *E) {
841 // First, convert to an r-value.
842 ExprResult Res = DefaultFunctionArrayLvalueConversion(E);
843 if (Res.isInvalid())
844 return ExprError();
845
846 // Promote floating-point types.
847 Res = UsualUnaryFPConversions(E: Res.get());
848 if (Res.isInvalid())
849 return ExprError();
850 E = Res.get();
851
852 QualType Ty = E->getType();
853 assert(!Ty.isNull() && "UsualUnaryConversions - missing type");
854
855 // Try to perform integral promotions if the object has a theoretically
856 // promotable type.
857 if (Ty->isIntegralOrUnscopedEnumerationType()) {
858 // C99 6.3.1.1p2:
859 //
860 // The following may be used in an expression wherever an int or
861 // unsigned int may be used:
862 // - an object or expression with an integer type whose integer
863 // conversion rank is less than or equal to the rank of int
864 // and unsigned int.
865 // - A bit-field of type _Bool, int, signed int, or unsigned int.
866 //
867 // If an int can represent all values of the original type, the
868 // value is converted to an int; otherwise, it is converted to an
869 // unsigned int. These are called the integer promotions. All
870 // other types are unchanged by the integer promotions.
871
872 QualType PTy = Context.isPromotableBitField(E);
873 if (!PTy.isNull()) {
874 E = ImpCastExprToType(E, Type: PTy, CK: CK_IntegralCast).get();
875 return E;
876 }
877 if (Context.isPromotableIntegerType(T: Ty)) {
878 QualType PT = Context.getPromotedIntegerType(PromotableType: Ty);
879 E = ImpCastExprToType(E, Type: PT, CK: CK_IntegralCast).get();
880 return E;
881 }
882 }
883 return E;
884}
885
886/// DefaultArgumentPromotion (C99 6.5.2.2p6). Used for function calls that
887/// do not have a prototype. Arguments that have type float or __fp16
888/// are promoted to double. All other argument types are converted by
889/// UsualUnaryConversions().
890ExprResult Sema::DefaultArgumentPromotion(Expr *E) {
891 QualType Ty = E->getType();
892 assert(!Ty.isNull() && "DefaultArgumentPromotion - missing type");
893
894 ExprResult Res = UsualUnaryConversions(E);
895 if (Res.isInvalid())
896 return ExprError();
897 E = Res.get();
898
899 // If this is a 'float' or '__fp16' (CVR qualified or typedef)
900 // promote to double.
901 // Note that default argument promotion applies only to float (and
902 // half/fp16); it does not apply to _Float16.
903 const BuiltinType *BTy = Ty->getAs<BuiltinType>();
904 if (BTy && (BTy->getKind() == BuiltinType::Half ||
905 BTy->getKind() == BuiltinType::Float)) {
906 if (getLangOpts().OpenCL &&
907 !getOpenCLOptions().isAvailableOption(Ext: "cl_khr_fp64", LO: getLangOpts())) {
908 if (BTy->getKind() == BuiltinType::Half) {
909 E = ImpCastExprToType(E, Type: Context.FloatTy, CK: CK_FloatingCast).get();
910 }
911 } else {
912 E = ImpCastExprToType(E, Type: Context.DoubleTy, CK: CK_FloatingCast).get();
913 }
914 }
915 if (BTy &&
916 getLangOpts().getExtendIntArgs() ==
917 LangOptions::ExtendArgsKind::ExtendTo64 &&
918 Context.getTargetInfo().supportsExtendIntArgs() && Ty->isIntegerType() &&
919 Context.getTypeSizeInChars(T: BTy) <
920 Context.getTypeSizeInChars(T: Context.LongLongTy)) {
921 E = (Ty->isUnsignedIntegerType())
922 ? ImpCastExprToType(E, Type: Context.UnsignedLongLongTy, CK: CK_IntegralCast)
923 .get()
924 : ImpCastExprToType(E, Type: Context.LongLongTy, CK: CK_IntegralCast).get();
925 assert(8 == Context.getTypeSizeInChars(Context.LongLongTy).getQuantity() &&
926 "Unexpected typesize for LongLongTy");
927 }
928
929 // C++ performs lvalue-to-rvalue conversion as a default argument
930 // promotion, even on class types, but note:
931 // C++11 [conv.lval]p2:
932 // When an lvalue-to-rvalue conversion occurs in an unevaluated
933 // operand or a subexpression thereof the value contained in the
934 // referenced object is not accessed. Otherwise, if the glvalue
935 // has a class type, the conversion copy-initializes a temporary
936 // of type T from the glvalue and the result of the conversion
937 // is a prvalue for the temporary.
938 // FIXME: add some way to gate this entire thing for correctness in
939 // potentially potentially evaluated contexts.
940 if (getLangOpts().CPlusPlus && E->isGLValue() && !isUnevaluatedContext()) {
941 ExprResult Temp = PerformCopyInitialization(
942 Entity: InitializedEntity::InitializeTemporary(Type: E->getType()),
943 EqualLoc: E->getExprLoc(), Init: E);
944 if (Temp.isInvalid())
945 return ExprError();
946 E = Temp.get();
947 }
948
949 // C++ [expr.call]p7, per CWG722:
950 // An argument that has (possibly cv-qualified) type std::nullptr_t is
951 // converted to void* ([conv.ptr]).
952 // (This does not apply to C23 nullptr)
953 if (getLangOpts().CPlusPlus && E->getType()->isNullPtrType())
954 E = ImpCastExprToType(E, Type: Context.VoidPtrTy, CK: CK_NullToPointer).get();
955
956 return E;
957}
958
959VarArgKind Sema::isValidVarArgType(const QualType &Ty) {
960 if (Ty->isIncompleteType()) {
961 // C++11 [expr.call]p7:
962 // After these conversions, if the argument does not have arithmetic,
963 // enumeration, pointer, pointer to member, or class type, the program
964 // is ill-formed.
965 //
966 // Since we've already performed null pointer conversion, array-to-pointer
967 // decay and function-to-pointer decay, the only such type in C++ is cv
968 // void. This also handles initializer lists as variadic arguments.
969 if (Ty->isVoidType())
970 return VarArgKind::Invalid;
971
972 if (Ty->isObjCObjectType())
973 return VarArgKind::Invalid;
974 return VarArgKind::Valid;
975 }
976
977 if (Ty.isDestructedType() == QualType::DK_nontrivial_c_struct)
978 return VarArgKind::Invalid;
979
980 if (Context.getTargetInfo().getTriple().isWasm() &&
981 Ty.isWebAssemblyReferenceType()) {
982 return VarArgKind::Invalid;
983 }
984
985 if (Ty.isCXX98PODType(Context))
986 return VarArgKind::Valid;
987
988 // C++11 [expr.call]p7:
989 // Passing a potentially-evaluated argument of class type (Clause 9)
990 // having a non-trivial copy constructor, a non-trivial move constructor,
991 // or a non-trivial destructor, with no corresponding parameter,
992 // is conditionally-supported with implementation-defined semantics.
993 if (getLangOpts().CPlusPlus11 && !Ty->isDependentType())
994 if (CXXRecordDecl *Record = Ty->getAsCXXRecordDecl())
995 if (!Record->hasNonTrivialCopyConstructor() &&
996 !Record->hasNonTrivialMoveConstructor() &&
997 !Record->hasNonTrivialDestructor())
998 return VarArgKind::ValidInCXX11;
999
1000 if (getLangOpts().ObjCAutoRefCount && Ty->isObjCLifetimeType())
1001 return VarArgKind::Valid;
1002
1003 if (Ty->isObjCObjectType())
1004 return VarArgKind::Invalid;
1005
1006 if (getLangOpts().HLSL && Ty->getAs<HLSLAttributedResourceType>())
1007 return VarArgKind::Valid;
1008
1009 if (getLangOpts().MSVCCompat)
1010 return VarArgKind::MSVCUndefined;
1011
1012 if (getLangOpts().HLSL && Ty->getAs<HLSLAttributedResourceType>())
1013 return VarArgKind::Valid;
1014
1015 // FIXME: In C++11, these cases are conditionally-supported, meaning we're
1016 // permitted to reject them. We should consider doing so.
1017 return VarArgKind::Undefined;
1018}
1019
1020void Sema::checkVariadicArgument(const Expr *E, VariadicCallType CT) {
1021 // Don't allow one to pass an Objective-C interface to a vararg.
1022 const QualType &Ty = E->getType();
1023 VarArgKind VAK = isValidVarArgType(Ty);
1024
1025 // Complain about passing non-POD types through varargs.
1026 switch (VAK) {
1027 case VarArgKind::ValidInCXX11:
1028 DiagRuntimeBehavior(
1029 Loc: E->getBeginLoc(), Statement: nullptr,
1030 PD: PDiag(DiagID: diag::warn_cxx98_compat_pass_non_pod_arg_to_vararg) << Ty << CT);
1031 [[fallthrough]];
1032 case VarArgKind::Valid:
1033 if (Ty->isRecordType()) {
1034 // This is unlikely to be what the user intended. If the class has a
1035 // 'c_str' member function, the user probably meant to call that.
1036 DiagRuntimeBehavior(Loc: E->getBeginLoc(), Statement: nullptr,
1037 PD: PDiag(DiagID: diag::warn_pass_class_arg_to_vararg)
1038 << Ty << CT << hasCStrMethod(E) << ".c_str()");
1039 }
1040 break;
1041
1042 case VarArgKind::Undefined:
1043 case VarArgKind::MSVCUndefined:
1044 DiagRuntimeBehavior(Loc: E->getBeginLoc(), Statement: nullptr,
1045 PD: PDiag(DiagID: diag::warn_cannot_pass_non_pod_arg_to_vararg)
1046 << getLangOpts().CPlusPlus11 << Ty << CT);
1047 break;
1048
1049 case VarArgKind::Invalid:
1050 if (Ty.isDestructedType() == QualType::DK_nontrivial_c_struct)
1051 Diag(Loc: E->getBeginLoc(),
1052 DiagID: diag::err_cannot_pass_non_trivial_c_struct_to_vararg)
1053 << Ty << CT;
1054 else if (Ty->isObjCObjectType())
1055 DiagRuntimeBehavior(Loc: E->getBeginLoc(), Statement: nullptr,
1056 PD: PDiag(DiagID: diag::err_cannot_pass_objc_interface_to_vararg)
1057 << Ty << CT);
1058 else
1059 Diag(Loc: E->getBeginLoc(), DiagID: diag::err_cannot_pass_to_vararg)
1060 << isa<InitListExpr>(Val: E) << Ty << CT;
1061 break;
1062 }
1063}
1064
1065ExprResult Sema::DefaultVariadicArgumentPromotion(Expr *E, VariadicCallType CT,
1066 FunctionDecl *FDecl) {
1067 if (const BuiltinType *PlaceholderTy = E->getType()->getAsPlaceholderType()) {
1068 // Strip the unbridged-cast placeholder expression off, if applicable.
1069 if (PlaceholderTy->getKind() == BuiltinType::ARCUnbridgedCast &&
1070 (CT == VariadicCallType::Method ||
1071 (FDecl && FDecl->hasAttr<CFAuditedTransferAttr>()))) {
1072 E = ObjC().stripARCUnbridgedCast(e: E);
1073
1074 // Otherwise, do normal placeholder checking.
1075 } else {
1076 ExprResult ExprRes = CheckPlaceholderExpr(E);
1077 if (ExprRes.isInvalid())
1078 return ExprError();
1079 E = ExprRes.get();
1080 }
1081 }
1082
1083 ExprResult ExprRes = DefaultArgumentPromotion(E);
1084 if (ExprRes.isInvalid())
1085 return ExprError();
1086
1087 // Copy blocks to the heap.
1088 if (ExprRes.get()->getType()->isBlockPointerType())
1089 maybeExtendBlockObject(E&: ExprRes);
1090
1091 E = ExprRes.get();
1092
1093 // Diagnostics regarding non-POD argument types are
1094 // emitted along with format string checking in Sema::CheckFunctionCall().
1095 if (isValidVarArgType(Ty: E->getType()) == VarArgKind::Undefined) {
1096 // Turn this into a trap.
1097 CXXScopeSpec SS;
1098 SourceLocation TemplateKWLoc;
1099 UnqualifiedId Name;
1100 Name.setIdentifier(Id: PP.getIdentifierInfo(Name: "__builtin_trap"),
1101 IdLoc: E->getBeginLoc());
1102 ExprResult TrapFn = ActOnIdExpression(S: TUScope, SS, TemplateKWLoc, Id&: Name,
1103 /*HasTrailingLParen=*/true,
1104 /*IsAddressOfOperand=*/false);
1105 if (TrapFn.isInvalid())
1106 return ExprError();
1107
1108 ExprResult Call = BuildCallExpr(S: TUScope, Fn: TrapFn.get(), LParenLoc: E->getBeginLoc(), ArgExprs: {},
1109 RParenLoc: E->getEndLoc());
1110 if (Call.isInvalid())
1111 return ExprError();
1112
1113 ExprResult Comma =
1114 ActOnBinOp(S: TUScope, TokLoc: E->getBeginLoc(), Kind: tok::comma, LHSExpr: Call.get(), RHSExpr: E);
1115 if (Comma.isInvalid())
1116 return ExprError();
1117 return Comma.get();
1118 }
1119
1120 if (!getLangOpts().CPlusPlus &&
1121 RequireCompleteType(Loc: E->getExprLoc(), T: E->getType(),
1122 DiagID: diag::err_call_incomplete_argument))
1123 return ExprError();
1124
1125 return E;
1126}
1127
1128/// Convert complex integers to complex floats and real integers to
1129/// real floats as required for complex arithmetic. Helper function of
1130/// UsualArithmeticConversions()
1131///
1132/// \return false if the integer expression is an integer type and is
1133/// successfully converted to the (complex) float type.
1134static bool handleComplexIntegerToFloatConversion(Sema &S, ExprResult &IntExpr,
1135 ExprResult &ComplexExpr,
1136 QualType IntTy,
1137 QualType ComplexTy,
1138 bool SkipCast) {
1139 if (IntTy->isComplexType() || IntTy->isRealFloatingType()) return true;
1140 if (SkipCast) return false;
1141 if (IntTy->isIntegerType()) {
1142 QualType fpTy = ComplexTy->castAs<ComplexType>()->getElementType();
1143 IntExpr = S.ImpCastExprToType(E: IntExpr.get(), Type: fpTy, CK: CK_IntegralToFloating);
1144 } else {
1145 assert(IntTy->isComplexIntegerType());
1146 IntExpr = S.ImpCastExprToType(E: IntExpr.get(), Type: ComplexTy,
1147 CK: CK_IntegralComplexToFloatingComplex);
1148 }
1149 return false;
1150}
1151
1152// This handles complex/complex, complex/float, or float/complex.
1153// When both operands are complex, the shorter operand is converted to the
1154// type of the longer, and that is the type of the result. This corresponds
1155// to what is done when combining two real floating-point operands.
1156// The fun begins when size promotion occur across type domains.
1157// From H&S 6.3.4: When one operand is complex and the other is a real
1158// floating-point type, the less precise type is converted, within it's
1159// real or complex domain, to the precision of the other type. For example,
1160// when combining a "long double" with a "double _Complex", the
1161// "double _Complex" is promoted to "long double _Complex".
1162static QualType handleComplexFloatConversion(Sema &S, ExprResult &Shorter,
1163 QualType ShorterType,
1164 QualType LongerType,
1165 bool PromotePrecision) {
1166 bool LongerIsComplex = isa<ComplexType>(Val: LongerType.getCanonicalType());
1167 QualType Result =
1168 LongerIsComplex ? LongerType : S.Context.getComplexType(T: LongerType);
1169
1170 if (PromotePrecision) {
1171 if (isa<ComplexType>(Val: ShorterType.getCanonicalType())) {
1172 Shorter =
1173 S.ImpCastExprToType(E: Shorter.get(), Type: Result, CK: CK_FloatingComplexCast);
1174 } else {
1175 if (LongerIsComplex)
1176 LongerType = LongerType->castAs<ComplexType>()->getElementType();
1177 Shorter = S.ImpCastExprToType(E: Shorter.get(), Type: LongerType, CK: CK_FloatingCast);
1178 }
1179 }
1180 return Result;
1181}
1182
1183/// Handle arithmetic conversion with complex types. Helper function of
1184/// UsualArithmeticConversions()
1185static QualType handleComplexConversion(Sema &S, ExprResult &LHS,
1186 ExprResult &RHS, QualType LHSType,
1187 QualType RHSType, bool IsCompAssign) {
1188 // Handle (complex) integer types.
1189 if (!handleComplexIntegerToFloatConversion(S, IntExpr&: RHS, ComplexExpr&: LHS, IntTy: RHSType, ComplexTy: LHSType,
1190 /*SkipCast=*/false))
1191 return LHSType;
1192 if (!handleComplexIntegerToFloatConversion(S, IntExpr&: LHS, ComplexExpr&: RHS, IntTy: LHSType, ComplexTy: RHSType,
1193 /*SkipCast=*/IsCompAssign))
1194 return RHSType;
1195
1196 // Compute the rank of the two types, regardless of whether they are complex.
1197 int Order = S.Context.getFloatingTypeOrder(LHS: LHSType, RHS: RHSType);
1198 if (Order < 0)
1199 // Promote the precision of the LHS if not an assignment.
1200 return handleComplexFloatConversion(S, Shorter&: LHS, ShorterType: LHSType, LongerType: RHSType,
1201 /*PromotePrecision=*/!IsCompAssign);
1202 // Promote the precision of the RHS unless it is already the same as the LHS.
1203 return handleComplexFloatConversion(S, Shorter&: RHS, ShorterType: RHSType, LongerType: LHSType,
1204 /*PromotePrecision=*/Order > 0);
1205}
1206
1207/// Handle arithmetic conversion from integer to float. Helper function
1208/// of UsualArithmeticConversions()
1209static QualType handleIntToFloatConversion(Sema &S, ExprResult &FloatExpr,
1210 ExprResult &IntExpr,
1211 QualType FloatTy, QualType IntTy,
1212 bool ConvertFloat, bool ConvertInt) {
1213 if (IntTy->isIntegerType()) {
1214 if (ConvertInt)
1215 // Convert intExpr to the lhs floating point type.
1216 IntExpr = S.ImpCastExprToType(E: IntExpr.get(), Type: FloatTy,
1217 CK: CK_IntegralToFloating);
1218 return FloatTy;
1219 }
1220
1221 // Convert both sides to the appropriate complex float.
1222 assert(IntTy->isComplexIntegerType());
1223 QualType result = S.Context.getComplexType(T: FloatTy);
1224
1225 // _Complex int -> _Complex float
1226 if (ConvertInt)
1227 IntExpr = S.ImpCastExprToType(E: IntExpr.get(), Type: result,
1228 CK: CK_IntegralComplexToFloatingComplex);
1229
1230 // float -> _Complex float
1231 if (ConvertFloat)
1232 FloatExpr = S.ImpCastExprToType(E: FloatExpr.get(), Type: result,
1233 CK: CK_FloatingRealToComplex);
1234
1235 return result;
1236}
1237
1238/// Handle arithmethic conversion with floating point types. Helper
1239/// function of UsualArithmeticConversions()
1240static QualType handleFloatConversion(Sema &S, ExprResult &LHS,
1241 ExprResult &RHS, QualType LHSType,
1242 QualType RHSType, bool IsCompAssign) {
1243 bool LHSFloat = LHSType->isRealFloatingType();
1244 bool RHSFloat = RHSType->isRealFloatingType();
1245
1246 // N1169 4.1.4: If one of the operands has a floating type and the other
1247 // operand has a fixed-point type, the fixed-point operand
1248 // is converted to the floating type [...]
1249 if (LHSType->isFixedPointType() || RHSType->isFixedPointType()) {
1250 if (LHSFloat)
1251 RHS = S.ImpCastExprToType(E: RHS.get(), Type: LHSType, CK: CK_FixedPointToFloating);
1252 else if (!IsCompAssign)
1253 LHS = S.ImpCastExprToType(E: LHS.get(), Type: RHSType, CK: CK_FixedPointToFloating);
1254 return LHSFloat ? LHSType : RHSType;
1255 }
1256
1257 // If we have two real floating types, convert the smaller operand
1258 // to the bigger result.
1259 if (LHSFloat && RHSFloat) {
1260 int order = S.Context.getFloatingTypeOrder(LHS: LHSType, RHS: RHSType);
1261 if (order > 0) {
1262 RHS = S.ImpCastExprToType(E: RHS.get(), Type: LHSType, CK: CK_FloatingCast);
1263 return LHSType;
1264 }
1265
1266 assert(order < 0 && "illegal float comparison");
1267 if (!IsCompAssign)
1268 LHS = S.ImpCastExprToType(E: LHS.get(), Type: RHSType, CK: CK_FloatingCast);
1269 return RHSType;
1270 }
1271
1272 if (LHSFloat) {
1273 // Half FP has to be promoted to float unless it is natively supported
1274 if (LHSType->isHalfType() && !S.getLangOpts().NativeHalfType)
1275 LHSType = S.Context.FloatTy;
1276
1277 return handleIntToFloatConversion(S, FloatExpr&: LHS, IntExpr&: RHS, FloatTy: LHSType, IntTy: RHSType,
1278 /*ConvertFloat=*/!IsCompAssign,
1279 /*ConvertInt=*/ true);
1280 }
1281 assert(RHSFloat);
1282 return handleIntToFloatConversion(S, FloatExpr&: RHS, IntExpr&: LHS, FloatTy: RHSType, IntTy: LHSType,
1283 /*ConvertFloat=*/ true,
1284 /*ConvertInt=*/!IsCompAssign);
1285}
1286
1287/// Diagnose attempts to convert between __float128, __ibm128 and
1288/// long double if there is no support for such conversion.
1289/// Helper function of UsualArithmeticConversions().
1290static bool unsupportedTypeConversion(const Sema &S, QualType LHSType,
1291 QualType RHSType) {
1292 // No issue if either is not a floating point type.
1293 if (!LHSType->isFloatingType() || !RHSType->isFloatingType())
1294 return false;
1295
1296 // No issue if both have the same 128-bit float semantics.
1297 auto *LHSComplex = LHSType->getAs<ComplexType>();
1298 auto *RHSComplex = RHSType->getAs<ComplexType>();
1299
1300 QualType LHSElem = LHSComplex ? LHSComplex->getElementType() : LHSType;
1301 QualType RHSElem = RHSComplex ? RHSComplex->getElementType() : RHSType;
1302
1303 const llvm::fltSemantics &LHSSem = S.Context.getFloatTypeSemantics(T: LHSElem);
1304 const llvm::fltSemantics &RHSSem = S.Context.getFloatTypeSemantics(T: RHSElem);
1305
1306 if ((&LHSSem != &llvm::APFloat::PPCDoubleDouble() ||
1307 &RHSSem != &llvm::APFloat::IEEEquad()) &&
1308 (&LHSSem != &llvm::APFloat::IEEEquad() ||
1309 &RHSSem != &llvm::APFloat::PPCDoubleDouble()))
1310 return false;
1311
1312 return true;
1313}
1314
1315typedef ExprResult PerformCastFn(Sema &S, Expr *operand, QualType toType);
1316
1317namespace {
1318/// These helper callbacks are placed in an anonymous namespace to
1319/// permit their use as function template parameters.
1320ExprResult doIntegralCast(Sema &S, Expr *op, QualType toType) {
1321 return S.ImpCastExprToType(E: op, Type: toType, CK: CK_IntegralCast);
1322}
1323
1324ExprResult doComplexIntegralCast(Sema &S, Expr *op, QualType toType) {
1325 return S.ImpCastExprToType(E: op, Type: S.Context.getComplexType(T: toType),
1326 CK: CK_IntegralComplexCast);
1327}
1328}
1329
1330/// Handle integer arithmetic conversions. Helper function of
1331/// UsualArithmeticConversions()
1332template <PerformCastFn doLHSCast, PerformCastFn doRHSCast>
1333static QualType handleIntegerConversion(Sema &S, ExprResult &LHS,
1334 ExprResult &RHS, QualType LHSType,
1335 QualType RHSType, bool IsCompAssign) {
1336 // The rules for this case are in C99 6.3.1.8
1337 int order = S.Context.getIntegerTypeOrder(LHS: LHSType, RHS: RHSType);
1338 bool LHSSigned = LHSType->hasSignedIntegerRepresentation();
1339 bool RHSSigned = RHSType->hasSignedIntegerRepresentation();
1340 if (LHSSigned == RHSSigned) {
1341 // Same signedness; use the higher-ranked type
1342 if (order >= 0) {
1343 RHS = (*doRHSCast)(S, RHS.get(), LHSType);
1344 return LHSType;
1345 } else if (!IsCompAssign)
1346 LHS = (*doLHSCast)(S, LHS.get(), RHSType);
1347 return RHSType;
1348 } else if (order != (LHSSigned ? 1 : -1)) {
1349 // The unsigned type has greater than or equal rank to the
1350 // signed type, so use the unsigned type
1351 if (RHSSigned) {
1352 RHS = (*doRHSCast)(S, RHS.get(), LHSType);
1353 return LHSType;
1354 } else if (!IsCompAssign)
1355 LHS = (*doLHSCast)(S, LHS.get(), RHSType);
1356 return RHSType;
1357 } else if (S.Context.getIntWidth(T: LHSType) != S.Context.getIntWidth(T: RHSType)) {
1358 // The two types are different widths; if we are here, that
1359 // means the signed type is larger than the unsigned type, so
1360 // use the signed type.
1361 if (LHSSigned) {
1362 RHS = (*doRHSCast)(S, RHS.get(), LHSType);
1363 return LHSType;
1364 } else if (!IsCompAssign)
1365 LHS = (*doLHSCast)(S, LHS.get(), RHSType);
1366 return RHSType;
1367 } else {
1368 // The signed type is higher-ranked than the unsigned type,
1369 // but isn't actually any bigger (like unsigned int and long
1370 // on most 32-bit systems). Use the unsigned type corresponding
1371 // to the signed type.
1372 QualType result =
1373 S.Context.getCorrespondingUnsignedType(T: LHSSigned ? LHSType : RHSType);
1374 RHS = (*doRHSCast)(S, RHS.get(), result);
1375 if (!IsCompAssign)
1376 LHS = (*doLHSCast)(S, LHS.get(), result);
1377 return result;
1378 }
1379}
1380
1381/// Handle conversions with GCC complex int extension. Helper function
1382/// of UsualArithmeticConversions()
1383static QualType handleComplexIntConversion(Sema &S, ExprResult &LHS,
1384 ExprResult &RHS, QualType LHSType,
1385 QualType RHSType,
1386 bool IsCompAssign) {
1387 const ComplexType *LHSComplexInt = LHSType->getAsComplexIntegerType();
1388 const ComplexType *RHSComplexInt = RHSType->getAsComplexIntegerType();
1389
1390 if (LHSComplexInt && RHSComplexInt) {
1391 QualType LHSEltType = LHSComplexInt->getElementType();
1392 QualType RHSEltType = RHSComplexInt->getElementType();
1393 QualType ScalarType =
1394 handleIntegerConversion<doComplexIntegralCast, doComplexIntegralCast>
1395 (S, LHS, RHS, LHSType: LHSEltType, RHSType: RHSEltType, IsCompAssign);
1396
1397 return S.Context.getComplexType(T: ScalarType);
1398 }
1399
1400 if (LHSComplexInt) {
1401 QualType LHSEltType = LHSComplexInt->getElementType();
1402 QualType ScalarType =
1403 handleIntegerConversion<doComplexIntegralCast, doIntegralCast>
1404 (S, LHS, RHS, LHSType: LHSEltType, RHSType, IsCompAssign);
1405 QualType ComplexType = S.Context.getComplexType(T: ScalarType);
1406 RHS = S.ImpCastExprToType(E: RHS.get(), Type: ComplexType,
1407 CK: CK_IntegralRealToComplex);
1408
1409 return ComplexType;
1410 }
1411
1412 assert(RHSComplexInt);
1413
1414 QualType RHSEltType = RHSComplexInt->getElementType();
1415 QualType ScalarType =
1416 handleIntegerConversion<doIntegralCast, doComplexIntegralCast>
1417 (S, LHS, RHS, LHSType, RHSType: RHSEltType, IsCompAssign);
1418 QualType ComplexType = S.Context.getComplexType(T: ScalarType);
1419
1420 if (!IsCompAssign)
1421 LHS = S.ImpCastExprToType(E: LHS.get(), Type: ComplexType,
1422 CK: CK_IntegralRealToComplex);
1423 return ComplexType;
1424}
1425
1426static QualType handleOverflowBehaviorTypeConversion(Sema &S, ExprResult &LHS,
1427 ExprResult &RHS,
1428 QualType LHSType,
1429 QualType RHSType,
1430 bool IsCompAssign) {
1431
1432 const auto *LhsOBT = LHSType->getAs<OverflowBehaviorType>();
1433 const auto *RhsOBT = RHSType->getAs<OverflowBehaviorType>();
1434
1435 assert(LHSType->isIntegerType() && RHSType->isIntegerType() &&
1436 "Non-integer type conversion not supported for OverflowBehaviorTypes");
1437
1438 bool LHSHasTrap =
1439 LhsOBT && LhsOBT->getBehaviorKind() ==
1440 OverflowBehaviorType::OverflowBehaviorKind::Trap;
1441 bool RHSHasTrap =
1442 RhsOBT && RhsOBT->getBehaviorKind() ==
1443 OverflowBehaviorType::OverflowBehaviorKind::Trap;
1444 bool LHSHasWrap =
1445 LhsOBT && LhsOBT->getBehaviorKind() ==
1446 OverflowBehaviorType::OverflowBehaviorKind::Wrap;
1447 bool RHSHasWrap =
1448 RhsOBT && RhsOBT->getBehaviorKind() ==
1449 OverflowBehaviorType::OverflowBehaviorKind::Wrap;
1450
1451 QualType LHSUnderlyingType = LhsOBT ? LhsOBT->getUnderlyingType() : LHSType;
1452 QualType RHSUnderlyingType = RhsOBT ? RhsOBT->getUnderlyingType() : RHSType;
1453
1454 std::optional<OverflowBehaviorType::OverflowBehaviorKind> DominantBehavior;
1455 if (LHSHasTrap || RHSHasTrap)
1456 DominantBehavior = OverflowBehaviorType::OverflowBehaviorKind::Trap;
1457 else if (LHSHasWrap || RHSHasWrap)
1458 DominantBehavior = OverflowBehaviorType::OverflowBehaviorKind::Wrap;
1459
1460 QualType LHSConvType = LHSUnderlyingType;
1461 QualType RHSConvType = RHSUnderlyingType;
1462 if (DominantBehavior) {
1463 if (!LhsOBT || LhsOBT->getBehaviorKind() != *DominantBehavior)
1464 LHSConvType = S.Context.getOverflowBehaviorType(Kind: *DominantBehavior,
1465 Wrapped: LHSUnderlyingType);
1466 else
1467 LHSConvType = LHSType;
1468
1469 if (!RhsOBT || RhsOBT->getBehaviorKind() != *DominantBehavior)
1470 RHSConvType = S.Context.getOverflowBehaviorType(Kind: *DominantBehavior,
1471 Wrapped: RHSUnderlyingType);
1472 else
1473 RHSConvType = RHSType;
1474 }
1475
1476 return handleIntegerConversion<doIntegralCast, doIntegralCast>(
1477 S, LHS, RHS, LHSType: LHSConvType, RHSType: RHSConvType, IsCompAssign);
1478}
1479
1480/// Return the rank of a given fixed point or integer type. The value itself
1481/// doesn't matter, but the values must be increasing with proper increasing
1482/// rank as described in N1169 4.1.1.
1483static unsigned GetFixedPointRank(QualType Ty) {
1484 const auto *BTy = Ty->getAs<BuiltinType>();
1485 assert(BTy && "Expected a builtin type.");
1486
1487 switch (BTy->getKind()) {
1488 case BuiltinType::ShortFract:
1489 case BuiltinType::UShortFract:
1490 case BuiltinType::SatShortFract:
1491 case BuiltinType::SatUShortFract:
1492 return 1;
1493 case BuiltinType::Fract:
1494 case BuiltinType::UFract:
1495 case BuiltinType::SatFract:
1496 case BuiltinType::SatUFract:
1497 return 2;
1498 case BuiltinType::LongFract:
1499 case BuiltinType::ULongFract:
1500 case BuiltinType::SatLongFract:
1501 case BuiltinType::SatULongFract:
1502 return 3;
1503 case BuiltinType::ShortAccum:
1504 case BuiltinType::UShortAccum:
1505 case BuiltinType::SatShortAccum:
1506 case BuiltinType::SatUShortAccum:
1507 return 4;
1508 case BuiltinType::Accum:
1509 case BuiltinType::UAccum:
1510 case BuiltinType::SatAccum:
1511 case BuiltinType::SatUAccum:
1512 return 5;
1513 case BuiltinType::LongAccum:
1514 case BuiltinType::ULongAccum:
1515 case BuiltinType::SatLongAccum:
1516 case BuiltinType::SatULongAccum:
1517 return 6;
1518 default:
1519 if (BTy->isInteger())
1520 return 0;
1521 llvm_unreachable("Unexpected fixed point or integer type");
1522 }
1523}
1524
1525/// handleFixedPointConversion - Fixed point operations between fixed
1526/// point types and integers or other fixed point types do not fall under
1527/// usual arithmetic conversion since these conversions could result in loss
1528/// of precsision (N1169 4.1.4). These operations should be calculated with
1529/// the full precision of their result type (N1169 4.1.6.2.1).
1530static QualType handleFixedPointConversion(Sema &S, QualType LHSTy,
1531 QualType RHSTy) {
1532 assert((LHSTy->isFixedPointType() || RHSTy->isFixedPointType()) &&
1533 "Expected at least one of the operands to be a fixed point type");
1534 assert((LHSTy->isFixedPointOrIntegerType() ||
1535 RHSTy->isFixedPointOrIntegerType()) &&
1536 "Special fixed point arithmetic operation conversions are only "
1537 "applied to ints or other fixed point types");
1538
1539 // If one operand has signed fixed-point type and the other operand has
1540 // unsigned fixed-point type, then the unsigned fixed-point operand is
1541 // converted to its corresponding signed fixed-point type and the resulting
1542 // type is the type of the converted operand.
1543 if (RHSTy->isSignedFixedPointType() && LHSTy->isUnsignedFixedPointType())
1544 LHSTy = S.Context.getCorrespondingSignedFixedPointType(Ty: LHSTy);
1545 else if (RHSTy->isUnsignedFixedPointType() && LHSTy->isSignedFixedPointType())
1546 RHSTy = S.Context.getCorrespondingSignedFixedPointType(Ty: RHSTy);
1547
1548 // The result type is the type with the highest rank, whereby a fixed-point
1549 // conversion rank is always greater than an integer conversion rank; if the
1550 // type of either of the operands is a saturating fixedpoint type, the result
1551 // type shall be the saturating fixed-point type corresponding to the type
1552 // with the highest rank; the resulting value is converted (taking into
1553 // account rounding and overflow) to the precision of the resulting type.
1554 // Same ranks between signed and unsigned types are resolved earlier, so both
1555 // types are either signed or both unsigned at this point.
1556 unsigned LHSTyRank = GetFixedPointRank(Ty: LHSTy);
1557 unsigned RHSTyRank = GetFixedPointRank(Ty: RHSTy);
1558
1559 QualType ResultTy = LHSTyRank > RHSTyRank ? LHSTy : RHSTy;
1560
1561 if (LHSTy->isSaturatedFixedPointType() || RHSTy->isSaturatedFixedPointType())
1562 ResultTy = S.Context.getCorrespondingSaturatedType(Ty: ResultTy);
1563
1564 return ResultTy;
1565}
1566
1567/// Check that the usual arithmetic conversions can be performed on this pair of
1568/// expressions that might be of enumeration type.
1569void Sema::checkEnumArithmeticConversions(Expr *LHS, Expr *RHS,
1570 SourceLocation Loc,
1571 ArithConvKind ACK) {
1572 // C++2a [expr.arith.conv]p1:
1573 // If one operand is of enumeration type and the other operand is of a
1574 // different enumeration type or a floating-point type, this behavior is
1575 // deprecated ([depr.arith.conv.enum]).
1576 //
1577 // Warn on this in all language modes. Produce a deprecation warning in C++20.
1578 // Eventually we will presumably reject these cases (in C++23 onwards?).
1579 QualType L = LHS->getEnumCoercedType(Ctx: Context),
1580 R = RHS->getEnumCoercedType(Ctx: Context);
1581 bool LEnum = L->isUnscopedEnumerationType(),
1582 REnum = R->isUnscopedEnumerationType();
1583 bool IsCompAssign = ACK == ArithConvKind::CompAssign;
1584 if ((!IsCompAssign && LEnum && R->isFloatingType()) ||
1585 (REnum && L->isFloatingType())) {
1586 Diag(Loc, DiagID: getLangOpts().CPlusPlus26 ? diag::err_arith_conv_enum_float_cxx26
1587 : getLangOpts().CPlusPlus20
1588 ? diag::warn_arith_conv_enum_float_cxx20
1589 : diag::warn_arith_conv_enum_float)
1590 << LHS->getSourceRange() << RHS->getSourceRange() << (int)ACK << LEnum
1591 << L << R;
1592 } else if (!IsCompAssign && LEnum && REnum &&
1593 !Context.hasSameUnqualifiedType(T1: L, T2: R)) {
1594 unsigned DiagID;
1595 // In C++ 26, usual arithmetic conversions between 2 different enum types
1596 // are ill-formed.
1597 if (getLangOpts().CPlusPlus26)
1598 DiagID = diag::warn_conv_mixed_enum_types_cxx26;
1599 else if (!L->castAsCanonical<EnumType>()->getDecl()->hasNameForLinkage() ||
1600 !R->castAsCanonical<EnumType>()->getDecl()->hasNameForLinkage()) {
1601 // If either enumeration type is unnamed, it's less likely that the
1602 // user cares about this, but this situation is still deprecated in
1603 // C++2a. Use a different warning group.
1604 DiagID = getLangOpts().CPlusPlus20
1605 ? diag::warn_arith_conv_mixed_anon_enum_types_cxx20
1606 : diag::warn_arith_conv_mixed_anon_enum_types;
1607 } else if (ACK == ArithConvKind::Conditional) {
1608 // Conditional expressions are separated out because they have
1609 // historically had a different warning flag.
1610 DiagID = getLangOpts().CPlusPlus20
1611 ? diag::warn_conditional_mixed_enum_types_cxx20
1612 : diag::warn_conditional_mixed_enum_types;
1613 } else if (ACK == ArithConvKind::Comparison) {
1614 // Comparison expressions are separated out because they have
1615 // historically had a different warning flag.
1616 DiagID = getLangOpts().CPlusPlus20
1617 ? diag::warn_comparison_mixed_enum_types_cxx20
1618 : diag::warn_comparison_mixed_enum_types;
1619 } else {
1620 DiagID = getLangOpts().CPlusPlus20
1621 ? diag::warn_arith_conv_mixed_enum_types_cxx20
1622 : diag::warn_arith_conv_mixed_enum_types;
1623 }
1624 Diag(Loc, DiagID) << LHS->getSourceRange() << RHS->getSourceRange()
1625 << (int)ACK << L << R;
1626 }
1627}
1628
1629static void CheckUnicodeArithmeticConversions(Sema &SemaRef, Expr *LHS,
1630 Expr *RHS, SourceLocation Loc,
1631 ArithConvKind ACK) {
1632 QualType LHSType = LHS->getType().getUnqualifiedType();
1633 QualType RHSType = RHS->getType().getUnqualifiedType();
1634
1635 if (!SemaRef.getLangOpts().CPlusPlus || !LHSType->isUnicodeCharacterType() ||
1636 !RHSType->isUnicodeCharacterType())
1637 return;
1638
1639 if (ACK == ArithConvKind::Comparison) {
1640 if (SemaRef.getASTContext().hasSameType(T1: LHSType, T2: RHSType))
1641 return;
1642
1643 auto IsSingleCodeUnitCP = [](const QualType &T, const llvm::APSInt &Value) {
1644 if (T->isChar8Type())
1645 return llvm::IsSingleCodeUnitUTF8Codepoint(Value.getExtValue());
1646 if (T->isChar16Type())
1647 return llvm::IsSingleCodeUnitUTF16Codepoint(Value.getExtValue());
1648 assert(T->isChar32Type());
1649 return llvm::IsSingleCodeUnitUTF32Codepoint(Value.getExtValue());
1650 };
1651
1652 Expr::EvalResult LHSRes, RHSRes;
1653 bool LHSSuccess = LHS->EvaluateAsInt(Result&: LHSRes, Ctx: SemaRef.getASTContext(),
1654 AllowSideEffects: Expr::SE_AllowSideEffects,
1655 InConstantContext: SemaRef.isConstantEvaluatedContext());
1656 bool RHSuccess = RHS->EvaluateAsInt(Result&: RHSRes, Ctx: SemaRef.getASTContext(),
1657 AllowSideEffects: Expr::SE_AllowSideEffects,
1658 InConstantContext: SemaRef.isConstantEvaluatedContext());
1659
1660 // Don't warn if the one known value is a representable
1661 // in the type of both expressions.
1662 if (LHSSuccess != RHSuccess) {
1663 Expr::EvalResult &Res = LHSSuccess ? LHSRes : RHSRes;
1664 if (IsSingleCodeUnitCP(LHSType, Res.Val.getInt()) &&
1665 IsSingleCodeUnitCP(RHSType, Res.Val.getInt()))
1666 return;
1667 }
1668
1669 if (!LHSSuccess || !RHSuccess) {
1670 SemaRef.Diag(Loc, DiagID: diag::warn_comparison_unicode_mixed_types)
1671 << LHS->getSourceRange() << RHS->getSourceRange() << LHSType
1672 << RHSType;
1673 return;
1674 }
1675
1676 llvm::APSInt LHSValue(32);
1677 LHSValue = LHSRes.Val.getInt();
1678 llvm::APSInt RHSValue(32);
1679 RHSValue = RHSRes.Val.getInt();
1680
1681 bool LHSSafe = IsSingleCodeUnitCP(LHSType, LHSValue);
1682 bool RHSSafe = IsSingleCodeUnitCP(RHSType, RHSValue);
1683 if (LHSSafe && RHSSafe)
1684 return;
1685
1686 SemaRef.Diag(Loc, DiagID: diag::warn_comparison_unicode_mixed_types_constant)
1687 << LHS->getSourceRange() << RHS->getSourceRange() << LHSType << RHSType
1688 << FormatUTFCodeUnitAsCodepoint(Value: LHSValue.getExtValue(), T: LHSType)
1689 << FormatUTFCodeUnitAsCodepoint(Value: RHSValue.getExtValue(), T: RHSType);
1690 return;
1691 }
1692
1693 if (SemaRef.getASTContext().hasSameType(T1: LHSType, T2: RHSType))
1694 return;
1695
1696 SemaRef.Diag(Loc, DiagID: diag::warn_arith_conv_mixed_unicode_types)
1697 << LHS->getSourceRange() << RHS->getSourceRange() << ACK << LHSType
1698 << RHSType;
1699}
1700
1701/// UsualArithmeticConversions - Performs various conversions that are common to
1702/// binary operators (C99 6.3.1.8). If both operands aren't arithmetic, this
1703/// routine returns the first non-arithmetic type found. The client is
1704/// responsible for emitting appropriate error diagnostics.
1705QualType Sema::UsualArithmeticConversions(ExprResult &LHS, ExprResult &RHS,
1706 SourceLocation Loc,
1707 ArithConvKind ACK) {
1708
1709 checkEnumArithmeticConversions(LHS: LHS.get(), RHS: RHS.get(), Loc, ACK);
1710
1711 CheckUnicodeArithmeticConversions(SemaRef&: *this, LHS: LHS.get(), RHS: RHS.get(), Loc, ACK);
1712
1713 if (ACK != ArithConvKind::CompAssign) {
1714 LHS = UsualUnaryConversions(E: LHS.get());
1715 if (LHS.isInvalid())
1716 return QualType();
1717 }
1718
1719 RHS = UsualUnaryConversions(E: RHS.get());
1720 if (RHS.isInvalid())
1721 return QualType();
1722
1723 // For conversion purposes, we ignore any qualifiers.
1724 // For example, "const float" and "float" are equivalent.
1725 QualType LHSType = LHS.get()->getType().getUnqualifiedType();
1726 QualType RHSType = RHS.get()->getType().getUnqualifiedType();
1727
1728 // For conversion purposes, we ignore any atomic qualifier on the LHS.
1729 if (const AtomicType *AtomicLHS = LHSType->getAs<AtomicType>())
1730 LHSType = AtomicLHS->getValueType();
1731
1732 // If both types are identical, no conversion is needed.
1733 if (Context.hasSameType(T1: LHSType, T2: RHSType))
1734 return Context.getCommonSugaredType(X: LHSType, Y: RHSType);
1735
1736 // If either side is a non-arithmetic type (e.g. a pointer), we are done.
1737 // The caller can deal with this (e.g. pointer + int).
1738 if (!LHSType->isArithmeticType() || !RHSType->isArithmeticType())
1739 return QualType();
1740
1741 // Apply unary and bitfield promotions to the LHS's type.
1742 QualType LHSUnpromotedType = LHSType;
1743 if (Context.isPromotableIntegerType(T: LHSType))
1744 LHSType = Context.getPromotedIntegerType(PromotableType: LHSType);
1745 QualType LHSBitfieldPromoteTy = Context.isPromotableBitField(E: LHS.get());
1746 if (!LHSBitfieldPromoteTy.isNull())
1747 LHSType = LHSBitfieldPromoteTy;
1748 if (LHSType != LHSUnpromotedType && ACK != ArithConvKind::CompAssign)
1749 LHS = ImpCastExprToType(E: LHS.get(), Type: LHSType, CK: CK_IntegralCast);
1750
1751 // If both types are identical, no conversion is needed.
1752 if (Context.hasSameType(T1: LHSType, T2: RHSType))
1753 return Context.getCommonSugaredType(X: LHSType, Y: RHSType);
1754
1755 // At this point, we have two different arithmetic types.
1756
1757 if ((LHSType->isFixedPointType() && RHSType->isBitIntType()) ||
1758 (LHSType->isBitIntType() && RHSType->isFixedPointType()))
1759 return QualType();
1760
1761 // Diagnose attempts to convert between __ibm128, __float128 and long double
1762 // where such conversions currently can't be handled.
1763 if (unsupportedTypeConversion(S: *this, LHSType, RHSType))
1764 return QualType();
1765
1766 // Handle complex types first (C99 6.3.1.8p1).
1767 if (LHSType->isComplexType() || RHSType->isComplexType())
1768 return handleComplexConversion(S&: *this, LHS, RHS, LHSType, RHSType,
1769 IsCompAssign: ACK == ArithConvKind::CompAssign);
1770
1771 // Now handle "real" floating types (i.e. float, double, long double).
1772 if (LHSType->isRealFloatingType() || RHSType->isRealFloatingType())
1773 return handleFloatConversion(S&: *this, LHS, RHS, LHSType, RHSType,
1774 IsCompAssign: ACK == ArithConvKind::CompAssign);
1775
1776 // Handle GCC complex int extension.
1777 if (LHSType->isComplexIntegerType() || RHSType->isComplexIntegerType())
1778 return handleComplexIntConversion(S&: *this, LHS, RHS, LHSType, RHSType,
1779 IsCompAssign: ACK == ArithConvKind::CompAssign);
1780
1781 if (LHSType->isFixedPointType() || RHSType->isFixedPointType())
1782 return handleFixedPointConversion(S&: *this, LHSTy: LHSType, RHSTy: RHSType);
1783
1784 if (LHSType->isOverflowBehaviorType() || RHSType->isOverflowBehaviorType())
1785 return handleOverflowBehaviorTypeConversion(
1786 S&: *this, LHS, RHS, LHSType, RHSType, IsCompAssign: ACK == ArithConvKind::CompAssign);
1787
1788 // Finally, we have two differing integer types.
1789 return handleIntegerConversion<doIntegralCast, doIntegralCast>(
1790 S&: *this, LHS, RHS, LHSType, RHSType, IsCompAssign: ACK == ArithConvKind::CompAssign);
1791}
1792
1793//===----------------------------------------------------------------------===//
1794// Semantic Analysis for various Expression Types
1795//===----------------------------------------------------------------------===//
1796
1797
1798ExprResult Sema::ActOnGenericSelectionExpr(
1799 SourceLocation KeyLoc, SourceLocation DefaultLoc, SourceLocation RParenLoc,
1800 bool PredicateIsExpr, void *ControllingExprOrType,
1801 ArrayRef<ParsedType> ArgTypes, ArrayRef<Expr *> ArgExprs) {
1802 unsigned NumAssocs = ArgTypes.size();
1803 assert(NumAssocs == ArgExprs.size());
1804
1805 TypeSourceInfo **Types = new TypeSourceInfo*[NumAssocs];
1806 for (unsigned i = 0; i < NumAssocs; ++i) {
1807 if (ArgTypes[i])
1808 (void) GetTypeFromParser(Ty: ArgTypes[i], TInfo: &Types[i]);
1809 else
1810 Types[i] = nullptr;
1811 }
1812
1813 // If we have a controlling type, we need to convert it from a parsed type
1814 // into a semantic type and then pass that along.
1815 if (!PredicateIsExpr) {
1816 TypeSourceInfo *ControllingType;
1817 (void)GetTypeFromParser(Ty: ParsedType::getFromOpaquePtr(P: ControllingExprOrType),
1818 TInfo: &ControllingType);
1819 assert(ControllingType && "couldn't get the type out of the parser");
1820 ControllingExprOrType = ControllingType;
1821 }
1822
1823 ExprResult ER = CreateGenericSelectionExpr(
1824 KeyLoc, DefaultLoc, RParenLoc, PredicateIsExpr, ControllingExprOrType,
1825 Types: llvm::ArrayRef(Types, NumAssocs), Exprs: ArgExprs);
1826 delete [] Types;
1827 return ER;
1828}
1829
1830// Helper function to determine type compatibility for C _Generic expressions.
1831// Multiple compatible types within the same _Generic expression is ambiguous
1832// and not valid.
1833static bool areTypesCompatibleForGeneric(ASTContext &Ctx, QualType T,
1834 QualType U) {
1835 // Try to handle special types like OverflowBehaviorTypes
1836 const auto *TOBT = T->getAs<OverflowBehaviorType>();
1837 const auto *UOBT = U.getCanonicalType()->getAs<OverflowBehaviorType>();
1838
1839 if (TOBT || UOBT) {
1840 if (TOBT && UOBT) {
1841 if (TOBT->getBehaviorKind() == UOBT->getBehaviorKind())
1842 return Ctx.typesAreCompatible(T1: TOBT->getUnderlyingType(),
1843 T2: UOBT->getUnderlyingType());
1844 return false;
1845 }
1846 return false;
1847 }
1848
1849 // We're dealing with types that don't require special handling.
1850 return Ctx.typesAreCompatible(T1: T, T2: U);
1851}
1852
1853ExprResult Sema::CreateGenericSelectionExpr(
1854 SourceLocation KeyLoc, SourceLocation DefaultLoc, SourceLocation RParenLoc,
1855 bool PredicateIsExpr, void *ControllingExprOrType,
1856 ArrayRef<TypeSourceInfo *> Types, ArrayRef<Expr *> Exprs) {
1857 unsigned NumAssocs = Types.size();
1858 assert(NumAssocs == Exprs.size());
1859 assert(ControllingExprOrType &&
1860 "Must have either a controlling expression or a controlling type");
1861
1862 Expr *ControllingExpr = nullptr;
1863 TypeSourceInfo *ControllingType = nullptr;
1864 if (PredicateIsExpr) {
1865 // Decay and strip qualifiers for the controlling expression type, and
1866 // handle placeholder type replacement. See committee discussion from WG14
1867 // DR423.
1868 EnterExpressionEvaluationContext Unevaluated(
1869 *this, Sema::ExpressionEvaluationContext::Unevaluated);
1870 ExprResult R = DefaultFunctionArrayLvalueConversion(
1871 E: reinterpret_cast<Expr *>(ControllingExprOrType));
1872 if (R.isInvalid())
1873 return ExprError();
1874 ControllingExpr = R.get();
1875 } else {
1876 // The extension form uses the type directly rather than converting it.
1877 ControllingType = reinterpret_cast<TypeSourceInfo *>(ControllingExprOrType);
1878 if (!ControllingType)
1879 return ExprError();
1880 }
1881
1882 bool TypeErrorFound = false,
1883 IsResultDependent = ControllingExpr
1884 ? ControllingExpr->isTypeDependent()
1885 : ControllingType->getType()->isDependentType(),
1886 ContainsUnexpandedParameterPack =
1887 ControllingExpr
1888 ? ControllingExpr->containsUnexpandedParameterPack()
1889 : ControllingType->getType()->containsUnexpandedParameterPack();
1890
1891 // The controlling expression is an unevaluated operand, so side effects are
1892 // likely unintended.
1893 if (!inTemplateInstantiation() && !IsResultDependent && ControllingExpr &&
1894 ControllingExpr->HasSideEffects(Ctx: Context, IncludePossibleEffects: false))
1895 Diag(Loc: ControllingExpr->getExprLoc(),
1896 DiagID: diag::warn_side_effects_unevaluated_context);
1897
1898 for (unsigned i = 0; i < NumAssocs; ++i) {
1899 if (Exprs[i]->containsUnexpandedParameterPack())
1900 ContainsUnexpandedParameterPack = true;
1901
1902 if (Types[i]) {
1903 if (Types[i]->getType()->containsUnexpandedParameterPack())
1904 ContainsUnexpandedParameterPack = true;
1905
1906 if (Types[i]->getType()->isDependentType()) {
1907 IsResultDependent = true;
1908 } else {
1909 // We relax the restriction on use of incomplete types and non-object
1910 // types with the type-based extension of _Generic. Allowing incomplete
1911 // objects means those can be used as "tags" for a type-safe way to map
1912 // to a value. Similarly, matching on function types rather than
1913 // function pointer types can be useful. However, the restriction on VM
1914 // types makes sense to retain as there are open questions about how
1915 // the selection can be made at compile time.
1916 //
1917 // C11 6.5.1.1p2 "The type name in a generic association shall specify a
1918 // complete object type other than a variably modified type."
1919 // C2y removed the requirement that an expression form must
1920 // use a complete type, though it's still as-if the type has undergone
1921 // lvalue conversion. We support this as an extension in C23 and
1922 // earlier because GCC does so.
1923 unsigned D = 0;
1924 if (ControllingExpr && Types[i]->getType()->isIncompleteType())
1925 D = LangOpts.C2y ? diag::warn_c2y_compat_assoc_type_incomplete
1926 : diag::ext_assoc_type_incomplete;
1927 else if (ControllingExpr && !Types[i]->getType()->isObjectType())
1928 D = diag::err_assoc_type_nonobject;
1929 else if (Types[i]->getType()->isVariablyModifiedType())
1930 D = diag::err_assoc_type_variably_modified;
1931 else if (ControllingExpr) {
1932 // Because the controlling expression undergoes lvalue conversion,
1933 // array conversion, and function conversion, an association which is
1934 // of array type, function type, or is qualified can never be
1935 // reached. We will warn about this so users are less surprised by
1936 // the unreachable association. However, we don't have to handle
1937 // function types; that's not an object type, so it's handled above.
1938 //
1939 // The logic is somewhat different for C++ because C++ has different
1940 // lvalue to rvalue conversion rules than C. [conv.lvalue]p1 says,
1941 // If T is a non-class type, the type of the prvalue is the cv-
1942 // unqualified version of T. Otherwise, the type of the prvalue is T.
1943 // The result of these rules is that all qualified types in an
1944 // association in C are unreachable, and in C++, only qualified non-
1945 // class types are unreachable.
1946 //
1947 // NB: this does not apply when the first operand is a type rather
1948 // than an expression, because the type form does not undergo
1949 // conversion.
1950 unsigned Reason = 0;
1951 QualType QT = Types[i]->getType();
1952 if (QT->isArrayType())
1953 Reason = 1;
1954 else if (QT.hasQualifiers() &&
1955 (!LangOpts.CPlusPlus || !QT->isRecordType()))
1956 Reason = 2;
1957
1958 if (Reason)
1959 Diag(Loc: Types[i]->getTypeLoc().getBeginLoc(),
1960 DiagID: diag::warn_unreachable_association)
1961 << QT << (Reason - 1);
1962 }
1963
1964 if (D != 0) {
1965 Diag(Loc: Types[i]->getTypeLoc().getBeginLoc(), DiagID: D)
1966 << Types[i]->getTypeLoc().getSourceRange() << Types[i]->getType();
1967 if (getDiagnostics().getDiagnosticLevel(
1968 DiagID: D, Loc: Types[i]->getTypeLoc().getBeginLoc()) >=
1969 DiagnosticsEngine::Error)
1970 TypeErrorFound = true;
1971 }
1972
1973 // C11 6.5.1.1p2 "No two generic associations in the same generic
1974 // selection shall specify compatible types."
1975 for (unsigned j = i+1; j < NumAssocs; ++j)
1976 if (Types[j] && !Types[j]->getType()->isDependentType() &&
1977 areTypesCompatibleForGeneric(Ctx&: Context, T: Types[i]->getType(),
1978 U: Types[j]->getType())) {
1979 Diag(Loc: Types[j]->getTypeLoc().getBeginLoc(),
1980 DiagID: diag::err_assoc_compatible_types)
1981 << Types[j]->getTypeLoc().getSourceRange()
1982 << Types[j]->getType()
1983 << Types[i]->getType();
1984 Diag(Loc: Types[i]->getTypeLoc().getBeginLoc(),
1985 DiagID: diag::note_compat_assoc)
1986 << Types[i]->getTypeLoc().getSourceRange()
1987 << Types[i]->getType();
1988 TypeErrorFound = true;
1989 }
1990 }
1991 }
1992 }
1993 if (TypeErrorFound)
1994 return ExprError();
1995
1996 // If we determined that the generic selection is result-dependent, don't
1997 // try to compute the result expression.
1998 if (IsResultDependent) {
1999 if (ControllingExpr)
2000 return GenericSelectionExpr::Create(Context, GenericLoc: KeyLoc, ControllingExpr,
2001 AssocTypes: Types, AssocExprs: Exprs, DefaultLoc, RParenLoc,
2002 ContainsUnexpandedParameterPack);
2003 return GenericSelectionExpr::Create(Context, GenericLoc: KeyLoc, ControllingType, AssocTypes: Types,
2004 AssocExprs: Exprs, DefaultLoc, RParenLoc,
2005 ContainsUnexpandedParameterPack);
2006 }
2007
2008 SmallVector<unsigned, 1> CompatIndices;
2009 unsigned DefaultIndex = std::numeric_limits<unsigned>::max();
2010 // Look at the canonical type of the controlling expression in case it was a
2011 // deduced type like __auto_type. However, when issuing diagnostics, use the
2012 // type the user wrote in source rather than the canonical one.
2013 for (unsigned i = 0; i < NumAssocs; ++i) {
2014 if (!Types[i])
2015 DefaultIndex = i;
2016 else {
2017 bool Compatible;
2018 QualType ControllingQT =
2019 ControllingExpr ? ControllingExpr->getType().getCanonicalType()
2020 : ControllingType->getType().getCanonicalType();
2021 QualType AssocQT = Types[i]->getType();
2022
2023 Compatible =
2024 areTypesCompatibleForGeneric(Ctx&: Context, T: ControllingQT, U: AssocQT);
2025
2026 if (Compatible)
2027 CompatIndices.push_back(Elt: i);
2028 }
2029 }
2030
2031 auto GetControllingRangeAndType = [](Expr *ControllingExpr,
2032 TypeSourceInfo *ControllingType) {
2033 // We strip parens here because the controlling expression is typically
2034 // parenthesized in macro definitions.
2035 if (ControllingExpr)
2036 ControllingExpr = ControllingExpr->IgnoreParens();
2037
2038 SourceRange SR = ControllingExpr
2039 ? ControllingExpr->getSourceRange()
2040 : ControllingType->getTypeLoc().getSourceRange();
2041 QualType QT = ControllingExpr ? ControllingExpr->getType()
2042 : ControllingType->getType();
2043
2044 return std::make_pair(x&: SR, y&: QT);
2045 };
2046
2047 // C11 6.5.1.1p2 "The controlling expression of a generic selection shall have
2048 // type compatible with at most one of the types named in its generic
2049 // association list."
2050 if (CompatIndices.size() > 1) {
2051 auto P = GetControllingRangeAndType(ControllingExpr, ControllingType);
2052 SourceRange SR = P.first;
2053 Diag(Loc: SR.getBegin(), DiagID: diag::err_generic_sel_multi_match)
2054 << SR << P.second << (unsigned)CompatIndices.size();
2055 for (unsigned I : CompatIndices) {
2056 Diag(Loc: Types[I]->getTypeLoc().getBeginLoc(),
2057 DiagID: diag::note_compat_assoc)
2058 << Types[I]->getTypeLoc().getSourceRange()
2059 << Types[I]->getType();
2060 }
2061 return ExprError();
2062 }
2063
2064 // C11 6.5.1.1p2 "If a generic selection has no default generic association,
2065 // its controlling expression shall have type compatible with exactly one of
2066 // the types named in its generic association list."
2067 if (DefaultIndex == std::numeric_limits<unsigned>::max() &&
2068 CompatIndices.size() == 0) {
2069 auto P = GetControllingRangeAndType(ControllingExpr, ControllingType);
2070 SourceRange SR = P.first;
2071 Diag(Loc: SR.getBegin(), DiagID: diag::err_generic_sel_no_match) << SR << P.second;
2072 return ExprError();
2073 }
2074
2075 // C11 6.5.1.1p3 "If a generic selection has a generic association with a
2076 // type name that is compatible with the type of the controlling expression,
2077 // then the result expression of the generic selection is the expression
2078 // in that generic association. Otherwise, the result expression of the
2079 // generic selection is the expression in the default generic association."
2080 unsigned ResultIndex =
2081 CompatIndices.size() ? CompatIndices[0] : DefaultIndex;
2082
2083 if (ControllingExpr) {
2084 return GenericSelectionExpr::Create(
2085 Context, GenericLoc: KeyLoc, ControllingExpr, AssocTypes: Types, AssocExprs: Exprs, DefaultLoc, RParenLoc,
2086 ContainsUnexpandedParameterPack, ResultIndex);
2087 }
2088 return GenericSelectionExpr::Create(
2089 Context, GenericLoc: KeyLoc, ControllingType, AssocTypes: Types, AssocExprs: Exprs, DefaultLoc, RParenLoc,
2090 ContainsUnexpandedParameterPack, ResultIndex);
2091}
2092
2093static PredefinedIdentKind getPredefinedExprKind(tok::TokenKind Kind) {
2094 switch (Kind) {
2095 default:
2096 llvm_unreachable("unexpected TokenKind");
2097 case tok::kw___func__:
2098 return PredefinedIdentKind::Func; // [C99 6.4.2.2]
2099 case tok::kw___FUNCTION__:
2100 return PredefinedIdentKind::Function;
2101 case tok::kw___FUNCDNAME__:
2102 return PredefinedIdentKind::FuncDName; // [MS]
2103 case tok::kw___FUNCSIG__:
2104 return PredefinedIdentKind::FuncSig; // [MS]
2105 case tok::kw_L__FUNCTION__:
2106 return PredefinedIdentKind::LFunction; // [MS]
2107 case tok::kw_L__FUNCSIG__:
2108 return PredefinedIdentKind::LFuncSig; // [MS]
2109 case tok::kw___PRETTY_FUNCTION__:
2110 return PredefinedIdentKind::PrettyFunction; // [GNU]
2111 }
2112}
2113
2114/// getPredefinedExprDecl - Returns Decl of a given DeclContext that can be used
2115/// to determine the value of a PredefinedExpr. This can be either a
2116/// block, lambda, captured statement, function, otherwise a nullptr.
2117static Decl *getPredefinedExprDecl(DeclContext *DC) {
2118 while (DC && !isa<BlockDecl, CapturedDecl, FunctionDecl, ObjCMethodDecl>(Val: DC))
2119 DC = DC->getParent();
2120 return cast_or_null<Decl>(Val: DC);
2121}
2122
2123/// getUDSuffixLoc - Create a SourceLocation for a ud-suffix, given the
2124/// location of the token and the offset of the ud-suffix within it.
2125static SourceLocation getUDSuffixLoc(Sema &S, SourceLocation TokLoc,
2126 unsigned Offset) {
2127 return Lexer::AdvanceToTokenCharacter(TokStart: TokLoc, Characters: Offset, SM: S.getSourceManager(),
2128 LangOpts: S.getLangOpts());
2129}
2130
2131/// BuildCookedLiteralOperatorCall - A user-defined literal was found. Look up
2132/// the corresponding cooked (non-raw) literal operator, and build a call to it.
2133static ExprResult BuildCookedLiteralOperatorCall(Sema &S, Scope *Scope,
2134 IdentifierInfo *UDSuffix,
2135 SourceLocation UDSuffixLoc,
2136 ArrayRef<Expr*> Args,
2137 SourceLocation LitEndLoc) {
2138 assert(Args.size() <= 2 && "too many arguments for literal operator");
2139
2140 QualType ArgTy[2];
2141 for (unsigned ArgIdx = 0; ArgIdx != Args.size(); ++ArgIdx) {
2142 ArgTy[ArgIdx] = Args[ArgIdx]->getType();
2143 if (ArgTy[ArgIdx]->isArrayType())
2144 ArgTy[ArgIdx] = S.Context.getArrayDecayedType(T: ArgTy[ArgIdx]);
2145 }
2146
2147 DeclarationName OpName =
2148 S.Context.DeclarationNames.getCXXLiteralOperatorName(II: UDSuffix);
2149 DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc);
2150 OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc);
2151
2152 LookupResult R(S, OpName, UDSuffixLoc, Sema::LookupOrdinaryName);
2153 if (S.LookupLiteralOperator(S: Scope, R, ArgTys: llvm::ArrayRef(ArgTy, Args.size()),
2154 /*AllowRaw*/ false, /*AllowTemplate*/ false,
2155 /*AllowStringTemplatePack*/ AllowStringTemplate: false,
2156 /*DiagnoseMissing*/ true) == Sema::LOLR_Error)
2157 return ExprError();
2158
2159 return S.BuildLiteralOperatorCall(R, SuffixInfo&: OpNameInfo, Args, LitEndLoc);
2160}
2161
2162ExprResult Sema::ActOnUnevaluatedStringLiteral(ArrayRef<Token> StringToks) {
2163 // StringToks needs backing storage as it doesn't hold array elements itself
2164 std::vector<Token> ExpandedToks;
2165 if (getLangOpts().MicrosoftExt)
2166 StringToks = ExpandedToks = ExpandFunctionLocalPredefinedMacros(Toks: StringToks);
2167
2168 StringLiteralParser Literal(StringToks, PP,
2169 StringLiteralEvalMethod::Unevaluated);
2170 if (Literal.hadError)
2171 return ExprError();
2172
2173 SmallVector<SourceLocation, 4> StringTokLocs;
2174 for (const Token &Tok : StringToks)
2175 StringTokLocs.push_back(Elt: Tok.getLocation());
2176
2177 StringLiteral *Lit = StringLiteral::Create(Ctx: Context, Str: Literal.GetString(),
2178 Kind: StringLiteralKind::Unevaluated,
2179 Pascal: false, Ty: {}, Locs: StringTokLocs);
2180
2181 if (!Literal.getUDSuffix().empty()) {
2182 SourceLocation UDSuffixLoc =
2183 getUDSuffixLoc(S&: *this, TokLoc: StringTokLocs[Literal.getUDSuffixToken()],
2184 Offset: Literal.getUDSuffixOffset());
2185 return ExprError(Diag(Loc: UDSuffixLoc, DiagID: diag::err_invalid_string_udl));
2186 }
2187
2188 return Lit;
2189}
2190
2191std::vector<Token>
2192Sema::ExpandFunctionLocalPredefinedMacros(ArrayRef<Token> Toks) {
2193 // MSVC treats some predefined identifiers (e.g. __FUNCTION__) as function
2194 // local macros that expand to string literals that may be concatenated.
2195 // These macros are expanded here (in Sema), because StringLiteralParser
2196 // (in Lex) doesn't know the enclosing function (because it hasn't been
2197 // parsed yet).
2198 assert(getLangOpts().MicrosoftExt);
2199
2200 // Note: Although function local macros are defined only inside functions,
2201 // we ensure a valid `CurrentDecl` even outside of a function. This allows
2202 // expansion of macros into empty string literals without additional checks.
2203 Decl *CurrentDecl = getPredefinedExprDecl(DC: CurContext);
2204 if (!CurrentDecl)
2205 CurrentDecl = Context.getTranslationUnitDecl();
2206
2207 std::vector<Token> ExpandedToks;
2208 ExpandedToks.reserve(n: Toks.size());
2209 for (const Token &Tok : Toks) {
2210 if (!isFunctionLocalStringLiteralMacro(K: Tok.getKind(), LO: getLangOpts())) {
2211 assert(tok::isStringLiteral(Tok.getKind()));
2212 ExpandedToks.emplace_back(args: Tok);
2213 continue;
2214 }
2215 if (isa<TranslationUnitDecl>(Val: CurrentDecl))
2216 Diag(Loc: Tok.getLocation(), DiagID: diag::ext_predef_outside_function);
2217 // Stringify predefined expression
2218 Diag(Loc: Tok.getLocation(), DiagID: diag::ext_string_literal_from_predefined)
2219 << Tok.getKind();
2220 SmallString<64> Str;
2221 llvm::raw_svector_ostream OS(Str);
2222 Token &Exp = ExpandedToks.emplace_back();
2223 Exp.startToken();
2224 if (Tok.getKind() == tok::kw_L__FUNCTION__ ||
2225 Tok.getKind() == tok::kw_L__FUNCSIG__) {
2226 OS << 'L';
2227 Exp.setKind(tok::wide_string_literal);
2228 } else {
2229 Exp.setKind(tok::string_literal);
2230 }
2231 OS << '"'
2232 << Lexer::Stringify(Str: PredefinedExpr::ComputeName(
2233 IK: getPredefinedExprKind(Kind: Tok.getKind()), CurrentDecl))
2234 << '"';
2235 PP.CreateString(Str: OS.str(), Tok&: Exp, ExpansionLocStart: Tok.getLocation(), ExpansionLocEnd: Tok.getEndLoc());
2236 }
2237 return ExpandedToks;
2238}
2239
2240ExprResult
2241Sema::ActOnStringLiteral(ArrayRef<Token> StringToks, Scope *UDLScope) {
2242 assert(!StringToks.empty() && "Must have at least one string!");
2243
2244 // StringToks needs backing storage as it doesn't hold array elements itself
2245 std::vector<Token> ExpandedToks;
2246 if (getLangOpts().MicrosoftExt)
2247 StringToks = ExpandedToks = ExpandFunctionLocalPredefinedMacros(Toks: StringToks);
2248
2249 StringLiteralParser Literal(StringToks, PP);
2250 if (Literal.hadError)
2251 return ExprError();
2252
2253 SmallVector<SourceLocation, 4> StringTokLocs;
2254 for (const Token &Tok : StringToks)
2255 StringTokLocs.push_back(Elt: Tok.getLocation());
2256
2257 QualType CharTy = Context.CharTy;
2258 StringLiteralKind Kind = StringLiteralKind::Ordinary;
2259 if (Literal.isWide()) {
2260 CharTy = Context.getWideCharType();
2261 Kind = StringLiteralKind::Wide;
2262 } else if (Literal.isUTF8()) {
2263 if (getLangOpts().Char8)
2264 CharTy = Context.Char8Ty;
2265 else if (getLangOpts().C23)
2266 CharTy = Context.UnsignedCharTy;
2267 Kind = StringLiteralKind::UTF8;
2268 } else if (Literal.isUTF16()) {
2269 CharTy = Context.Char16Ty;
2270 Kind = StringLiteralKind::UTF16;
2271 } else if (Literal.isUTF32()) {
2272 CharTy = Context.Char32Ty;
2273 Kind = StringLiteralKind::UTF32;
2274 } else if (Literal.isPascal()) {
2275 CharTy = Context.UnsignedCharTy;
2276 }
2277
2278 // Warn on u8 string literals before C++20 and C23, whose type
2279 // was an array of char before but becomes an array of char8_t.
2280 // In C++20, it cannot be used where a pointer to char is expected.
2281 // In C23, it might have an unexpected value if char was signed.
2282 if (Kind == StringLiteralKind::UTF8 &&
2283 (getLangOpts().CPlusPlus
2284 ? !getLangOpts().CPlusPlus20 && !getLangOpts().Char8
2285 : !getLangOpts().C23)) {
2286 Diag(Loc: StringTokLocs.front(), DiagID: getLangOpts().CPlusPlus
2287 ? diag::warn_cxx20_compat_utf8_string
2288 : diag::warn_c23_compat_utf8_string);
2289
2290 // Create removals for all 'u8' prefixes in the string literal(s). This
2291 // ensures C++20/C23 compatibility (but may change the program behavior when
2292 // built by non-Clang compilers for which the execution character set is
2293 // not always UTF-8).
2294 auto RemovalDiag = PDiag(DiagID: diag::note_cxx20_c23_compat_utf8_string_remove_u8);
2295 SourceLocation RemovalDiagLoc;
2296 for (const Token &Tok : StringToks) {
2297 if (Tok.getKind() == tok::utf8_string_literal) {
2298 if (RemovalDiagLoc.isInvalid())
2299 RemovalDiagLoc = Tok.getLocation();
2300 RemovalDiag << FixItHint::CreateRemoval(RemoveRange: CharSourceRange::getCharRange(
2301 B: Tok.getLocation(),
2302 E: Lexer::AdvanceToTokenCharacter(TokStart: Tok.getLocation(), Characters: 2,
2303 SM: getSourceManager(), LangOpts: getLangOpts())));
2304 }
2305 }
2306 Diag(Loc: RemovalDiagLoc, PD: RemovalDiag);
2307 }
2308
2309 QualType StrTy =
2310 Context.getStringLiteralArrayType(EltTy: CharTy, Length: Literal.GetNumStringChars());
2311
2312 // Pass &StringTokLocs[0], StringTokLocs.size() to factory!
2313 StringLiteral *Lit = StringLiteral::Create(
2314 Ctx: Context, Str: Literal.GetString(), Kind, Pascal: Literal.Pascal, Ty: StrTy, Locs: StringTokLocs);
2315 if (Literal.getUDSuffix().empty())
2316 return Lit;
2317
2318 // We're building a user-defined literal.
2319 IdentifierInfo *UDSuffix = &Context.Idents.get(Name: Literal.getUDSuffix());
2320 SourceLocation UDSuffixLoc =
2321 getUDSuffixLoc(S&: *this, TokLoc: StringTokLocs[Literal.getUDSuffixToken()],
2322 Offset: Literal.getUDSuffixOffset());
2323
2324 // Make sure we're allowed user-defined literals here.
2325 if (!UDLScope)
2326 return ExprError(Diag(Loc: UDSuffixLoc, DiagID: diag::err_invalid_string_udl));
2327
2328 // C++11 [lex.ext]p5: The literal L is treated as a call of the form
2329 // operator "" X (str, len)
2330 QualType SizeType = Context.getSizeType();
2331
2332 DeclarationName OpName =
2333 Context.DeclarationNames.getCXXLiteralOperatorName(II: UDSuffix);
2334 DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc);
2335 OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc);
2336
2337 QualType ArgTy[] = {
2338 Context.getArrayDecayedType(T: StrTy), SizeType
2339 };
2340
2341 LookupResult R(*this, OpName, UDSuffixLoc, LookupOrdinaryName);
2342 switch (LookupLiteralOperator(S: UDLScope, R, ArgTys: ArgTy,
2343 /*AllowRaw*/ false, /*AllowTemplate*/ true,
2344 /*AllowStringTemplatePack*/ AllowStringTemplate: true,
2345 /*DiagnoseMissing*/ true, StringLit: Lit)) {
2346
2347 case LOLR_Cooked: {
2348 llvm::APInt Len(Context.getIntWidth(T: SizeType), Literal.GetNumStringChars());
2349 IntegerLiteral *LenArg = IntegerLiteral::Create(C: Context, V: Len, type: SizeType,
2350 l: StringTokLocs[0]);
2351 Expr *Args[] = { Lit, LenArg };
2352
2353 return BuildLiteralOperatorCall(R, SuffixInfo&: OpNameInfo, Args, LitEndLoc: StringTokLocs.back());
2354 }
2355
2356 case LOLR_Template: {
2357 TemplateArgumentListInfo ExplicitArgs;
2358 TemplateArgument Arg(Lit, /*IsCanonical=*/false);
2359 TemplateArgumentLocInfo ArgInfo(Lit);
2360 ExplicitArgs.addArgument(Loc: TemplateArgumentLoc(Arg, ArgInfo));
2361 return BuildLiteralOperatorCall(R, SuffixInfo&: OpNameInfo, Args: {}, LitEndLoc: StringTokLocs.back(),
2362 ExplicitTemplateArgs: &ExplicitArgs);
2363 }
2364
2365 case LOLR_StringTemplatePack: {
2366 TemplateArgumentListInfo ExplicitArgs;
2367
2368 unsigned CharBits = Context.getIntWidth(T: CharTy);
2369 bool CharIsUnsigned = CharTy->isUnsignedIntegerType();
2370 llvm::APSInt Value(CharBits, CharIsUnsigned);
2371
2372 TemplateArgument TypeArg(CharTy);
2373 TemplateArgumentLocInfo TypeArgInfo(Context.getTrivialTypeSourceInfo(T: CharTy));
2374 ExplicitArgs.addArgument(Loc: TemplateArgumentLoc(TypeArg, TypeArgInfo));
2375
2376 SourceLocation Loc = StringTokLocs.back();
2377 for (unsigned I = 0, N = Lit->getLength(); I != N; ++I) {
2378 Value = Lit->getCodeUnit(i: I);
2379 TemplateArgument Arg(Context, Value, CharTy);
2380 TemplateArgumentLocInfo ArgInfo(Context, Loc.getLocWithOffset(Offset: I));
2381 ExplicitArgs.addArgument(Loc: TemplateArgumentLoc(Arg, ArgInfo));
2382 }
2383 return BuildLiteralOperatorCall(R, SuffixInfo&: OpNameInfo, Args: {}, LitEndLoc: Loc, ExplicitTemplateArgs: &ExplicitArgs);
2384 }
2385 case LOLR_Raw:
2386 case LOLR_ErrorNoDiagnostic:
2387 llvm_unreachable("unexpected literal operator lookup result");
2388 case LOLR_Error:
2389 return ExprError();
2390 }
2391 llvm_unreachable("unexpected literal operator lookup result");
2392}
2393
2394DeclRefExpr *
2395Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK,
2396 SourceLocation Loc,
2397 const CXXScopeSpec *SS) {
2398 DeclarationNameInfo NameInfo(D->getDeclName(), Loc);
2399 return BuildDeclRefExpr(D, Ty, VK, NameInfo, SS);
2400}
2401
2402DeclRefExpr *
2403Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK,
2404 const DeclarationNameInfo &NameInfo,
2405 const CXXScopeSpec *SS, NamedDecl *FoundD,
2406 SourceLocation TemplateKWLoc,
2407 const TemplateArgumentListInfo *TemplateArgs) {
2408 NestedNameSpecifierLoc NNS =
2409 SS ? SS->getWithLocInContext(Context) : NestedNameSpecifierLoc();
2410 return BuildDeclRefExpr(D, Ty, VK, NameInfo, NNS, FoundD, TemplateKWLoc,
2411 TemplateArgs);
2412}
2413
2414// CUDA/HIP: Check whether a captured reference variable is referencing a
2415// host variable in a device or host device lambda.
2416static bool isCapturingReferenceToHostVarInCUDADeviceLambda(const Sema &S,
2417 VarDecl *VD) {
2418 if (!S.getLangOpts().CUDA || !VD->hasInit())
2419 return false;
2420 assert(VD->getType()->isReferenceType());
2421
2422 // Check whether the reference variable is referencing a host variable.
2423 auto *DRE = dyn_cast<DeclRefExpr>(Val: VD->getInit());
2424 if (!DRE)
2425 return false;
2426 auto *Referee = dyn_cast<VarDecl>(Val: DRE->getDecl());
2427 if (!Referee || !Referee->hasGlobalStorage() ||
2428 Referee->hasAttr<CUDADeviceAttr>())
2429 return false;
2430
2431 // Check whether the current function is a device or host device lambda.
2432 // Check whether the reference variable is a capture by getDeclContext()
2433 // since refersToEnclosingVariableOrCapture() is not ready at this point.
2434 auto *MD = dyn_cast_or_null<CXXMethodDecl>(Val: S.CurContext);
2435 if (MD && MD->getParent()->isLambda() &&
2436 MD->getOverloadedOperator() == OO_Call && MD->hasAttr<CUDADeviceAttr>() &&
2437 VD->getDeclContext() != MD)
2438 return true;
2439
2440 return false;
2441}
2442
2443NonOdrUseReason Sema::getNonOdrUseReasonInCurrentContext(ValueDecl *D) {
2444 // A declaration named in an unevaluated operand never constitutes an odr-use.
2445 if (isUnevaluatedContext())
2446 return NOUR_Unevaluated;
2447
2448 // C++2a [basic.def.odr]p4:
2449 // A variable x whose name appears as a potentially-evaluated expression e
2450 // is odr-used by e unless [...] x is a reference that is usable in
2451 // constant expressions.
2452 // CUDA/HIP:
2453 // If a reference variable referencing a host variable is captured in a
2454 // device or host device lambda, the value of the referee must be copied
2455 // to the capture and the reference variable must be treated as odr-use
2456 // since the value of the referee is not known at compile time and must
2457 // be loaded from the captured.
2458 if (VarDecl *VD = dyn_cast<VarDecl>(Val: D)) {
2459 if (VD->getType()->isReferenceType() &&
2460 !(getLangOpts().OpenMP && OpenMP().isOpenMPCapturedDecl(D)) &&
2461 !isCapturingReferenceToHostVarInCUDADeviceLambda(S: *this, VD) &&
2462 VD->isUsableInConstantExpressions(C: Context))
2463 return NOUR_Constant;
2464 }
2465
2466 // All remaining non-variable cases constitute an odr-use. For variables, we
2467 // need to wait and see how the expression is used.
2468 return NOUR_None;
2469}
2470
2471DeclRefExpr *
2472Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK,
2473 const DeclarationNameInfo &NameInfo,
2474 NestedNameSpecifierLoc NNS, NamedDecl *FoundD,
2475 SourceLocation TemplateKWLoc,
2476 const TemplateArgumentListInfo *TemplateArgs) {
2477 bool RefersToCapturedVariable = isa<VarDecl, BindingDecl>(Val: D) &&
2478 NeedToCaptureVariable(Var: D, Loc: NameInfo.getLoc());
2479
2480 DeclRefExpr *E = DeclRefExpr::Create(
2481 Context, QualifierLoc: NNS, TemplateKWLoc, D, RefersToEnclosingVariableOrCapture: RefersToCapturedVariable, NameInfo, T: Ty,
2482 VK, FoundD, TemplateArgs, NOUR: getNonOdrUseReasonInCurrentContext(D));
2483 MarkDeclRefReferenced(E);
2484
2485 // C++ [except.spec]p17:
2486 // An exception-specification is considered to be needed when:
2487 // - in an expression, the function is the unique lookup result or
2488 // the selected member of a set of overloaded functions.
2489 //
2490 // We delay doing this until after we've built the function reference and
2491 // marked it as used so that:
2492 // a) if the function is defaulted, we get errors from defining it before /
2493 // instead of errors from computing its exception specification, and
2494 // b) if the function is a defaulted comparison, we can use the body we
2495 // build when defining it as input to the exception specification
2496 // computation rather than computing a new body.
2497 if (const auto *FPT = Ty->getAs<FunctionProtoType>()) {
2498 if (isUnresolvedExceptionSpec(ESpecType: FPT->getExceptionSpecType())) {
2499 if (const auto *NewFPT = ResolveExceptionSpec(Loc: NameInfo.getLoc(), FPT))
2500 E->setType(Context.getQualifiedType(T: NewFPT, Qs: Ty.getQualifiers()));
2501 }
2502 }
2503
2504 if (getLangOpts().ObjCWeak && isa<VarDecl>(Val: D) &&
2505 Ty.getObjCLifetime() == Qualifiers::OCL_Weak && !isUnevaluatedContext() &&
2506 !Diags.isIgnored(DiagID: diag::warn_arc_repeated_use_of_weak, Loc: E->getBeginLoc()))
2507 getCurFunction()->recordUseOfWeak(E);
2508
2509 const auto *FD = dyn_cast<FieldDecl>(Val: D);
2510 if (const auto *IFD = dyn_cast<IndirectFieldDecl>(Val: D))
2511 FD = IFD->getAnonField();
2512 if (FD) {
2513 UnusedPrivateFields.remove(X: FD);
2514 // Just in case we're building an illegal pointer-to-member.
2515 if (FD->isBitField())
2516 E->setObjectKind(OK_BitField);
2517 }
2518
2519 // C++ [expr.prim]/8: The expression [...] is a bit-field if the identifier
2520 // designates a bit-field.
2521 if (const auto *BD = dyn_cast<BindingDecl>(Val: D))
2522 if (const auto *BE = BD->getBinding())
2523 E->setObjectKind(BE->getObjectKind());
2524
2525 return E;
2526}
2527
2528void
2529Sema::DecomposeUnqualifiedId(const UnqualifiedId &Id,
2530 TemplateArgumentListInfo &Buffer,
2531 DeclarationNameInfo &NameInfo,
2532 const TemplateArgumentListInfo *&TemplateArgs) {
2533 if (Id.getKind() == UnqualifiedIdKind::IK_TemplateId) {
2534 Buffer.setLAngleLoc(Id.TemplateId->LAngleLoc);
2535 Buffer.setRAngleLoc(Id.TemplateId->RAngleLoc);
2536
2537 ASTTemplateArgsPtr TemplateArgsPtr(Id.TemplateId->getTemplateArgs(),
2538 Id.TemplateId->NumArgs);
2539 translateTemplateArguments(In: TemplateArgsPtr, Out&: Buffer);
2540
2541 TemplateName TName = Id.TemplateId->Template.get();
2542 SourceLocation TNameLoc = Id.TemplateId->TemplateNameLoc;
2543 NameInfo = Context.getNameForTemplate(Name: TName, NameLoc: TNameLoc);
2544 TemplateArgs = &Buffer;
2545 } else {
2546 NameInfo = GetNameFromUnqualifiedId(Name: Id);
2547 TemplateArgs = nullptr;
2548 }
2549}
2550
2551bool Sema::DiagnoseDependentMemberLookup(const LookupResult &R) {
2552 // During a default argument instantiation the CurContext points
2553 // to a CXXMethodDecl; but we can't apply a this-> fixit inside a
2554 // function parameter list, hence add an explicit check.
2555 bool isDefaultArgument =
2556 !CodeSynthesisContexts.empty() &&
2557 CodeSynthesisContexts.back().Kind ==
2558 CodeSynthesisContext::DefaultFunctionArgumentInstantiation;
2559 const auto *CurMethod = dyn_cast<CXXMethodDecl>(Val: CurContext);
2560 bool isInstance = CurMethod && CurMethod->isInstance() &&
2561 R.getNamingClass() == CurMethod->getParent() &&
2562 !isDefaultArgument;
2563
2564 // There are two ways we can find a class-scope declaration during template
2565 // instantiation that we did not find in the template definition: if it is a
2566 // member of a dependent base class, or if it is declared after the point of
2567 // use in the same class. Distinguish these by comparing the class in which
2568 // the member was found to the naming class of the lookup.
2569 unsigned DiagID = diag::err_found_in_dependent_base;
2570 unsigned NoteID = diag::note_member_declared_at;
2571 if (R.getRepresentativeDecl()->getDeclContext()->Equals(DC: R.getNamingClass())) {
2572 DiagID = getLangOpts().MSVCCompat ? diag::ext_found_later_in_class
2573 : diag::err_found_later_in_class;
2574 } else if (getLangOpts().MSVCCompat) {
2575 DiagID = diag::ext_found_in_dependent_base;
2576 NoteID = diag::note_dependent_member_use;
2577 }
2578
2579 if (isInstance) {
2580 // Give a code modification hint to insert 'this->'.
2581 Diag(Loc: R.getNameLoc(), DiagID)
2582 << R.getLookupName()
2583 << FixItHint::CreateInsertion(InsertionLoc: R.getNameLoc(), Code: "this->");
2584 CheckCXXThisCapture(Loc: R.getNameLoc());
2585 } else {
2586 // FIXME: Add a FixItHint to insert 'Base::' or 'Derived::' (assuming
2587 // they're not shadowed).
2588 Diag(Loc: R.getNameLoc(), DiagID) << R.getLookupName();
2589 }
2590
2591 for (const NamedDecl *D : R)
2592 Diag(Loc: D->getLocation(), DiagID: NoteID);
2593
2594 // Return true if we are inside a default argument instantiation
2595 // and the found name refers to an instance member function, otherwise
2596 // the caller will try to create an implicit member call and this is wrong
2597 // for default arguments.
2598 //
2599 // FIXME: Is this special case necessary? We could allow the caller to
2600 // diagnose this.
2601 if (isDefaultArgument && ((*R.begin())->isCXXInstanceMember())) {
2602 Diag(Loc: R.getNameLoc(), DiagID: diag::err_member_call_without_object) << 0;
2603 return true;
2604 }
2605
2606 // Tell the callee to try to recover.
2607 return false;
2608}
2609
2610bool Sema::DiagnoseEmptyLookup(Scope *S, CXXScopeSpec &SS, LookupResult &R,
2611 CorrectionCandidateCallback &CCC,
2612 TemplateArgumentListInfo *ExplicitTemplateArgs,
2613 ArrayRef<Expr *> Args, DeclContext *LookupCtx) {
2614 DeclarationName Name = R.getLookupName();
2615 SourceRange NameRange = R.getLookupNameInfo().getSourceRange();
2616
2617 unsigned diagnostic = diag::err_undeclared_var_use;
2618 unsigned diagnostic_suggest = diag::err_undeclared_var_use_suggest;
2619 if (Name.getNameKind() == DeclarationName::CXXOperatorName ||
2620 Name.getNameKind() == DeclarationName::CXXLiteralOperatorName ||
2621 Name.getNameKind() == DeclarationName::CXXConversionFunctionName) {
2622 diagnostic = diag::err_undeclared_use;
2623 diagnostic_suggest = diag::err_undeclared_use_suggest;
2624 }
2625
2626 // If the original lookup was an unqualified lookup, fake an
2627 // unqualified lookup. This is useful when (for example) the
2628 // original lookup would not have found something because it was a
2629 // dependent name.
2630 DeclContext *DC =
2631 LookupCtx ? LookupCtx : (SS.isEmpty() ? CurContext : nullptr);
2632 while (DC) {
2633 if (isa<CXXRecordDecl>(Val: DC)) {
2634 if (ExplicitTemplateArgs) {
2635 if (LookupTemplateName(
2636 R, S, SS, ObjectType: Context.getCanonicalTagType(TD: cast<CXXRecordDecl>(Val: DC)),
2637 /*EnteringContext*/ false, RequiredTemplate: TemplateNameIsRequired,
2638 /*RequiredTemplateKind*/ ATK: nullptr, /*AllowTypoCorrection*/ true))
2639 return true;
2640 } else {
2641 LookupQualifiedName(R, LookupCtx: DC);
2642 }
2643
2644 if (!R.empty()) {
2645 // Don't give errors about ambiguities in this lookup.
2646 R.suppressDiagnostics();
2647
2648 // If there's a best viable function among the results, only mention
2649 // that one in the notes.
2650 OverloadCandidateSet Candidates(R.getNameLoc(),
2651 OverloadCandidateSet::CSK_Normal);
2652 AddOverloadedCallCandidates(R, ExplicitTemplateArgs, Args, CandidateSet&: Candidates);
2653 OverloadCandidateSet::iterator Best;
2654 if (Candidates.BestViableFunction(S&: *this, Loc: R.getNameLoc(), Best) ==
2655 OR_Success) {
2656 R.clear();
2657 R.addDecl(D: Best->FoundDecl.getDecl(), AS: Best->FoundDecl.getAccess());
2658 R.resolveKind();
2659 }
2660
2661 return DiagnoseDependentMemberLookup(R);
2662 }
2663
2664 R.clear();
2665 }
2666
2667 DC = DC->getLookupParent();
2668 }
2669
2670 // We didn't find anything, so try to correct for a typo.
2671 TypoCorrection Corrected;
2672 if (S && (Corrected =
2673 CorrectTypo(Typo: R.getLookupNameInfo(), LookupKind: R.getLookupKind(), S, SS: &SS,
2674 CCC, Mode: CorrectTypoKind::ErrorRecovery, MemberContext: LookupCtx))) {
2675 std::string CorrectedStr(Corrected.getAsString(LO: getLangOpts()));
2676 bool DroppedSpecifier =
2677 Corrected.WillReplaceSpecifier() && Name.getAsString() == CorrectedStr;
2678 R.setLookupName(Corrected.getCorrection());
2679
2680 bool AcceptableWithRecovery = false;
2681 bool AcceptableWithoutRecovery = false;
2682 NamedDecl *ND = Corrected.getFoundDecl();
2683 if (ND) {
2684 if (Corrected.isOverloaded()) {
2685 OverloadCandidateSet OCS(R.getNameLoc(),
2686 OverloadCandidateSet::CSK_Normal);
2687 OverloadCandidateSet::iterator Best;
2688 for (NamedDecl *CD : Corrected) {
2689 if (FunctionTemplateDecl *FTD =
2690 dyn_cast<FunctionTemplateDecl>(Val: CD))
2691 AddTemplateOverloadCandidate(
2692 FunctionTemplate: FTD, FoundDecl: DeclAccessPair::make(D: FTD, AS: AS_none), ExplicitTemplateArgs,
2693 Args, CandidateSet&: OCS);
2694 else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Val: CD))
2695 if (!ExplicitTemplateArgs || ExplicitTemplateArgs->size() == 0)
2696 AddOverloadCandidate(Function: FD, FoundDecl: DeclAccessPair::make(D: FD, AS: AS_none),
2697 Args, CandidateSet&: OCS);
2698 }
2699 switch (OCS.BestViableFunction(S&: *this, Loc: R.getNameLoc(), Best)) {
2700 case OR_Success:
2701 ND = Best->FoundDecl;
2702 Corrected.setCorrectionDecl(ND);
2703 break;
2704 default:
2705 // FIXME: Arbitrarily pick the first declaration for the note.
2706 Corrected.setCorrectionDecl(ND);
2707 break;
2708 }
2709 }
2710 R.addDecl(D: ND);
2711 if (getLangOpts().CPlusPlus && ND->isCXXClassMember()) {
2712 CXXRecordDecl *Record =
2713 Corrected.getCorrectionSpecifier().getAsRecordDecl();
2714 if (!Record)
2715 Record = cast<CXXRecordDecl>(
2716 Val: ND->getDeclContext()->getRedeclContext());
2717 R.setNamingClass(Record);
2718 }
2719
2720 auto *UnderlyingND = ND->getUnderlyingDecl();
2721 AcceptableWithRecovery = isa<ValueDecl>(Val: UnderlyingND) ||
2722 isa<FunctionTemplateDecl>(Val: UnderlyingND);
2723 // FIXME: If we ended up with a typo for a type name or
2724 // Objective-C class name, we're in trouble because the parser
2725 // is in the wrong place to recover. Suggest the typo
2726 // correction, but don't make it a fix-it since we're not going
2727 // to recover well anyway.
2728 AcceptableWithoutRecovery = isa<TypeDecl>(Val: UnderlyingND) ||
2729 getAsTypeTemplateDecl(D: UnderlyingND) ||
2730 isa<ObjCInterfaceDecl>(Val: UnderlyingND);
2731 } else {
2732 // FIXME: We found a keyword. Suggest it, but don't provide a fix-it
2733 // because we aren't able to recover.
2734 AcceptableWithoutRecovery = true;
2735 }
2736
2737 if (AcceptableWithRecovery || AcceptableWithoutRecovery) {
2738 unsigned NoteID = Corrected.getCorrectionDeclAs<ImplicitParamDecl>()
2739 ? diag::note_implicit_param_decl
2740 : diag::note_previous_decl;
2741 if (SS.isEmpty())
2742 diagnoseTypo(Correction: Corrected, TypoDiag: PDiag(DiagID: diagnostic_suggest) << Name << NameRange,
2743 PrevNote: PDiag(DiagID: NoteID), ErrorRecovery: AcceptableWithRecovery);
2744 else
2745 diagnoseTypo(Correction: Corrected,
2746 TypoDiag: PDiag(DiagID: diag::err_no_member_suggest)
2747 << Name << computeDeclContext(SS, EnteringContext: false)
2748 << DroppedSpecifier << NameRange,
2749 PrevNote: PDiag(DiagID: NoteID), ErrorRecovery: AcceptableWithRecovery);
2750
2751 if (Corrected.WillReplaceSpecifier()) {
2752 NestedNameSpecifier NNS = Corrected.getCorrectionSpecifier();
2753 // In order to be valid, a non-empty CXXScopeSpec needs a source range.
2754 SS.MakeTrivial(Context, Qualifier: NNS,
2755 R: NNS ? NameRange.getBegin() : SourceRange());
2756 }
2757
2758 // Tell the callee whether to try to recover.
2759 return !AcceptableWithRecovery;
2760 }
2761 }
2762 R.clear();
2763
2764 // Emit a special diagnostic for failed member lookups.
2765 // FIXME: computing the declaration context might fail here (?)
2766 if (!SS.isEmpty()) {
2767 Diag(Loc: R.getNameLoc(), DiagID: diag::err_no_member)
2768 << Name << computeDeclContext(SS, EnteringContext: false) << NameRange;
2769 return true;
2770 }
2771
2772 // Give up, we can't recover.
2773 Diag(Loc: R.getNameLoc(), DiagID: diagnostic) << Name << NameRange;
2774 return true;
2775}
2776
2777/// In Microsoft mode, if we are inside a template class whose parent class has
2778/// dependent base classes, and we can't resolve an unqualified identifier, then
2779/// assume the identifier is a member of a dependent base class. We can only
2780/// recover successfully in static methods, instance methods, and other contexts
2781/// where 'this' is available. This doesn't precisely match MSVC's
2782/// instantiation model, but it's close enough.
2783static Expr *
2784recoverFromMSUnqualifiedLookup(Sema &S, ASTContext &Context,
2785 DeclarationNameInfo &NameInfo,
2786 SourceLocation TemplateKWLoc,
2787 const TemplateArgumentListInfo *TemplateArgs) {
2788 // Only try to recover from lookup into dependent bases in static methods or
2789 // contexts where 'this' is available.
2790 QualType ThisType = S.getCurrentThisType();
2791 const CXXRecordDecl *RD = nullptr;
2792 if (!ThisType.isNull())
2793 RD = ThisType->getPointeeType()->getAsCXXRecordDecl();
2794 else if (auto *MD = dyn_cast<CXXMethodDecl>(Val: S.CurContext))
2795 RD = MD->getParent();
2796 if (!RD || !RD->hasDefinition() || !RD->hasAnyDependentBases())
2797 return nullptr;
2798
2799 // Diagnose this as unqualified lookup into a dependent base class. If 'this'
2800 // is available, suggest inserting 'this->' as a fixit.
2801 SourceLocation Loc = NameInfo.getLoc();
2802 auto DB = S.Diag(Loc, DiagID: diag::ext_undeclared_unqual_id_with_dependent_base);
2803 DB << NameInfo.getName() << RD;
2804
2805 if (!ThisType.isNull()) {
2806 DB << FixItHint::CreateInsertion(InsertionLoc: Loc, Code: "this->");
2807 return CXXDependentScopeMemberExpr::Create(
2808 Ctx: Context, /*This=*/Base: nullptr, BaseType: ThisType, /*IsArrow=*/true,
2809 /*Op=*/OperatorLoc: SourceLocation(), QualifierLoc: NestedNameSpecifierLoc(), TemplateKWLoc,
2810 /*FirstQualifierFoundInScope=*/nullptr, MemberNameInfo: NameInfo, TemplateArgs);
2811 }
2812
2813 // Synthesize a fake NNS that points to the derived class. This will
2814 // perform name lookup during template instantiation.
2815 CXXScopeSpec SS;
2816 NestedNameSpecifier NNS(Context.getCanonicalTagType(TD: RD)->getTypePtr());
2817 SS.MakeTrivial(Context, Qualifier: NNS, R: SourceRange(Loc, Loc));
2818 return DependentScopeDeclRefExpr::Create(
2819 Context, QualifierLoc: SS.getWithLocInContext(Context), TemplateKWLoc, NameInfo,
2820 TemplateArgs);
2821}
2822
2823ExprResult Sema::ActOnIdExpression(Scope *S, CXXScopeSpec &SS,
2824 SourceLocation TemplateKWLoc,
2825 UnqualifiedId &Id, bool HasTrailingLParen,
2826 bool IsAddressOfOperand,
2827 CorrectionCandidateCallback *CCC,
2828 bool IsInlineAsmIdentifier) {
2829 assert(!(IsAddressOfOperand && HasTrailingLParen) &&
2830 "cannot be direct & operand and have a trailing lparen");
2831 if (SS.isInvalid())
2832 return ExprError();
2833
2834 TemplateArgumentListInfo TemplateArgsBuffer;
2835
2836 // Decompose the UnqualifiedId into the following data.
2837 DeclarationNameInfo NameInfo;
2838 const TemplateArgumentListInfo *TemplateArgs;
2839 DecomposeUnqualifiedId(Id, Buffer&: TemplateArgsBuffer, NameInfo, TemplateArgs);
2840
2841 DeclarationName Name = NameInfo.getName();
2842 IdentifierInfo *II = Name.getAsIdentifierInfo();
2843 SourceLocation NameLoc = NameInfo.getLoc();
2844
2845 if (II && II->isEditorPlaceholder()) {
2846 // FIXME: When typed placeholders are supported we can create a typed
2847 // placeholder expression node.
2848 return ExprError();
2849 }
2850
2851 // This specially handles arguments of attributes appertains to a type of C
2852 // struct field such that the name lookup within a struct finds the member
2853 // name, which is not the case for other contexts in C.
2854 if (isAttrContext() && !getLangOpts().CPlusPlus && S->isClassScope()) {
2855 // See if this is reference to a field of struct.
2856 LookupResult R(*this, NameInfo, LookupMemberName);
2857 // LookupName handles a name lookup from within anonymous struct.
2858 if (LookupName(R, S)) {
2859 if (auto *VD = dyn_cast<ValueDecl>(Val: R.getFoundDecl())) {
2860 QualType type = VD->getType().getNonReferenceType();
2861 // This will eventually be translated into MemberExpr upon
2862 // the use of instantiated struct fields.
2863 return BuildDeclRefExpr(D: VD, Ty: type, VK: VK_LValue, Loc: NameLoc);
2864 }
2865 }
2866 }
2867
2868 // Perform the required lookup.
2869 LookupResult R(*this, NameInfo,
2870 (Id.getKind() == UnqualifiedIdKind::IK_ImplicitSelfParam)
2871 ? LookupObjCImplicitSelfParam
2872 : LookupOrdinaryName);
2873 if (TemplateKWLoc.isValid() || TemplateArgs) {
2874 // Lookup the template name again to correctly establish the context in
2875 // which it was found. This is really unfortunate as we already did the
2876 // lookup to determine that it was a template name in the first place. If
2877 // this becomes a performance hit, we can work harder to preserve those
2878 // results until we get here but it's likely not worth it.
2879 AssumedTemplateKind AssumedTemplate;
2880 if (LookupTemplateName(R, S, SS, /*ObjectType=*/QualType(),
2881 /*EnteringContext=*/false, RequiredTemplate: TemplateKWLoc,
2882 ATK: &AssumedTemplate))
2883 return ExprError();
2884
2885 if (R.wasNotFoundInCurrentInstantiation() || SS.isInvalid())
2886 return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo,
2887 isAddressOfOperand: IsAddressOfOperand, TemplateArgs);
2888 } else {
2889 bool IvarLookupFollowUp = II && !SS.isSet() && getCurMethodDecl();
2890 LookupParsedName(R, S, SS: &SS, /*ObjectType=*/QualType(),
2891 /*AllowBuiltinCreation=*/!IvarLookupFollowUp);
2892
2893 // If the result might be in a dependent base class, this is a dependent
2894 // id-expression.
2895 if (R.wasNotFoundInCurrentInstantiation() || SS.isInvalid())
2896 return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo,
2897 isAddressOfOperand: IsAddressOfOperand, TemplateArgs);
2898
2899 // If this reference is in an Objective-C method, then we need to do
2900 // some special Objective-C lookup, too.
2901 if (IvarLookupFollowUp) {
2902 ExprResult E(ObjC().LookupInObjCMethod(LookUp&: R, S, II, AllowBuiltinCreation: true));
2903 if (E.isInvalid())
2904 return ExprError();
2905
2906 if (Expr *Ex = E.getAs<Expr>())
2907 return Ex;
2908 }
2909 }
2910
2911 if (R.isAmbiguous())
2912 return ExprError();
2913
2914 // This could be an implicitly declared function reference if the language
2915 // mode allows it as a feature.
2916 if (R.empty() && HasTrailingLParen && II &&
2917 getLangOpts().implicitFunctionsAllowed()) {
2918 NamedDecl *D = ImplicitlyDefineFunction(Loc: NameLoc, II&: *II, S);
2919 if (D) R.addDecl(D);
2920 }
2921
2922 // Determine whether this name might be a candidate for
2923 // argument-dependent lookup.
2924 bool ADL = UseArgumentDependentLookup(SS, R, HasTrailingLParen);
2925
2926 if (R.empty() && !ADL) {
2927 if (SS.isEmpty() && getLangOpts().MSVCCompat) {
2928 if (Expr *E = recoverFromMSUnqualifiedLookup(S&: *this, Context, NameInfo,
2929 TemplateKWLoc, TemplateArgs))
2930 return E;
2931 }
2932
2933 // Don't diagnose an empty lookup for inline assembly.
2934 if (IsInlineAsmIdentifier)
2935 return ExprError();
2936
2937 // If this name wasn't predeclared and if this is not a function
2938 // call, diagnose the problem.
2939 DefaultFilterCCC DefaultValidator(II, SS.getScopeRep());
2940 DefaultValidator.IsAddressOfOperand = IsAddressOfOperand;
2941 assert((!CCC || CCC->IsAddressOfOperand == IsAddressOfOperand) &&
2942 "Typo correction callback misconfigured");
2943 if (CCC) {
2944 // Make sure the callback knows what the typo being diagnosed is.
2945 CCC->setTypoName(II);
2946 if (SS.isValid())
2947 CCC->setTypoNNS(SS.getScopeRep());
2948 }
2949 // FIXME: DiagnoseEmptyLookup produces bad diagnostics if we're looking for
2950 // a template name, but we happen to have always already looked up the name
2951 // before we get here if it must be a template name.
2952 if (DiagnoseEmptyLookup(S, SS, R, CCC&: CCC ? *CCC : DefaultValidator, ExplicitTemplateArgs: nullptr,
2953 Args: {}, LookupCtx: nullptr))
2954 return ExprError();
2955
2956 assert(!R.empty() &&
2957 "DiagnoseEmptyLookup returned false but added no results");
2958
2959 // If we found an Objective-C instance variable, let
2960 // LookupInObjCMethod build the appropriate expression to
2961 // reference the ivar.
2962 if (ObjCIvarDecl *Ivar = R.getAsSingle<ObjCIvarDecl>()) {
2963 R.clear();
2964 ExprResult E(ObjC().LookupInObjCMethod(LookUp&: R, S, II: Ivar->getIdentifier()));
2965 // In a hopelessly buggy code, Objective-C instance variable
2966 // lookup fails and no expression will be built to reference it.
2967 if (!E.isInvalid() && !E.get())
2968 return ExprError();
2969 return E;
2970 }
2971 }
2972
2973 // This is guaranteed from this point on.
2974 assert(!R.empty() || ADL);
2975
2976 // Check whether this might be a C++ implicit instance member access.
2977 // C++ [class.mfct.non-static]p3:
2978 // When an id-expression that is not part of a class member access
2979 // syntax and not used to form a pointer to member is used in the
2980 // body of a non-static member function of class X, if name lookup
2981 // resolves the name in the id-expression to a non-static non-type
2982 // member of some class C, the id-expression is transformed into a
2983 // class member access expression using (*this) as the
2984 // postfix-expression to the left of the . operator.
2985 //
2986 // But we don't actually need to do this for '&' operands if R
2987 // resolved to a function or overloaded function set, because the
2988 // expression is ill-formed if it actually works out to be a
2989 // non-static member function:
2990 //
2991 // C++ [expr.ref]p4:
2992 // Otherwise, if E1.E2 refers to a non-static member function. . .
2993 // [t]he expression can be used only as the left-hand operand of a
2994 // member function call.
2995 //
2996 // There are other safeguards against such uses, but it's important
2997 // to get this right here so that we don't end up making a
2998 // spuriously dependent expression if we're inside a dependent
2999 // instance method.
3000 if (isPotentialImplicitMemberAccess(SS, R, IsAddressOfOperand))
3001 return BuildPossibleImplicitMemberExpr(SS, TemplateKWLoc, R, TemplateArgs,
3002 S);
3003
3004 if (TemplateArgs || TemplateKWLoc.isValid()) {
3005
3006 // In C++1y, if this is a variable template id, then check it
3007 // in BuildTemplateIdExpr().
3008 // The single lookup result must be a variable template declaration.
3009 if (Id.getKind() == UnqualifiedIdKind::IK_TemplateId && Id.TemplateId &&
3010 (Id.TemplateId->Kind == TNK_Var_template ||
3011 Id.TemplateId->Kind == TNK_Concept_template)) {
3012 assert(R.getAsSingle<TemplateDecl>() &&
3013 "There should only be one declaration found.");
3014 }
3015
3016 return BuildTemplateIdExpr(SS, TemplateKWLoc, R, RequiresADL: ADL, TemplateArgs);
3017 }
3018
3019 return BuildDeclarationNameExpr(SS, R, NeedsADL: ADL);
3020}
3021
3022ExprResult Sema::BuildQualifiedDeclarationNameExpr(
3023 CXXScopeSpec &SS, const DeclarationNameInfo &NameInfo,
3024 bool IsAddressOfOperand, TypeSourceInfo **RecoveryTSI) {
3025 LookupResult R(*this, NameInfo, LookupOrdinaryName);
3026 LookupParsedName(R, /*S=*/nullptr, SS: &SS, /*ObjectType=*/QualType());
3027
3028 if (R.isAmbiguous())
3029 return ExprError();
3030
3031 if (R.wasNotFoundInCurrentInstantiation() || SS.isInvalid())
3032 return BuildDependentDeclRefExpr(SS, /*TemplateKWLoc=*/SourceLocation(),
3033 NameInfo, /*TemplateArgs=*/nullptr);
3034
3035 if (R.empty()) {
3036 // Don't diagnose problems with invalid record decl, the secondary no_member
3037 // diagnostic during template instantiation is likely bogus, e.g. if a class
3038 // is invalid because it's derived from an invalid base class, then missing
3039 // members were likely supposed to be inherited.
3040 DeclContext *DC = computeDeclContext(SS);
3041 if (const auto *CD = dyn_cast<CXXRecordDecl>(Val: DC))
3042 if (CD->isInvalidDecl() || CD->isBeingDefined())
3043 return ExprError();
3044 Diag(Loc: NameInfo.getLoc(), DiagID: diag::err_no_member)
3045 << NameInfo.getName() << DC << SS.getRange();
3046 return ExprError();
3047 }
3048
3049 if (const TypeDecl *TD = R.getAsSingle<TypeDecl>()) {
3050 QualType ET;
3051 TypeLocBuilder TLB;
3052 if (auto *TagD = dyn_cast<TagDecl>(Val: TD)) {
3053 ET = SemaRef.Context.getTagType(Keyword: ElaboratedTypeKeyword::None,
3054 Qualifier: SS.getScopeRep(), TD: TagD,
3055 /*OwnsTag=*/false);
3056 auto TL = TLB.push<TagTypeLoc>(T: ET);
3057 TL.setElaboratedKeywordLoc(SourceLocation());
3058 TL.setQualifierLoc(SS.getWithLocInContext(Context));
3059 TL.setNameLoc(NameInfo.getLoc());
3060 } else if (auto *TypedefD = dyn_cast<TypedefNameDecl>(Val: TD)) {
3061 ET = SemaRef.Context.getTypedefType(Keyword: ElaboratedTypeKeyword::None,
3062 Qualifier: SS.getScopeRep(), Decl: TypedefD);
3063 TLB.push<TypedefTypeLoc>(T: ET).set(
3064 /*ElaboratedKeywordLoc=*/SourceLocation(),
3065 QualifierLoc: SS.getWithLocInContext(Context), NameLoc: NameInfo.getLoc());
3066 } else {
3067 // FIXME: What else can appear here?
3068 ET = SemaRef.Context.getTypeDeclType(Decl: TD);
3069 TLB.pushTypeSpec(T: ET).setNameLoc(NameInfo.getLoc());
3070 assert(SS.isEmpty());
3071 }
3072
3073 // Diagnose a missing typename if this resolved unambiguously to a type in
3074 // a dependent context. If we can recover with a type, downgrade this to
3075 // a warning in Microsoft compatibility mode.
3076 unsigned DiagID = diag::err_typename_missing;
3077 if (RecoveryTSI && getLangOpts().MSVCCompat)
3078 DiagID = diag::ext_typename_missing;
3079 SourceLocation Loc = SS.getBeginLoc();
3080 auto D = Diag(Loc, DiagID);
3081 D << ET << SourceRange(Loc, NameInfo.getEndLoc());
3082
3083 // Don't recover if the caller isn't expecting us to or if we're in a SFINAE
3084 // context.
3085 if (!RecoveryTSI)
3086 return ExprError();
3087
3088 // Only issue the fixit if we're prepared to recover.
3089 D << FixItHint::CreateInsertion(InsertionLoc: Loc, Code: "typename ");
3090
3091 // Recover by pretending this was an elaborated type.
3092 *RecoveryTSI = TLB.getTypeSourceInfo(Context, T: ET);
3093
3094 return ExprEmpty();
3095 }
3096
3097 // If necessary, build an implicit class member access.
3098 if (isPotentialImplicitMemberAccess(SS, R, IsAddressOfOperand))
3099 return BuildPossibleImplicitMemberExpr(SS,
3100 /*TemplateKWLoc=*/SourceLocation(),
3101 R, /*TemplateArgs=*/nullptr,
3102 /*S=*/nullptr);
3103
3104 return BuildDeclarationNameExpr(SS, R, /*ADL=*/NeedsADL: false);
3105}
3106
3107ExprResult Sema::PerformObjectMemberConversion(Expr *From,
3108 NestedNameSpecifier Qualifier,
3109 NamedDecl *FoundDecl,
3110 NamedDecl *Member) {
3111 const auto *RD = dyn_cast<CXXRecordDecl>(Val: Member->getDeclContext());
3112 if (!RD)
3113 return From;
3114
3115 QualType DestRecordType;
3116 QualType DestType;
3117 QualType FromRecordType;
3118 QualType FromType = From->getType();
3119 bool PointerConversions = false;
3120 if (isa<FieldDecl>(Val: Member)) {
3121 DestRecordType = Context.getCanonicalTagType(TD: RD);
3122 auto FromPtrType = FromType->getAs<PointerType>();
3123 DestRecordType = Context.getAddrSpaceQualType(
3124 T: DestRecordType, AddressSpace: FromPtrType
3125 ? FromType->getPointeeType().getAddressSpace()
3126 : FromType.getAddressSpace());
3127
3128 if (FromPtrType) {
3129 DestType = Context.getPointerType(T: DestRecordType);
3130 FromRecordType = FromPtrType->getPointeeType();
3131 PointerConversions = true;
3132 } else {
3133 DestType = DestRecordType;
3134 FromRecordType = FromType;
3135 }
3136 } else if (const auto *Method = dyn_cast<CXXMethodDecl>(Val: Member)) {
3137 if (!Method->isImplicitObjectMemberFunction())
3138 return From;
3139
3140 DestType = Method->getThisType().getNonReferenceType();
3141 DestRecordType = Method->getFunctionObjectParameterType();
3142
3143 if (FromType->getAs<PointerType>()) {
3144 FromRecordType = FromType->getPointeeType();
3145 PointerConversions = true;
3146 } else {
3147 FromRecordType = FromType;
3148 DestType = DestRecordType;
3149 }
3150
3151 LangAS FromAS = FromRecordType.getAddressSpace();
3152 LangAS DestAS = DestRecordType.getAddressSpace();
3153 if (FromAS != DestAS) {
3154 QualType FromRecordTypeWithoutAS =
3155 Context.removeAddrSpaceQualType(T: FromRecordType);
3156 QualType FromTypeWithDestAS =
3157 Context.getAddrSpaceQualType(T: FromRecordTypeWithoutAS, AddressSpace: DestAS);
3158 if (PointerConversions)
3159 FromTypeWithDestAS = Context.getPointerType(T: FromTypeWithDestAS);
3160 From = ImpCastExprToType(E: From, Type: FromTypeWithDestAS,
3161 CK: CK_AddressSpaceConversion, VK: From->getValueKind())
3162 .get();
3163 }
3164 } else {
3165 // No conversion necessary.
3166 return From;
3167 }
3168
3169 if (DestType->isDependentType() || FromType->isDependentType())
3170 return From;
3171
3172 // If the unqualified types are the same, no conversion is necessary.
3173 if (Context.hasSameUnqualifiedType(T1: FromRecordType, T2: DestRecordType))
3174 return From;
3175
3176 SourceRange FromRange = From->getSourceRange();
3177 SourceLocation FromLoc = FromRange.getBegin();
3178
3179 ExprValueKind VK = From->getValueKind();
3180
3181 // C++ [class.member.lookup]p8:
3182 // [...] Ambiguities can often be resolved by qualifying a name with its
3183 // class name.
3184 //
3185 // If the member was a qualified name and the qualified referred to a
3186 // specific base subobject type, we'll cast to that intermediate type
3187 // first and then to the object in which the member is declared. That allows
3188 // one to resolve ambiguities in, e.g., a diamond-shaped hierarchy such as:
3189 //
3190 // class Base { public: int x; };
3191 // class Derived1 : public Base { };
3192 // class Derived2 : public Base { };
3193 // class VeryDerived : public Derived1, public Derived2 { void f(); };
3194 //
3195 // void VeryDerived::f() {
3196 // x = 17; // error: ambiguous base subobjects
3197 // Derived1::x = 17; // okay, pick the Base subobject of Derived1
3198 // }
3199 if (Qualifier.getKind() == NestedNameSpecifier::Kind::Type) {
3200 QualType QType = QualType(Qualifier.getAsType(), 0);
3201 assert(QType->isRecordType() && "lookup done with non-record type");
3202
3203 QualType QRecordType = QualType(QType->castAs<RecordType>(), 0);
3204
3205 // In C++98, the qualifier type doesn't actually have to be a base
3206 // type of the object type, in which case we just ignore it.
3207 // Otherwise build the appropriate casts.
3208 if (IsDerivedFrom(Loc: FromLoc, Derived: FromRecordType, Base: QRecordType)) {
3209 CXXCastPath BasePath;
3210 if (CheckDerivedToBaseConversion(Derived: FromRecordType, Base: QRecordType,
3211 Loc: FromLoc, Range: FromRange, BasePath: &BasePath))
3212 return ExprError();
3213
3214 if (PointerConversions)
3215 QType = Context.getPointerType(T: QType);
3216 From = ImpCastExprToType(E: From, Type: QType, CK: CK_UncheckedDerivedToBase,
3217 VK, BasePath: &BasePath).get();
3218
3219 FromType = QType;
3220 FromRecordType = QRecordType;
3221
3222 // If the qualifier type was the same as the destination type,
3223 // we're done.
3224 if (Context.hasSameUnqualifiedType(T1: FromRecordType, T2: DestRecordType))
3225 return From;
3226 }
3227 }
3228
3229 CXXCastPath BasePath;
3230 if (CheckDerivedToBaseConversion(Derived: FromRecordType, Base: DestRecordType,
3231 Loc: FromLoc, Range: FromRange, BasePath: &BasePath,
3232 /*IgnoreAccess=*/true))
3233 return ExprError();
3234
3235 // Propagate qualifiers to base subobjects as per:
3236 // C++ [basic.type.qualifier]p1.2:
3237 // A volatile object is [...] a subobject of a volatile object.
3238 Qualifiers FromTypeQuals = FromType.getQualifiers();
3239 FromTypeQuals.setAddressSpace(DestType.getAddressSpace());
3240 DestType = Context.getQualifiedType(T: DestType, Qs: FromTypeQuals);
3241
3242 return ImpCastExprToType(E: From, Type: DestType, CK: CK_UncheckedDerivedToBase, VK,
3243 BasePath: &BasePath);
3244}
3245
3246bool Sema::UseArgumentDependentLookup(const CXXScopeSpec &SS,
3247 const LookupResult &R,
3248 bool HasTrailingLParen) {
3249 // Only when used directly as the postfix-expression of a call.
3250 if (!HasTrailingLParen)
3251 return false;
3252
3253 // Never if a scope specifier was provided.
3254 if (SS.isNotEmpty())
3255 return false;
3256
3257 // Only in C++ or ObjC++.
3258 if (!getLangOpts().CPlusPlus)
3259 return false;
3260
3261 // Turn off ADL when we find certain kinds of declarations during
3262 // normal lookup:
3263 for (const NamedDecl *D : R) {
3264 // C++0x [basic.lookup.argdep]p3:
3265 // -- a declaration of a class member
3266 // Since using decls preserve this property, we check this on the
3267 // original decl.
3268 if (D->isCXXClassMember())
3269 return false;
3270
3271 // C++0x [basic.lookup.argdep]p3:
3272 // -- a block-scope function declaration that is not a
3273 // using-declaration
3274 // NOTE: we also trigger this for function templates (in fact, we
3275 // don't check the decl type at all, since all other decl types
3276 // turn off ADL anyway).
3277 if (isa<UsingShadowDecl>(Val: D))
3278 D = cast<UsingShadowDecl>(Val: D)->getTargetDecl();
3279 else if (D->getLexicalDeclContext()->isFunctionOrMethod())
3280 return false;
3281
3282 // C++0x [basic.lookup.argdep]p3:
3283 // -- a declaration that is neither a function or a function
3284 // template
3285 // And also for builtin functions.
3286 if (const auto *FDecl = dyn_cast<FunctionDecl>(Val: D)) {
3287 // But also builtin functions.
3288 if (FDecl->getBuiltinID() && FDecl->isImplicit())
3289 return false;
3290 } else if (!isa<FunctionTemplateDecl>(Val: D))
3291 return false;
3292 }
3293
3294 return true;
3295}
3296
3297
3298/// Diagnoses obvious problems with the use of the given declaration
3299/// as an expression. This is only actually called for lookups that
3300/// were not overloaded, and it doesn't promise that the declaration
3301/// will in fact be used.
3302static bool CheckDeclInExpr(Sema &S, SourceLocation Loc, NamedDecl *D,
3303 bool AcceptInvalid) {
3304 if (D->isInvalidDecl() && !AcceptInvalid)
3305 return true;
3306
3307 if (isa<TypedefNameDecl>(Val: D)) {
3308 S.Diag(Loc, DiagID: diag::err_unexpected_typedef) << D->getDeclName();
3309 return true;
3310 }
3311
3312 if (isa<ObjCInterfaceDecl>(Val: D)) {
3313 S.Diag(Loc, DiagID: diag::err_unexpected_interface) << D->getDeclName();
3314 return true;
3315 }
3316
3317 if (isa<NamespaceDecl>(Val: D)) {
3318 S.Diag(Loc, DiagID: diag::err_unexpected_namespace) << D->getDeclName();
3319 return true;
3320 }
3321
3322 return false;
3323}
3324
3325// Certain multiversion types should be treated as overloaded even when there is
3326// only one result.
3327static bool ShouldLookupResultBeMultiVersionOverload(const LookupResult &R) {
3328 assert(R.isSingleResult() && "Expected only a single result");
3329 const auto *FD = dyn_cast<FunctionDecl>(Val: R.getFoundDecl());
3330 return FD &&
3331 (FD->isCPUDispatchMultiVersion() || FD->isCPUSpecificMultiVersion());
3332}
3333
3334ExprResult Sema::BuildDeclarationNameExpr(const CXXScopeSpec &SS,
3335 LookupResult &R, bool NeedsADL,
3336 bool AcceptInvalidDecl) {
3337 // If this is a single, fully-resolved result and we don't need ADL,
3338 // just build an ordinary singleton decl ref.
3339 if (!NeedsADL && R.isSingleResult() &&
3340 !R.getAsSingle<FunctionTemplateDecl>() &&
3341 !ShouldLookupResultBeMultiVersionOverload(R))
3342 return BuildDeclarationNameExpr(SS, NameInfo: R.getLookupNameInfo(), D: R.getFoundDecl(),
3343 FoundD: R.getRepresentativeDecl(), TemplateArgs: nullptr,
3344 AcceptInvalidDecl);
3345
3346 // We only need to check the declaration if there's exactly one
3347 // result, because in the overloaded case the results can only be
3348 // functions and function templates.
3349 if (R.isSingleResult() && !ShouldLookupResultBeMultiVersionOverload(R) &&
3350 CheckDeclInExpr(S&: *this, Loc: R.getNameLoc(), D: R.getFoundDecl(),
3351 AcceptInvalid: AcceptInvalidDecl))
3352 return ExprError();
3353
3354 // Otherwise, just build an unresolved lookup expression. Suppress
3355 // any lookup-related diagnostics; we'll hash these out later, when
3356 // we've picked a target.
3357 R.suppressDiagnostics();
3358
3359 UnresolvedLookupExpr *ULE = UnresolvedLookupExpr::Create(
3360 Context, NamingClass: R.getNamingClass(), QualifierLoc: SS.getWithLocInContext(Context),
3361 NameInfo: R.getLookupNameInfo(), RequiresADL: NeedsADL, Begin: R.begin(), End: R.end(),
3362 /*KnownDependent=*/false, /*KnownInstantiationDependent=*/false);
3363
3364 return ULE;
3365}
3366
3367ExprResult Sema::BuildDeclarationNameExpr(
3368 const CXXScopeSpec &SS, const DeclarationNameInfo &NameInfo, NamedDecl *D,
3369 NamedDecl *FoundD, const TemplateArgumentListInfo *TemplateArgs,
3370 bool AcceptInvalidDecl) {
3371 assert(D && "Cannot refer to a NULL declaration");
3372 assert(!isa<FunctionTemplateDecl>(D) &&
3373 "Cannot refer unambiguously to a function template");
3374
3375 SourceLocation Loc = NameInfo.getLoc();
3376 if (CheckDeclInExpr(S&: *this, Loc, D, AcceptInvalid: AcceptInvalidDecl)) {
3377 // Recovery from invalid cases (e.g. D is an invalid Decl).
3378 // We use the dependent type for the RecoveryExpr to prevent bogus follow-up
3379 // diagnostics, as invalid decls use int as a fallback type.
3380 return CreateRecoveryExpr(Begin: NameInfo.getBeginLoc(), End: NameInfo.getEndLoc(), SubExprs: {});
3381 }
3382
3383 if (TemplateDecl *TD = dyn_cast<TemplateDecl>(Val: D)) {
3384 // Specifically diagnose references to class templates that are missing
3385 // a template argument list.
3386 diagnoseMissingTemplateArguments(SS, /*TemplateKeyword=*/false, TD, Loc);
3387 return ExprError();
3388 }
3389
3390 // Make sure that we're referring to a value.
3391 if (!isa<ValueDecl, UnresolvedUsingIfExistsDecl>(Val: D)) {
3392 Diag(Loc, DiagID: diag::err_ref_non_value) << D << SS.getRange();
3393 Diag(Loc: D->getLocation(), DiagID: diag::note_declared_at);
3394 return ExprError();
3395 }
3396
3397 // Check whether this declaration can be used. Note that we suppress
3398 // this check when we're going to perform argument-dependent lookup
3399 // on this function name, because this might not be the function
3400 // that overload resolution actually selects.
3401 if (DiagnoseUseOfDecl(D, Locs: Loc))
3402 return ExprError();
3403
3404 auto *VD = cast<ValueDecl>(Val: D);
3405
3406 // Only create DeclRefExpr's for valid Decl's.
3407 if (VD->isInvalidDecl() && !AcceptInvalidDecl)
3408 return ExprError();
3409
3410 // Handle members of anonymous structs and unions. If we got here,
3411 // and the reference is to a class member indirect field, then this
3412 // must be the subject of a pointer-to-member expression.
3413 if (auto *IndirectField = dyn_cast<IndirectFieldDecl>(Val: VD);
3414 IndirectField && !IndirectField->isCXXClassMember())
3415 return BuildAnonymousStructUnionMemberReference(SS, nameLoc: NameInfo.getLoc(),
3416 indirectField: IndirectField);
3417
3418 QualType type = VD->getType();
3419 if (type.isNull())
3420 return ExprError();
3421 ExprValueKind valueKind = VK_PRValue;
3422
3423 // In 'T ...V;', the type of the declaration 'V' is 'T...', but the type of
3424 // a reference to 'V' is simply (unexpanded) 'T'. The type, like the value,
3425 // is expanded by some outer '...' in the context of the use.
3426 type = type.getNonPackExpansionType();
3427
3428 switch (D->getKind()) {
3429 // Ignore all the non-ValueDecl kinds.
3430#define ABSTRACT_DECL(kind)
3431#define VALUE(type, base)
3432#define DECL(type, base) case Decl::type:
3433#include "clang/AST/DeclNodes.inc"
3434 llvm_unreachable("invalid value decl kind");
3435
3436 // These shouldn't make it here.
3437 case Decl::ObjCAtDefsField:
3438 llvm_unreachable("forming non-member reference to ivar?");
3439
3440 // Enum constants are always r-values and never references.
3441 // Unresolved using declarations are dependent.
3442 case Decl::EnumConstant:
3443 case Decl::UnresolvedUsingValue:
3444 case Decl::OMPDeclareReduction:
3445 case Decl::OMPDeclareMapper:
3446 valueKind = VK_PRValue;
3447 break;
3448
3449 // Fields and indirect fields that got here must be for
3450 // pointer-to-member expressions; we just call them l-values for
3451 // internal consistency, because this subexpression doesn't really
3452 // exist in the high-level semantics.
3453 case Decl::Field:
3454 case Decl::IndirectField:
3455 case Decl::ObjCIvar:
3456 assert((getLangOpts().CPlusPlus || isAttrContext()) &&
3457 "building reference to field in C?");
3458
3459 // These can't have reference type in well-formed programs, but
3460 // for internal consistency we do this anyway.
3461 type = type.getNonReferenceType();
3462 valueKind = VK_LValue;
3463 break;
3464
3465 // Non-type template parameters are either l-values or r-values
3466 // depending on the type.
3467 case Decl::NonTypeTemplateParm: {
3468 if (const ReferenceType *reftype = type->getAs<ReferenceType>()) {
3469 type = reftype->getPointeeType();
3470 valueKind = VK_LValue; // even if the parameter is an r-value reference
3471 break;
3472 }
3473
3474 // [expr.prim.id.unqual]p2:
3475 // If the entity is a template parameter object for a template
3476 // parameter of type T, the type of the expression is const T.
3477 // [...] The expression is an lvalue if the entity is a [...] template
3478 // parameter object.
3479 if (type->isRecordType()) {
3480 type = type.getUnqualifiedType().withConst();
3481 valueKind = VK_LValue;
3482 break;
3483 }
3484
3485 // For non-references, we need to strip qualifiers just in case
3486 // the template parameter was declared as 'const int' or whatever.
3487 valueKind = VK_PRValue;
3488 type = type.getUnqualifiedType();
3489 break;
3490 }
3491
3492 case Decl::Var:
3493 case Decl::VarTemplateSpecialization:
3494 case Decl::VarTemplatePartialSpecialization:
3495 case Decl::Decomposition:
3496 case Decl::Binding:
3497 case Decl::OMPCapturedExpr:
3498 // In C, "extern void blah;" is valid and is an r-value.
3499 if (!getLangOpts().CPlusPlus && !type.hasQualifiers() &&
3500 type->isVoidType()) {
3501 valueKind = VK_PRValue;
3502 break;
3503 }
3504 [[fallthrough]];
3505
3506 case Decl::ImplicitParam:
3507 case Decl::ParmVar: {
3508 // These are always l-values.
3509 valueKind = VK_LValue;
3510 type = type.getNonReferenceType();
3511
3512 // FIXME: Does the addition of const really only apply in
3513 // potentially-evaluated contexts? Since the variable isn't actually
3514 // captured in an unevaluated context, it seems that the answer is no.
3515 if (!isUnevaluatedContext()) {
3516 QualType CapturedType = getCapturedDeclRefType(Var: cast<ValueDecl>(Val: VD), Loc);
3517 if (!CapturedType.isNull())
3518 type = CapturedType;
3519 }
3520 break;
3521 }
3522
3523 case Decl::Function: {
3524 if (unsigned BID = cast<FunctionDecl>(Val: VD)->getBuiltinID()) {
3525 if (!Context.BuiltinInfo.isDirectlyAddressable(ID: BID)) {
3526 type = Context.BuiltinFnTy;
3527 valueKind = VK_PRValue;
3528 break;
3529 }
3530 }
3531
3532 const FunctionType *fty = type->castAs<FunctionType>();
3533
3534 // If we're referring to a function with an __unknown_anytype
3535 // result type, make the entire expression __unknown_anytype.
3536 if (fty->getReturnType() == Context.UnknownAnyTy) {
3537 type = Context.UnknownAnyTy;
3538 valueKind = VK_PRValue;
3539 break;
3540 }
3541
3542 // Functions are l-values in C++.
3543 if (getLangOpts().CPlusPlus) {
3544 valueKind = VK_LValue;
3545 break;
3546 }
3547
3548 // C99 DR 316 says that, if a function type comes from a
3549 // function definition (without a prototype), that type is only
3550 // used for checking compatibility. Therefore, when referencing
3551 // the function, we pretend that we don't have the full function
3552 // type.
3553 if (!cast<FunctionDecl>(Val: VD)->hasPrototype() && isa<FunctionProtoType>(Val: fty))
3554 type = Context.getFunctionNoProtoType(ResultTy: fty->getReturnType(),
3555 Info: fty->getExtInfo());
3556
3557 // Functions are r-values in C.
3558 valueKind = VK_PRValue;
3559 break;
3560 }
3561
3562 case Decl::CXXDeductionGuide:
3563 llvm_unreachable("building reference to deduction guide");
3564
3565 case Decl::MSProperty:
3566 case Decl::MSGuid:
3567 case Decl::TemplateParamObject:
3568 // FIXME: Should MSGuidDecl and template parameter objects be subject to
3569 // capture in OpenMP, or duplicated between host and device?
3570 valueKind = VK_LValue;
3571 break;
3572
3573 case Decl::UnnamedGlobalConstant:
3574 valueKind = VK_LValue;
3575 break;
3576
3577 case Decl::CXXMethod:
3578 // If we're referring to a method with an __unknown_anytype
3579 // result type, make the entire expression __unknown_anytype.
3580 // This should only be possible with a type written directly.
3581 if (const FunctionProtoType *proto =
3582 dyn_cast<FunctionProtoType>(Val: VD->getType()))
3583 if (proto->getReturnType() == Context.UnknownAnyTy) {
3584 type = Context.UnknownAnyTy;
3585 valueKind = VK_PRValue;
3586 break;
3587 }
3588
3589 // C++ methods are l-values if static, r-values if non-static.
3590 if (cast<CXXMethodDecl>(Val: VD)->isStatic()) {
3591 valueKind = VK_LValue;
3592 break;
3593 }
3594 [[fallthrough]];
3595
3596 case Decl::CXXConversion:
3597 case Decl::CXXDestructor:
3598 case Decl::CXXConstructor:
3599 valueKind = VK_PRValue;
3600 break;
3601 }
3602
3603 auto *E =
3604 BuildDeclRefExpr(D: VD, Ty: type, VK: valueKind, NameInfo, SS: &SS, FoundD,
3605 /*FIXME: TemplateKWLoc*/ TemplateKWLoc: SourceLocation(), TemplateArgs);
3606 // Clang AST consumers assume a DeclRefExpr refers to a valid decl. We
3607 // wrap a DeclRefExpr referring to an invalid decl with a dependent-type
3608 // RecoveryExpr to avoid follow-up semantic analysis (thus prevent bogus
3609 // diagnostics).
3610 if (VD->isInvalidDecl() && E)
3611 return CreateRecoveryExpr(Begin: E->getBeginLoc(), End: E->getEndLoc(), SubExprs: {E});
3612 return E;
3613}
3614
3615static void ConvertUTF8ToWideString(unsigned CharByteWidth, StringRef Source,
3616 SmallString<32> &Target) {
3617 Target.resize(N: CharByteWidth * (Source.size() + 1));
3618 char *ResultPtr = &Target[0];
3619 const llvm::UTF8 *ErrorPtr;
3620 bool success =
3621 llvm::ConvertUTF8toWide(WideCharWidth: CharByteWidth, Source, ResultPtr, ErrorPtr);
3622 (void)success;
3623 assert(success);
3624 Target.resize(N: ResultPtr - &Target[0]);
3625}
3626
3627ExprResult Sema::BuildPredefinedExpr(SourceLocation Loc,
3628 PredefinedIdentKind IK) {
3629 Decl *currentDecl = getPredefinedExprDecl(DC: CurContext);
3630 if (!currentDecl) {
3631 Diag(Loc, DiagID: diag::ext_predef_outside_function);
3632 currentDecl = Context.getTranslationUnitDecl();
3633 }
3634
3635 QualType ResTy;
3636 StringLiteral *SL = nullptr;
3637 if (cast<DeclContext>(Val: currentDecl)->isDependentContext())
3638 ResTy = Context.DependentTy;
3639 else {
3640 // Pre-defined identifiers are of type char[x], where x is the length of
3641 // the string.
3642 bool ForceElaboratedPrinting =
3643 IK == PredefinedIdentKind::Function && getLangOpts().MSVCCompat;
3644 auto Str =
3645 PredefinedExpr::ComputeName(IK, CurrentDecl: currentDecl, ForceElaboratedPrinting);
3646 unsigned Length = Str.length();
3647
3648 llvm::APInt LengthI(32, Length + 1);
3649 if (IK == PredefinedIdentKind::LFunction ||
3650 IK == PredefinedIdentKind::LFuncSig) {
3651 ResTy =
3652 Context.adjustStringLiteralBaseType(StrLTy: Context.WideCharTy.withConst());
3653 SmallString<32> RawChars;
3654 ConvertUTF8ToWideString(CharByteWidth: Context.getTypeSizeInChars(T: ResTy).getQuantity(),
3655 Source: Str, Target&: RawChars);
3656 ResTy = Context.getConstantArrayType(EltTy: ResTy, ArySize: LengthI, SizeExpr: nullptr,
3657 ASM: ArraySizeModifier::Normal,
3658 /*IndexTypeQuals*/ 0);
3659 SL = StringLiteral::Create(Ctx: Context, Str: RawChars, Kind: StringLiteralKind::Wide,
3660 /*Pascal*/ false, Ty: ResTy, Locs: Loc);
3661 } else {
3662 ResTy = Context.adjustStringLiteralBaseType(StrLTy: Context.CharTy.withConst());
3663 ResTy = Context.getConstantArrayType(EltTy: ResTy, ArySize: LengthI, SizeExpr: nullptr,
3664 ASM: ArraySizeModifier::Normal,
3665 /*IndexTypeQuals*/ 0);
3666 SL = StringLiteral::Create(Ctx: Context, Str, Kind: StringLiteralKind::Ordinary,
3667 /*Pascal*/ false, Ty: ResTy, Locs: Loc);
3668 }
3669 }
3670
3671 return PredefinedExpr::Create(Ctx: Context, L: Loc, FNTy: ResTy, IK, IsTransparent: LangOpts.MicrosoftExt,
3672 SL);
3673}
3674
3675ExprResult Sema::ActOnPredefinedExpr(SourceLocation Loc, tok::TokenKind Kind) {
3676 return BuildPredefinedExpr(Loc, IK: getPredefinedExprKind(Kind));
3677}
3678
3679ExprResult Sema::ActOnCharacterConstant(const Token &Tok, Scope *UDLScope) {
3680 SmallString<16> CharBuffer;
3681 bool Invalid = false;
3682 StringRef ThisTok = PP.getSpelling(Tok, Buffer&: CharBuffer, Invalid: &Invalid);
3683 if (Invalid)
3684 return ExprError();
3685
3686 CharLiteralParser Literal(ThisTok.begin(), ThisTok.end(), Tok.getLocation(),
3687 PP, Tok.getKind());
3688 if (Literal.hadError())
3689 return ExprError();
3690
3691 QualType Ty;
3692 if (Literal.isWide())
3693 Ty = Context.WideCharTy; // L'x' -> wchar_t in C and C++.
3694 else if (Literal.isUTF8() && getLangOpts().C23)
3695 Ty = Context.UnsignedCharTy; // u8'x' -> unsigned char in C23
3696 else if (Literal.isUTF8() && getLangOpts().Char8)
3697 Ty = Context.Char8Ty; // u8'x' -> char8_t when it exists.
3698 else if (Literal.isUTF16())
3699 Ty = Context.Char16Ty; // u'x' -> char16_t in C11 and C++11.
3700 else if (Literal.isUTF32())
3701 Ty = Context.Char32Ty; // U'x' -> char32_t in C11 and C++11.
3702 else if (!getLangOpts().CPlusPlus || Literal.isMultiChar())
3703 Ty = Context.IntTy; // 'x' -> int in C, 'wxyz' -> int in C++.
3704 else
3705 Ty = Context.CharTy; // 'x' -> char in C++;
3706 // u8'x' -> char in C11-C17 and in C++ without char8_t.
3707
3708 CharacterLiteralKind Kind = CharacterLiteralKind::Ascii;
3709 if (Literal.isWide())
3710 Kind = CharacterLiteralKind::Wide;
3711 else if (Literal.isUTF16())
3712 Kind = CharacterLiteralKind::UTF16;
3713 else if (Literal.isUTF32())
3714 Kind = CharacterLiteralKind::UTF32;
3715 else if (Literal.isUTF8())
3716 Kind = CharacterLiteralKind::UTF8;
3717
3718 Expr *Lit = new (Context) CharacterLiteral(Literal.getValue(), Kind, Ty,
3719 Tok.getLocation());
3720
3721 if (Literal.getUDSuffix().empty())
3722 return Lit;
3723
3724 // We're building a user-defined literal.
3725 IdentifierInfo *UDSuffix = &Context.Idents.get(Name: Literal.getUDSuffix());
3726 SourceLocation UDSuffixLoc =
3727 getUDSuffixLoc(S&: *this, TokLoc: Tok.getLocation(), Offset: Literal.getUDSuffixOffset());
3728
3729 // Make sure we're allowed user-defined literals here.
3730 if (!UDLScope)
3731 return ExprError(Diag(Loc: UDSuffixLoc, DiagID: diag::err_invalid_character_udl));
3732
3733 // C++11 [lex.ext]p6: The literal L is treated as a call of the form
3734 // operator "" X (ch)
3735 return BuildCookedLiteralOperatorCall(S&: *this, Scope: UDLScope, UDSuffix, UDSuffixLoc,
3736 Args: Lit, LitEndLoc: Tok.getLocation());
3737}
3738
3739ExprResult Sema::ActOnIntegerConstant(SourceLocation Loc, int64_t Val) {
3740 unsigned IntSize = Context.getTargetInfo().getIntWidth();
3741 return IntegerLiteral::Create(C: Context,
3742 V: llvm::APInt(IntSize, Val, /*isSigned=*/true),
3743 type: Context.IntTy, l: Loc);
3744}
3745
3746ExprResult Sema::BuildBoolLiteral(SourceLocation Loc, bool Value) {
3747 ExprResult Inner;
3748 if (getLangOpts().CPlusPlus) {
3749 Inner = ActOnCXXBoolLiteral(OpLoc: Loc, Kind: Value ? tok::kw_true : tok::kw_false);
3750 } else {
3751 // C doesn't actually have a way to represent literal values of type
3752 // _Bool. So, we'll use 0/1 and implicit cast to _Bool.
3753 Inner = ActOnIntegerConstant(Loc, Val: Value ? 1 : 0);
3754 Inner =
3755 ImpCastExprToType(E: Inner.get(), Type: Context.BoolTy, CK: CK_IntegralToBoolean);
3756 }
3757 return Inner;
3758}
3759
3760static Expr *BuildFloatingLiteral(Sema &S, NumericLiteralParser &Literal,
3761 QualType Ty, SourceLocation Loc) {
3762 const llvm::fltSemantics &Format = S.Context.getFloatTypeSemantics(T: Ty);
3763
3764 using llvm::APFloat;
3765 APFloat Val(Format);
3766
3767 llvm::RoundingMode RM = S.CurFPFeatures.getRoundingMode();
3768 if (RM == llvm::RoundingMode::Dynamic)
3769 RM = llvm::RoundingMode::NearestTiesToEven;
3770 APFloat::opStatus result = Literal.GetFloatValue(Result&: Val, RM);
3771
3772 // Overflow is always an error, but underflow is only an error if
3773 // we underflowed to zero (APFloat reports denormals as underflow).
3774 if ((result & APFloat::opOverflow) ||
3775 ((result & APFloat::opUnderflow) && Val.isZero())) {
3776 unsigned diagnostic;
3777 SmallString<20> buffer;
3778 if (result & APFloat::opOverflow) {
3779 diagnostic = diag::warn_float_overflow;
3780 APFloat::getLargest(Sem: Format).toString(Str&: buffer);
3781 } else {
3782 diagnostic = diag::warn_float_underflow;
3783 APFloat::getSmallest(Sem: Format).toString(Str&: buffer);
3784 }
3785
3786 S.Diag(Loc, DiagID: diagnostic) << Ty << buffer.str();
3787 }
3788
3789 bool isExact = (result == APFloat::opOK);
3790 return FloatingLiteral::Create(C: S.Context, V: Val, isexact: isExact, Type: Ty, L: Loc);
3791}
3792
3793bool Sema::CheckLoopHintExpr(Expr *E, SourceLocation Loc, bool AllowZero) {
3794 assert(E && "Invalid expression");
3795
3796 if (E->isValueDependent())
3797 return false;
3798
3799 QualType QT = E->getType();
3800 if (!QT->isIntegerType() || QT->isBooleanType() || QT->isCharType()) {
3801 Diag(Loc: E->getExprLoc(), DiagID: diag::err_pragma_loop_invalid_argument_type) << QT;
3802 return true;
3803 }
3804
3805 llvm::APSInt ValueAPS;
3806 ExprResult R = VerifyIntegerConstantExpression(E, Result: &ValueAPS);
3807
3808 if (R.isInvalid())
3809 return true;
3810
3811 // GCC allows the value of unroll count to be 0.
3812 // https://gcc.gnu.org/onlinedocs/gcc/Loop-Specific-Pragmas.html says
3813 // "The values of 0 and 1 block any unrolling of the loop."
3814 // The values doesn't have to be strictly positive in '#pragma GCC unroll' and
3815 // '#pragma unroll' cases.
3816 bool ValueIsPositive =
3817 AllowZero ? ValueAPS.isNonNegative() : ValueAPS.isStrictlyPositive();
3818 if (!ValueIsPositive || ValueAPS.getActiveBits() > 31) {
3819 Diag(Loc: E->getExprLoc(), DiagID: diag::err_requires_positive_value)
3820 << toString(I: ValueAPS, Radix: 10) << ValueIsPositive;
3821 return true;
3822 }
3823
3824 return false;
3825}
3826
3827ExprResult Sema::ActOnNumericConstant(const Token &Tok, Scope *UDLScope) {
3828 // Fast path for a single digit (which is quite common). A single digit
3829 // cannot have a trigraph, escaped newline, radix prefix, or suffix.
3830 if (Tok.getLength() == 1 || Tok.getKind() == tok::binary_data) {
3831 const uint8_t Val = PP.getSpellingOfSingleCharacterNumericConstant(Tok);
3832 return ActOnIntegerConstant(Loc: Tok.getLocation(), Val);
3833 }
3834
3835 SmallString<128> SpellingBuffer;
3836 // NumericLiteralParser wants to overread by one character. Add padding to
3837 // the buffer in case the token is copied to the buffer. If getSpelling()
3838 // returns a StringRef to the memory buffer, it should have a null char at
3839 // the EOF, so it is also safe.
3840 SpellingBuffer.resize(N: Tok.getLength() + 1);
3841
3842 // Get the spelling of the token, which eliminates trigraphs, etc.
3843 bool Invalid = false;
3844 StringRef TokSpelling = PP.getSpelling(Tok, Buffer&: SpellingBuffer, Invalid: &Invalid);
3845 if (Invalid)
3846 return ExprError();
3847
3848 NumericLiteralParser Literal(TokSpelling, Tok.getLocation(),
3849 PP.getSourceManager(), PP.getLangOpts(),
3850 PP.getTargetInfo(), PP.getDiagnostics());
3851 if (Literal.hadError)
3852 return ExprError();
3853
3854 if (Literal.hasUDSuffix()) {
3855 // We're building a user-defined literal.
3856 const IdentifierInfo *UDSuffix = &Context.Idents.get(Name: Literal.getUDSuffix());
3857 SourceLocation UDSuffixLoc =
3858 getUDSuffixLoc(S&: *this, TokLoc: Tok.getLocation(), Offset: Literal.getUDSuffixOffset());
3859
3860 // Make sure we're allowed user-defined literals here.
3861 if (!UDLScope)
3862 return ExprError(Diag(Loc: UDSuffixLoc, DiagID: diag::err_invalid_numeric_udl));
3863
3864 QualType CookedTy;
3865 if (Literal.isFloatingLiteral()) {
3866 // C++11 [lex.ext]p4: If S contains a literal operator with parameter type
3867 // long double, the literal is treated as a call of the form
3868 // operator "" X (f L)
3869 CookedTy = Context.LongDoubleTy;
3870 } else {
3871 // C++11 [lex.ext]p3: If S contains a literal operator with parameter type
3872 // unsigned long long, the literal is treated as a call of the form
3873 // operator "" X (n ULL)
3874 CookedTy = Context.UnsignedLongLongTy;
3875 }
3876
3877 DeclarationName OpName =
3878 Context.DeclarationNames.getCXXLiteralOperatorName(II: UDSuffix);
3879 DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc);
3880 OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc);
3881
3882 SourceLocation TokLoc = Tok.getLocation();
3883
3884 // Perform literal operator lookup to determine if we're building a raw
3885 // literal or a cooked one.
3886 LookupResult R(*this, OpName, UDSuffixLoc, LookupOrdinaryName);
3887 switch (LookupLiteralOperator(S: UDLScope, R, ArgTys: CookedTy,
3888 /*AllowRaw*/ true, /*AllowTemplate*/ true,
3889 /*AllowStringTemplatePack*/ AllowStringTemplate: false,
3890 /*DiagnoseMissing*/ !Literal.isImaginary)) {
3891 case LOLR_ErrorNoDiagnostic:
3892 // Lookup failure for imaginary constants isn't fatal, there's still the
3893 // GNU extension producing _Complex types.
3894 break;
3895 case LOLR_Error:
3896 return ExprError();
3897 case LOLR_Cooked: {
3898 Expr *Lit;
3899 if (Literal.isFloatingLiteral()) {
3900 Lit = BuildFloatingLiteral(S&: *this, Literal, Ty: CookedTy, Loc: Tok.getLocation());
3901 } else {
3902 llvm::APInt ResultVal(Context.getTargetInfo().getLongLongWidth(), 0);
3903 if (Literal.GetIntegerValue(Val&: ResultVal))
3904 Diag(Loc: Tok.getLocation(), DiagID: diag::err_integer_literal_too_large)
3905 << /* Unsigned */ 1;
3906 Lit = IntegerLiteral::Create(C: Context, V: ResultVal, type: CookedTy,
3907 l: Tok.getLocation());
3908 }
3909 return BuildLiteralOperatorCall(R, SuffixInfo&: OpNameInfo, Args: Lit, LitEndLoc: TokLoc);
3910 }
3911
3912 case LOLR_Raw: {
3913 // C++11 [lit.ext]p3, p4: If S contains a raw literal operator, the
3914 // literal is treated as a call of the form
3915 // operator "" X ("n")
3916 unsigned Length = Literal.getUDSuffixOffset();
3917 QualType StrTy = Context.getConstantArrayType(
3918 EltTy: Context.adjustStringLiteralBaseType(StrLTy: Context.CharTy.withConst()),
3919 ArySize: llvm::APInt(32, Length + 1), SizeExpr: nullptr, ASM: ArraySizeModifier::Normal, IndexTypeQuals: 0);
3920 Expr *Lit =
3921 StringLiteral::Create(Ctx: Context, Str: StringRef(TokSpelling.data(), Length),
3922 Kind: StringLiteralKind::Ordinary,
3923 /*Pascal*/ false, Ty: StrTy, Locs: TokLoc);
3924 return BuildLiteralOperatorCall(R, SuffixInfo&: OpNameInfo, Args: Lit, LitEndLoc: TokLoc);
3925 }
3926
3927 case LOLR_Template: {
3928 // C++11 [lit.ext]p3, p4: Otherwise (S contains a literal operator
3929 // template), L is treated as a call fo the form
3930 // operator "" X <'c1', 'c2', ... 'ck'>()
3931 // where n is the source character sequence c1 c2 ... ck.
3932 TemplateArgumentListInfo ExplicitArgs;
3933 unsigned CharBits = Context.getIntWidth(T: Context.CharTy);
3934 bool CharIsUnsigned = Context.CharTy->isUnsignedIntegerType();
3935 llvm::APSInt Value(CharBits, CharIsUnsigned);
3936 for (unsigned I = 0, N = Literal.getUDSuffixOffset(); I != N; ++I) {
3937 Value = TokSpelling[I];
3938 TemplateArgument Arg(Context, Value, Context.CharTy);
3939 TemplateArgumentLocInfo ArgInfo(Context, TokLoc.getLocWithOffset(Offset: I));
3940 ExplicitArgs.addArgument(Loc: TemplateArgumentLoc(Arg, ArgInfo));
3941 }
3942 return BuildLiteralOperatorCall(R, SuffixInfo&: OpNameInfo, Args: {}, LitEndLoc: TokLoc, ExplicitTemplateArgs: &ExplicitArgs);
3943 }
3944 case LOLR_StringTemplatePack:
3945 llvm_unreachable("unexpected literal operator lookup result");
3946 }
3947 }
3948
3949 Expr *Res;
3950
3951 if (Literal.isFixedPointLiteral()) {
3952 QualType Ty;
3953
3954 if (Literal.isAccum) {
3955 if (Literal.isHalf) {
3956 Ty = Context.ShortAccumTy;
3957 } else if (Literal.isLong) {
3958 Ty = Context.LongAccumTy;
3959 } else {
3960 Ty = Context.AccumTy;
3961 }
3962 } else if (Literal.isFract) {
3963 if (Literal.isHalf) {
3964 Ty = Context.ShortFractTy;
3965 } else if (Literal.isLong) {
3966 Ty = Context.LongFractTy;
3967 } else {
3968 Ty = Context.FractTy;
3969 }
3970 }
3971
3972 if (Literal.isUnsigned) Ty = Context.getCorrespondingUnsignedType(T: Ty);
3973
3974 bool isSigned = !Literal.isUnsigned;
3975 unsigned scale = Context.getFixedPointScale(Ty);
3976 unsigned bit_width = Context.getTypeInfo(T: Ty).Width;
3977
3978 llvm::APInt Val(bit_width, 0, isSigned);
3979 bool Overflowed = Literal.GetFixedPointValue(StoreVal&: Val, Scale: scale);
3980 bool ValIsZero = Val.isZero() && !Overflowed;
3981
3982 auto MaxVal = Context.getFixedPointMax(Ty).getValue();
3983 if (Literal.isFract && Val == MaxVal + 1 && !ValIsZero)
3984 // Clause 6.4.4 - The value of a constant shall be in the range of
3985 // representable values for its type, with exception for constants of a
3986 // fract type with a value of exactly 1; such a constant shall denote
3987 // the maximal value for the type.
3988 --Val;
3989 else if (Val.ugt(RHS: MaxVal) || Overflowed)
3990 Diag(Loc: Tok.getLocation(), DiagID: diag::err_too_large_for_fixed_point);
3991
3992 Res = FixedPointLiteral::CreateFromRawInt(C: Context, V: Val, type: Ty,
3993 l: Tok.getLocation(), Scale: scale);
3994 } else if (Literal.isFloatingLiteral()) {
3995 QualType Ty;
3996 if (Literal.isHalf){
3997 if (getLangOpts().HLSL ||
3998 getOpenCLOptions().isAvailableOption(Ext: "cl_khr_fp16", LO: getLangOpts()))
3999 Ty = Context.HalfTy;
4000 else {
4001 Diag(Loc: Tok.getLocation(), DiagID: diag::err_half_const_requires_fp16);
4002 return ExprError();
4003 }
4004 } else if (Literal.isFloat)
4005 Ty = Context.FloatTy;
4006 else if (Literal.isLong)
4007 Ty = !getLangOpts().HLSL ? Context.LongDoubleTy : Context.DoubleTy;
4008 else if (Literal.isFloat16)
4009 Ty = Context.Float16Ty;
4010 else if (Literal.isFloat128)
4011 Ty = Context.Float128Ty;
4012 else if (getLangOpts().HLSL)
4013 Ty = Context.FloatTy;
4014 else
4015 Ty = Context.DoubleTy;
4016
4017 Res = BuildFloatingLiteral(S&: *this, Literal, Ty, Loc: Tok.getLocation());
4018
4019 if (Ty == Context.DoubleTy) {
4020 if (getLangOpts().SinglePrecisionConstants) {
4021 if (Ty->castAs<BuiltinType>()->getKind() != BuiltinType::Float) {
4022 Res = ImpCastExprToType(E: Res, Type: Context.FloatTy, CK: CK_FloatingCast).get();
4023 }
4024 } else if (getLangOpts().OpenCL && !getOpenCLOptions().isAvailableOption(
4025 Ext: "cl_khr_fp64", LO: getLangOpts())) {
4026 // Impose single-precision float type when cl_khr_fp64 is not enabled.
4027 Diag(Loc: Tok.getLocation(), DiagID: diag::warn_double_const_requires_fp64)
4028 << (getLangOpts().getOpenCLCompatibleVersion() >= 300);
4029 Res = ImpCastExprToType(E: Res, Type: Context.FloatTy, CK: CK_FloatingCast).get();
4030 }
4031 }
4032 } else if (!Literal.isIntegerLiteral()) {
4033 return ExprError();
4034 } else {
4035 QualType Ty;
4036
4037 // 'z/uz' literals are a C++23 feature.
4038 if (Literal.isSizeT)
4039 Diag(Loc: Tok.getLocation(), DiagID: getLangOpts().CPlusPlus
4040 ? getLangOpts().CPlusPlus23
4041 ? diag::warn_cxx20_compat_size_t_suffix
4042 : diag::ext_cxx23_size_t_suffix
4043 : diag::err_cxx23_size_t_suffix);
4044
4045 // 'wb/uwb' literals are a C23 feature. We support _BitInt as a type in C++,
4046 // but we do not currently support the suffix in C++ mode because it's not
4047 // entirely clear whether WG21 will prefer this suffix to return a library
4048 // type such as std::bit_int instead of returning a _BitInt. '__wb/__uwb'
4049 // literals are a C++ extension.
4050 if (Literal.isBitInt)
4051 PP.Diag(Loc: Tok.getLocation(),
4052 DiagID: getLangOpts().CPlusPlus ? diag::ext_cxx_bitint_suffix
4053 : getLangOpts().C23 ? diag::warn_c23_compat_bitint_suffix
4054 : diag::ext_c23_bitint_suffix);
4055
4056 // Get the value in the widest-possible width. What is "widest" depends on
4057 // whether the literal is a bit-precise integer or not. For a bit-precise
4058 // integer type, try to scan the source to determine how many bits are
4059 // needed to represent the value. This may seem a bit expensive, but trying
4060 // to get the integer value from an overly-wide APInt is *extremely*
4061 // expensive, so the naive approach of assuming
4062 // llvm::IntegerType::MAX_INT_BITS is a big performance hit.
4063 unsigned BitsNeeded = Context.getTargetInfo().getIntMaxTWidth();
4064 if (Literal.isBitInt)
4065 BitsNeeded = llvm::APInt::getSufficientBitsNeeded(
4066 Str: Literal.getLiteralDigits(), Radix: Literal.getRadix());
4067 if (Literal.MicrosoftInteger) {
4068 if (Literal.MicrosoftInteger == 128 &&
4069 !Context.getTargetInfo().hasInt128Type())
4070 PP.Diag(Loc: Tok.getLocation(), DiagID: diag::err_integer_literal_too_large)
4071 << Literal.isUnsigned;
4072 BitsNeeded = Literal.MicrosoftInteger;
4073 }
4074
4075 llvm::APInt ResultVal(BitsNeeded, 0);
4076
4077 if (Literal.GetIntegerValue(Val&: ResultVal)) {
4078 // If this value didn't fit into uintmax_t, error and force to ull.
4079 Diag(Loc: Tok.getLocation(), DiagID: diag::err_integer_literal_too_large)
4080 << /* Unsigned */ 1;
4081 Ty = Context.UnsignedLongLongTy;
4082 assert(Context.getTypeSize(Ty) == ResultVal.getBitWidth() &&
4083 "long long is not intmax_t?");
4084 } else {
4085 // If this value fits into a ULL, try to figure out what else it fits into
4086 // according to the rules of C99 6.4.4.1p5.
4087
4088 // Octal, Hexadecimal, and integers with a U suffix are allowed to
4089 // be an unsigned int.
4090 bool AllowUnsigned = Literal.isUnsigned || Literal.getRadix() != 10;
4091
4092 // HLSL doesn't really have `long` or `long long`. We support the `ll`
4093 // suffix for portability of code with C++, but both `l` and `ll` are
4094 // 64-bit integer types, and we want the type of `1l` and `1ll` to be the
4095 // same.
4096 if (getLangOpts().HLSL && !Literal.isLong && Literal.isLongLong) {
4097 Literal.isLong = true;
4098 Literal.isLongLong = false;
4099 }
4100
4101 // Check from smallest to largest, picking the smallest type we can.
4102 unsigned Width = 0;
4103
4104 // Microsoft specific integer suffixes are explicitly sized.
4105 if (Literal.MicrosoftInteger) {
4106 if (Literal.MicrosoftInteger == 8 && !Literal.isUnsigned) {
4107 Width = 8;
4108 Ty = Context.CharTy;
4109 } else {
4110 Width = Literal.MicrosoftInteger;
4111 Ty = Context.getIntTypeForBitwidth(DestWidth: Width,
4112 /*Signed=*/!Literal.isUnsigned);
4113 }
4114 }
4115
4116 // Bit-precise integer literals are automagically-sized based on the
4117 // width required by the literal.
4118 if (Literal.isBitInt) {
4119 // The signed version has one more bit for the sign value. There are no
4120 // zero-width bit-precise integers, even if the literal value is 0.
4121 Width = std::max(a: ResultVal.getActiveBits(), b: 1u) +
4122 (Literal.isUnsigned ? 0u : 1u);
4123
4124 // Diagnose if the width of the constant is larger than BITINT_MAXWIDTH,
4125 // and reset the type to the largest supported width.
4126 unsigned int MaxBitIntWidth =
4127 Context.getTargetInfo().getMaxBitIntWidth();
4128 if (Width > MaxBitIntWidth) {
4129 Diag(Loc: Tok.getLocation(), DiagID: diag::err_integer_literal_too_large)
4130 << Literal.isUnsigned;
4131 Width = MaxBitIntWidth;
4132 }
4133
4134 // Reset the result value to the smaller APInt and select the correct
4135 // type to be used. Note, we zext even for signed values because the
4136 // literal itself is always an unsigned value (a preceeding - is a
4137 // unary operator, not part of the literal).
4138 ResultVal = ResultVal.zextOrTrunc(width: Width);
4139 Ty = Context.getBitIntType(Unsigned: Literal.isUnsigned, NumBits: Width);
4140 }
4141
4142 // Check C++23 size_t literals.
4143 if (Literal.isSizeT) {
4144 assert(!Literal.MicrosoftInteger &&
4145 "size_t literals can't be Microsoft literals");
4146 unsigned SizeTSize = Context.getTargetInfo().getTypeWidth(
4147 T: Context.getTargetInfo().getSizeType());
4148
4149 // Does it fit in size_t?
4150 if (ResultVal.isIntN(N: SizeTSize)) {
4151 // Does it fit in ssize_t?
4152 if (!Literal.isUnsigned && ResultVal[SizeTSize - 1] == 0)
4153 Ty = Context.getSignedSizeType();
4154 else if (AllowUnsigned)
4155 Ty = Context.getSizeType();
4156 Width = SizeTSize;
4157 }
4158 }
4159
4160 if (Ty.isNull() && !Literal.isLong && !Literal.isLongLong &&
4161 !Literal.isSizeT) {
4162 // Are int/unsigned possibilities?
4163 unsigned IntSize = Context.getTargetInfo().getIntWidth();
4164
4165 // Does it fit in a unsigned int?
4166 if (ResultVal.isIntN(N: IntSize)) {
4167 // Does it fit in a signed int?
4168 if (!Literal.isUnsigned && ResultVal[IntSize-1] == 0)
4169 Ty = Context.IntTy;
4170 else if (AllowUnsigned)
4171 Ty = Context.UnsignedIntTy;
4172 Width = IntSize;
4173 }
4174 }
4175
4176 // Are long/unsigned long possibilities?
4177 if (Ty.isNull() && !Literal.isLongLong && !Literal.isSizeT) {
4178 unsigned LongSize = Context.getTargetInfo().getLongWidth();
4179
4180 // Does it fit in a unsigned long?
4181 if (ResultVal.isIntN(N: LongSize)) {
4182 // Does it fit in a signed long?
4183 if (!Literal.isUnsigned && ResultVal[LongSize-1] == 0)
4184 Ty = Context.LongTy;
4185 else if (AllowUnsigned)
4186 Ty = Context.UnsignedLongTy;
4187 // Check according to the rules of C90 6.1.3.2p5. C++03 [lex.icon]p2
4188 // is compatible.
4189 else if (!getLangOpts().C99 && !getLangOpts().CPlusPlus11) {
4190 const unsigned LongLongSize =
4191 Context.getTargetInfo().getLongLongWidth();
4192 Diag(Loc: Tok.getLocation(),
4193 DiagID: getLangOpts().CPlusPlus
4194 ? Literal.isLong
4195 ? diag::warn_old_implicitly_unsigned_long_cxx
4196 : /*C++98 UB*/ diag::
4197 ext_old_implicitly_unsigned_long_cxx
4198 : diag::warn_old_implicitly_unsigned_long)
4199 << (LongLongSize > LongSize ? /*will have type 'long long'*/ 0
4200 : /*will be ill-formed*/ 1);
4201 Ty = Context.UnsignedLongTy;
4202 }
4203 Width = LongSize;
4204 }
4205 }
4206
4207 // Check long long if needed.
4208 if (Ty.isNull() && !Literal.isSizeT) {
4209 unsigned LongLongSize = Context.getTargetInfo().getLongLongWidth();
4210
4211 // Does it fit in a unsigned long long?
4212 if (ResultVal.isIntN(N: LongLongSize)) {
4213 // Does it fit in a signed long long?
4214 // To be compatible with MSVC, hex integer literals ending with the
4215 // LL or i64 suffix are always signed in Microsoft mode.
4216 if (!Literal.isUnsigned && (ResultVal[LongLongSize-1] == 0 ||
4217 (getLangOpts().MSVCCompat && Literal.isLongLong)))
4218 Ty = Context.LongLongTy;
4219 else if (AllowUnsigned)
4220 Ty = Context.UnsignedLongLongTy;
4221 Width = LongLongSize;
4222
4223 // 'long long' is a C99 or C++11 feature, whether the literal
4224 // explicitly specified 'long long' or we needed the extra width.
4225 if (getLangOpts().CPlusPlus)
4226 Diag(Loc: Tok.getLocation(), DiagID: getLangOpts().CPlusPlus11
4227 ? diag::warn_cxx98_compat_longlong
4228 : diag::ext_cxx11_longlong);
4229 else if (!getLangOpts().C99)
4230 Diag(Loc: Tok.getLocation(), DiagID: diag::ext_c99_longlong);
4231 }
4232 }
4233
4234 // If we still couldn't decide a type, we either have 'size_t' literal
4235 // that is out of range, or a decimal literal that does not fit in a
4236 // signed long long and has no U suffix.
4237 if (Ty.isNull()) {
4238 if (Literal.isSizeT)
4239 Diag(Loc: Tok.getLocation(), DiagID: diag::err_size_t_literal_too_large)
4240 << Literal.isUnsigned;
4241 else
4242 Diag(Loc: Tok.getLocation(),
4243 DiagID: diag::ext_integer_literal_too_large_for_signed);
4244 Ty = Context.UnsignedLongLongTy;
4245 Width = Context.getTargetInfo().getLongLongWidth();
4246 }
4247
4248 if (ResultVal.getBitWidth() != Width)
4249 ResultVal = ResultVal.trunc(width: Width);
4250 }
4251 Res = IntegerLiteral::Create(C: Context, V: ResultVal, type: Ty, l: Tok.getLocation());
4252 }
4253
4254 // If this is an imaginary literal, create the ImaginaryLiteral wrapper.
4255 if (Literal.isImaginary) {
4256 Res = new (Context) ImaginaryLiteral(Res,
4257 Context.getComplexType(T: Res->getType()));
4258
4259 // In C++, this is a GNU extension. In C, it's a C2y extension.
4260 unsigned DiagId;
4261 if (getLangOpts().CPlusPlus)
4262 DiagId = diag::ext_gnu_imaginary_constant;
4263 else if (getLangOpts().C2y)
4264 DiagId = diag::warn_c23_compat_imaginary_constant;
4265 else
4266 DiagId = diag::ext_c2y_imaginary_constant;
4267 Diag(Loc: Tok.getLocation(), DiagID: DiagId);
4268 }
4269 return Res;
4270}
4271
4272ExprResult Sema::ActOnParenExpr(SourceLocation L, SourceLocation R, Expr *E) {
4273 assert(E && "ActOnParenExpr() missing expr");
4274 QualType ExprTy = E->getType();
4275 if (getLangOpts().ProtectParens && CurFPFeatures.getAllowFPReassociate() &&
4276 !E->isLValue() && ExprTy->hasFloatingRepresentation())
4277 return BuildBuiltinCallExpr(Loc: R, Id: Builtin::BI__arithmetic_fence, CallArgs: E);
4278 return new (Context) ParenExpr(L, R, E);
4279}
4280
4281static bool CheckVecStepTraitOperandType(Sema &S, QualType T,
4282 SourceLocation Loc,
4283 SourceRange ArgRange) {
4284 // [OpenCL 1.1 6.11.12] "The vec_step built-in function takes a built-in
4285 // scalar or vector data type argument..."
4286 // Every built-in scalar type (OpenCL 1.1 6.1.1) is either an arithmetic
4287 // type (C99 6.2.5p18) or void.
4288 if (!(T->isArithmeticType() || T->isVoidType() || T->isVectorType())) {
4289 S.Diag(Loc, DiagID: diag::err_vecstep_non_scalar_vector_type)
4290 << T << ArgRange;
4291 return true;
4292 }
4293
4294 assert((T->isVoidType() || !T->isIncompleteType()) &&
4295 "Scalar types should always be complete");
4296 return false;
4297}
4298
4299static bool CheckVectorElementsTraitOperandType(Sema &S, QualType T,
4300 SourceLocation Loc,
4301 SourceRange ArgRange) {
4302 // builtin_vectorelements supports both fixed-sized and scalable vectors.
4303 if (!T->isVectorType() && !T->isSizelessVectorType())
4304 return S.Diag(Loc, DiagID: diag::err_builtin_non_vector_type)
4305 << ""
4306 << "__builtin_vectorelements" << T << ArgRange;
4307
4308 if (auto *FD = dyn_cast<FunctionDecl>(Val: S.CurContext)) {
4309 if (T->isSVESizelessBuiltinType()) {
4310 llvm::StringMap<bool> CallerFeatureMap;
4311 S.Context.getFunctionFeatureMap(FeatureMap&: CallerFeatureMap, FD);
4312 return S.ARM().checkSVETypeSupport(Ty: T, Loc, FD, FeatureMap: CallerFeatureMap);
4313 }
4314 }
4315
4316 return false;
4317}
4318
4319static bool checkPtrAuthTypeDiscriminatorOperandType(Sema &S, QualType T,
4320 SourceLocation Loc,
4321 SourceRange ArgRange) {
4322 if (S.checkPointerAuthEnabled(Loc, Range: ArgRange))
4323 return true;
4324
4325 if (!T->isFunctionType() && !T->isFunctionPointerType() &&
4326 !T->isFunctionReferenceType() && !T->isMemberFunctionPointerType()) {
4327 S.Diag(Loc, DiagID: diag::err_ptrauth_type_disc_undiscriminated) << T << ArgRange;
4328 return true;
4329 }
4330
4331 return false;
4332}
4333
4334static bool CheckExtensionTraitOperandType(Sema &S, QualType T,
4335 SourceLocation Loc,
4336 SourceRange ArgRange,
4337 UnaryExprOrTypeTrait TraitKind) {
4338 // Invalid types must be hard errors for SFINAE in C++.
4339 if (S.LangOpts.CPlusPlus)
4340 return true;
4341
4342 // C99 6.5.3.4p1:
4343 if (TraitKind == UETT_SizeOf || TraitKind == UETT_AlignOf ||
4344 TraitKind == UETT_PreferredAlignOf) {
4345
4346 // sizeof(function)/alignof(function) is allowed as an extension.
4347 if (T->isFunctionType()) {
4348 S.Diag(Loc, DiagID: diag::ext_sizeof_alignof_function_type)
4349 << getTraitSpelling(T: TraitKind) << ArgRange;
4350 return false;
4351 }
4352
4353 // Allow sizeof(void)/alignof(void) as an extension, unless in OpenCL where
4354 // this is an error (OpenCL v1.1 s6.3.k)
4355 if (T->isVoidType()) {
4356 unsigned DiagID = S.LangOpts.OpenCL ? diag::err_opencl_sizeof_alignof_type
4357 : diag::ext_sizeof_alignof_void_type;
4358 S.Diag(Loc, DiagID) << getTraitSpelling(T: TraitKind) << ArgRange;
4359 return false;
4360 }
4361 }
4362 return true;
4363}
4364
4365static bool CheckObjCTraitOperandConstraints(Sema &S, QualType T,
4366 SourceLocation Loc,
4367 SourceRange ArgRange,
4368 UnaryExprOrTypeTrait TraitKind) {
4369 // Reject sizeof(interface) and sizeof(interface<proto>) if the
4370 // runtime doesn't allow it.
4371 if (!S.LangOpts.ObjCRuntime.allowsSizeofAlignof() && T->isObjCObjectType()) {
4372 S.Diag(Loc, DiagID: diag::err_sizeof_nonfragile_interface)
4373 << T << (TraitKind == UETT_SizeOf)
4374 << ArgRange;
4375 return true;
4376 }
4377
4378 return false;
4379}
4380
4381/// Check whether E is a pointer from a decayed array type (the decayed
4382/// pointer type is equal to T) and emit a warning if it is.
4383static void warnOnSizeofOnArrayDecay(Sema &S, SourceLocation Loc, QualType T,
4384 const Expr *E) {
4385 // Don't warn if the operation changed the type.
4386 if (T != E->getType())
4387 return;
4388
4389 // Now look for array decays.
4390 const auto *ICE = dyn_cast<ImplicitCastExpr>(Val: E);
4391 if (!ICE || ICE->getCastKind() != CK_ArrayToPointerDecay)
4392 return;
4393
4394 S.Diag(Loc, DiagID: diag::warn_sizeof_array_decay) << ICE->getSourceRange()
4395 << ICE->getType()
4396 << ICE->getSubExpr()->getType();
4397}
4398
4399bool Sema::CheckUnaryExprOrTypeTraitOperand(Expr *E,
4400 UnaryExprOrTypeTrait ExprKind) {
4401 QualType ExprTy = E->getType();
4402 assert(!ExprTy->isReferenceType());
4403
4404 bool IsUnevaluatedOperand =
4405 (ExprKind == UETT_SizeOf || ExprKind == UETT_DataSizeOf ||
4406 ExprKind == UETT_AlignOf || ExprKind == UETT_PreferredAlignOf ||
4407 ExprKind == UETT_VecStep || ExprKind == UETT_CountOf);
4408 if (IsUnevaluatedOperand) {
4409 ExprResult Result = CheckUnevaluatedOperand(E);
4410 if (Result.isInvalid())
4411 return true;
4412 E = Result.get();
4413 }
4414
4415 // The operand for sizeof and alignof is in an unevaluated expression context,
4416 // so side effects could result in unintended consequences.
4417 // Exclude instantiation-dependent expressions, because 'sizeof' is sometimes
4418 // used to build SFINAE gadgets.
4419 // FIXME: Should we consider instantiation-dependent operands to 'alignof'?
4420 if (IsUnevaluatedOperand && !inTemplateInstantiation() &&
4421 !E->isInstantiationDependent() &&
4422 !E->getType()->isVariableArrayType() &&
4423 E->HasSideEffects(Ctx: Context, IncludePossibleEffects: false))
4424 Diag(Loc: E->getExprLoc(), DiagID: diag::warn_side_effects_unevaluated_context);
4425
4426 if (ExprKind == UETT_VecStep)
4427 return CheckVecStepTraitOperandType(S&: *this, T: ExprTy, Loc: E->getExprLoc(),
4428 ArgRange: E->getSourceRange());
4429
4430 if (ExprKind == UETT_VectorElements)
4431 return CheckVectorElementsTraitOperandType(S&: *this, T: ExprTy, Loc: E->getExprLoc(),
4432 ArgRange: E->getSourceRange());
4433
4434 // Explicitly list some types as extensions.
4435 if (!CheckExtensionTraitOperandType(S&: *this, T: ExprTy, Loc: E->getExprLoc(),
4436 ArgRange: E->getSourceRange(), TraitKind: ExprKind))
4437 return false;
4438
4439 // WebAssembly tables are always illegal operands to unary expressions and
4440 // type traits.
4441 if (Context.getTargetInfo().getTriple().isWasm() &&
4442 E->getType()->isWebAssemblyTableType()) {
4443 Diag(Loc: E->getExprLoc(), DiagID: diag::err_wasm_table_invalid_uett_operand)
4444 << getTraitSpelling(T: ExprKind);
4445 return true;
4446 }
4447
4448 // 'alignof' applied to an expression only requires the base element type of
4449 // the expression to be complete. 'sizeof' requires the expression's type to
4450 // be complete (and will attempt to complete it if it's an array of unknown
4451 // bound).
4452 if (ExprKind == UETT_AlignOf || ExprKind == UETT_PreferredAlignOf) {
4453 if (RequireCompleteSizedType(
4454 Loc: E->getExprLoc(), T: Context.getBaseElementType(QT: E->getType()),
4455 DiagID: diag::err_sizeof_alignof_incomplete_or_sizeless_type,
4456 Args: getTraitSpelling(T: ExprKind), Args: E->getSourceRange()))
4457 return true;
4458 } else {
4459 if (RequireCompleteSizedExprType(
4460 E, DiagID: diag::err_sizeof_alignof_incomplete_or_sizeless_type,
4461 Args: getTraitSpelling(T: ExprKind), Args: E->getSourceRange()))
4462 return true;
4463 }
4464
4465 // Completing the expression's type may have changed it.
4466 ExprTy = E->getType();
4467 assert(!ExprTy->isReferenceType());
4468
4469 if (ExprTy->isFunctionType()) {
4470 Diag(Loc: E->getExprLoc(), DiagID: diag::err_sizeof_alignof_function_type)
4471 << getTraitSpelling(T: ExprKind) << E->getSourceRange();
4472 return true;
4473 }
4474
4475 if (CheckObjCTraitOperandConstraints(S&: *this, T: ExprTy, Loc: E->getExprLoc(),
4476 ArgRange: E->getSourceRange(), TraitKind: ExprKind))
4477 return true;
4478
4479 if (ExprKind == UETT_CountOf) {
4480 // The type has to be an array type. We already checked for incomplete
4481 // types above.
4482 QualType ExprType = E->IgnoreParens()->getType();
4483 if (!ExprType->isArrayType()) {
4484 Diag(Loc: E->getExprLoc(), DiagID: diag::err_countof_arg_not_array_type) << ExprType;
4485 return true;
4486 }
4487 // FIXME: warn on _Countof on an array parameter. Not warning on it
4488 // currently because there are papers in WG14 about array types which do
4489 // not decay that could impact this behavior, so we want to see if anything
4490 // changes here before coming up with a warning group for _Countof-related
4491 // diagnostics.
4492 }
4493
4494 if (ExprKind == UETT_SizeOf) {
4495 if (const auto *DeclRef = dyn_cast<DeclRefExpr>(Val: E->IgnoreParens())) {
4496 if (const auto *PVD = dyn_cast<ParmVarDecl>(Val: DeclRef->getFoundDecl())) {
4497 QualType OType = PVD->getOriginalType();
4498 QualType Type = PVD->getType();
4499 if (Type->isPointerType() && OType->isArrayType()) {
4500 Diag(Loc: E->getExprLoc(), DiagID: diag::warn_sizeof_array_param)
4501 << Type << OType;
4502 Diag(Loc: PVD->getLocation(), DiagID: diag::note_declared_at);
4503 }
4504 }
4505 }
4506
4507 // Warn on "sizeof(array op x)" and "sizeof(x op array)", where the array
4508 // decays into a pointer and returns an unintended result. This is most
4509 // likely a typo for "sizeof(array) op x".
4510 if (const auto *BO = dyn_cast<BinaryOperator>(Val: E->IgnoreParens())) {
4511 warnOnSizeofOnArrayDecay(S&: *this, Loc: BO->getOperatorLoc(), T: BO->getType(),
4512 E: BO->getLHS());
4513 warnOnSizeofOnArrayDecay(S&: *this, Loc: BO->getOperatorLoc(), T: BO->getType(),
4514 E: BO->getRHS());
4515 }
4516 }
4517
4518 return false;
4519}
4520
4521static bool CheckAlignOfExpr(Sema &S, Expr *E, UnaryExprOrTypeTrait ExprKind) {
4522 // Cannot know anything else if the expression is dependent.
4523 if (E->isTypeDependent())
4524 return false;
4525
4526 if (E->getObjectKind() == OK_BitField) {
4527 S.Diag(Loc: E->getExprLoc(), DiagID: diag::err_sizeof_alignof_typeof_bitfield)
4528 << 1 << E->getSourceRange();
4529 return true;
4530 }
4531
4532 ValueDecl *D = nullptr;
4533 Expr *Inner = E->IgnoreParens();
4534 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Val: Inner)) {
4535 D = DRE->getDecl();
4536 } else if (MemberExpr *ME = dyn_cast<MemberExpr>(Val: Inner)) {
4537 D = ME->getMemberDecl();
4538 }
4539
4540 // If it's a field, require the containing struct to have a
4541 // complete definition so that we can compute the layout.
4542 //
4543 // This can happen in C++11 onwards, either by naming the member
4544 // in a way that is not transformed into a member access expression
4545 // (in an unevaluated operand, for instance), or by naming the member
4546 // in a trailing-return-type.
4547 //
4548 // For the record, since __alignof__ on expressions is a GCC
4549 // extension, GCC seems to permit this but always gives the
4550 // nonsensical answer 0.
4551 //
4552 // We don't really need the layout here --- we could instead just
4553 // directly check for all the appropriate alignment-lowing
4554 // attributes --- but that would require duplicating a lot of
4555 // logic that just isn't worth duplicating for such a marginal
4556 // use-case.
4557 if (FieldDecl *FD = dyn_cast_or_null<FieldDecl>(Val: D)) {
4558 // Fast path this check, since we at least know the record has a
4559 // definition if we can find a member of it.
4560 if (!FD->getParent()->isCompleteDefinition()) {
4561 S.Diag(Loc: E->getExprLoc(), DiagID: diag::err_alignof_member_of_incomplete_type)
4562 << E->getSourceRange();
4563 return true;
4564 }
4565
4566 // Otherwise, if it's a field, and the field doesn't have
4567 // reference type, then it must have a complete type (or be a
4568 // flexible array member, which we explicitly want to
4569 // white-list anyway), which makes the following checks trivial.
4570 if (!FD->getType()->isReferenceType())
4571 return false;
4572 }
4573
4574 return S.CheckUnaryExprOrTypeTraitOperand(E, ExprKind);
4575}
4576
4577bool Sema::CheckVecStepExpr(Expr *E) {
4578 E = E->IgnoreParens();
4579
4580 // Cannot know anything else if the expression is dependent.
4581 if (E->isTypeDependent())
4582 return false;
4583
4584 return CheckUnaryExprOrTypeTraitOperand(E, ExprKind: UETT_VecStep);
4585}
4586
4587static void captureVariablyModifiedType(ASTContext &Context, QualType T,
4588 CapturingScopeInfo *CSI) {
4589 assert(T->isVariablyModifiedType());
4590 assert(CSI != nullptr);
4591
4592 // We're going to walk down into the type and look for VLA expressions.
4593 do {
4594 const Type *Ty = T.getTypePtr();
4595 switch (Ty->getTypeClass()) {
4596#define TYPE(Class, Base)
4597#define ABSTRACT_TYPE(Class, Base)
4598#define NON_CANONICAL_TYPE(Class, Base)
4599#define DEPENDENT_TYPE(Class, Base) case Type::Class:
4600#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base)
4601#include "clang/AST/TypeNodes.inc"
4602 T = QualType();
4603 break;
4604 // These types are never variably-modified.
4605 case Type::Builtin:
4606 case Type::Complex:
4607 case Type::Vector:
4608 case Type::ExtVector:
4609 case Type::ConstantMatrix:
4610 case Type::Record:
4611 case Type::Enum:
4612 case Type::TemplateSpecialization:
4613 case Type::ObjCObject:
4614 case Type::ObjCInterface:
4615 case Type::ObjCObjectPointer:
4616 case Type::ObjCTypeParam:
4617 case Type::Pipe:
4618 case Type::BitInt:
4619 case Type::HLSLInlineSpirv:
4620 llvm_unreachable("type class is never variably-modified!");
4621 case Type::Adjusted:
4622 T = cast<AdjustedType>(Val: Ty)->getOriginalType();
4623 break;
4624 case Type::Decayed:
4625 T = cast<DecayedType>(Val: Ty)->getPointeeType();
4626 break;
4627 case Type::ArrayParameter:
4628 T = cast<ArrayParameterType>(Val: Ty)->getElementType();
4629 break;
4630 case Type::Pointer:
4631 T = cast<PointerType>(Val: Ty)->getPointeeType();
4632 break;
4633 case Type::BlockPointer:
4634 T = cast<BlockPointerType>(Val: Ty)->getPointeeType();
4635 break;
4636 case Type::LValueReference:
4637 case Type::RValueReference:
4638 T = cast<ReferenceType>(Val: Ty)->getPointeeType();
4639 break;
4640 case Type::MemberPointer:
4641 T = cast<MemberPointerType>(Val: Ty)->getPointeeType();
4642 break;
4643 case Type::ConstantArray:
4644 case Type::IncompleteArray:
4645 // Losing element qualification here is fine.
4646 T = cast<ArrayType>(Val: Ty)->getElementType();
4647 break;
4648 case Type::VariableArray: {
4649 // Losing element qualification here is fine.
4650 const VariableArrayType *VAT = cast<VariableArrayType>(Val: Ty);
4651
4652 // Unknown size indication requires no size computation.
4653 // Otherwise, evaluate and record it.
4654 auto Size = VAT->getSizeExpr();
4655 if (Size && !CSI->isVLATypeCaptured(VAT) &&
4656 (isa<CapturedRegionScopeInfo>(Val: CSI) || isa<LambdaScopeInfo>(Val: CSI)))
4657 CSI->addVLATypeCapture(Loc: Size->getExprLoc(), VLAType: VAT, CaptureType: Context.getSizeType());
4658
4659 T = VAT->getElementType();
4660 break;
4661 }
4662 case Type::FunctionProto:
4663 case Type::FunctionNoProto:
4664 T = cast<FunctionType>(Val: Ty)->getReturnType();
4665 break;
4666 case Type::Paren:
4667 case Type::TypeOf:
4668 case Type::UnaryTransform:
4669 case Type::Attributed:
4670 case Type::BTFTagAttributed:
4671 case Type::OverflowBehavior:
4672 case Type::HLSLAttributedResource:
4673 case Type::SubstTemplateTypeParm:
4674 case Type::MacroQualified:
4675 case Type::CountAttributed:
4676 // Keep walking after single level desugaring.
4677 T = T.getSingleStepDesugaredType(Context);
4678 break;
4679 case Type::Typedef:
4680 T = cast<TypedefType>(Val: Ty)->desugar();
4681 break;
4682 case Type::Decltype:
4683 T = cast<DecltypeType>(Val: Ty)->desugar();
4684 break;
4685 case Type::PackIndexing:
4686 T = cast<PackIndexingType>(Val: Ty)->desugar();
4687 break;
4688 case Type::Using:
4689 T = cast<UsingType>(Val: Ty)->desugar();
4690 break;
4691 case Type::Auto:
4692 case Type::DeducedTemplateSpecialization:
4693 T = cast<DeducedType>(Val: Ty)->getDeducedType();
4694 break;
4695 case Type::TypeOfExpr:
4696 T = cast<TypeOfExprType>(Val: Ty)->getUnderlyingExpr()->getType();
4697 break;
4698 case Type::Atomic:
4699 T = cast<AtomicType>(Val: Ty)->getValueType();
4700 break;
4701 case Type::PredefinedSugar:
4702 T = cast<PredefinedSugarType>(Val: Ty)->desugar();
4703 break;
4704 }
4705 } while (!T.isNull() && T->isVariablyModifiedType());
4706}
4707
4708bool Sema::CheckUnaryExprOrTypeTraitOperand(QualType ExprType,
4709 SourceLocation OpLoc,
4710 SourceRange ExprRange,
4711 UnaryExprOrTypeTrait ExprKind,
4712 StringRef KWName) {
4713 if (ExprType->isDependentType())
4714 return false;
4715
4716 // C++ [expr.sizeof]p2:
4717 // When applied to a reference or a reference type, the result
4718 // is the size of the referenced type.
4719 // C++11 [expr.alignof]p3:
4720 // When alignof is applied to a reference type, the result
4721 // shall be the alignment of the referenced type.
4722 if (const ReferenceType *Ref = ExprType->getAs<ReferenceType>())
4723 ExprType = Ref->getPointeeType();
4724
4725 // C11 6.5.3.4/3, C++11 [expr.alignof]p3:
4726 // When alignof or _Alignof is applied to an array type, the result
4727 // is the alignment of the element type.
4728 if (ExprKind == UETT_AlignOf || ExprKind == UETT_PreferredAlignOf ||
4729 ExprKind == UETT_OpenMPRequiredSimdAlign) {
4730 // If the trait is 'alignof' in C before C2y, the ability to apply the
4731 // trait to an incomplete array is an extension.
4732 if (ExprKind == UETT_AlignOf && !getLangOpts().CPlusPlus &&
4733 ExprType->isIncompleteArrayType())
4734 Diag(Loc: OpLoc, DiagID: getLangOpts().C2y
4735 ? diag::warn_c2y_compat_alignof_incomplete_array
4736 : diag::ext_c2y_alignof_incomplete_array);
4737 ExprType = Context.getBaseElementType(QT: ExprType);
4738 }
4739
4740 if (ExprKind == UETT_VecStep)
4741 return CheckVecStepTraitOperandType(S&: *this, T: ExprType, Loc: OpLoc, ArgRange: ExprRange);
4742
4743 if (ExprKind == UETT_VectorElements)
4744 return CheckVectorElementsTraitOperandType(S&: *this, T: ExprType, Loc: OpLoc,
4745 ArgRange: ExprRange);
4746
4747 if (ExprKind == UETT_PtrAuthTypeDiscriminator)
4748 return checkPtrAuthTypeDiscriminatorOperandType(S&: *this, T: ExprType, Loc: OpLoc,
4749 ArgRange: ExprRange);
4750
4751 // Explicitly list some types as extensions.
4752 if (!CheckExtensionTraitOperandType(S&: *this, T: ExprType, Loc: OpLoc, ArgRange: ExprRange,
4753 TraitKind: ExprKind))
4754 return false;
4755
4756 if (RequireCompleteSizedType(
4757 Loc: OpLoc, T: ExprType, DiagID: diag::err_sizeof_alignof_incomplete_or_sizeless_type,
4758 Args: KWName, Args: ExprRange))
4759 return true;
4760
4761 if (ExprType->isFunctionType()) {
4762 Diag(Loc: OpLoc, DiagID: diag::err_sizeof_alignof_function_type) << KWName << ExprRange;
4763 return true;
4764 }
4765
4766 if (ExprKind == UETT_CountOf) {
4767 // The type has to be an array type. We already checked for incomplete
4768 // types above.
4769 if (!ExprType->isArrayType()) {
4770 Diag(Loc: OpLoc, DiagID: diag::err_countof_arg_not_array_type) << ExprType;
4771 return true;
4772 }
4773 }
4774
4775 // WebAssembly tables are always illegal operands to unary expressions and
4776 // type traits.
4777 if (Context.getTargetInfo().getTriple().isWasm() &&
4778 ExprType->isWebAssemblyTableType()) {
4779 Diag(Loc: OpLoc, DiagID: diag::err_wasm_table_invalid_uett_operand)
4780 << getTraitSpelling(T: ExprKind);
4781 return true;
4782 }
4783
4784 if (CheckObjCTraitOperandConstraints(S&: *this, T: ExprType, Loc: OpLoc, ArgRange: ExprRange,
4785 TraitKind: ExprKind))
4786 return true;
4787
4788 if (ExprType->isVariablyModifiedType() && FunctionScopes.size() > 1) {
4789 if (auto *TT = ExprType->getAs<TypedefType>()) {
4790 for (auto I = FunctionScopes.rbegin(),
4791 E = std::prev(x: FunctionScopes.rend());
4792 I != E; ++I) {
4793 auto *CSI = dyn_cast<CapturingScopeInfo>(Val: *I);
4794 if (CSI == nullptr)
4795 break;
4796 DeclContext *DC = nullptr;
4797 if (auto *LSI = dyn_cast<LambdaScopeInfo>(Val: CSI))
4798 DC = LSI->CallOperator;
4799 else if (auto *CRSI = dyn_cast<CapturedRegionScopeInfo>(Val: CSI))
4800 DC = CRSI->TheCapturedDecl;
4801 else if (auto *BSI = dyn_cast<BlockScopeInfo>(Val: CSI))
4802 DC = BSI->TheDecl;
4803 if (DC) {
4804 if (DC->containsDecl(D: TT->getDecl()))
4805 break;
4806 captureVariablyModifiedType(Context, T: ExprType, CSI);
4807 }
4808 }
4809 }
4810 }
4811
4812 return false;
4813}
4814
4815ExprResult Sema::CreateUnaryExprOrTypeTraitExpr(TypeSourceInfo *TInfo,
4816 SourceLocation OpLoc,
4817 UnaryExprOrTypeTrait ExprKind,
4818 SourceRange R) {
4819 if (!TInfo)
4820 return ExprError();
4821
4822 QualType T = TInfo->getType();
4823
4824 if (!T->isDependentType() &&
4825 CheckUnaryExprOrTypeTraitOperand(ExprType: T, OpLoc, ExprRange: R, ExprKind,
4826 KWName: getTraitSpelling(T: ExprKind)))
4827 return ExprError();
4828
4829 // Adds overload of TransformToPotentiallyEvaluated for TypeSourceInfo to
4830 // properly deal with VLAs in nested calls of sizeof and typeof.
4831 if (currentEvaluationContext().isUnevaluated() &&
4832 currentEvaluationContext().InConditionallyConstantEvaluateContext &&
4833 (ExprKind == UETT_SizeOf || ExprKind == UETT_CountOf) &&
4834 TInfo->getType()->isVariablyModifiedType())
4835 TInfo = TransformToPotentiallyEvaluated(TInfo);
4836
4837 // It's possible that the transformation above failed.
4838 if (!TInfo)
4839 return ExprError();
4840
4841 // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t.
4842 return new (Context) UnaryExprOrTypeTraitExpr(
4843 ExprKind, TInfo, Context.getSizeType(), OpLoc, R.getEnd());
4844}
4845
4846ExprResult
4847Sema::CreateUnaryExprOrTypeTraitExpr(Expr *E, SourceLocation OpLoc,
4848 UnaryExprOrTypeTrait ExprKind) {
4849 ExprResult PE = CheckPlaceholderExpr(E);
4850 if (PE.isInvalid())
4851 return ExprError();
4852
4853 E = PE.get();
4854
4855 // Verify that the operand is valid.
4856 bool isInvalid = false;
4857 if (E->isTypeDependent()) {
4858 // Delay type-checking for type-dependent expressions.
4859 } else if (ExprKind == UETT_AlignOf || ExprKind == UETT_PreferredAlignOf) {
4860 isInvalid = CheckAlignOfExpr(S&: *this, E, ExprKind);
4861 } else if (ExprKind == UETT_VecStep) {
4862 isInvalid = CheckVecStepExpr(E);
4863 } else if (ExprKind == UETT_OpenMPRequiredSimdAlign) {
4864 Diag(Loc: E->getExprLoc(), DiagID: diag::err_openmp_default_simd_align_expr);
4865 isInvalid = true;
4866 } else if (E->refersToBitField()) { // C99 6.5.3.4p1.
4867 Diag(Loc: E->getExprLoc(), DiagID: diag::err_sizeof_alignof_typeof_bitfield) << 0;
4868 isInvalid = true;
4869 } else if (ExprKind == UETT_VectorElements || ExprKind == UETT_SizeOf ||
4870 ExprKind == UETT_CountOf) { // FIXME: __datasizeof?
4871 isInvalid = CheckUnaryExprOrTypeTraitOperand(E, ExprKind);
4872 }
4873
4874 if (isInvalid)
4875 return ExprError();
4876
4877 if ((ExprKind == UETT_SizeOf || ExprKind == UETT_CountOf) &&
4878 E->getType()->isVariableArrayType()) {
4879 PE = TransformToPotentiallyEvaluated(E);
4880 if (PE.isInvalid()) return ExprError();
4881 E = PE.get();
4882 }
4883
4884 // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t.
4885 return new (Context) UnaryExprOrTypeTraitExpr(
4886 ExprKind, E, Context.getSizeType(), OpLoc, E->getSourceRange().getEnd());
4887}
4888
4889ExprResult
4890Sema::ActOnUnaryExprOrTypeTraitExpr(SourceLocation OpLoc,
4891 UnaryExprOrTypeTrait ExprKind, bool IsType,
4892 void *TyOrEx, SourceRange ArgRange) {
4893 // If error parsing type, ignore.
4894 if (!TyOrEx) return ExprError();
4895
4896 if (IsType) {
4897 TypeSourceInfo *TInfo;
4898 (void) GetTypeFromParser(Ty: ParsedType::getFromOpaquePtr(P: TyOrEx), TInfo: &TInfo);
4899 return CreateUnaryExprOrTypeTraitExpr(TInfo, OpLoc, ExprKind, R: ArgRange);
4900 }
4901
4902 Expr *ArgEx = (Expr *)TyOrEx;
4903 ExprResult Result = CreateUnaryExprOrTypeTraitExpr(E: ArgEx, OpLoc, ExprKind);
4904 return Result;
4905}
4906
4907bool Sema::CheckAlignasTypeArgument(StringRef KWName, TypeSourceInfo *TInfo,
4908 SourceLocation OpLoc, SourceRange R) {
4909 if (!TInfo)
4910 return true;
4911 return CheckUnaryExprOrTypeTraitOperand(ExprType: TInfo->getType(), OpLoc, ExprRange: R,
4912 ExprKind: UETT_AlignOf, KWName);
4913}
4914
4915bool Sema::ActOnAlignasTypeArgument(StringRef KWName, ParsedType Ty,
4916 SourceLocation OpLoc, SourceRange R) {
4917 TypeSourceInfo *TInfo;
4918 (void)GetTypeFromParser(Ty: ParsedType::getFromOpaquePtr(P: Ty.getAsOpaquePtr()),
4919 TInfo: &TInfo);
4920 return CheckAlignasTypeArgument(KWName, TInfo, OpLoc, R);
4921}
4922
4923static QualType CheckRealImagOperand(Sema &S, ExprResult &V, SourceLocation Loc,
4924 bool IsReal) {
4925 if (V.get()->isTypeDependent())
4926 return S.Context.DependentTy;
4927
4928 // _Real and _Imag are only l-values for normal l-values.
4929 if (V.get()->getObjectKind() != OK_Ordinary) {
4930 V = S.DefaultLvalueConversion(E: V.get());
4931 if (V.isInvalid())
4932 return QualType();
4933 }
4934
4935 // These operators return the element type of a complex type.
4936 if (const ComplexType *CT = V.get()->getType()->getAs<ComplexType>())
4937 return CT->getElementType();
4938
4939 // Otherwise they pass through real integer and floating point types here.
4940 if (V.get()->getType()->isArithmeticType())
4941 return V.get()->getType();
4942
4943 // Test for placeholders.
4944 ExprResult PR = S.CheckPlaceholderExpr(E: V.get());
4945 if (PR.isInvalid()) return QualType();
4946 if (PR.get() != V.get()) {
4947 V = PR;
4948 return CheckRealImagOperand(S, V, Loc, IsReal);
4949 }
4950
4951 // Reject anything else.
4952 S.Diag(Loc, DiagID: diag::err_realimag_invalid_type) << V.get()->getType()
4953 << (IsReal ? "__real" : "__imag");
4954 return QualType();
4955}
4956
4957
4958
4959ExprResult
4960Sema::ActOnPostfixUnaryOp(Scope *S, SourceLocation OpLoc,
4961 tok::TokenKind Kind, Expr *Input) {
4962 UnaryOperatorKind Opc;
4963 switch (Kind) {
4964 default: llvm_unreachable("Unknown unary op!");
4965 case tok::plusplus: Opc = UO_PostInc; break;
4966 case tok::minusminus: Opc = UO_PostDec; break;
4967 }
4968
4969 // Since this might is a postfix expression, get rid of ParenListExprs.
4970 ExprResult Result = MaybeConvertParenListExprToParenExpr(S, ME: Input);
4971 if (Result.isInvalid()) return ExprError();
4972 Input = Result.get();
4973
4974 return BuildUnaryOp(S, OpLoc, Opc, Input);
4975}
4976
4977/// Diagnose if arithmetic on the given ObjC pointer is illegal.
4978///
4979/// \return true on error
4980static bool checkArithmeticOnObjCPointer(Sema &S,
4981 SourceLocation opLoc,
4982 Expr *op) {
4983 assert(op->getType()->isObjCObjectPointerType());
4984 if (S.LangOpts.ObjCRuntime.allowsPointerArithmetic() &&
4985 !S.LangOpts.ObjCSubscriptingLegacyRuntime)
4986 return false;
4987
4988 S.Diag(Loc: opLoc, DiagID: diag::err_arithmetic_nonfragile_interface)
4989 << op->getType()->castAs<ObjCObjectPointerType>()->getPointeeType()
4990 << op->getSourceRange();
4991 return true;
4992}
4993
4994static bool isMSPropertySubscriptExpr(Sema &S, Expr *Base) {
4995 auto *BaseNoParens = Base->IgnoreParens();
4996 if (auto *MSProp = dyn_cast<MSPropertyRefExpr>(Val: BaseNoParens))
4997 return MSProp->getPropertyDecl()->getType()->isArrayType();
4998 return isa<MSPropertySubscriptExpr>(Val: BaseNoParens);
4999}
5000
5001// Returns the type used for LHS[RHS], given one of LHS, RHS is type-dependent.
5002// Typically this is DependentTy, but can sometimes be more precise.
5003//
5004// There are cases when we could determine a non-dependent type:
5005// - LHS and RHS may have non-dependent types despite being type-dependent
5006// (e.g. unbounded array static members of the current instantiation)
5007// - one may be a dependent-sized array with known element type
5008// - one may be a dependent-typed valid index (enum in current instantiation)
5009//
5010// We *always* return a dependent type, in such cases it is DependentTy.
5011// This avoids creating type-dependent expressions with non-dependent types.
5012// FIXME: is this important to avoid? See https://reviews.llvm.org/D107275
5013static QualType getDependentArraySubscriptType(Expr *LHS, Expr *RHS,
5014 const ASTContext &Ctx) {
5015 assert(LHS->isTypeDependent() || RHS->isTypeDependent());
5016 QualType LTy = LHS->getType(), RTy = RHS->getType();
5017 QualType Result = Ctx.DependentTy;
5018 if (RTy->isIntegralOrUnscopedEnumerationType()) {
5019 if (const PointerType *PT = LTy->getAs<PointerType>())
5020 Result = PT->getPointeeType();
5021 else if (const ArrayType *AT = LTy->getAsArrayTypeUnsafe())
5022 Result = AT->getElementType();
5023 } else if (LTy->isIntegralOrUnscopedEnumerationType()) {
5024 if (const PointerType *PT = RTy->getAs<PointerType>())
5025 Result = PT->getPointeeType();
5026 else if (const ArrayType *AT = RTy->getAsArrayTypeUnsafe())
5027 Result = AT->getElementType();
5028 }
5029 // Ensure we return a dependent type.
5030 return Result->isDependentType() ? Result : Ctx.DependentTy;
5031}
5032
5033ExprResult Sema::ActOnArraySubscriptExpr(Scope *S, Expr *base,
5034 SourceLocation lbLoc,
5035 MultiExprArg ArgExprs,
5036 SourceLocation rbLoc) {
5037
5038 if (base && !base->getType().isNull() &&
5039 base->hasPlaceholderType(K: BuiltinType::ArraySection)) {
5040 auto *AS = cast<ArraySectionExpr>(Val: base);
5041 if (AS->isOMPArraySection())
5042 return OpenMP().ActOnOMPArraySectionExpr(
5043 Base: base, LBLoc: lbLoc, LowerBound: ArgExprs.front(), ColonLocFirst: SourceLocation(), ColonLocSecond: SourceLocation(),
5044 /*Length*/ nullptr,
5045 /*Stride=*/nullptr, RBLoc: rbLoc);
5046
5047 return OpenACC().ActOnArraySectionExpr(Base: base, LBLoc: lbLoc, LowerBound: ArgExprs.front(),
5048 ColonLocFirst: SourceLocation(), /*Length*/ nullptr,
5049 RBLoc: rbLoc);
5050 }
5051
5052 // Since this might be a postfix expression, get rid of ParenListExprs.
5053 if (isa<ParenListExpr>(Val: base)) {
5054 ExprResult result = MaybeConvertParenListExprToParenExpr(S, ME: base);
5055 if (result.isInvalid())
5056 return ExprError();
5057 base = result.get();
5058 }
5059
5060 // Check if base and idx form a MatrixSubscriptExpr.
5061 //
5062 // Helper to check for comma expressions, which are not allowed as indices for
5063 // matrix subscript expressions.
5064 //
5065 // In C++23, we get multiple arguments instead of a comma expression.
5066 auto CheckAndReportCommaError = [&](Expr *E) {
5067 if (ArgExprs.size() > 1 ||
5068 (isa<BinaryOperator>(Val: E) && cast<BinaryOperator>(Val: E)->isCommaOp())) {
5069 Diag(Loc: E->getExprLoc(), DiagID: diag::err_matrix_subscript_comma)
5070 << SourceRange(base->getBeginLoc(), rbLoc);
5071 return true;
5072 }
5073 return false;
5074 };
5075 // The matrix subscript operator ([][])is considered a single operator.
5076 // Separating the index expressions by parenthesis is not allowed.
5077 if (base && !base->getType().isNull() &&
5078 base->hasPlaceholderType(K: BuiltinType::IncompleteMatrixIdx) &&
5079 !isa<MatrixSubscriptExpr>(Val: base)) {
5080 Diag(Loc: base->getExprLoc(), DiagID: diag::err_matrix_separate_incomplete_index)
5081 << SourceRange(base->getBeginLoc(), rbLoc);
5082 return ExprError();
5083 }
5084 // If the base is a MatrixSubscriptExpr, try to create a new
5085 // MatrixSubscriptExpr.
5086 auto *matSubscriptE = dyn_cast<MatrixSubscriptExpr>(Val: base);
5087 if (matSubscriptE) {
5088 if (CheckAndReportCommaError(ArgExprs.front()))
5089 return ExprError();
5090
5091 assert(matSubscriptE->isIncomplete() &&
5092 "base has to be an incomplete matrix subscript");
5093 return CreateBuiltinMatrixSubscriptExpr(Base: matSubscriptE->getBase(),
5094 RowIdx: matSubscriptE->getRowIdx(),
5095 ColumnIdx: ArgExprs.front(), RBLoc: rbLoc);
5096 }
5097 if (base->getType()->isWebAssemblyTableType()) {
5098 Diag(Loc: base->getExprLoc(), DiagID: diag::err_wasm_table_art)
5099 << SourceRange(base->getBeginLoc(), rbLoc) << 3;
5100 return ExprError();
5101 }
5102
5103 CheckInvalidBuiltinCountedByRef(E: base,
5104 K: BuiltinCountedByRefKind::ArraySubscript);
5105
5106 // Handle any non-overload placeholder types in the base and index
5107 // expressions. We can't handle overloads here because the other
5108 // operand might be an overloadable type, in which case the overload
5109 // resolution for the operator overload should get the first crack
5110 // at the overload.
5111 bool IsMSPropertySubscript = false;
5112 if (base->getType()->isNonOverloadPlaceholderType()) {
5113 IsMSPropertySubscript = isMSPropertySubscriptExpr(S&: *this, Base: base);
5114 if (!IsMSPropertySubscript) {
5115 ExprResult result = CheckPlaceholderExpr(E: base);
5116 if (result.isInvalid())
5117 return ExprError();
5118 base = result.get();
5119 }
5120 }
5121
5122 // If the base is a matrix type, try to create a new MatrixSubscriptExpr.
5123 if (base->getType()->isMatrixType()) {
5124 if (CheckAndReportCommaError(ArgExprs.front()))
5125 return ExprError();
5126
5127 return CreateBuiltinMatrixSubscriptExpr(Base: base, RowIdx: ArgExprs.front(), ColumnIdx: nullptr,
5128 RBLoc: rbLoc);
5129 }
5130
5131 if (ArgExprs.size() == 1 && getLangOpts().CPlusPlus20) {
5132 Expr *idx = ArgExprs[0];
5133 if ((isa<BinaryOperator>(Val: idx) && cast<BinaryOperator>(Val: idx)->isCommaOp()) ||
5134 (isa<CXXOperatorCallExpr>(Val: idx) &&
5135 cast<CXXOperatorCallExpr>(Val: idx)->getOperator() == OO_Comma)) {
5136 Diag(Loc: idx->getExprLoc(), DiagID: diag::warn_deprecated_comma_subscript)
5137 << SourceRange(base->getBeginLoc(), rbLoc);
5138 }
5139 }
5140
5141 if (ArgExprs.size() == 1 &&
5142 ArgExprs[0]->getType()->isNonOverloadPlaceholderType()) {
5143 ExprResult result = CheckPlaceholderExpr(E: ArgExprs[0]);
5144 if (result.isInvalid())
5145 return ExprError();
5146 ArgExprs[0] = result.get();
5147 } else {
5148 if (CheckArgsForPlaceholders(args: ArgExprs))
5149 return ExprError();
5150 }
5151
5152 // Build an unanalyzed expression if either operand is type-dependent.
5153 if (getLangOpts().CPlusPlus && ArgExprs.size() == 1 &&
5154 (base->isTypeDependent() ||
5155 Expr::hasAnyTypeDependentArguments(Exprs: ArgExprs)) &&
5156 !isa<PackExpansionExpr>(Val: ArgExprs[0])) {
5157 return new (Context) ArraySubscriptExpr(
5158 base, ArgExprs.front(),
5159 getDependentArraySubscriptType(LHS: base, RHS: ArgExprs.front(), Ctx: getASTContext()),
5160 VK_LValue, OK_Ordinary, rbLoc);
5161 }
5162
5163 // MSDN, property (C++)
5164 // https://msdn.microsoft.com/en-us/library/yhfk0thd(v=vs.120).aspx
5165 // This attribute can also be used in the declaration of an empty array in a
5166 // class or structure definition. For example:
5167 // __declspec(property(get=GetX, put=PutX)) int x[];
5168 // The above statement indicates that x[] can be used with one or more array
5169 // indices. In this case, i=p->x[a][b] will be turned into i=p->GetX(a, b),
5170 // and p->x[a][b] = i will be turned into p->PutX(a, b, i);
5171 if (IsMSPropertySubscript) {
5172 if (ArgExprs.size() > 1) {
5173 Diag(Loc: base->getExprLoc(),
5174 DiagID: diag::err_ms_property_subscript_expects_single_arg);
5175 return ExprError();
5176 }
5177
5178 // Build MS property subscript expression if base is MS property reference
5179 // or MS property subscript.
5180 return new (Context)
5181 MSPropertySubscriptExpr(base, ArgExprs.front(), Context.PseudoObjectTy,
5182 VK_LValue, OK_Ordinary, rbLoc);
5183 }
5184
5185 // Use C++ overloaded-operator rules if either operand has record
5186 // type. The spec says to do this if either type is *overloadable*,
5187 // but enum types can't declare subscript operators or conversion
5188 // operators, so there's nothing interesting for overload resolution
5189 // to do if there aren't any record types involved.
5190 //
5191 // ObjC pointers have their own subscripting logic that is not tied
5192 // to overload resolution and so should not take this path.
5193 //
5194 // Issue a better diagnostic if we tried to pass multiple arguments to
5195 // a builtin subscript operator rather than diagnosing this as a generic
5196 // overload resolution failure.
5197 if (ArgExprs.size() != 1 && !base->getType()->isDependentType() &&
5198 !base->getType()->isRecordType() &&
5199 !base->getType()->isObjCObjectPointerType()) {
5200 Diag(Loc: base->getExprLoc(), DiagID: diag::err_ovl_builtin_subscript_expects_single_arg)
5201 << base->getType() << base->getSourceRange();
5202 return ExprError();
5203 }
5204
5205 if (getLangOpts().CPlusPlus && !base->getType()->isObjCObjectPointerType() &&
5206 ((base->getType()->isRecordType() ||
5207 (ArgExprs.size() != 1 || isa<PackExpansionExpr>(Val: ArgExprs[0]) ||
5208 ArgExprs[0]->getType()->isRecordType())))) {
5209 return CreateOverloadedArraySubscriptExpr(LLoc: lbLoc, RLoc: rbLoc, Base: base, Args: ArgExprs);
5210 }
5211
5212 ExprResult Res =
5213 CreateBuiltinArraySubscriptExpr(Base: base, LLoc: lbLoc, Idx: ArgExprs.front(), RLoc: rbLoc);
5214
5215 if (!Res.isInvalid() && isa<ArraySubscriptExpr>(Val: Res.get()))
5216 CheckSubscriptAccessOfNoDeref(E: cast<ArraySubscriptExpr>(Val: Res.get()));
5217
5218 return Res;
5219}
5220
5221ExprResult Sema::tryConvertExprToType(Expr *E, QualType Ty) {
5222 InitializedEntity Entity = InitializedEntity::InitializeTemporary(Type: Ty);
5223 InitializationKind Kind =
5224 InitializationKind::CreateCopy(InitLoc: E->getBeginLoc(), EqualLoc: SourceLocation());
5225 InitializationSequence InitSeq(*this, Entity, Kind, E);
5226 return InitSeq.Perform(S&: *this, Entity, Kind, Args: E);
5227}
5228
5229ExprResult Sema::CreateBuiltinMatrixSingleSubscriptExpr(Expr *Base,
5230 Expr *RowIdx,
5231 SourceLocation RBLoc) {
5232 ExprResult BaseR = CheckPlaceholderExpr(E: Base);
5233 if (BaseR.isInvalid())
5234 return BaseR;
5235 Base = BaseR.get();
5236
5237 ExprResult RowR = CheckPlaceholderExpr(E: RowIdx);
5238 if (RowR.isInvalid())
5239 return RowR;
5240 RowIdx = RowR.get();
5241
5242 // Build an unanalyzed expression if any of the operands is type-dependent.
5243 if (Base->isTypeDependent() || RowIdx->isTypeDependent())
5244 return new (Context)
5245 MatrixSingleSubscriptExpr(Base, RowIdx, Context.DependentTy, RBLoc);
5246
5247 // Check that IndexExpr is an integer expression. If it is a constant
5248 // expression, check that it is less than Dim (= the number of elements in the
5249 // corresponding dimension).
5250 auto IsIndexValid = [&](Expr *IndexExpr, unsigned Dim,
5251 bool IsColumnIdx) -> Expr * {
5252 if (!IndexExpr->getType()->isIntegerType() &&
5253 !IndexExpr->isTypeDependent()) {
5254 Diag(Loc: IndexExpr->getBeginLoc(), DiagID: diag::err_matrix_index_not_integer)
5255 << IsColumnIdx;
5256 return nullptr;
5257 }
5258
5259 if (std::optional<llvm::APSInt> Idx =
5260 IndexExpr->getIntegerConstantExpr(Ctx: Context)) {
5261 if ((*Idx < 0 || *Idx >= Dim)) {
5262 Diag(Loc: IndexExpr->getBeginLoc(), DiagID: diag::err_matrix_index_outside_range)
5263 << IsColumnIdx << Dim;
5264 return nullptr;
5265 }
5266 }
5267
5268 ExprResult ConvExpr = IndexExpr;
5269 assert(!ConvExpr.isInvalid() &&
5270 "should be able to convert any integer type to size type");
5271 return ConvExpr.get();
5272 };
5273
5274 auto *MTy = Base->getType()->getAs<ConstantMatrixType>();
5275 RowIdx = IsIndexValid(RowIdx, MTy->getNumRows(), false);
5276 if (!RowIdx)
5277 return ExprError();
5278
5279 QualType RowVecQT =
5280 Context.getExtVectorType(VectorType: MTy->getElementType(), NumElts: MTy->getNumColumns());
5281
5282 return new (Context) MatrixSingleSubscriptExpr(Base, RowIdx, RowVecQT, RBLoc);
5283}
5284
5285ExprResult Sema::CreateBuiltinMatrixSubscriptExpr(Expr *Base, Expr *RowIdx,
5286 Expr *ColumnIdx,
5287 SourceLocation RBLoc) {
5288 ExprResult BaseR = CheckPlaceholderExpr(E: Base);
5289 if (BaseR.isInvalid())
5290 return BaseR;
5291 Base = BaseR.get();
5292
5293 ExprResult RowR = CheckPlaceholderExpr(E: RowIdx);
5294 if (RowR.isInvalid())
5295 return RowR;
5296 RowIdx = RowR.get();
5297
5298 if (!ColumnIdx)
5299 return new (Context) MatrixSubscriptExpr(
5300 Base, RowIdx, ColumnIdx, Context.IncompleteMatrixIdxTy, RBLoc);
5301
5302 // Build an unanalyzed expression if any of the operands is type-dependent.
5303 if (Base->isTypeDependent() || RowIdx->isTypeDependent() ||
5304 ColumnIdx->isTypeDependent())
5305 return new (Context) MatrixSubscriptExpr(Base, RowIdx, ColumnIdx,
5306 Context.DependentTy, RBLoc);
5307
5308 ExprResult ColumnR = CheckPlaceholderExpr(E: ColumnIdx);
5309 if (ColumnR.isInvalid())
5310 return ColumnR;
5311 ColumnIdx = ColumnR.get();
5312
5313 // Check that IndexExpr is an integer expression. If it is a constant
5314 // expression, check that it is less than Dim (= the number of elements in the
5315 // corresponding dimension).
5316 auto IsIndexValid = [&](Expr *IndexExpr, unsigned Dim,
5317 bool IsColumnIdx) -> Expr * {
5318 if (!IndexExpr->getType()->isIntegerType() &&
5319 !IndexExpr->isTypeDependent()) {
5320 Diag(Loc: IndexExpr->getBeginLoc(), DiagID: diag::err_matrix_index_not_integer)
5321 << IsColumnIdx;
5322 return nullptr;
5323 }
5324
5325 if (std::optional<llvm::APSInt> Idx =
5326 IndexExpr->getIntegerConstantExpr(Ctx: Context)) {
5327 if ((*Idx < 0 || *Idx >= Dim)) {
5328 Diag(Loc: IndexExpr->getBeginLoc(), DiagID: diag::err_matrix_index_outside_range)
5329 << IsColumnIdx << Dim;
5330 return nullptr;
5331 }
5332 }
5333
5334 ExprResult ConvExpr = IndexExpr;
5335 assert(!ConvExpr.isInvalid() &&
5336 "should be able to convert any integer type to size type");
5337 return ConvExpr.get();
5338 };
5339
5340 auto *MTy = Base->getType()->getAs<ConstantMatrixType>();
5341 RowIdx = IsIndexValid(RowIdx, MTy->getNumRows(), false);
5342 ColumnIdx = IsIndexValid(ColumnIdx, MTy->getNumColumns(), true);
5343 if (!RowIdx || !ColumnIdx)
5344 return ExprError();
5345
5346 return new (Context) MatrixSubscriptExpr(Base, RowIdx, ColumnIdx,
5347 MTy->getElementType(), RBLoc);
5348}
5349
5350void Sema::CheckAddressOfNoDeref(const Expr *E) {
5351 ExpressionEvaluationContextRecord &LastRecord = ExprEvalContexts.back();
5352 const Expr *StrippedExpr = E->IgnoreParenImpCasts();
5353
5354 // For expressions like `&(*s).b`, the base is recorded and what should be
5355 // checked.
5356 const MemberExpr *Member = nullptr;
5357 while ((Member = dyn_cast<MemberExpr>(Val: StrippedExpr)) && !Member->isArrow())
5358 StrippedExpr = Member->getBase()->IgnoreParenImpCasts();
5359
5360 LastRecord.PossibleDerefs.erase(Ptr: StrippedExpr);
5361}
5362
5363void Sema::CheckSubscriptAccessOfNoDeref(const ArraySubscriptExpr *E) {
5364 if (isUnevaluatedContext())
5365 return;
5366
5367 QualType ResultTy = E->getType();
5368 ExpressionEvaluationContextRecord &LastRecord = ExprEvalContexts.back();
5369
5370 // Bail if the element is an array since it is not memory access.
5371 if (isa<ArrayType>(Val: ResultTy))
5372 return;
5373
5374 if (ResultTy->hasAttr(AK: attr::NoDeref)) {
5375 LastRecord.PossibleDerefs.insert(Ptr: E);
5376 return;
5377 }
5378
5379 // Check if the base type is a pointer to a member access of a struct
5380 // marked with noderef.
5381 const Expr *Base = E->getBase();
5382 QualType BaseTy = Base->getType();
5383 if (!(isa<ArrayType>(Val: BaseTy) || isa<PointerType>(Val: BaseTy)))
5384 // Not a pointer access
5385 return;
5386
5387 const MemberExpr *Member = nullptr;
5388 while ((Member = dyn_cast<MemberExpr>(Val: Base->IgnoreParenCasts())) &&
5389 Member->isArrow())
5390 Base = Member->getBase();
5391
5392 if (const auto *Ptr = dyn_cast<PointerType>(Val: Base->getType())) {
5393 if (Ptr->getPointeeType()->hasAttr(AK: attr::NoDeref))
5394 LastRecord.PossibleDerefs.insert(Ptr: E);
5395 }
5396}
5397
5398ExprResult
5399Sema::CreateBuiltinArraySubscriptExpr(Expr *Base, SourceLocation LLoc,
5400 Expr *Idx, SourceLocation RLoc) {
5401 Expr *LHSExp = Base;
5402 Expr *RHSExp = Idx;
5403
5404 ExprValueKind VK = VK_LValue;
5405 ExprObjectKind OK = OK_Ordinary;
5406
5407 // Per C++ core issue 1213, the result is an xvalue if either operand is
5408 // a non-lvalue array, and an lvalue otherwise.
5409 if (getLangOpts().CPlusPlus11) {
5410 for (auto *Op : {LHSExp, RHSExp}) {
5411 Op = Op->IgnoreImplicit();
5412 if (Op->getType()->isArrayType() && !Op->isLValue())
5413 VK = VK_XValue;
5414 }
5415 }
5416
5417 // Perform default conversions.
5418 if (!LHSExp->getType()->isSubscriptableVectorType()) {
5419 ExprResult Result = DefaultFunctionArrayLvalueConversion(E: LHSExp);
5420 if (Result.isInvalid())
5421 return ExprError();
5422 LHSExp = Result.get();
5423 }
5424 ExprResult Result = DefaultFunctionArrayLvalueConversion(E: RHSExp);
5425 if (Result.isInvalid())
5426 return ExprError();
5427 RHSExp = Result.get();
5428
5429 QualType LHSTy = LHSExp->getType(), RHSTy = RHSExp->getType();
5430
5431 // C99 6.5.2.1p2: the expression e1[e2] is by definition precisely equivalent
5432 // to the expression *((e1)+(e2)). This means the array "Base" may actually be
5433 // in the subscript position. As a result, we need to derive the array base
5434 // and index from the expression types.
5435 Expr *BaseExpr, *IndexExpr;
5436 QualType ResultType;
5437 if (LHSTy->isDependentType() || RHSTy->isDependentType()) {
5438 BaseExpr = LHSExp;
5439 IndexExpr = RHSExp;
5440 ResultType =
5441 getDependentArraySubscriptType(LHS: LHSExp, RHS: RHSExp, Ctx: getASTContext());
5442 } else if (const PointerType *PTy = LHSTy->getAs<PointerType>()) {
5443 BaseExpr = LHSExp;
5444 IndexExpr = RHSExp;
5445 ResultType = PTy->getPointeeType();
5446 } else if (const ObjCObjectPointerType *PTy =
5447 LHSTy->getAs<ObjCObjectPointerType>()) {
5448 BaseExpr = LHSExp;
5449 IndexExpr = RHSExp;
5450
5451 // Use custom logic if this should be the pseudo-object subscript
5452 // expression.
5453 if (!LangOpts.isSubscriptPointerArithmetic())
5454 return ObjC().BuildObjCSubscriptExpression(RB: RLoc, BaseExpr, IndexExpr,
5455 getterMethod: nullptr, setterMethod: nullptr);
5456
5457 ResultType = PTy->getPointeeType();
5458 } else if (const PointerType *PTy = RHSTy->getAs<PointerType>()) {
5459 // Handle the uncommon case of "123[Ptr]".
5460 BaseExpr = RHSExp;
5461 IndexExpr = LHSExp;
5462 ResultType = PTy->getPointeeType();
5463 } else if (const ObjCObjectPointerType *PTy =
5464 RHSTy->getAs<ObjCObjectPointerType>()) {
5465 // Handle the uncommon case of "123[Ptr]".
5466 BaseExpr = RHSExp;
5467 IndexExpr = LHSExp;
5468 ResultType = PTy->getPointeeType();
5469 if (!LangOpts.isSubscriptPointerArithmetic()) {
5470 Diag(Loc: LLoc, DiagID: diag::err_subscript_nonfragile_interface)
5471 << ResultType << BaseExpr->getSourceRange();
5472 return ExprError();
5473 }
5474 } else if (LHSTy->isSubscriptableVectorType()) {
5475 if (LHSTy->isBuiltinType() &&
5476 LHSTy->getAs<BuiltinType>()->isSveVLSBuiltinType()) {
5477 const BuiltinType *BTy = LHSTy->getAs<BuiltinType>();
5478 if (BTy->isSVEBool())
5479 return ExprError(Diag(Loc: LLoc, DiagID: diag::err_subscript_svbool_t)
5480 << LHSExp->getSourceRange()
5481 << RHSExp->getSourceRange());
5482 ResultType = BTy->getSveEltType(Ctx: Context);
5483 } else {
5484 const VectorType *VTy = LHSTy->getAs<VectorType>();
5485 ResultType = VTy->getElementType();
5486 }
5487 BaseExpr = LHSExp; // vectors: V[123]
5488 IndexExpr = RHSExp;
5489 // We apply C++ DR1213 to vector subscripting too.
5490 if (getLangOpts().CPlusPlus11 && LHSExp->isPRValue()) {
5491 ExprResult Materialized = TemporaryMaterializationConversion(E: LHSExp);
5492 if (Materialized.isInvalid())
5493 return ExprError();
5494 LHSExp = Materialized.get();
5495 }
5496 VK = LHSExp->getValueKind();
5497 if (VK != VK_PRValue)
5498 OK = OK_VectorComponent;
5499
5500 QualType BaseType = BaseExpr->getType();
5501 Qualifiers BaseQuals = BaseType.getQualifiers();
5502 Qualifiers MemberQuals = ResultType.getQualifiers();
5503 Qualifiers Combined = BaseQuals + MemberQuals;
5504 if (Combined != MemberQuals)
5505 ResultType = Context.getQualifiedType(T: ResultType, Qs: Combined);
5506 } else if (LHSTy->isArrayType()) {
5507 // If we see an array that wasn't promoted by
5508 // DefaultFunctionArrayLvalueConversion, it must be an array that
5509 // wasn't promoted because of the C90 rule that doesn't
5510 // allow promoting non-lvalue arrays. Warn, then
5511 // force the promotion here.
5512 Diag(Loc: LHSExp->getBeginLoc(), DiagID: diag::ext_subscript_non_lvalue)
5513 << LHSExp->getSourceRange();
5514 LHSExp = ImpCastExprToType(E: LHSExp, Type: Context.getArrayDecayedType(T: LHSTy),
5515 CK: CK_ArrayToPointerDecay).get();
5516 LHSTy = LHSExp->getType();
5517
5518 BaseExpr = LHSExp;
5519 IndexExpr = RHSExp;
5520 ResultType = LHSTy->castAs<PointerType>()->getPointeeType();
5521 } else if (RHSTy->isArrayType()) {
5522 // Same as previous, except for 123[f().a] case
5523 Diag(Loc: RHSExp->getBeginLoc(), DiagID: diag::ext_subscript_non_lvalue)
5524 << RHSExp->getSourceRange();
5525 RHSExp = ImpCastExprToType(E: RHSExp, Type: Context.getArrayDecayedType(T: RHSTy),
5526 CK: CK_ArrayToPointerDecay).get();
5527 RHSTy = RHSExp->getType();
5528
5529 BaseExpr = RHSExp;
5530 IndexExpr = LHSExp;
5531 ResultType = RHSTy->castAs<PointerType>()->getPointeeType();
5532 } else {
5533 return ExprError(Diag(Loc: LLoc, DiagID: diag::err_typecheck_subscript_value)
5534 << LHSExp->getSourceRange() << RHSExp->getSourceRange());
5535 }
5536 // C99 6.5.2.1p1
5537 if (!IndexExpr->getType()->isIntegerType() && !IndexExpr->isTypeDependent())
5538 return ExprError(Diag(Loc: LLoc, DiagID: diag::err_typecheck_subscript_not_integer)
5539 << IndexExpr->getSourceRange());
5540
5541 if ((IndexExpr->getType()->isSpecificBuiltinType(K: BuiltinType::Char_S) ||
5542 IndexExpr->getType()->isSpecificBuiltinType(K: BuiltinType::Char_U)) &&
5543 !IndexExpr->isTypeDependent()) {
5544 std::optional<llvm::APSInt> IntegerContantExpr =
5545 IndexExpr->getIntegerConstantExpr(Ctx: getASTContext());
5546 if (!IntegerContantExpr.has_value() ||
5547 IntegerContantExpr.value().isNegative())
5548 Diag(Loc: LLoc, DiagID: diag::warn_subscript_is_char) << IndexExpr->getSourceRange();
5549 }
5550
5551 // C99 6.5.2.1p1: "shall have type "pointer to *object* type". Similarly,
5552 // C++ [expr.sub]p1: The type "T" shall be a completely-defined object
5553 // type. Note that Functions are not objects, and that (in C99 parlance)
5554 // incomplete types are not object types.
5555 if (ResultType->isFunctionType()) {
5556 Diag(Loc: BaseExpr->getBeginLoc(), DiagID: diag::err_subscript_function_type)
5557 << ResultType << BaseExpr->getSourceRange();
5558 return ExprError();
5559 }
5560
5561 if (ResultType->isVoidType() && !getLangOpts().CPlusPlus) {
5562 // GNU extension: subscripting on pointer to void
5563 Diag(Loc: LLoc, DiagID: diag::ext_gnu_subscript_void_type)
5564 << BaseExpr->getSourceRange();
5565
5566 // C forbids expressions of unqualified void type from being l-values.
5567 // See IsCForbiddenLValueType.
5568 if (!ResultType.hasQualifiers())
5569 VK = VK_PRValue;
5570 } else if (!ResultType->isDependentType() &&
5571 !ResultType.isWebAssemblyReferenceType() &&
5572 RequireCompleteSizedType(
5573 Loc: LLoc, T: ResultType,
5574 DiagID: diag::err_subscript_incomplete_or_sizeless_type, Args: BaseExpr))
5575 return ExprError();
5576
5577 assert(VK == VK_PRValue || LangOpts.CPlusPlus ||
5578 !ResultType.isCForbiddenLValueType());
5579
5580 if (LHSExp->IgnoreParenImpCasts()->getType()->isVariablyModifiedType() &&
5581 FunctionScopes.size() > 1) {
5582 if (auto *TT =
5583 LHSExp->IgnoreParenImpCasts()->getType()->getAs<TypedefType>()) {
5584 for (auto I = FunctionScopes.rbegin(),
5585 E = std::prev(x: FunctionScopes.rend());
5586 I != E; ++I) {
5587 auto *CSI = dyn_cast<CapturingScopeInfo>(Val: *I);
5588 if (CSI == nullptr)
5589 break;
5590 DeclContext *DC = nullptr;
5591 if (auto *LSI = dyn_cast<LambdaScopeInfo>(Val: CSI))
5592 DC = LSI->CallOperator;
5593 else if (auto *CRSI = dyn_cast<CapturedRegionScopeInfo>(Val: CSI))
5594 DC = CRSI->TheCapturedDecl;
5595 else if (auto *BSI = dyn_cast<BlockScopeInfo>(Val: CSI))
5596 DC = BSI->TheDecl;
5597 if (DC) {
5598 if (DC->containsDecl(D: TT->getDecl()))
5599 break;
5600 captureVariablyModifiedType(
5601 Context, T: LHSExp->IgnoreParenImpCasts()->getType(), CSI);
5602 }
5603 }
5604 }
5605 }
5606
5607 return new (Context)
5608 ArraySubscriptExpr(LHSExp, RHSExp, ResultType, VK, OK, RLoc);
5609}
5610
5611bool Sema::CheckCXXDefaultArgExpr(SourceLocation CallLoc, FunctionDecl *FD,
5612 ParmVarDecl *Param, Expr *RewrittenInit,
5613 bool SkipImmediateInvocations) {
5614 if (Param->hasUnparsedDefaultArg()) {
5615 assert(!RewrittenInit && "Should not have a rewritten init expression yet");
5616 // If we've already cleared out the location for the default argument,
5617 // that means we're parsing it right now.
5618 if (!UnparsedDefaultArgLocs.count(Val: Param)) {
5619 Diag(Loc: Param->getBeginLoc(), DiagID: diag::err_recursive_default_argument) << FD;
5620 Diag(Loc: CallLoc, DiagID: diag::note_recursive_default_argument_used_here);
5621 Param->setInvalidDecl();
5622 return true;
5623 }
5624
5625 Diag(Loc: CallLoc, DiagID: diag::err_use_of_default_argument_to_function_declared_later)
5626 << FD << cast<CXXRecordDecl>(Val: FD->getDeclContext());
5627 Diag(Loc: UnparsedDefaultArgLocs[Param],
5628 DiagID: diag::note_default_argument_declared_here);
5629 return true;
5630 }
5631
5632 if (Param->hasUninstantiatedDefaultArg()) {
5633 assert(!RewrittenInit && "Should not have a rewitten init expression yet");
5634 if (InstantiateDefaultArgument(CallLoc, FD, Param))
5635 return true;
5636 }
5637
5638 Expr *Init = RewrittenInit ? RewrittenInit : Param->getInit();
5639 assert(Init && "default argument but no initializer?");
5640
5641 // If the default expression creates temporaries, we need to
5642 // push them to the current stack of expression temporaries so they'll
5643 // be properly destroyed.
5644 // FIXME: We should really be rebuilding the default argument with new
5645 // bound temporaries; see the comment in PR5810.
5646 // We don't need to do that with block decls, though, because
5647 // blocks in default argument expression can never capture anything.
5648 if (auto *InitWithCleanup = dyn_cast<ExprWithCleanups>(Val: Init)) {
5649 // Set the "needs cleanups" bit regardless of whether there are
5650 // any explicit objects.
5651 Cleanup.setExprNeedsCleanups(InitWithCleanup->cleanupsHaveSideEffects());
5652 // Append all the objects to the cleanup list. Right now, this
5653 // should always be a no-op, because blocks in default argument
5654 // expressions should never be able to capture anything.
5655 assert(!InitWithCleanup->getNumObjects() &&
5656 "default argument expression has capturing blocks?");
5657 }
5658 // C++ [expr.const]p15.1:
5659 // An expression or conversion is in an immediate function context if it is
5660 // potentially evaluated and [...] its innermost enclosing non-block scope
5661 // is a function parameter scope of an immediate function.
5662 EnterExpressionEvaluationContext EvalContext(
5663 *this,
5664 FD->isImmediateFunction()
5665 ? ExpressionEvaluationContext::ImmediateFunctionContext
5666 : ExpressionEvaluationContext::PotentiallyEvaluated,
5667 Param);
5668 ExprEvalContexts.back().IsCurrentlyCheckingDefaultArgumentOrInitializer =
5669 SkipImmediateInvocations;
5670 runWithSufficientStackSpace(Loc: CallLoc, Fn: [&] {
5671 MarkDeclarationsReferencedInExpr(E: Init, /*SkipLocalVariables=*/true);
5672 });
5673 return false;
5674}
5675
5676struct ImmediateCallVisitor : DynamicRecursiveASTVisitor {
5677 const ASTContext &Context;
5678 ImmediateCallVisitor(const ASTContext &Ctx) : Context(Ctx) {
5679 ShouldVisitImplicitCode = true;
5680 }
5681
5682 bool HasImmediateCalls = false;
5683
5684 bool VisitCallExpr(CallExpr *E) override {
5685 if (const FunctionDecl *FD = E->getDirectCallee())
5686 HasImmediateCalls |= FD->isImmediateFunction();
5687 return DynamicRecursiveASTVisitor::VisitStmt(S: E);
5688 }
5689
5690 bool VisitCXXConstructExpr(CXXConstructExpr *E) override {
5691 if (const FunctionDecl *FD = E->getConstructor())
5692 HasImmediateCalls |= FD->isImmediateFunction();
5693 return DynamicRecursiveASTVisitor::VisitStmt(S: E);
5694 }
5695
5696 // SourceLocExpr are not immediate invocations
5697 // but CXXDefaultInitExpr/CXXDefaultArgExpr containing a SourceLocExpr
5698 // need to be rebuilt so that they refer to the correct SourceLocation and
5699 // DeclContext.
5700 bool VisitSourceLocExpr(SourceLocExpr *E) override {
5701 HasImmediateCalls = true;
5702 return DynamicRecursiveASTVisitor::VisitStmt(S: E);
5703 }
5704
5705 // A nested lambda might have parameters with immediate invocations
5706 // in their default arguments.
5707 // The compound statement is not visited (as it does not constitute a
5708 // subexpression).
5709 // FIXME: We should consider visiting and transforming captures
5710 // with init expressions.
5711 bool VisitLambdaExpr(LambdaExpr *E) override {
5712 return VisitCXXMethodDecl(D: E->getCallOperator());
5713 }
5714
5715 bool VisitCXXDefaultArgExpr(CXXDefaultArgExpr *E) override {
5716 return TraverseStmt(S: E->getExpr());
5717 }
5718
5719 bool VisitCXXDefaultInitExpr(CXXDefaultInitExpr *E) override {
5720 return TraverseStmt(S: E->getExpr());
5721 }
5722};
5723
5724struct EnsureImmediateInvocationInDefaultArgs
5725 : TreeTransform<EnsureImmediateInvocationInDefaultArgs> {
5726 EnsureImmediateInvocationInDefaultArgs(Sema &SemaRef)
5727 : TreeTransform(SemaRef) {}
5728
5729 bool AlwaysRebuild() { return true; }
5730
5731 // Lambda can only have immediate invocations in the default
5732 // args of their parameters, which is transformed upon calling the closure.
5733 // The body is not a subexpression, so we have nothing to do.
5734 // FIXME: Immediate calls in capture initializers should be transformed.
5735 ExprResult TransformLambdaExpr(LambdaExpr *E) { return E; }
5736 ExprResult TransformBlockExpr(BlockExpr *E) { return E; }
5737
5738 // Make sure we don't rebuild the this pointer as it would
5739 // cause it to incorrectly point it to the outermost class
5740 // in the case of nested struct initialization.
5741 ExprResult TransformCXXThisExpr(CXXThisExpr *E) { return E; }
5742
5743 // Rewrite to source location to refer to the context in which they are used.
5744 ExprResult TransformSourceLocExpr(SourceLocExpr *E) {
5745 DeclContext *DC = E->getParentContext();
5746 if (DC == SemaRef.CurContext)
5747 return E;
5748
5749 // FIXME: During instantiation, because the rebuild of defaults arguments
5750 // is not always done in the context of the template instantiator,
5751 // we run the risk of producing a dependent source location
5752 // that would never be rebuilt.
5753 // This usually happens during overload resolution, or in contexts
5754 // where the value of the source location does not matter.
5755 // However, we should find a better way to deal with source location
5756 // of function templates.
5757 if (!SemaRef.CurrentInstantiationScope ||
5758 !SemaRef.CurContext->isDependentContext() || DC->isDependentContext())
5759 DC = SemaRef.CurContext;
5760
5761 return getDerived().RebuildSourceLocExpr(
5762 Kind: E->getIdentKind(), ResultTy: E->getType(), BuiltinLoc: E->getBeginLoc(), RPLoc: E->getEndLoc(), ParentContext: DC);
5763 }
5764};
5765
5766ExprResult Sema::BuildCXXDefaultArgExpr(SourceLocation CallLoc,
5767 FunctionDecl *FD, ParmVarDecl *Param,
5768 Expr *Init) {
5769 assert(Param->hasDefaultArg() && "can't build nonexistent default arg");
5770
5771 bool NestedDefaultChecking = isCheckingDefaultArgumentOrInitializer();
5772 bool NeedRebuild = needsRebuildOfDefaultArgOrInit();
5773 std::optional<ExpressionEvaluationContextRecord::InitializationContext>
5774 InitializationContext =
5775 OutermostDeclarationWithDelayedImmediateInvocations();
5776 if (!InitializationContext.has_value())
5777 InitializationContext.emplace(args&: CallLoc, args&: Param, args&: CurContext);
5778
5779 if (!Init && !Param->hasUnparsedDefaultArg()) {
5780 // Mark that we are replacing a default argument first.
5781 // If we are instantiating a template we won't have to
5782 // retransform immediate calls.
5783 // C++ [expr.const]p15.1:
5784 // An expression or conversion is in an immediate function context if it
5785 // is potentially evaluated and [...] its innermost enclosing non-block
5786 // scope is a function parameter scope of an immediate function.
5787 EnterExpressionEvaluationContext EvalContext(
5788 *this,
5789 FD->isImmediateFunction()
5790 ? ExpressionEvaluationContext::ImmediateFunctionContext
5791 : ExpressionEvaluationContext::PotentiallyEvaluated,
5792 Param);
5793
5794 if (Param->hasUninstantiatedDefaultArg()) {
5795 if (InstantiateDefaultArgument(CallLoc, FD, Param))
5796 return ExprError();
5797 }
5798 // CWG2631
5799 // An immediate invocation that is not evaluated where it appears is
5800 // evaluated and checked for whether it is a constant expression at the
5801 // point where the enclosing initializer is used in a function call.
5802 ImmediateCallVisitor V(getASTContext());
5803 if (!NestedDefaultChecking)
5804 V.TraverseDecl(D: Param);
5805
5806 // Rewrite the call argument that was created from the corresponding
5807 // parameter's default argument.
5808 if (V.HasImmediateCalls ||
5809 (NeedRebuild && isa_and_present<ExprWithCleanups>(Val: Param->getInit()))) {
5810 if (V.HasImmediateCalls)
5811 ExprEvalContexts.back().DelayedDefaultInitializationContext = {
5812 CallLoc, Param, CurContext};
5813 // Pass down lifetime extending flag, and collect temporaries in
5814 // CreateMaterializeTemporaryExpr when we rewrite the call argument.
5815 currentEvaluationContext().InLifetimeExtendingContext =
5816 parentEvaluationContext().InLifetimeExtendingContext;
5817 EnsureImmediateInvocationInDefaultArgs Immediate(*this);
5818 ExprResult Res;
5819 runWithSufficientStackSpace(Loc: CallLoc, Fn: [&] {
5820 Res = Immediate.TransformInitializer(Init: Param->getInit(),
5821 /*NotCopy=*/NotCopyInit: false);
5822 });
5823 if (Res.isInvalid())
5824 return ExprError();
5825 Res = ConvertParamDefaultArgument(Param, DefaultArg: Res.get(),
5826 EqualLoc: Res.get()->getBeginLoc());
5827 if (Res.isInvalid())
5828 return ExprError();
5829 Init = Res.get();
5830 }
5831 }
5832
5833 if (CheckCXXDefaultArgExpr(
5834 CallLoc, FD, Param, RewrittenInit: Init,
5835 /*SkipImmediateInvocations=*/NestedDefaultChecking))
5836 return ExprError();
5837
5838 return CXXDefaultArgExpr::Create(C: Context, Loc: InitializationContext->Loc, Param,
5839 RewrittenExpr: Init, UsedContext: InitializationContext->Context);
5840}
5841
5842static FieldDecl *FindFieldDeclInstantiationPattern(const ASTContext &Ctx,
5843 FieldDecl *Field) {
5844 if (FieldDecl *Pattern = Ctx.getInstantiatedFromUnnamedFieldDecl(Field))
5845 return Pattern;
5846 auto *ParentRD = cast<CXXRecordDecl>(Val: Field->getParent());
5847 CXXRecordDecl *ClassPattern = ParentRD->getTemplateInstantiationPattern();
5848 DeclContext::lookup_result Lookup =
5849 ClassPattern->lookup(Name: Field->getDeclName());
5850 auto Rng = llvm::make_filter_range(
5851 Range&: Lookup, Pred: [](auto &&L) { return isa<FieldDecl>(*L); });
5852 if (Rng.empty())
5853 return nullptr;
5854 // FIXME: this breaks clang/test/Modules/pr28812.cpp
5855 // assert(std::distance(Rng.begin(), Rng.end()) <= 1
5856 // && "Duplicated instantiation pattern for field decl");
5857 return cast<FieldDecl>(Val: *Rng.begin());
5858}
5859
5860ExprResult Sema::BuildCXXDefaultInitExpr(SourceLocation Loc, FieldDecl *Field) {
5861 assert(Field->hasInClassInitializer());
5862
5863 CXXThisScopeRAII This(*this, Field->getParent(), Qualifiers());
5864
5865 auto *ParentRD = cast<CXXRecordDecl>(Val: Field->getParent());
5866
5867 std::optional<ExpressionEvaluationContextRecord::InitializationContext>
5868 InitializationContext =
5869 OutermostDeclarationWithDelayedImmediateInvocations();
5870 if (!InitializationContext.has_value())
5871 InitializationContext.emplace(args&: Loc, args&: Field, args&: CurContext);
5872
5873 Expr *Init = nullptr;
5874
5875 bool NestedDefaultChecking = isCheckingDefaultArgumentOrInitializer();
5876 bool NeedRebuild = needsRebuildOfDefaultArgOrInit();
5877 EnterExpressionEvaluationContext EvalContext(
5878 *this, ExpressionEvaluationContext::PotentiallyEvaluated, Field);
5879
5880 if (!Field->getInClassInitializer()) {
5881 // Maybe we haven't instantiated the in-class initializer. Go check the
5882 // pattern FieldDecl to see if it has one.
5883 if (isTemplateInstantiation(Kind: ParentRD->getTemplateSpecializationKind())) {
5884 FieldDecl *Pattern =
5885 FindFieldDeclInstantiationPattern(Ctx: getASTContext(), Field);
5886 assert(Pattern && "We must have set the Pattern!");
5887 if (!Pattern->hasInClassInitializer() ||
5888 InstantiateInClassInitializer(PointOfInstantiation: Loc, Instantiation: Field, Pattern,
5889 TemplateArgs: getTemplateInstantiationArgs(D: Field))) {
5890 Field->setInvalidDecl();
5891 return ExprError();
5892 }
5893 }
5894 }
5895
5896 // CWG2631
5897 // An immediate invocation that is not evaluated where it appears is
5898 // evaluated and checked for whether it is a constant expression at the
5899 // point where the enclosing initializer is used in a [...] a constructor
5900 // definition, or an aggregate initialization.
5901 ImmediateCallVisitor V(getASTContext());
5902 if (!NestedDefaultChecking)
5903 V.TraverseDecl(D: Field);
5904
5905 // CWG1815
5906 // Support lifetime extension of temporary created by aggregate
5907 // initialization using a default member initializer. We should rebuild
5908 // the initializer in a lifetime extension context if the initializer
5909 // expression is an ExprWithCleanups. Then make sure the normal lifetime
5910 // extension code recurses into the default initializer and does lifetime
5911 // extension when warranted.
5912 bool ContainsAnyTemporaries =
5913 isa_and_present<ExprWithCleanups>(Val: Field->getInClassInitializer());
5914 if (Field->getInClassInitializer() &&
5915 !Field->getInClassInitializer()->containsErrors() &&
5916 (V.HasImmediateCalls || (NeedRebuild && ContainsAnyTemporaries))) {
5917 ExprEvalContexts.back().DelayedDefaultInitializationContext = {Loc, Field,
5918 CurContext};
5919 ExprEvalContexts.back().IsCurrentlyCheckingDefaultArgumentOrInitializer =
5920 NestedDefaultChecking;
5921 // Pass down lifetime extending flag, and collect temporaries in
5922 // CreateMaterializeTemporaryExpr when we rewrite the call argument.
5923 currentEvaluationContext().InLifetimeExtendingContext =
5924 parentEvaluationContext().InLifetimeExtendingContext;
5925 EnsureImmediateInvocationInDefaultArgs Immediate(*this);
5926 ExprResult Res;
5927 runWithSufficientStackSpace(Loc, Fn: [&] {
5928 Res = Immediate.TransformInitializer(Init: Field->getInClassInitializer(),
5929 /*CXXDirectInit=*/NotCopyInit: false);
5930 });
5931 if (!Res.isInvalid())
5932 Res = ConvertMemberDefaultInitExpression(FD: Field, InitExpr: Res.get(), InitLoc: Loc);
5933 if (Res.isInvalid()) {
5934 Field->setInvalidDecl();
5935 return ExprError();
5936 }
5937 Init = Res.get();
5938 }
5939
5940 if (Field->getInClassInitializer()) {
5941 Expr *E = Init ? Init : Field->getInClassInitializer();
5942 if (!NestedDefaultChecking)
5943 runWithSufficientStackSpace(Loc, Fn: [&] {
5944 MarkDeclarationsReferencedInExpr(E, /*SkipLocalVariables=*/false);
5945 });
5946 if (isInLifetimeExtendingContext())
5947 DiscardCleanupsInEvaluationContext();
5948 // C++11 [class.base.init]p7:
5949 // The initialization of each base and member constitutes a
5950 // full-expression.
5951 ExprResult Res = ActOnFinishFullExpr(Expr: E, /*DiscardedValue=*/false);
5952 if (Res.isInvalid()) {
5953 Field->setInvalidDecl();
5954 return ExprError();
5955 }
5956 Init = Res.get();
5957
5958 return CXXDefaultInitExpr::Create(Ctx: Context, Loc: InitializationContext->Loc,
5959 Field, UsedContext: InitializationContext->Context,
5960 RewrittenInitExpr: Init);
5961 }
5962
5963 // DR1351:
5964 // If the brace-or-equal-initializer of a non-static data member
5965 // invokes a defaulted default constructor of its class or of an
5966 // enclosing class in a potentially evaluated subexpression, the
5967 // program is ill-formed.
5968 //
5969 // This resolution is unworkable: the exception specification of the
5970 // default constructor can be needed in an unevaluated context, in
5971 // particular, in the operand of a noexcept-expression, and we can be
5972 // unable to compute an exception specification for an enclosed class.
5973 //
5974 // Any attempt to resolve the exception specification of a defaulted default
5975 // constructor before the initializer is lexically complete will ultimately
5976 // come here at which point we can diagnose it.
5977 RecordDecl *OutermostClass = ParentRD->getOuterLexicalRecordContext();
5978 Diag(Loc, DiagID: diag::err_default_member_initializer_not_yet_parsed)
5979 << OutermostClass << Field;
5980 Diag(Loc: Field->getEndLoc(),
5981 DiagID: diag::note_default_member_initializer_not_yet_parsed);
5982 // Recover by marking the field invalid, unless we're in a SFINAE context.
5983 if (!isSFINAEContext())
5984 Field->setInvalidDecl();
5985 return ExprError();
5986}
5987
5988VariadicCallType Sema::getVariadicCallType(FunctionDecl *FDecl,
5989 const FunctionProtoType *Proto,
5990 Expr *Fn) {
5991 if (Proto && Proto->isVariadic()) {
5992 if (isa_and_nonnull<CXXConstructorDecl>(Val: FDecl))
5993 return VariadicCallType::Constructor;
5994 else if (Fn && Fn->getType()->isBlockPointerType())
5995 return VariadicCallType::Block;
5996 else if (FDecl) {
5997 if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(Val: FDecl))
5998 if (Method->isInstance())
5999 return VariadicCallType::Method;
6000 } else if (Fn && Fn->getType() == Context.BoundMemberTy)
6001 return VariadicCallType::Method;
6002 return VariadicCallType::Function;
6003 }
6004 return VariadicCallType::DoesNotApply;
6005}
6006
6007namespace {
6008class FunctionCallCCC final : public FunctionCallFilterCCC {
6009public:
6010 FunctionCallCCC(Sema &SemaRef, const IdentifierInfo *FuncName,
6011 unsigned NumArgs, MemberExpr *ME)
6012 : FunctionCallFilterCCC(SemaRef, NumArgs, false, ME),
6013 FunctionName(FuncName) {}
6014
6015 bool ValidateCandidate(const TypoCorrection &candidate) override {
6016 if (!candidate.getCorrectionSpecifier() ||
6017 candidate.getCorrectionAsIdentifierInfo() != FunctionName) {
6018 return false;
6019 }
6020
6021 return FunctionCallFilterCCC::ValidateCandidate(candidate);
6022 }
6023
6024 std::unique_ptr<CorrectionCandidateCallback> clone() override {
6025 return std::make_unique<FunctionCallCCC>(args&: *this);
6026 }
6027
6028private:
6029 const IdentifierInfo *const FunctionName;
6030};
6031}
6032
6033static TypoCorrection TryTypoCorrectionForCall(Sema &S, Expr *Fn,
6034 FunctionDecl *FDecl,
6035 ArrayRef<Expr *> Args) {
6036 MemberExpr *ME = dyn_cast<MemberExpr>(Val: Fn);
6037 DeclarationName FuncName = FDecl->getDeclName();
6038 SourceLocation NameLoc = ME ? ME->getMemberLoc() : Fn->getBeginLoc();
6039
6040 FunctionCallCCC CCC(S, FuncName.getAsIdentifierInfo(), Args.size(), ME);
6041 if (TypoCorrection Corrected = S.CorrectTypo(
6042 Typo: DeclarationNameInfo(FuncName, NameLoc), LookupKind: Sema::LookupOrdinaryName,
6043 S: S.getScopeForContext(Ctx: S.CurContext), SS: nullptr, CCC,
6044 Mode: CorrectTypoKind::ErrorRecovery)) {
6045 if (NamedDecl *ND = Corrected.getFoundDecl()) {
6046 if (Corrected.isOverloaded()) {
6047 OverloadCandidateSet OCS(NameLoc, OverloadCandidateSet::CSK_Normal);
6048 OverloadCandidateSet::iterator Best;
6049 for (NamedDecl *CD : Corrected) {
6050 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Val: CD))
6051 S.AddOverloadCandidate(Function: FD, FoundDecl: DeclAccessPair::make(D: FD, AS: AS_none), Args,
6052 CandidateSet&: OCS);
6053 }
6054 switch (OCS.BestViableFunction(S, Loc: NameLoc, Best)) {
6055 case OR_Success:
6056 ND = Best->FoundDecl;
6057 Corrected.setCorrectionDecl(ND);
6058 break;
6059 default:
6060 break;
6061 }
6062 }
6063 ND = ND->getUnderlyingDecl();
6064 if (isa<ValueDecl>(Val: ND) || isa<FunctionTemplateDecl>(Val: ND))
6065 return Corrected;
6066 }
6067 }
6068 return TypoCorrection();
6069}
6070
6071// [C++26][[expr.unary.op]/p4
6072// A pointer to member is only formed when an explicit &
6073// is used and its operand is a qualified-id not enclosed in parentheses.
6074static bool isParenthetizedAndQualifiedAddressOfExpr(Expr *Fn) {
6075 if (!isa<ParenExpr>(Val: Fn))
6076 return false;
6077
6078 Fn = Fn->IgnoreParens();
6079
6080 auto *UO = dyn_cast<UnaryOperator>(Val: Fn);
6081 if (!UO || UO->getOpcode() != clang::UO_AddrOf)
6082 return false;
6083 if (auto *DRE = dyn_cast<DeclRefExpr>(Val: UO->getSubExpr()->IgnoreParens())) {
6084 return DRE->hasQualifier();
6085 }
6086 if (auto *OVL = dyn_cast<OverloadExpr>(Val: UO->getSubExpr()->IgnoreParens()))
6087 return bool(OVL->getQualifier());
6088 return false;
6089}
6090
6091bool
6092Sema::ConvertArgumentsForCall(CallExpr *Call, Expr *Fn,
6093 FunctionDecl *FDecl,
6094 const FunctionProtoType *Proto,
6095 ArrayRef<Expr *> Args,
6096 SourceLocation RParenLoc,
6097 bool IsExecConfig) {
6098 // Bail out early if calling a builtin with custom typechecking.
6099 // For HLSL builtin aliases, argument conversion is still needed because
6100 // overload resolution may have selected a conversion sequence (e.g.,
6101 // vector-to-scalar truncation) that must be applied before the custom
6102 // type checker runs.
6103 if (FDecl)
6104 if (unsigned ID = FDecl->getBuiltinID())
6105 if (Context.BuiltinInfo.hasCustomTypechecking(ID) &&
6106 !(Context.getLangOpts().HLSL && FDecl->hasAttr<BuiltinAliasAttr>()))
6107 return false;
6108
6109 // C99 6.5.2.2p7 - the arguments are implicitly converted, as if by
6110 // assignment, to the types of the corresponding parameter, ...
6111
6112 bool AddressOf = isParenthetizedAndQualifiedAddressOfExpr(Fn);
6113 bool HasExplicitObjectParameter =
6114 !AddressOf && FDecl && FDecl->hasCXXExplicitFunctionObjectParameter();
6115 unsigned ExplicitObjectParameterOffset = HasExplicitObjectParameter ? 1 : 0;
6116 unsigned NumParams = Proto->getNumParams();
6117 bool Invalid = false;
6118 unsigned MinArgs = FDecl ? FDecl->getMinRequiredArguments() : NumParams;
6119 unsigned FnKind = Fn->getType()->isBlockPointerType()
6120 ? 1 /* block */
6121 : (IsExecConfig ? 3 /* kernel function (exec config) */
6122 : 0 /* function */);
6123
6124 // If too few arguments are available (and we don't have default
6125 // arguments for the remaining parameters), don't make the call.
6126 if (Args.size() < NumParams) {
6127 if (Args.size() < MinArgs) {
6128 TypoCorrection TC;
6129 if (FDecl && (TC = TryTypoCorrectionForCall(S&: *this, Fn, FDecl, Args))) {
6130 unsigned diag_id =
6131 MinArgs == NumParams && !Proto->isVariadic()
6132 ? diag::err_typecheck_call_too_few_args_suggest
6133 : diag::err_typecheck_call_too_few_args_at_least_suggest;
6134 diagnoseTypo(
6135 Correction: TC, TypoDiag: PDiag(DiagID: diag_id)
6136 << FnKind << MinArgs - ExplicitObjectParameterOffset
6137 << static_cast<unsigned>(Args.size()) -
6138 ExplicitObjectParameterOffset
6139 << HasExplicitObjectParameter << TC.getCorrectionRange());
6140 } else if (MinArgs - ExplicitObjectParameterOffset == 1 && FDecl &&
6141 FDecl->getParamDecl(i: ExplicitObjectParameterOffset)
6142 ->getDeclName())
6143 Diag(Loc: RParenLoc,
6144 DiagID: MinArgs == NumParams && !Proto->isVariadic()
6145 ? diag::err_typecheck_call_too_few_args_one
6146 : diag::err_typecheck_call_too_few_args_at_least_one)
6147 << FnKind << FDecl->getParamDecl(i: ExplicitObjectParameterOffset)
6148 << HasExplicitObjectParameter << Fn->getSourceRange();
6149 else
6150 Diag(Loc: RParenLoc, DiagID: MinArgs == NumParams && !Proto->isVariadic()
6151 ? diag::err_typecheck_call_too_few_args
6152 : diag::err_typecheck_call_too_few_args_at_least)
6153 << FnKind << MinArgs - ExplicitObjectParameterOffset
6154 << static_cast<unsigned>(Args.size()) -
6155 ExplicitObjectParameterOffset
6156 << HasExplicitObjectParameter << Fn->getSourceRange();
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 return true;
6164 }
6165 // We reserve space for the default arguments when we create
6166 // the call expression, before calling ConvertArgumentsForCall.
6167 assert((Call->getNumArgs() == NumParams) &&
6168 "We should have reserved space for the default arguments before!");
6169 }
6170
6171 // If too many are passed and not variadic, error on the extras and drop
6172 // them.
6173 if (Args.size() > NumParams) {
6174 if (!Proto->isVariadic()) {
6175 TypoCorrection TC;
6176 if (FDecl && (TC = TryTypoCorrectionForCall(S&: *this, Fn, FDecl, Args))) {
6177 unsigned diag_id =
6178 MinArgs == NumParams && !Proto->isVariadic()
6179 ? diag::err_typecheck_call_too_many_args_suggest
6180 : diag::err_typecheck_call_too_many_args_at_most_suggest;
6181 diagnoseTypo(
6182 Correction: TC, TypoDiag: PDiag(DiagID: diag_id)
6183 << FnKind << NumParams - ExplicitObjectParameterOffset
6184 << static_cast<unsigned>(Args.size()) -
6185 ExplicitObjectParameterOffset
6186 << HasExplicitObjectParameter << TC.getCorrectionRange());
6187 } else if (NumParams - ExplicitObjectParameterOffset == 1 && FDecl &&
6188 FDecl->getParamDecl(i: ExplicitObjectParameterOffset)
6189 ->getDeclName())
6190 Diag(Loc: Args[NumParams]->getBeginLoc(),
6191 DiagID: MinArgs == NumParams
6192 ? diag::err_typecheck_call_too_many_args_one
6193 : diag::err_typecheck_call_too_many_args_at_most_one)
6194 << FnKind << FDecl->getParamDecl(i: ExplicitObjectParameterOffset)
6195 << static_cast<unsigned>(Args.size()) -
6196 ExplicitObjectParameterOffset
6197 << HasExplicitObjectParameter << Fn->getSourceRange()
6198 << SourceRange(Args[NumParams]->getBeginLoc(),
6199 Args.back()->getEndLoc());
6200 else
6201 Diag(Loc: Args[NumParams]->getBeginLoc(),
6202 DiagID: MinArgs == NumParams
6203 ? diag::err_typecheck_call_too_many_args
6204 : diag::err_typecheck_call_too_many_args_at_most)
6205 << FnKind << NumParams - ExplicitObjectParameterOffset
6206 << static_cast<unsigned>(Args.size()) -
6207 ExplicitObjectParameterOffset
6208 << HasExplicitObjectParameter << Fn->getSourceRange()
6209 << SourceRange(Args[NumParams]->getBeginLoc(),
6210 Args.back()->getEndLoc());
6211
6212 // Emit the location of the prototype.
6213 if (!TC && FDecl && !FDecl->getBuiltinID() && !IsExecConfig)
6214 Diag(Loc: FDecl->getLocation(), DiagID: diag::note_callee_decl)
6215 << FDecl << FDecl->getParametersSourceRange();
6216
6217 // This deletes the extra arguments.
6218 Call->shrinkNumArgs(NewNumArgs: NumParams);
6219 return true;
6220 }
6221 }
6222 SmallVector<Expr *, 8> AllArgs;
6223 VariadicCallType CallType = getVariadicCallType(FDecl, Proto, Fn);
6224
6225 Invalid = GatherArgumentsForCall(CallLoc: Call->getExprLoc(), FDecl, Proto, FirstParam: 0, Args,
6226 AllArgs, CallType);
6227 if (Invalid)
6228 return true;
6229 unsigned TotalNumArgs = AllArgs.size();
6230 for (unsigned i = 0; i < TotalNumArgs; ++i)
6231 Call->setArg(Arg: i, ArgExpr: AllArgs[i]);
6232
6233 Call->computeDependence();
6234 return false;
6235}
6236
6237bool Sema::GatherArgumentsForCall(SourceLocation CallLoc, FunctionDecl *FDecl,
6238 const FunctionProtoType *Proto,
6239 unsigned FirstParam, ArrayRef<Expr *> Args,
6240 SmallVectorImpl<Expr *> &AllArgs,
6241 VariadicCallType CallType, bool AllowExplicit,
6242 bool IsListInitialization) {
6243 unsigned NumParams = Proto->getNumParams();
6244 bool Invalid = false;
6245 size_t ArgIx = 0;
6246 // Continue to check argument types (even if we have too few/many args).
6247 for (unsigned i = FirstParam; i < NumParams; i++) {
6248 QualType ProtoArgType = Proto->getParamType(i);
6249
6250 Expr *Arg;
6251 ParmVarDecl *Param = FDecl ? FDecl->getParamDecl(i) : nullptr;
6252 if (ArgIx < Args.size()) {
6253 Arg = Args[ArgIx++];
6254
6255 if (RequireCompleteType(Loc: Arg->getBeginLoc(), T: ProtoArgType,
6256 DiagID: diag::err_call_incomplete_argument, Args: Arg))
6257 return true;
6258
6259 // Strip the unbridged-cast placeholder expression off, if applicable.
6260 bool CFAudited = false;
6261 if (Arg->getType() == Context.ARCUnbridgedCastTy &&
6262 FDecl && FDecl->hasAttr<CFAuditedTransferAttr>() &&
6263 (!Param || !Param->hasAttr<CFConsumedAttr>()))
6264 Arg = ObjC().stripARCUnbridgedCast(e: Arg);
6265 else if (getLangOpts().ObjCAutoRefCount &&
6266 FDecl && FDecl->hasAttr<CFAuditedTransferAttr>() &&
6267 (!Param || !Param->hasAttr<CFConsumedAttr>()))
6268 CFAudited = true;
6269
6270 if (Proto->getExtParameterInfo(I: i).isNoEscape() &&
6271 ProtoArgType->isBlockPointerType())
6272 if (auto *BE = dyn_cast<BlockExpr>(Val: Arg->IgnoreParenNoopCasts(Ctx: Context)))
6273 BE->getBlockDecl()->setDoesNotEscape();
6274 if ((Proto->getExtParameterInfo(I: i).getABI() == ParameterABI::HLSLOut ||
6275 Proto->getExtParameterInfo(I: i).getABI() == ParameterABI::HLSLInOut)) {
6276 ExprResult ArgExpr = HLSL().ActOnOutParamExpr(Param, Arg);
6277 if (ArgExpr.isInvalid())
6278 return true;
6279 Arg = ArgExpr.getAs<Expr>();
6280 }
6281
6282 InitializedEntity Entity =
6283 Param ? InitializedEntity::InitializeParameter(Context, Parm: Param,
6284 Type: ProtoArgType)
6285 : InitializedEntity::InitializeParameter(
6286 Context, Type: ProtoArgType, Consumed: Proto->isParamConsumed(I: i));
6287
6288 // Remember that parameter belongs to a CF audited API.
6289 if (CFAudited)
6290 Entity.setParameterCFAudited();
6291
6292 // Warn if argument has OBT but parameter doesn't, discarding OBTs at
6293 // function boundaries is a common oversight.
6294 if (const auto *OBT = Arg->getType()->getAs<OverflowBehaviorType>();
6295 OBT && !ProtoArgType->isOverflowBehaviorType()) {
6296 bool isPedantic =
6297 OBT->isUnsignedIntegerOrEnumerationType() && OBT->isWrapKind();
6298 Diag(Loc: Arg->getExprLoc(),
6299 DiagID: isPedantic ? diag::warn_obt_discarded_at_function_boundary_pedantic
6300 : diag::warn_obt_discarded_at_function_boundary)
6301 << Arg->getType() << ProtoArgType;
6302 }
6303
6304 ExprResult ArgE = PerformCopyInitialization(
6305 Entity, EqualLoc: SourceLocation(), Init: Arg, TopLevelOfInitList: IsListInitialization, AllowExplicit);
6306 if (ArgE.isInvalid())
6307 return true;
6308
6309 Arg = ArgE.getAs<Expr>();
6310 } else {
6311 assert(Param && "can't use default arguments without a known callee");
6312
6313 ExprResult ArgExpr = BuildCXXDefaultArgExpr(CallLoc, FD: FDecl, Param);
6314 if (ArgExpr.isInvalid())
6315 return true;
6316
6317 Arg = ArgExpr.getAs<Expr>();
6318 }
6319
6320 // Check for array bounds violations for each argument to the call. This
6321 // check only triggers warnings when the argument isn't a more complex Expr
6322 // with its own checking, such as a BinaryOperator.
6323 CheckArrayAccess(E: Arg);
6324
6325 // Check for violations of C99 static array rules (C99 6.7.5.3p7).
6326 CheckStaticArrayArgument(CallLoc, Param, ArgExpr: Arg);
6327
6328 AllArgs.push_back(Elt: Arg);
6329 }
6330
6331 // If this is a variadic call, handle args passed through "...".
6332 if (CallType != VariadicCallType::DoesNotApply) {
6333 // Assume that extern "C" functions with variadic arguments that
6334 // return __unknown_anytype aren't *really* variadic.
6335 if (Proto->getReturnType() == Context.UnknownAnyTy && FDecl &&
6336 FDecl->isExternC()) {
6337 for (Expr *A : Args.slice(N: ArgIx)) {
6338 QualType paramType; // ignored
6339 ExprResult arg = checkUnknownAnyArg(callLoc: CallLoc, result: A, paramType);
6340 Invalid |= arg.isInvalid();
6341 AllArgs.push_back(Elt: arg.get());
6342 }
6343
6344 // Otherwise do argument promotion, (C99 6.5.2.2p7).
6345 } else {
6346 for (Expr *A : Args.slice(N: ArgIx)) {
6347 ExprResult Arg = DefaultVariadicArgumentPromotion(E: A, CT: CallType, FDecl);
6348 Invalid |= Arg.isInvalid();
6349 AllArgs.push_back(Elt: Arg.get());
6350 }
6351 }
6352
6353 // Check for array bounds violations.
6354 for (Expr *A : Args.slice(N: ArgIx))
6355 CheckArrayAccess(E: A);
6356 }
6357 return Invalid;
6358}
6359
6360static void DiagnoseCalleeStaticArrayParam(Sema &S, ParmVarDecl *PVD) {
6361 TypeLoc TL = PVD->getTypeSourceInfo()->getTypeLoc();
6362 if (DecayedTypeLoc DTL = TL.getAs<DecayedTypeLoc>())
6363 TL = DTL.getOriginalLoc();
6364 if (ArrayTypeLoc ATL = TL.getAs<ArrayTypeLoc>())
6365 S.Diag(Loc: PVD->getLocation(), DiagID: diag::note_callee_static_array)
6366 << ATL.getLocalSourceRange();
6367}
6368
6369void
6370Sema::CheckStaticArrayArgument(SourceLocation CallLoc,
6371 ParmVarDecl *Param,
6372 const Expr *ArgExpr) {
6373 // Static array parameters are not supported in C++.
6374 if (!Param || getLangOpts().CPlusPlus)
6375 return;
6376
6377 QualType OrigTy = Param->getOriginalType();
6378
6379 const ArrayType *AT = Context.getAsArrayType(T: OrigTy);
6380 if (!AT || AT->getSizeModifier() != ArraySizeModifier::Static)
6381 return;
6382
6383 if (ArgExpr->isNullPointerConstant(Ctx&: Context,
6384 NPC: Expr::NPC_NeverValueDependent)) {
6385 Diag(Loc: CallLoc, DiagID: diag::warn_null_arg) << ArgExpr->getSourceRange();
6386 DiagnoseCalleeStaticArrayParam(S&: *this, PVD: Param);
6387 return;
6388 }
6389
6390 const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(Val: AT);
6391 if (!CAT)
6392 return;
6393
6394 const ConstantArrayType *ArgCAT =
6395 Context.getAsConstantArrayType(T: ArgExpr->IgnoreParenCasts()->getType());
6396 if (!ArgCAT)
6397 return;
6398
6399 if (getASTContext().hasSameUnqualifiedType(T1: CAT->getElementType(),
6400 T2: ArgCAT->getElementType())) {
6401 if (ArgCAT->getSize().ult(RHS: CAT->getSize())) {
6402 Diag(Loc: CallLoc, DiagID: diag::warn_static_array_too_small)
6403 << ArgExpr->getSourceRange() << (unsigned)ArgCAT->getZExtSize()
6404 << (unsigned)CAT->getZExtSize() << 0;
6405 DiagnoseCalleeStaticArrayParam(S&: *this, PVD: Param);
6406 }
6407 return;
6408 }
6409
6410 std::optional<CharUnits> ArgSize =
6411 getASTContext().getTypeSizeInCharsIfKnown(Ty: ArgCAT);
6412 std::optional<CharUnits> ParmSize =
6413 getASTContext().getTypeSizeInCharsIfKnown(Ty: CAT);
6414 if (ArgSize && ParmSize && *ArgSize < *ParmSize) {
6415 Diag(Loc: CallLoc, DiagID: diag::warn_static_array_too_small)
6416 << ArgExpr->getSourceRange() << (unsigned)ArgSize->getQuantity()
6417 << (unsigned)ParmSize->getQuantity() << 1;
6418 DiagnoseCalleeStaticArrayParam(S&: *this, PVD: Param);
6419 }
6420}
6421
6422/// Given a function expression of unknown-any type, try to rebuild it
6423/// to have a function type.
6424static ExprResult rebuildUnknownAnyFunction(Sema &S, Expr *fn);
6425
6426/// Is the given type a placeholder that we need to lower out
6427/// immediately during argument processing?
6428static bool isPlaceholderToRemoveAsArg(QualType type) {
6429 // Placeholders are never sugared.
6430 const BuiltinType *placeholder = dyn_cast<BuiltinType>(Val&: type);
6431 if (!placeholder) return false;
6432
6433 switch (placeholder->getKind()) {
6434 // Ignore all the non-placeholder types.
6435#define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
6436 case BuiltinType::Id:
6437#include "clang/Basic/OpenCLImageTypes.def"
6438#define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \
6439 case BuiltinType::Id:
6440#include "clang/Basic/OpenCLExtensionTypes.def"
6441 // In practice we'll never use this, since all SVE types are sugared
6442 // via TypedefTypes rather than exposed directly as BuiltinTypes.
6443#define SVE_TYPE(Name, Id, SingletonId) \
6444 case BuiltinType::Id:
6445#include "clang/Basic/AArch64ACLETypes.def"
6446#define PPC_VECTOR_TYPE(Name, Id, Size) \
6447 case BuiltinType::Id:
6448#include "clang/Basic/PPCTypes.def"
6449#define RVV_TYPE(Name, Id, SingletonId) case BuiltinType::Id:
6450#include "clang/Basic/RISCVVTypes.def"
6451#define WASM_TYPE(Name, Id, SingletonId) case BuiltinType::Id:
6452#include "clang/Basic/WebAssemblyReferenceTypes.def"
6453#define AMDGPU_TYPE(Name, Id, SingletonId, Width, Align) case BuiltinType::Id:
6454#include "clang/Basic/AMDGPUTypes.def"
6455#define HLSL_INTANGIBLE_TYPE(Name, Id, SingletonId) case BuiltinType::Id:
6456#include "clang/Basic/HLSLIntangibleTypes.def"
6457#define PLACEHOLDER_TYPE(ID, SINGLETON_ID)
6458#define BUILTIN_TYPE(ID, SINGLETON_ID) case BuiltinType::ID:
6459#include "clang/AST/BuiltinTypes.def"
6460 return false;
6461
6462 case BuiltinType::UnresolvedTemplate:
6463 // We cannot lower out overload sets; they might validly be resolved
6464 // by the call machinery.
6465 case BuiltinType::Overload:
6466 return false;
6467
6468 // Unbridged casts in ARC can be handled in some call positions and
6469 // should be left in place.
6470 case BuiltinType::ARCUnbridgedCast:
6471 return false;
6472
6473 // Pseudo-objects should be converted as soon as possible.
6474 case BuiltinType::PseudoObject:
6475 return true;
6476
6477 // The debugger mode could theoretically but currently does not try
6478 // to resolve unknown-typed arguments based on known parameter types.
6479 case BuiltinType::UnknownAny:
6480 return true;
6481
6482 // These are always invalid as call arguments and should be reported.
6483 case BuiltinType::BoundMember:
6484 case BuiltinType::BuiltinFn:
6485 case BuiltinType::IncompleteMatrixIdx:
6486 case BuiltinType::ArraySection:
6487 case BuiltinType::OMPArrayShaping:
6488 case BuiltinType::OMPIterator:
6489 return true;
6490
6491 }
6492 llvm_unreachable("bad builtin type kind");
6493}
6494
6495bool Sema::CheckArgsForPlaceholders(MultiExprArg args) {
6496 // Apply this processing to all the arguments at once instead of
6497 // dying at the first failure.
6498 bool hasInvalid = false;
6499 for (size_t i = 0, e = args.size(); i != e; i++) {
6500 if (isPlaceholderToRemoveAsArg(type: args[i]->getType())) {
6501 ExprResult result = CheckPlaceholderExpr(E: args[i]);
6502 if (result.isInvalid()) hasInvalid = true;
6503 else args[i] = result.get();
6504 }
6505 }
6506 return hasInvalid;
6507}
6508
6509/// If a builtin function has a pointer argument with no explicit address
6510/// space, then it should be able to accept a pointer to any address
6511/// space as input. In order to do this, we need to replace the
6512/// standard builtin declaration with one that uses the same address space
6513/// as the call.
6514///
6515/// \returns nullptr If this builtin is not a candidate for a rewrite i.e.
6516/// it does not contain any pointer arguments without
6517/// an address space qualifer. Otherwise the rewritten
6518/// FunctionDecl is returned.
6519/// TODO: Handle pointer return types.
6520static FunctionDecl *rewriteBuiltinFunctionDecl(Sema *Sema, ASTContext &Context,
6521 FunctionDecl *FDecl,
6522 MultiExprArg ArgExprs) {
6523
6524 QualType DeclType = FDecl->getType();
6525 const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(Val&: DeclType);
6526
6527 if (!Context.BuiltinInfo.hasPtrArgsOrResult(ID: FDecl->getBuiltinID()) || !FT ||
6528 ArgExprs.size() < FT->getNumParams())
6529 return nullptr;
6530
6531 bool NeedsNewDecl = false;
6532 unsigned i = 0;
6533 SmallVector<QualType, 8> OverloadParams;
6534
6535 {
6536 // The lvalue conversions in this loop are only for type resolution and
6537 // don't actually occur.
6538 EnterExpressionEvaluationContext Unevaluated(
6539 *Sema, Sema::ExpressionEvaluationContext::Unevaluated);
6540 Sema::SFINAETrap Trap(*Sema, /*ForValidityCheck=*/true);
6541
6542 for (QualType ParamType : FT->param_types()) {
6543
6544 // Convert array arguments to pointer to simplify type lookup.
6545 ExprResult ArgRes =
6546 Sema->DefaultFunctionArrayLvalueConversion(E: ArgExprs[i++]);
6547 if (ArgRes.isInvalid())
6548 return nullptr;
6549 Expr *Arg = ArgRes.get();
6550 QualType ArgType = Arg->getType();
6551 if (!ParamType->isPointerType() ||
6552 ParamType->getPointeeType().hasAddressSpace() ||
6553 !ArgType->isPointerType() ||
6554 !ArgType->getPointeeType().hasAddressSpace() ||
6555 isPtrSizeAddressSpace(AS: ArgType->getPointeeType().getAddressSpace())) {
6556 OverloadParams.push_back(Elt: ParamType);
6557 continue;
6558 }
6559
6560 QualType PointeeType = ParamType->getPointeeType();
6561 NeedsNewDecl = true;
6562 LangAS AS = ArgType->getPointeeType().getAddressSpace();
6563
6564 PointeeType = Context.getAddrSpaceQualType(T: PointeeType, AddressSpace: AS);
6565 OverloadParams.push_back(Elt: Context.getPointerType(T: PointeeType));
6566 }
6567 }
6568
6569 if (!NeedsNewDecl)
6570 return nullptr;
6571
6572 FunctionProtoType::ExtProtoInfo EPI;
6573 EPI.Variadic = FT->isVariadic();
6574 QualType OverloadTy = Context.getFunctionType(ResultTy: FT->getReturnType(),
6575 Args: OverloadParams, EPI);
6576 DeclContext *Parent = FDecl->getParent();
6577 FunctionDecl *OverloadDecl = FunctionDecl::Create(
6578 C&: Context, DC: Parent, StartLoc: FDecl->getLocation(), NLoc: FDecl->getLocation(),
6579 N: FDecl->getIdentifier(), T: OverloadTy,
6580 /*TInfo=*/nullptr, SC: SC_Extern, UsesFPIntrin: Sema->getCurFPFeatures().isFPConstrained(),
6581 isInlineSpecified: false,
6582 /*hasPrototype=*/hasWrittenPrototype: true);
6583 SmallVector<ParmVarDecl*, 16> Params;
6584 FT = cast<FunctionProtoType>(Val&: OverloadTy);
6585 for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i) {
6586 QualType ParamType = FT->getParamType(i);
6587 ParmVarDecl *Parm =
6588 ParmVarDecl::Create(C&: Context, DC: OverloadDecl, StartLoc: SourceLocation(),
6589 IdLoc: SourceLocation(), Id: nullptr, T: ParamType,
6590 /*TInfo=*/nullptr, S: SC_None, DefArg: nullptr);
6591 Parm->setScopeInfo(scopeDepth: 0, parameterIndex: i);
6592 Params.push_back(Elt: Parm);
6593 }
6594 OverloadDecl->setParams(Params);
6595 // We cannot merge host/device attributes of redeclarations. They have to
6596 // be consistent when created.
6597 if (Sema->LangOpts.CUDA) {
6598 if (FDecl->hasAttr<CUDAHostAttr>())
6599 OverloadDecl->addAttr(A: CUDAHostAttr::CreateImplicit(Ctx&: Context));
6600 if (FDecl->hasAttr<CUDADeviceAttr>())
6601 OverloadDecl->addAttr(A: CUDADeviceAttr::CreateImplicit(Ctx&: Context));
6602 }
6603 Sema->mergeDeclAttributes(New: OverloadDecl, Old: FDecl);
6604 return OverloadDecl;
6605}
6606
6607static void checkDirectCallValidity(Sema &S, const Expr *Fn,
6608 FunctionDecl *Callee,
6609 MultiExprArg ArgExprs) {
6610 // `Callee` (when called with ArgExprs) may be ill-formed. enable_if (and
6611 // similar attributes) really don't like it when functions are called with an
6612 // invalid number of args.
6613 if (S.TooManyArguments(NumParams: Callee->getNumParams(), NumArgs: ArgExprs.size(),
6614 /*PartialOverloading=*/false) &&
6615 !Callee->isVariadic())
6616 return;
6617 if (Callee->getMinRequiredArguments() > ArgExprs.size())
6618 return;
6619
6620 if (const EnableIfAttr *Attr =
6621 S.CheckEnableIf(Function: Callee, CallLoc: Fn->getBeginLoc(), Args: ArgExprs, MissingImplicitThis: true)) {
6622 S.Diag(Loc: Fn->getBeginLoc(),
6623 DiagID: isa<CXXMethodDecl>(Val: Callee)
6624 ? diag::err_ovl_no_viable_member_function_in_call
6625 : diag::err_ovl_no_viable_function_in_call)
6626 << Callee << Callee->getSourceRange();
6627 S.Diag(Loc: Callee->getLocation(),
6628 DiagID: diag::note_ovl_candidate_disabled_by_function_cond_attr)
6629 << Attr->getCond()->getSourceRange() << Attr->getMessage();
6630 return;
6631 }
6632}
6633
6634static bool enclosingClassIsRelatedToClassInWhichMembersWereFound(
6635 const UnresolvedMemberExpr *const UME, Sema &S) {
6636
6637 const auto GetFunctionLevelDCIfCXXClass =
6638 [](Sema &S) -> const CXXRecordDecl * {
6639 const DeclContext *const DC = S.getFunctionLevelDeclContext();
6640 if (!DC || !DC->getParent())
6641 return nullptr;
6642
6643 // If the call to some member function was made from within a member
6644 // function body 'M' return return 'M's parent.
6645 if (const auto *MD = dyn_cast<CXXMethodDecl>(Val: DC))
6646 return MD->getParent()->getCanonicalDecl();
6647 // else the call was made from within a default member initializer of a
6648 // class, so return the class.
6649 if (const auto *RD = dyn_cast<CXXRecordDecl>(Val: DC))
6650 return RD->getCanonicalDecl();
6651 return nullptr;
6652 };
6653 // If our DeclContext is neither a member function nor a class (in the
6654 // case of a lambda in a default member initializer), we can't have an
6655 // enclosing 'this'.
6656
6657 const CXXRecordDecl *const CurParentClass = GetFunctionLevelDCIfCXXClass(S);
6658 if (!CurParentClass)
6659 return false;
6660
6661 // The naming class for implicit member functions call is the class in which
6662 // name lookup starts.
6663 const CXXRecordDecl *const NamingClass =
6664 UME->getNamingClass()->getCanonicalDecl();
6665 assert(NamingClass && "Must have naming class even for implicit access");
6666
6667 // If the unresolved member functions were found in a 'naming class' that is
6668 // related (either the same or derived from) to the class that contains the
6669 // member function that itself contained the implicit member access.
6670
6671 return CurParentClass == NamingClass ||
6672 CurParentClass->isDerivedFrom(Base: NamingClass);
6673}
6674
6675static void
6676tryImplicitlyCaptureThisIfImplicitMemberFunctionAccessWithDependentArgs(
6677 Sema &S, const UnresolvedMemberExpr *const UME, SourceLocation CallLoc) {
6678
6679 if (!UME)
6680 return;
6681
6682 LambdaScopeInfo *const CurLSI = S.getCurLambda();
6683 // Only try and implicitly capture 'this' within a C++ Lambda if it hasn't
6684 // already been captured, or if this is an implicit member function call (if
6685 // it isn't, an attempt to capture 'this' should already have been made).
6686 if (!CurLSI || CurLSI->ImpCaptureStyle == CurLSI->ImpCap_None ||
6687 !UME->isImplicitAccess() || CurLSI->isCXXThisCaptured())
6688 return;
6689
6690 // Check if the naming class in which the unresolved members were found is
6691 // related (same as or is a base of) to the enclosing class.
6692
6693 if (!enclosingClassIsRelatedToClassInWhichMembersWereFound(UME, S))
6694 return;
6695
6696
6697 DeclContext *EnclosingFunctionCtx = S.CurContext->getParent()->getParent();
6698 // If the enclosing function is not dependent, then this lambda is
6699 // capture ready, so if we can capture this, do so.
6700 if (!EnclosingFunctionCtx->isDependentContext()) {
6701 // If the current lambda and all enclosing lambdas can capture 'this' -
6702 // then go ahead and capture 'this' (since our unresolved overload set
6703 // contains at least one non-static member function).
6704 if (!S.CheckCXXThisCapture(Loc: CallLoc, /*Explcit*/ Explicit: false, /*Diagnose*/ BuildAndDiagnose: false))
6705 S.CheckCXXThisCapture(Loc: CallLoc);
6706 } else if (S.CurContext->isDependentContext()) {
6707 // ... since this is an implicit member reference, that might potentially
6708 // involve a 'this' capture, mark 'this' for potential capture in
6709 // enclosing lambdas.
6710 if (CurLSI->ImpCaptureStyle != CurLSI->ImpCap_None)
6711 CurLSI->addPotentialThisCapture(Loc: CallLoc);
6712 }
6713}
6714
6715// Once a call is fully resolved, warn for unqualified calls to specific
6716// C++ standard functions, like move and forward.
6717static void DiagnosedUnqualifiedCallsToStdFunctions(Sema &S,
6718 const CallExpr *Call) {
6719 // We are only checking unary move and forward so exit early here.
6720 if (Call->getNumArgs() != 1)
6721 return;
6722
6723 const Expr *E = Call->getCallee()->IgnoreParenImpCasts();
6724 if (!E || isa<UnresolvedLookupExpr>(Val: E))
6725 return;
6726 const DeclRefExpr *DRE = dyn_cast_if_present<DeclRefExpr>(Val: E);
6727 if (!DRE || !DRE->getLocation().isValid())
6728 return;
6729
6730 if (DRE->getQualifier())
6731 return;
6732
6733 const FunctionDecl *FD = Call->getDirectCallee();
6734 if (!FD)
6735 return;
6736
6737 // Only warn for some functions deemed more frequent or problematic.
6738 unsigned BuiltinID = FD->getBuiltinID();
6739 if (BuiltinID != Builtin::BImove && BuiltinID != Builtin::BIforward)
6740 return;
6741
6742 S.Diag(Loc: DRE->getLocation(), DiagID: diag::warn_unqualified_call_to_std_cast_function)
6743 << FD->getQualifiedNameAsString()
6744 << FixItHint::CreateInsertion(InsertionLoc: DRE->getLocation(), Code: "std::");
6745}
6746
6747ExprResult Sema::ActOnCallExpr(Scope *Scope, Expr *Fn, SourceLocation LParenLoc,
6748 MultiExprArg ArgExprs, SourceLocation RParenLoc,
6749 Expr *ExecConfig) {
6750 ExprResult Call =
6751 BuildCallExpr(S: Scope, Fn, LParenLoc, ArgExprs, RParenLoc, ExecConfig,
6752 /*IsExecConfig=*/false, /*AllowRecovery=*/true);
6753 if (Call.isInvalid())
6754 return Call;
6755
6756 // Diagnose uses of the C++20 "ADL-only template-id call" feature in earlier
6757 // language modes.
6758 if (const auto *ULE = dyn_cast<UnresolvedLookupExpr>(Val: Fn);
6759 ULE && ULE->hasExplicitTemplateArgs() && ULE->decls().empty()) {
6760 DiagCompat(Loc: Fn->getExprLoc(), CompatDiagId: diag_compat::adl_only_template_id)
6761 << ULE->getName();
6762 }
6763
6764 if (LangOpts.OpenMP)
6765 Call = OpenMP().ActOnOpenMPCall(Call, Scope, LParenLoc, ArgExprs, RParenLoc,
6766 ExecConfig);
6767 if (LangOpts.CPlusPlus) {
6768 if (const auto *CE = dyn_cast<CallExpr>(Val: Call.get()))
6769 DiagnosedUnqualifiedCallsToStdFunctions(S&: *this, Call: CE);
6770
6771 // If we previously found that the id-expression of this call refers to a
6772 // consteval function but the call is dependent, we should not treat is an
6773 // an invalid immediate call.
6774 if (auto *DRE = dyn_cast<DeclRefExpr>(Val: Fn->IgnoreParens());
6775 DRE && Call.get()->isValueDependent()) {
6776 currentEvaluationContext().ReferenceToConsteval.erase(Ptr: DRE);
6777 }
6778 }
6779 return Call;
6780}
6781
6782// Any type that could be used to form a callable expression
6783static bool MayBeFunctionType(const ASTContext &Context, const Expr *E) {
6784 QualType T = E->getType();
6785 if (T->isDependentType())
6786 return true;
6787
6788 if (T == Context.BoundMemberTy || T == Context.UnknownAnyTy ||
6789 T == Context.BuiltinFnTy || T == Context.OverloadTy ||
6790 T->isFunctionType() || T->isFunctionReferenceType() ||
6791 T->isMemberFunctionPointerType() || T->isFunctionPointerType() ||
6792 T->isBlockPointerType() || T->isRecordType())
6793 return true;
6794
6795 return isa<CallExpr, DeclRefExpr, MemberExpr, CXXPseudoDestructorExpr,
6796 OverloadExpr, UnresolvedMemberExpr, UnaryOperator>(Val: E);
6797}
6798
6799ExprResult Sema::BuildCallExpr(Scope *Scope, Expr *Fn, SourceLocation LParenLoc,
6800 MultiExprArg ArgExprs, SourceLocation RParenLoc,
6801 Expr *ExecConfig, bool IsExecConfig,
6802 bool AllowRecovery) {
6803 // Since this might be a postfix expression, get rid of ParenListExprs.
6804 ExprResult Result = MaybeConvertParenListExprToParenExpr(S: Scope, ME: Fn);
6805 if (Result.isInvalid()) return ExprError();
6806 Fn = Result.get();
6807
6808 // The __builtin_amdgcn_is_invocable builtin is special, and will be resolved
6809 // later, when we check boolean conditions, for now we merely forward it
6810 // without any additional checking.
6811 if (Fn->getType() == Context.BuiltinFnTy && ArgExprs.size() == 1 &&
6812 ArgExprs[0]->getType() == Context.BuiltinFnTy) {
6813 const auto *FD = cast<FunctionDecl>(Val: Fn->getReferencedDeclOfCallee());
6814
6815 if (FD->getName() == "__builtin_amdgcn_is_invocable") {
6816 QualType FnPtrTy = Context.getPointerType(T: FD->getType());
6817 Expr *R = ImpCastExprToType(E: Fn, Type: FnPtrTy, CK: CK_BuiltinFnToFnPtr).get();
6818 return CallExpr::Create(
6819 Ctx: Context, Fn: R, Args: ArgExprs, Ty: Context.AMDGPUFeaturePredicateTy,
6820 VK: ExprValueKind::VK_PRValue, RParenLoc, FPFeatures: FPOptionsOverride());
6821 }
6822 }
6823
6824 if (CheckArgsForPlaceholders(args: ArgExprs))
6825 return ExprError();
6826
6827 // The result of __builtin_counted_by_ref cannot be used as a function
6828 // argument. It allows leaking and modification of bounds safety information.
6829 for (const Expr *Arg : ArgExprs)
6830 if (CheckInvalidBuiltinCountedByRef(E: Arg,
6831 K: BuiltinCountedByRefKind::FunctionArg))
6832 return ExprError();
6833
6834 if (getLangOpts().CPlusPlus) {
6835 // If this is a pseudo-destructor expression, build the call immediately.
6836 if (isa<CXXPseudoDestructorExpr>(Val: Fn)) {
6837 if (!ArgExprs.empty()) {
6838 // Pseudo-destructor calls should not have any arguments.
6839 Diag(Loc: Fn->getBeginLoc(), DiagID: diag::err_pseudo_dtor_call_with_args)
6840 << FixItHint::CreateRemoval(
6841 RemoveRange: SourceRange(ArgExprs.front()->getBeginLoc(),
6842 ArgExprs.back()->getEndLoc()));
6843 }
6844
6845 return CallExpr::Create(Ctx: Context, Fn, /*Args=*/{}, Ty: Context.VoidTy,
6846 VK: VK_PRValue, RParenLoc, FPFeatures: CurFPFeatureOverrides());
6847 }
6848 if (Fn->getType() == Context.PseudoObjectTy) {
6849 ExprResult result = CheckPlaceholderExpr(E: Fn);
6850 if (result.isInvalid()) return ExprError();
6851 Fn = result.get();
6852 }
6853
6854 // Determine whether this is a dependent call inside a C++ template,
6855 // in which case we won't do any semantic analysis now.
6856 if (Fn->isTypeDependent() || Expr::hasAnyTypeDependentArguments(Exprs: ArgExprs)) {
6857 if (ExecConfig) {
6858 return CUDAKernelCallExpr::Create(Ctx: Context, Fn,
6859 Config: cast<CallExpr>(Val: ExecConfig), Args: ArgExprs,
6860 Ty: Context.DependentTy, VK: VK_PRValue,
6861 RP: RParenLoc, FPFeatures: CurFPFeatureOverrides());
6862 } else {
6863
6864 tryImplicitlyCaptureThisIfImplicitMemberFunctionAccessWithDependentArgs(
6865 S&: *this, UME: dyn_cast<UnresolvedMemberExpr>(Val: Fn->IgnoreParens()),
6866 CallLoc: Fn->getBeginLoc());
6867
6868 // If the type of the function itself is not dependent
6869 // check that it is a reasonable as a function, as type deduction
6870 // later assume the CallExpr has a sensible TYPE.
6871 if (!MayBeFunctionType(Context, E: Fn))
6872 return ExprError(
6873 Diag(Loc: LParenLoc, DiagID: diag::err_typecheck_call_not_function)
6874 << Fn->getType() << Fn->getSourceRange());
6875
6876 return CallExpr::Create(Ctx: Context, Fn, Args: ArgExprs, Ty: Context.DependentTy,
6877 VK: VK_PRValue, RParenLoc, FPFeatures: CurFPFeatureOverrides());
6878 }
6879 }
6880
6881 // Determine whether this is a call to an object (C++ [over.call.object]).
6882 if (Fn->getType()->isRecordType())
6883 return BuildCallToObjectOfClassType(S: Scope, Object: Fn, LParenLoc, Args: ArgExprs,
6884 RParenLoc);
6885
6886 if (Fn->getType() == Context.UnknownAnyTy) {
6887 ExprResult result = rebuildUnknownAnyFunction(S&: *this, fn: Fn);
6888 if (result.isInvalid()) return ExprError();
6889 Fn = result.get();
6890 }
6891
6892 if (Fn->getType() == Context.BoundMemberTy) {
6893 return BuildCallToMemberFunction(S: Scope, MemExpr: Fn, LParenLoc, Args: ArgExprs,
6894 RParenLoc, ExecConfig, IsExecConfig,
6895 AllowRecovery);
6896 }
6897 }
6898
6899 // Check for overloaded calls. This can happen even in C due to extensions.
6900 if (Fn->getType() == Context.OverloadTy) {
6901 OverloadExpr::FindResult find = OverloadExpr::find(E: Fn);
6902
6903 // We aren't supposed to apply this logic if there's an '&' involved.
6904 if (!find.HasFormOfMemberPointer || find.IsAddressOfOperandWithParen) {
6905 if (Expr::hasAnyTypeDependentArguments(Exprs: ArgExprs))
6906 return CallExpr::Create(Ctx: Context, Fn, Args: ArgExprs, Ty: Context.DependentTy,
6907 VK: VK_PRValue, RParenLoc, FPFeatures: CurFPFeatureOverrides());
6908 OverloadExpr *ovl = find.Expression;
6909 if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(Val: ovl))
6910 return BuildOverloadedCallExpr(
6911 S: Scope, Fn, ULE, LParenLoc, Args: ArgExprs, RParenLoc, ExecConfig,
6912 /*AllowTypoCorrection=*/true, CalleesAddressIsTaken: find.IsAddressOfOperand);
6913 return BuildCallToMemberFunction(S: Scope, MemExpr: Fn, LParenLoc, Args: ArgExprs,
6914 RParenLoc, ExecConfig, IsExecConfig,
6915 AllowRecovery);
6916 }
6917 }
6918
6919 // If we're directly calling a function, get the appropriate declaration.
6920 if (Fn->getType() == Context.UnknownAnyTy) {
6921 ExprResult result = rebuildUnknownAnyFunction(S&: *this, fn: Fn);
6922 if (result.isInvalid()) return ExprError();
6923 Fn = result.get();
6924 }
6925
6926 Expr *NakedFn = Fn->IgnoreParens();
6927
6928 bool CallingNDeclIndirectly = false;
6929 NamedDecl *NDecl = nullptr;
6930 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(Val: NakedFn)) {
6931 if (UnOp->getOpcode() == UO_AddrOf) {
6932 CallingNDeclIndirectly = true;
6933 NakedFn = UnOp->getSubExpr()->IgnoreParens();
6934 }
6935 }
6936
6937 if (auto *DRE = dyn_cast<DeclRefExpr>(Val: NakedFn)) {
6938 NDecl = DRE->getDecl();
6939
6940 FunctionDecl *FDecl = dyn_cast<FunctionDecl>(Val: NDecl);
6941 if (FDecl && FDecl->getBuiltinID()) {
6942 const llvm::Triple &Triple = Context.getTargetInfo().getTriple();
6943 if (Triple.isSPIRV() && Triple.getVendor() == llvm::Triple::AMD) {
6944 if (Context.BuiltinInfo.isTSBuiltin(ID: FDecl->getBuiltinID()) &&
6945 !Context.BuiltinInfo.isAuxBuiltinID(ID: FDecl->getBuiltinID())) {
6946 AMDGPU().AddPotentiallyUnguardedBuiltinUser(FD: cast<FunctionDecl>(
6947 Val: getFunctionLevelDeclContext(/*AllowLambda=*/true)));
6948 }
6949 }
6950
6951 // Rewrite the function decl for this builtin by replacing parameters
6952 // with no explicit address space with the address space of the arguments
6953 // in ArgExprs.
6954 if ((FDecl =
6955 rewriteBuiltinFunctionDecl(Sema: this, Context, FDecl, ArgExprs))) {
6956 NDecl = FDecl;
6957 Fn = DeclRefExpr::Create(
6958 Context, QualifierLoc: DRE->getQualifierLoc(), TemplateKWLoc: SourceLocation(), D: FDecl, RefersToEnclosingVariableOrCapture: false,
6959 NameLoc: SourceLocation(), T: Fn->getType() /* BuiltinFnTy */,
6960 VK: Fn->getValueKind(), FoundD: FDecl, TemplateArgs: nullptr, NOUR: DRE->isNonOdrUse());
6961 }
6962 }
6963 } else if (auto *ME = dyn_cast<MemberExpr>(Val: NakedFn))
6964 NDecl = ME->getMemberDecl();
6965
6966 if (FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(Val: NDecl)) {
6967 if (CallingNDeclIndirectly && !checkAddressOfFunctionIsAvailable(
6968 Function: FD, /*Complain=*/true, Loc: Fn->getBeginLoc()))
6969 return ExprError();
6970
6971 checkDirectCallValidity(S&: *this, Fn, Callee: FD, ArgExprs);
6972
6973 // If this expression is a call to a builtin function in HIP compilation,
6974 // allow a pointer-type argument to default address space to be passed as a
6975 // pointer-type parameter to a non-default address space. If Arg is declared
6976 // in the default address space and Param is declared in a non-default
6977 // address space, perform an implicit address space cast to the parameter
6978 // type.
6979 if (getLangOpts().HIP && FD && FD->getBuiltinID()) {
6980 for (unsigned Idx = 0; Idx < ArgExprs.size() && Idx < FD->param_size();
6981 ++Idx) {
6982 ParmVarDecl *Param = FD->getParamDecl(i: Idx);
6983 if (!ArgExprs[Idx] || !Param || !Param->getType()->isPointerType() ||
6984 !ArgExprs[Idx]->getType()->isPointerType())
6985 continue;
6986
6987 auto ParamAS = Param->getType()->getPointeeType().getAddressSpace();
6988 auto ArgTy = ArgExprs[Idx]->getType();
6989 auto ArgPtTy = ArgTy->getPointeeType();
6990 auto ArgAS = ArgPtTy.getAddressSpace();
6991
6992 // Add address space cast if target address spaces are different
6993 bool NeedImplicitASC =
6994 ParamAS != LangAS::Default && // Pointer params in generic AS don't need special handling.
6995 ( ArgAS == LangAS::Default || // We do allow implicit conversion from generic AS
6996 // or from specific AS which has target AS matching that of Param.
6997 getASTContext().getTargetAddressSpace(AS: ArgAS) == getASTContext().getTargetAddressSpace(AS: ParamAS));
6998 if (!NeedImplicitASC)
6999 continue;
7000
7001 // First, ensure that the Arg is an RValue.
7002 if (ArgExprs[Idx]->isGLValue()) {
7003 ExprResult Res = DefaultLvalueConversion(E: ArgExprs[Idx]);
7004 if (Res.isInvalid())
7005 return ExprError();
7006 ArgExprs[Idx] = Res.get();
7007 }
7008
7009 // Construct a new arg type with address space of Param
7010 Qualifiers ArgPtQuals = ArgPtTy.getQualifiers();
7011 ArgPtQuals.setAddressSpace(ParamAS);
7012 auto NewArgPtTy =
7013 Context.getQualifiedType(T: ArgPtTy.getUnqualifiedType(), Qs: ArgPtQuals);
7014 auto NewArgTy =
7015 Context.getQualifiedType(T: Context.getPointerType(T: NewArgPtTy),
7016 Qs: ArgTy.getQualifiers());
7017
7018 // Finally perform an implicit address space cast
7019 ArgExprs[Idx] = ImpCastExprToType(E: ArgExprs[Idx], Type: NewArgTy,
7020 CK: CK_AddressSpaceConversion)
7021 .get();
7022 }
7023 }
7024 }
7025
7026 if (Context.isDependenceAllowed() &&
7027 (Fn->isTypeDependent() || Expr::hasAnyTypeDependentArguments(Exprs: ArgExprs))) {
7028 assert(!getLangOpts().CPlusPlus);
7029 assert((Fn->containsErrors() ||
7030 llvm::any_of(ArgExprs,
7031 [](clang::Expr *E) { return E->containsErrors(); })) &&
7032 "should only occur in error-recovery path.");
7033 return CallExpr::Create(Ctx: Context, Fn, Args: ArgExprs, Ty: Context.DependentTy,
7034 VK: VK_PRValue, RParenLoc, FPFeatures: CurFPFeatureOverrides());
7035 }
7036 return BuildResolvedCallExpr(Fn, NDecl, LParenLoc, Arg: ArgExprs, RParenLoc,
7037 Config: ExecConfig, IsExecConfig);
7038}
7039
7040Expr *Sema::BuildBuiltinCallExpr(SourceLocation Loc, Builtin::ID Id,
7041 MultiExprArg CallArgs) {
7042 std::string Name = Context.BuiltinInfo.getName(ID: Id);
7043 LookupResult R(*this, &Context.Idents.get(Name), Loc,
7044 Sema::LookupOrdinaryName);
7045 LookupName(R, S: TUScope, /*AllowBuiltinCreation=*/true);
7046
7047 auto *BuiltInDecl = R.getAsSingle<FunctionDecl>();
7048 assert(BuiltInDecl && "failed to find builtin declaration");
7049
7050 ExprResult DeclRef =
7051 BuildDeclRefExpr(D: BuiltInDecl, Ty: BuiltInDecl->getType(), VK: VK_LValue, Loc);
7052 assert(DeclRef.isUsable() && "Builtin reference cannot fail");
7053
7054 ExprResult Call =
7055 BuildCallExpr(/*Scope=*/nullptr, Fn: DeclRef.get(), LParenLoc: Loc, ArgExprs: CallArgs, RParenLoc: Loc);
7056
7057 assert(!Call.isInvalid() && "Call to builtin cannot fail!");
7058 return Call.get();
7059}
7060
7061ExprResult Sema::ActOnAsTypeExpr(Expr *E, ParsedType ParsedDestTy,
7062 SourceLocation BuiltinLoc,
7063 SourceLocation RParenLoc) {
7064 QualType DstTy = GetTypeFromParser(Ty: ParsedDestTy);
7065 return BuildAsTypeExpr(E, DestTy: DstTy, BuiltinLoc, RParenLoc);
7066}
7067
7068ExprResult Sema::BuildAsTypeExpr(Expr *E, QualType DestTy,
7069 SourceLocation BuiltinLoc,
7070 SourceLocation RParenLoc) {
7071 ExprValueKind VK = VK_PRValue;
7072 ExprObjectKind OK = OK_Ordinary;
7073 QualType SrcTy = E->getType();
7074 if (!SrcTy->isDependentType() &&
7075 Context.getTypeSize(T: DestTy) != Context.getTypeSize(T: SrcTy))
7076 return ExprError(
7077 Diag(Loc: BuiltinLoc, DiagID: diag::err_invalid_astype_of_different_size)
7078 << DestTy << SrcTy << E->getSourceRange());
7079 return new (Context) AsTypeExpr(E, DestTy, VK, OK, BuiltinLoc, RParenLoc);
7080}
7081
7082ExprResult Sema::ActOnConvertVectorExpr(Expr *E, ParsedType ParsedDestTy,
7083 SourceLocation BuiltinLoc,
7084 SourceLocation RParenLoc) {
7085 TypeSourceInfo *TInfo;
7086 GetTypeFromParser(Ty: ParsedDestTy, TInfo: &TInfo);
7087 return ConvertVectorExpr(E, TInfo, BuiltinLoc, RParenLoc);
7088}
7089
7090ExprResult Sema::BuildResolvedCallExpr(Expr *Fn, NamedDecl *NDecl,
7091 SourceLocation LParenLoc,
7092 ArrayRef<Expr *> Args,
7093 SourceLocation RParenLoc, Expr *Config,
7094 bool IsExecConfig, ADLCallKind UsesADL) {
7095 FunctionDecl *FDecl = dyn_cast_or_null<FunctionDecl>(Val: NDecl);
7096 unsigned BuiltinID = (FDecl ? FDecl->getBuiltinID() : 0);
7097
7098 auto IsSJLJ = [&] {
7099 switch (BuiltinID) {
7100 case Builtin::BI__builtin_longjmp:
7101 case Builtin::BI__builtin_setjmp:
7102 case Builtin::BI__sigsetjmp:
7103 case Builtin::BI_longjmp:
7104 case Builtin::BI_setjmp:
7105 case Builtin::BIlongjmp:
7106 case Builtin::BIsetjmp:
7107 case Builtin::BIsiglongjmp:
7108 case Builtin::BIsigsetjmp:
7109 return true;
7110 default:
7111 return false;
7112 }
7113 };
7114
7115 // Forbid any call to setjmp/longjmp and friends inside a '_Defer' statement.
7116 if (!CurrentDefer.empty() && IsSJLJ()) {
7117 // Note: If we ever start supporting '_Defer' in C++ we'll have to check
7118 // for more than just blocks (e.g. lambdas, nested classes...).
7119 Scope *DeferParent = CurrentDefer.back().first;
7120 Scope *Block = CurScope->getBlockParent();
7121 if (DeferParent->Contains(rhs: *CurScope) &&
7122 (!Block || !DeferParent->Contains(rhs: *Block)))
7123 Diag(Loc: Fn->getExprLoc(), DiagID: diag::err_defer_invalid_sjlj) << FDecl;
7124 }
7125
7126 // Functions with 'interrupt' attribute cannot be called directly.
7127 if (FDecl) {
7128 if (FDecl->hasAttr<AnyX86InterruptAttr>()) {
7129 Diag(Loc: Fn->getExprLoc(), DiagID: diag::err_anyx86_interrupt_called);
7130 return ExprError();
7131 }
7132 if (FDecl->hasAttr<ARMInterruptAttr>()) {
7133 Diag(Loc: Fn->getExprLoc(), DiagID: diag::err_arm_interrupt_called);
7134 return ExprError();
7135 }
7136 }
7137
7138 // X86 interrupt handlers may only call routines with attribute
7139 // no_caller_saved_registers since there is no efficient way to
7140 // save and restore the non-GPR state.
7141 if (auto *Caller = getCurFunctionDecl()) {
7142 if (Caller->hasAttr<AnyX86InterruptAttr>() ||
7143 Caller->hasAttr<AnyX86NoCallerSavedRegistersAttr>()) {
7144 const TargetInfo &TI = Context.getTargetInfo();
7145 bool HasNonGPRRegisters =
7146 TI.hasFeature(Feature: "sse") || TI.hasFeature(Feature: "x87") || TI.hasFeature(Feature: "mmx");
7147 if (HasNonGPRRegisters &&
7148 (!FDecl || !FDecl->hasAttr<AnyX86NoCallerSavedRegistersAttr>())) {
7149 Diag(Loc: Fn->getExprLoc(), DiagID: diag::warn_anyx86_excessive_regsave)
7150 << (Caller->hasAttr<AnyX86InterruptAttr>() ? 0 : 1);
7151 if (FDecl)
7152 Diag(Loc: FDecl->getLocation(), DiagID: diag::note_callee_decl) << FDecl;
7153 }
7154 }
7155 }
7156
7157 // Extract the return type from the builtin function pointer type.
7158 QualType ResultTy;
7159 if (BuiltinID)
7160 ResultTy = FDecl->getCallResultType();
7161 else
7162 ResultTy = Context.BoolTy;
7163
7164 // Promote the function operand.
7165 // We special-case function promotion here because we only allow promoting
7166 // builtin functions to function pointers in the callee of a call.
7167 ExprResult Result;
7168 if (BuiltinID &&
7169 Fn->getType()->isSpecificBuiltinType(K: BuiltinType::BuiltinFn)) {
7170 // FIXME Several builtins still have setType in
7171 // Sema::CheckBuiltinFunctionCall. One should review their definitions in
7172 // Builtins.td to ensure they are correct before removing setType calls.
7173 QualType FnPtrTy = Context.getPointerType(T: FDecl->getType());
7174 Result = ImpCastExprToType(E: Fn, Type: FnPtrTy, CK: CK_BuiltinFnToFnPtr).get();
7175 } else
7176 Result = CallExprUnaryConversions(E: Fn);
7177 if (Result.isInvalid())
7178 return ExprError();
7179 Fn = Result.get();
7180
7181 // Check for a valid function type, but only if it is not a builtin which
7182 // requires custom type checking. These will be handled by
7183 // CheckBuiltinFunctionCall below just after creation of the call expression.
7184 const FunctionType *FuncT = nullptr;
7185 if (!BuiltinID || !Context.BuiltinInfo.hasCustomTypechecking(ID: BuiltinID)) {
7186 retry:
7187 if (const PointerType *PT = Fn->getType()->getAs<PointerType>()) {
7188 // C99 6.5.2.2p1 - "The expression that denotes the called function shall
7189 // have type pointer to function".
7190 FuncT = PT->getPointeeType()->getAs<FunctionType>();
7191 if (!FuncT)
7192 return ExprError(Diag(Loc: LParenLoc, DiagID: diag::err_typecheck_call_not_function)
7193 << Fn->getType() << Fn->getSourceRange());
7194 } else if (const BlockPointerType *BPT =
7195 Fn->getType()->getAs<BlockPointerType>()) {
7196 FuncT = BPT->getPointeeType()->castAs<FunctionType>();
7197 } else {
7198 // Handle calls to expressions of unknown-any type.
7199 if (Fn->getType() == Context.UnknownAnyTy) {
7200 ExprResult rewrite = rebuildUnknownAnyFunction(S&: *this, fn: Fn);
7201 if (rewrite.isInvalid())
7202 return ExprError();
7203 Fn = rewrite.get();
7204 goto retry;
7205 }
7206
7207 return ExprError(Diag(Loc: LParenLoc, DiagID: diag::err_typecheck_call_not_function)
7208 << Fn->getType() << Fn->getSourceRange());
7209 }
7210 }
7211
7212 // Get the number of parameters in the function prototype, if any.
7213 // We will allocate space for max(Args.size(), NumParams) arguments
7214 // in the call expression.
7215 const auto *Proto = dyn_cast_or_null<FunctionProtoType>(Val: FuncT);
7216 unsigned NumParams = Proto ? Proto->getNumParams() : 0;
7217
7218 CallExpr *TheCall;
7219 if (Config) {
7220 assert(UsesADL == ADLCallKind::NotADL &&
7221 "CUDAKernelCallExpr should not use ADL");
7222 TheCall = CUDAKernelCallExpr::Create(Ctx: Context, Fn, Config: cast<CallExpr>(Val: Config),
7223 Args, Ty: ResultTy, VK: VK_PRValue, RP: RParenLoc,
7224 FPFeatures: CurFPFeatureOverrides(), MinNumArgs: NumParams);
7225 } else {
7226 TheCall =
7227 CallExpr::Create(Ctx: Context, Fn, Args, Ty: ResultTy, VK: VK_PRValue, RParenLoc,
7228 FPFeatures: CurFPFeatureOverrides(), MinNumArgs: NumParams, UsesADL);
7229 }
7230
7231 // Bail out early if calling a builtin with custom type checking.
7232 if (BuiltinID && Context.BuiltinInfo.hasCustomTypechecking(ID: BuiltinID)) {
7233 // For HLSL builtin aliases, the call was resolved via overload resolution
7234 // which may have selected a conversion sequence (e.g., vector-to-scalar
7235 // truncation). Convert arguments to match the declared prototype before
7236 // the custom type checker runs, otherwise the builtin will operate on
7237 // the unconverted argument types.
7238 if (getLangOpts().HLSL && FDecl && FDecl->hasAttr<BuiltinAliasAttr>()) {
7239 if (const auto *P = FDecl->getType()->getAs<FunctionProtoType>()) {
7240 if (ConvertArgumentsForCall(Call: TheCall, Fn, FDecl, Proto: P, Args, RParenLoc,
7241 IsExecConfig))
7242 return ExprError();
7243 }
7244 }
7245 ExprResult E = CheckBuiltinFunctionCall(FDecl, BuiltinID, TheCall);
7246 if (!E.isInvalid() && Context.BuiltinInfo.isImmediate(ID: BuiltinID))
7247 E = CheckForImmediateInvocation(E, Decl: FDecl);
7248 return E;
7249 }
7250
7251 if (getLangOpts().CUDA) {
7252 if (Config) {
7253 // CUDA: Kernel calls must be to global functions
7254 if (FDecl && !FDecl->hasAttr<CUDAGlobalAttr>())
7255 return ExprError(Diag(Loc: LParenLoc,DiagID: diag::err_kern_call_not_global_function)
7256 << FDecl << Fn->getSourceRange());
7257
7258 // CUDA: Kernel function must have 'void' return type
7259 if (!FuncT->getReturnType()->isVoidType() &&
7260 !FuncT->getReturnType()->getAs<AutoType>() &&
7261 !FuncT->getReturnType()->isInstantiationDependentType())
7262 return ExprError(Diag(Loc: LParenLoc, DiagID: diag::err_kern_type_not_void_return)
7263 << Fn->getType() << Fn->getSourceRange());
7264 } else {
7265 // CUDA: Calls to global functions must be configured
7266 if (FDecl && FDecl->hasAttr<CUDAGlobalAttr>())
7267 return ExprError(Diag(Loc: LParenLoc, DiagID: diag::err_global_call_not_config)
7268 << FDecl << Fn->getSourceRange());
7269 }
7270 }
7271
7272 // Check for a valid return type
7273 if (CheckCallReturnType(ReturnType: FuncT->getReturnType(), Loc: Fn->getBeginLoc(), CE: TheCall,
7274 FD: FDecl))
7275 return ExprError();
7276
7277 // We know the result type of the call, set it.
7278 TheCall->setType(FuncT->getCallResultType(Context));
7279 TheCall->setValueKind(Expr::getValueKindForType(T: FuncT->getReturnType()));
7280
7281 // WebAssembly tables can't be used as arguments.
7282 if (Context.getTargetInfo().getTriple().isWasm()) {
7283 for (const Expr *Arg : Args) {
7284 if (Arg && Arg->getType()->isWebAssemblyTableType()) {
7285 return ExprError(Diag(Loc: Arg->getExprLoc(),
7286 DiagID: diag::err_wasm_table_as_function_parameter));
7287 }
7288 }
7289 }
7290
7291 // Check read_image{i|ui} sampler argument before ConvertArgumentsForCall
7292 // replaces sampler DeclRefExprs with their integer initializers.
7293 if (getLangOpts().OpenCL && FDecl) {
7294 OpenCL().checkBuiltinReadImage(FDecl, Call: TheCall);
7295 }
7296
7297 if (Proto) {
7298 if (ConvertArgumentsForCall(Call: TheCall, Fn, FDecl, Proto, Args, RParenLoc,
7299 IsExecConfig))
7300 return ExprError();
7301 } else {
7302 assert(isa<FunctionNoProtoType>(FuncT) && "Unknown FunctionType!");
7303
7304 if (FDecl) {
7305 // Check if we have too few/too many template arguments, based
7306 // on our knowledge of the function definition.
7307 const FunctionDecl *Def = nullptr;
7308 if (FDecl->hasBody(Definition&: Def) && Args.size() != Def->param_size()) {
7309 Proto = Def->getType()->getAs<FunctionProtoType>();
7310 if (!Proto || !(Proto->isVariadic() && Args.size() >= Def->param_size()))
7311 Diag(Loc: RParenLoc, DiagID: diag::warn_call_wrong_number_of_arguments)
7312 << (Args.size() > Def->param_size()) << FDecl << Fn->getSourceRange();
7313 }
7314
7315 // If the function we're calling isn't a function prototype, but we have
7316 // a function prototype from a prior declaratiom, use that prototype.
7317 if (!FDecl->hasPrototype())
7318 Proto = FDecl->getType()->getAs<FunctionProtoType>();
7319 }
7320
7321 // If we still haven't found a prototype to use but there are arguments to
7322 // the call, diagnose this as calling a function without a prototype.
7323 // However, if we found a function declaration, check to see if
7324 // -Wdeprecated-non-prototype was disabled where the function was declared.
7325 // If so, we will silence the diagnostic here on the assumption that this
7326 // interface is intentional and the user knows what they're doing. We will
7327 // also silence the diagnostic if there is a function declaration but it
7328 // was implicitly defined (the user already gets diagnostics about the
7329 // creation of the implicit function declaration, so the additional warning
7330 // is not helpful).
7331 if (!Proto && !Args.empty() &&
7332 (!FDecl || (!FDecl->isImplicit() &&
7333 !Diags.isIgnored(DiagID: diag::warn_strict_uses_without_prototype,
7334 Loc: FDecl->getLocation()))))
7335 Diag(Loc: LParenLoc, DiagID: diag::warn_strict_uses_without_prototype)
7336 << (FDecl != nullptr) << FDecl;
7337
7338 // Promote the arguments (C99 6.5.2.2p6).
7339 for (unsigned i = 0, e = Args.size(); i != e; i++) {
7340 Expr *Arg = Args[i];
7341
7342 if (Proto && i < Proto->getNumParams()) {
7343 InitializedEntity Entity = InitializedEntity::InitializeParameter(
7344 Context, Type: Proto->getParamType(i), Consumed: Proto->isParamConsumed(I: i));
7345 ExprResult ArgE =
7346 PerformCopyInitialization(Entity, EqualLoc: SourceLocation(), Init: Arg);
7347 if (ArgE.isInvalid())
7348 return true;
7349
7350 Arg = ArgE.getAs<Expr>();
7351
7352 } else {
7353 ExprResult ArgE = DefaultArgumentPromotion(E: Arg);
7354
7355 if (ArgE.isInvalid())
7356 return true;
7357
7358 Arg = ArgE.getAs<Expr>();
7359 }
7360
7361 if (RequireCompleteType(Loc: Arg->getBeginLoc(), T: Arg->getType(),
7362 DiagID: diag::err_call_incomplete_argument, Args: Arg))
7363 return ExprError();
7364
7365 TheCall->setArg(Arg: i, ArgExpr: Arg);
7366 }
7367 TheCall->computeDependence();
7368 }
7369
7370 if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(Val: FDecl))
7371 if (Method->isImplicitObjectMemberFunction())
7372 return ExprError(Diag(Loc: LParenLoc, DiagID: diag::err_member_call_without_object)
7373 << Fn->getSourceRange() << 0);
7374
7375 // Check for sentinels
7376 if (NDecl)
7377 DiagnoseSentinelCalls(D: NDecl, Loc: LParenLoc, Args);
7378
7379 // Warn for unions passing across security boundary (CMSE).
7380 if (FuncT != nullptr && FuncT->getCmseNSCallAttr()) {
7381 for (unsigned i = 0, e = Args.size(); i != e; i++) {
7382 if (const auto *RT =
7383 dyn_cast<RecordType>(Val: Args[i]->getType().getCanonicalType())) {
7384 if (RT->getDecl()->isOrContainsUnion())
7385 Diag(Loc: Args[i]->getBeginLoc(), DiagID: diag::warn_cmse_nonsecure_union)
7386 << 0 << i;
7387 }
7388 }
7389 }
7390
7391 // Do special checking on direct calls to functions.
7392 if (FDecl) {
7393 if (CheckFunctionCall(FDecl, TheCall, Proto))
7394 return ExprError();
7395
7396 checkFortifiedBuiltinMemoryFunction(FD: FDecl, TheCall);
7397
7398 if (BuiltinID)
7399 return CheckBuiltinFunctionCall(FDecl, BuiltinID, TheCall);
7400 } else if (NDecl) {
7401 if (CheckPointerCall(NDecl, TheCall, Proto))
7402 return ExprError();
7403 } else {
7404 if (CheckOtherCall(TheCall, Proto))
7405 return ExprError();
7406 }
7407
7408 return CheckForImmediateInvocation(E: MaybeBindToTemporary(E: TheCall), Decl: FDecl);
7409}
7410
7411ExprResult
7412Sema::ActOnCompoundLiteral(SourceLocation LParenLoc, ParsedType Ty,
7413 SourceLocation RParenLoc, Expr *InitExpr) {
7414 assert(Ty && "ActOnCompoundLiteral(): missing type");
7415 assert(InitExpr && "ActOnCompoundLiteral(): missing expression");
7416
7417 TypeSourceInfo *TInfo;
7418 QualType literalType = GetTypeFromParser(Ty, TInfo: &TInfo);
7419 if (!TInfo)
7420 TInfo = Context.getTrivialTypeSourceInfo(T: literalType);
7421
7422 return BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc, LiteralExpr: InitExpr);
7423}
7424
7425ExprResult
7426Sema::BuildCompoundLiteralExpr(SourceLocation LParenLoc, TypeSourceInfo *TInfo,
7427 SourceLocation RParenLoc, Expr *LiteralExpr) {
7428 QualType literalType = TInfo->getType();
7429
7430 if (literalType->isArrayType()) {
7431 if (RequireCompleteSizedType(
7432 Loc: LParenLoc, T: Context.getBaseElementType(QT: literalType),
7433 DiagID: diag::err_array_incomplete_or_sizeless_type,
7434 Args: SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd())))
7435 return ExprError();
7436 if (literalType->isVariableArrayType()) {
7437 // C23 6.7.10p4: An entity of variable length array type shall not be
7438 // initialized except by an empty initializer.
7439 //
7440 // The C extension warnings are issued from ParseBraceInitializer() and
7441 // do not need to be issued here. However, we continue to issue an error
7442 // in the case there are initializers or we are compiling C++. We allow
7443 // use of VLAs in C++, but it's not clear we want to allow {} to zero
7444 // init a VLA in C++ in all cases (such as with non-trivial constructors).
7445 // FIXME: should we allow this construct in C++ when it makes sense to do
7446 // so?
7447 //
7448 // But: C99-C23 6.5.2.5 Compound literals constraint 1: The type name
7449 // shall specify an object type or an array of unknown size, but not a
7450 // variable length array type. This seems odd, as it allows 'int a[size] =
7451 // {}', but forbids 'int *a = (int[size]){}'. As this is what the standard
7452 // says, this is what's implemented here for C (except for the extension
7453 // that permits constant foldable size arrays)
7454
7455 auto diagID = LangOpts.CPlusPlus
7456 ? diag::err_variable_object_no_init
7457 : diag::err_compound_literal_with_vla_type;
7458 if (!tryToFixVariablyModifiedVarType(TInfo, T&: literalType, Loc: LParenLoc,
7459 FailedFoldDiagID: diagID))
7460 return ExprError();
7461 }
7462 } else if (!literalType->isDependentType() &&
7463 RequireCompleteType(Loc: LParenLoc, T: literalType,
7464 DiagID: diag::err_typecheck_decl_incomplete_type,
7465 Args: SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd())))
7466 return ExprError();
7467
7468 InitializedEntity Entity
7469 = InitializedEntity::InitializeCompoundLiteralInit(TSI: TInfo);
7470 InitializationKind Kind
7471 = InitializationKind::CreateCStyleCast(StartLoc: LParenLoc,
7472 TypeRange: SourceRange(LParenLoc, RParenLoc),
7473 /*InitList=*/true);
7474 InitializationSequence InitSeq(*this, Entity, Kind, LiteralExpr);
7475 ExprResult Result = InitSeq.Perform(S&: *this, Entity, Kind, Args: LiteralExpr,
7476 ResultType: &literalType);
7477 if (Result.isInvalid())
7478 return ExprError();
7479 LiteralExpr = Result.get();
7480
7481 // We treat the compound literal as being at file scope if it's not in a
7482 // function or method body, or within the function's prototype scope. This
7483 // means the following compound literal is not at file scope:
7484 // void func(char *para[(int [1]){ 0 }[0]);
7485 const Scope *S = getCurScope();
7486 bool IsFileScope = !CurContext->isFunctionOrMethod() &&
7487 !S->isInCFunctionScope() &&
7488 (!S || !S->isFunctionPrototypeScope());
7489
7490 // In C, compound literals are l-values for some reason.
7491 // For GCC compatibility, in C++, file-scope array compound literals with
7492 // constant initializers are also l-values, and compound literals are
7493 // otherwise prvalues.
7494 //
7495 // (GCC also treats C++ list-initialized file-scope array prvalues with
7496 // constant initializers as l-values, but that's non-conforming, so we don't
7497 // follow it there.)
7498 //
7499 // FIXME: It would be better to handle the lvalue cases as materializing and
7500 // lifetime-extending a temporary object, but our materialized temporaries
7501 // representation only supports lifetime extension from a variable, not "out
7502 // of thin air".
7503 // FIXME: For C++, we might want to instead lifetime-extend only if a pointer
7504 // is bound to the result of applying array-to-pointer decay to the compound
7505 // literal.
7506 // FIXME: GCC supports compound literals of reference type, which should
7507 // obviously have a value kind derived from the kind of reference involved.
7508 ExprValueKind VK =
7509 (getLangOpts().CPlusPlus && !(IsFileScope && literalType->isArrayType()))
7510 ? VK_PRValue
7511 : VK_LValue;
7512
7513 // C99 6.5.2.5
7514 // "If the compound literal occurs outside the body of a function, the
7515 // initializer list shall consist of constant expressions."
7516 if (IsFileScope)
7517 if (auto ILE = dyn_cast<InitListExpr>(Val: LiteralExpr))
7518 for (unsigned i = 0, j = ILE->getNumInits(); i != j; i++) {
7519 Expr *Init = ILE->getInit(Init: i);
7520 if (!Init->isTypeDependent() && !Init->isValueDependent() &&
7521 !Init->isConstantInitializer(Ctx&: Context)) {
7522 Diag(Loc: Init->getExprLoc(), DiagID: diag::err_init_element_not_constant)
7523 << Init->getSourceBitField();
7524 return ExprError();
7525 }
7526
7527 ILE->setInit(Init: i, expr: ConstantExpr::Create(Context, E: Init));
7528 }
7529
7530 auto *E = new (Context) CompoundLiteralExpr(LParenLoc, TInfo, literalType, VK,
7531 LiteralExpr, IsFileScope);
7532 if (IsFileScope) {
7533 if (!LiteralExpr->isTypeDependent() &&
7534 !LiteralExpr->isValueDependent() &&
7535 !literalType->isDependentType()) // C99 6.5.2.5p3
7536 if (CheckForConstantInitializer(Init: LiteralExpr))
7537 return ExprError();
7538 } else if (literalType.getAddressSpace() != LangAS::opencl_private &&
7539 literalType.getAddressSpace() != LangAS::Default) {
7540 // Embedded-C extensions to C99 6.5.2.5:
7541 // "If the compound literal occurs inside the body of a function, the
7542 // type name shall not be qualified by an address-space qualifier."
7543 Diag(Loc: LParenLoc, DiagID: diag::err_compound_literal_with_address_space)
7544 << SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd());
7545 return ExprError();
7546 }
7547
7548 if (!IsFileScope && !getLangOpts().CPlusPlus) {
7549 // Compound literals that have automatic storage duration are destroyed at
7550 // the end of the scope in C; in C++, they're just temporaries.
7551
7552 // Emit diagnostics if it is or contains a C union type that is non-trivial
7553 // to destruct.
7554 if (E->getType().hasNonTrivialToPrimitiveDestructCUnion())
7555 checkNonTrivialCUnion(QT: E->getType(), Loc: E->getExprLoc(),
7556 UseContext: NonTrivialCUnionContext::CompoundLiteral,
7557 NonTrivialKind: NTCUK_Destruct);
7558
7559 // Diagnose jumps that enter or exit the lifetime of the compound literal.
7560 if (literalType.isDestructedType()) {
7561 Cleanup.setExprNeedsCleanups(true);
7562 ExprCleanupObjects.push_back(Elt: E);
7563 getCurFunction()->setHasBranchProtectedScope();
7564 }
7565 }
7566
7567 if (E->getType().hasNonTrivialToPrimitiveDefaultInitializeCUnion() ||
7568 E->getType().hasNonTrivialToPrimitiveCopyCUnion())
7569 checkNonTrivialCUnionInInitializer(Init: E->getInitializer(),
7570 Loc: E->getInitializer()->getExprLoc());
7571
7572 return MaybeBindToTemporary(E);
7573}
7574
7575ExprResult
7576Sema::ActOnInitList(SourceLocation LBraceLoc, MultiExprArg InitArgList,
7577 SourceLocation RBraceLoc) {
7578 // Only produce each kind of designated initialization diagnostic once.
7579 SourceLocation FirstDesignator;
7580 bool DiagnosedArrayDesignator = false;
7581 bool DiagnosedNestedDesignator = false;
7582 bool DiagnosedMixedDesignator = false;
7583
7584 // Check that any designated initializers are syntactically valid in the
7585 // current language mode.
7586 for (unsigned I = 0, E = InitArgList.size(); I != E; ++I) {
7587 if (auto *DIE = dyn_cast<DesignatedInitExpr>(Val: InitArgList[I])) {
7588 if (FirstDesignator.isInvalid())
7589 FirstDesignator = DIE->getBeginLoc();
7590
7591 if (!getLangOpts().CPlusPlus)
7592 break;
7593
7594 if (!DiagnosedNestedDesignator && DIE->size() > 1) {
7595 DiagnosedNestedDesignator = true;
7596 Diag(Loc: DIE->getBeginLoc(), DiagID: diag::ext_designated_init_nested)
7597 << DIE->getDesignatorsSourceRange();
7598 }
7599
7600 for (auto &Desig : DIE->designators()) {
7601 if (!Desig.isFieldDesignator() && !DiagnosedArrayDesignator) {
7602 DiagnosedArrayDesignator = true;
7603 Diag(Loc: Desig.getBeginLoc(), DiagID: diag::ext_designated_init_array)
7604 << Desig.getSourceRange();
7605 }
7606 }
7607
7608 if (!DiagnosedMixedDesignator &&
7609 !isa<DesignatedInitExpr>(Val: InitArgList[0])) {
7610 DiagnosedMixedDesignator = true;
7611 Diag(Loc: DIE->getBeginLoc(), DiagID: diag::ext_designated_init_mixed)
7612 << DIE->getSourceRange();
7613 Diag(Loc: InitArgList[0]->getBeginLoc(), DiagID: diag::note_designated_init_mixed)
7614 << InitArgList[0]->getSourceRange();
7615 }
7616 } else if (getLangOpts().CPlusPlus && !DiagnosedMixedDesignator &&
7617 isa<DesignatedInitExpr>(Val: InitArgList[0])) {
7618 DiagnosedMixedDesignator = true;
7619 auto *DIE = cast<DesignatedInitExpr>(Val: InitArgList[0]);
7620 Diag(Loc: DIE->getBeginLoc(), DiagID: diag::ext_designated_init_mixed)
7621 << DIE->getSourceRange();
7622 Diag(Loc: InitArgList[I]->getBeginLoc(), DiagID: diag::note_designated_init_mixed)
7623 << InitArgList[I]->getSourceRange();
7624 }
7625 }
7626
7627 if (FirstDesignator.isValid()) {
7628 // Only diagnose designated initiaization as a C++20 extension if we didn't
7629 // already diagnose use of (non-C++20) C99 designator syntax.
7630 if (getLangOpts().CPlusPlus && !DiagnosedArrayDesignator &&
7631 !DiagnosedNestedDesignator && !DiagnosedMixedDesignator) {
7632 Diag(Loc: FirstDesignator, DiagID: getLangOpts().CPlusPlus20
7633 ? diag::warn_cxx17_compat_designated_init
7634 : diag::ext_cxx_designated_init);
7635 } else if (!getLangOpts().CPlusPlus && !getLangOpts().C99) {
7636 Diag(Loc: FirstDesignator, DiagID: diag::ext_designated_init);
7637 }
7638 }
7639
7640 return BuildInitList(LBraceLoc, InitArgList, RBraceLoc, /*IsExplicit=*/true);
7641}
7642
7643ExprResult Sema::BuildInitList(SourceLocation LBraceLoc,
7644 MultiExprArg InitArgList,
7645 SourceLocation RBraceLoc, bool IsExplicit) {
7646 // Semantic analysis for initializers is done by ActOnDeclarator() and
7647 // CheckInitializer() - it requires knowledge of the object being initialized.
7648
7649 // Immediately handle non-overload placeholders. Overloads can be
7650 // resolved contextually, but everything else here can't.
7651 for (unsigned I = 0, E = InitArgList.size(); I != E; ++I) {
7652 if (InitArgList[I]->getType()->isNonOverloadPlaceholderType()) {
7653 ExprResult result = CheckPlaceholderExpr(E: InitArgList[I]);
7654
7655 // Ignore failures; dropping the entire initializer list because
7656 // of one failure would be terrible for indexing/etc.
7657 if (result.isInvalid()) continue;
7658
7659 InitArgList[I] = result.get();
7660 }
7661 }
7662
7663 InitListExpr *E = new (Context)
7664 InitListExpr(Context, LBraceLoc, InitArgList, RBraceLoc, IsExplicit);
7665 E->setType(Context.VoidTy); // FIXME: just a place holder for now.
7666 return E;
7667}
7668
7669void Sema::maybeExtendBlockObject(ExprResult &E) {
7670 assert(E.get()->getType()->isBlockPointerType());
7671 assert(E.get()->isPRValue());
7672
7673 // Only do this in an r-value context.
7674 if (!getLangOpts().ObjCAutoRefCount) return;
7675
7676 E = ImplicitCastExpr::Create(
7677 Context, T: E.get()->getType(), Kind: CK_ARCExtendBlockObject, Operand: E.get(),
7678 /*base path*/ BasePath: nullptr, Cat: VK_PRValue, FPO: FPOptionsOverride());
7679 Cleanup.setExprNeedsCleanups(true);
7680}
7681
7682CastKind Sema::PrepareScalarCast(ExprResult &Src, QualType DestTy) {
7683 // Both Src and Dest are scalar types, i.e. arithmetic or pointer.
7684 // Also, callers should have filtered out the invalid cases with
7685 // pointers. Everything else should be possible.
7686
7687 QualType SrcTy = Src.get()->getType();
7688 if (Context.hasSameUnqualifiedType(T1: SrcTy, T2: DestTy))
7689 return CK_NoOp;
7690
7691 switch (Type::ScalarTypeKind SrcKind = SrcTy->getScalarTypeKind()) {
7692 case Type::STK_MemberPointer:
7693 llvm_unreachable("member pointer type in C");
7694
7695 case Type::STK_CPointer:
7696 case Type::STK_BlockPointer:
7697 case Type::STK_ObjCObjectPointer:
7698 switch (DestTy->getScalarTypeKind()) {
7699 case Type::STK_CPointer: {
7700 LangAS SrcAS = SrcTy->getPointeeType().getAddressSpace();
7701 LangAS DestAS = DestTy->getPointeeType().getAddressSpace();
7702 if (SrcAS != DestAS)
7703 return CK_AddressSpaceConversion;
7704 if (Context.hasCvrSimilarType(T1: SrcTy, T2: DestTy))
7705 return CK_NoOp;
7706 return CK_BitCast;
7707 }
7708 case Type::STK_BlockPointer:
7709 return (SrcKind == Type::STK_BlockPointer
7710 ? CK_BitCast : CK_AnyPointerToBlockPointerCast);
7711 case Type::STK_ObjCObjectPointer:
7712 if (SrcKind == Type::STK_ObjCObjectPointer)
7713 return CK_BitCast;
7714 if (SrcKind == Type::STK_CPointer)
7715 return CK_CPointerToObjCPointerCast;
7716 maybeExtendBlockObject(E&: Src);
7717 return CK_BlockPointerToObjCPointerCast;
7718 case Type::STK_Bool:
7719 return CK_PointerToBoolean;
7720 case Type::STK_Integral:
7721 return CK_PointerToIntegral;
7722 case Type::STK_Floating:
7723 case Type::STK_FloatingComplex:
7724 case Type::STK_IntegralComplex:
7725 case Type::STK_MemberPointer:
7726 case Type::STK_FixedPoint:
7727 llvm_unreachable("illegal cast from pointer");
7728 }
7729 llvm_unreachable("Should have returned before this");
7730
7731 case Type::STK_FixedPoint:
7732 switch (DestTy->getScalarTypeKind()) {
7733 case Type::STK_FixedPoint:
7734 return CK_FixedPointCast;
7735 case Type::STK_Bool:
7736 return CK_FixedPointToBoolean;
7737 case Type::STK_Integral:
7738 return CK_FixedPointToIntegral;
7739 case Type::STK_Floating:
7740 return CK_FixedPointToFloating;
7741 case Type::STK_IntegralComplex:
7742 case Type::STK_FloatingComplex:
7743 Diag(Loc: Src.get()->getExprLoc(),
7744 DiagID: diag::err_unimplemented_conversion_with_fixed_point_type)
7745 << DestTy;
7746 return CK_IntegralCast;
7747 case Type::STK_CPointer:
7748 case Type::STK_ObjCObjectPointer:
7749 case Type::STK_BlockPointer:
7750 case Type::STK_MemberPointer:
7751 llvm_unreachable("illegal cast to pointer type");
7752 }
7753 llvm_unreachable("Should have returned before this");
7754
7755 case Type::STK_Bool: // casting from bool is like casting from an integer
7756 case Type::STK_Integral:
7757 switch (DestTy->getScalarTypeKind()) {
7758 case Type::STK_CPointer:
7759 case Type::STK_ObjCObjectPointer:
7760 case Type::STK_BlockPointer:
7761 if (Src.get()->isNullPointerConstant(Ctx&: Context,
7762 NPC: Expr::NPC_ValueDependentIsNull))
7763 return CK_NullToPointer;
7764 return CK_IntegralToPointer;
7765 case Type::STK_Bool:
7766 return CK_IntegralToBoolean;
7767 case Type::STK_Integral:
7768 return CK_IntegralCast;
7769 case Type::STK_Floating:
7770 return CK_IntegralToFloating;
7771 case Type::STK_IntegralComplex:
7772 Src = ImpCastExprToType(E: Src.get(),
7773 Type: DestTy->castAs<ComplexType>()->getElementType(),
7774 CK: CK_IntegralCast);
7775 return CK_IntegralRealToComplex;
7776 case Type::STK_FloatingComplex:
7777 Src = ImpCastExprToType(E: Src.get(),
7778 Type: DestTy->castAs<ComplexType>()->getElementType(),
7779 CK: CK_IntegralToFloating);
7780 return CK_FloatingRealToComplex;
7781 case Type::STK_MemberPointer:
7782 llvm_unreachable("member pointer type in C");
7783 case Type::STK_FixedPoint:
7784 return CK_IntegralToFixedPoint;
7785 }
7786 llvm_unreachable("Should have returned before this");
7787
7788 case Type::STK_Floating:
7789 switch (DestTy->getScalarTypeKind()) {
7790 case Type::STK_Floating:
7791 return CK_FloatingCast;
7792 case Type::STK_Bool:
7793 return CK_FloatingToBoolean;
7794 case Type::STK_Integral:
7795 return CK_FloatingToIntegral;
7796 case Type::STK_FloatingComplex:
7797 Src = ImpCastExprToType(E: Src.get(),
7798 Type: DestTy->castAs<ComplexType>()->getElementType(),
7799 CK: CK_FloatingCast);
7800 return CK_FloatingRealToComplex;
7801 case Type::STK_IntegralComplex:
7802 Src = ImpCastExprToType(E: Src.get(),
7803 Type: DestTy->castAs<ComplexType>()->getElementType(),
7804 CK: CK_FloatingToIntegral);
7805 return CK_IntegralRealToComplex;
7806 case Type::STK_CPointer:
7807 case Type::STK_ObjCObjectPointer:
7808 case Type::STK_BlockPointer:
7809 llvm_unreachable("valid float->pointer cast?");
7810 case Type::STK_MemberPointer:
7811 llvm_unreachable("member pointer type in C");
7812 case Type::STK_FixedPoint:
7813 return CK_FloatingToFixedPoint;
7814 }
7815 llvm_unreachable("Should have returned before this");
7816
7817 case Type::STK_FloatingComplex:
7818 switch (DestTy->getScalarTypeKind()) {
7819 case Type::STK_FloatingComplex:
7820 return CK_FloatingComplexCast;
7821 case Type::STK_IntegralComplex:
7822 return CK_FloatingComplexToIntegralComplex;
7823 case Type::STK_Floating: {
7824 QualType ET = SrcTy->castAs<ComplexType>()->getElementType();
7825 if (Context.hasSameType(T1: ET, T2: DestTy))
7826 return CK_FloatingComplexToReal;
7827 Src = ImpCastExprToType(E: Src.get(), Type: ET, CK: CK_FloatingComplexToReal);
7828 return CK_FloatingCast;
7829 }
7830 case Type::STK_Bool:
7831 return CK_FloatingComplexToBoolean;
7832 case Type::STK_Integral:
7833 Src = ImpCastExprToType(E: Src.get(),
7834 Type: SrcTy->castAs<ComplexType>()->getElementType(),
7835 CK: CK_FloatingComplexToReal);
7836 return CK_FloatingToIntegral;
7837 case Type::STK_CPointer:
7838 case Type::STK_ObjCObjectPointer:
7839 case Type::STK_BlockPointer:
7840 llvm_unreachable("valid complex float->pointer cast?");
7841 case Type::STK_MemberPointer:
7842 llvm_unreachable("member pointer type in C");
7843 case Type::STK_FixedPoint:
7844 Diag(Loc: Src.get()->getExprLoc(),
7845 DiagID: diag::err_unimplemented_conversion_with_fixed_point_type)
7846 << SrcTy;
7847 return CK_IntegralCast;
7848 }
7849 llvm_unreachable("Should have returned before this");
7850
7851 case Type::STK_IntegralComplex:
7852 switch (DestTy->getScalarTypeKind()) {
7853 case Type::STK_FloatingComplex:
7854 return CK_IntegralComplexToFloatingComplex;
7855 case Type::STK_IntegralComplex:
7856 return CK_IntegralComplexCast;
7857 case Type::STK_Integral: {
7858 QualType ET = SrcTy->castAs<ComplexType>()->getElementType();
7859 if (Context.hasSameType(T1: ET, T2: DestTy))
7860 return CK_IntegralComplexToReal;
7861 Src = ImpCastExprToType(E: Src.get(), Type: ET, CK: CK_IntegralComplexToReal);
7862 return CK_IntegralCast;
7863 }
7864 case Type::STK_Bool:
7865 return CK_IntegralComplexToBoolean;
7866 case Type::STK_Floating:
7867 Src = ImpCastExprToType(E: Src.get(),
7868 Type: SrcTy->castAs<ComplexType>()->getElementType(),
7869 CK: CK_IntegralComplexToReal);
7870 return CK_IntegralToFloating;
7871 case Type::STK_CPointer:
7872 case Type::STK_ObjCObjectPointer:
7873 case Type::STK_BlockPointer:
7874 llvm_unreachable("valid complex int->pointer cast?");
7875 case Type::STK_MemberPointer:
7876 llvm_unreachable("member pointer type in C");
7877 case Type::STK_FixedPoint:
7878 Diag(Loc: Src.get()->getExprLoc(),
7879 DiagID: diag::err_unimplemented_conversion_with_fixed_point_type)
7880 << SrcTy;
7881 return CK_IntegralCast;
7882 }
7883 llvm_unreachable("Should have returned before this");
7884 }
7885
7886 llvm_unreachable("Unhandled scalar cast");
7887}
7888
7889static bool breakDownVectorType(QualType type, uint64_t &len,
7890 QualType &eltType) {
7891 // Vectors are simple.
7892 if (const VectorType *vecType = type->getAs<VectorType>()) {
7893 len = vecType->getNumElements();
7894 eltType = vecType->getElementType();
7895 assert(eltType->isScalarType() || eltType->isMFloat8Type());
7896 return true;
7897 }
7898
7899 // We allow lax conversion to and from non-vector types, but only if
7900 // they're real types (i.e. non-complex, non-pointer scalar types).
7901 if (!type->isRealType()) return false;
7902
7903 len = 1;
7904 eltType = type;
7905 return true;
7906}
7907
7908bool Sema::isValidSveBitcast(QualType srcTy, QualType destTy) {
7909 assert(srcTy->isVectorType() || destTy->isVectorType());
7910
7911 auto ValidScalableConversion = [](QualType FirstType, QualType SecondType) {
7912 if (!FirstType->isSVESizelessBuiltinType())
7913 return false;
7914
7915 const auto *VecTy = SecondType->getAs<VectorType>();
7916 return VecTy && VecTy->getVectorKind() == VectorKind::SveFixedLengthData;
7917 };
7918
7919 return ValidScalableConversion(srcTy, destTy) ||
7920 ValidScalableConversion(destTy, srcTy);
7921}
7922
7923bool Sema::areMatrixTypesOfTheSameDimension(QualType srcTy, QualType destTy) {
7924 if (!destTy->isMatrixType() || !srcTy->isMatrixType())
7925 return false;
7926
7927 const ConstantMatrixType *matSrcType = srcTy->getAs<ConstantMatrixType>();
7928 const ConstantMatrixType *matDestType = destTy->getAs<ConstantMatrixType>();
7929
7930 return matSrcType->getNumRows() == matDestType->getNumRows() &&
7931 matSrcType->getNumColumns() == matDestType->getNumColumns();
7932}
7933
7934bool Sema::areVectorTypesSameSize(QualType SrcTy, QualType DestTy) {
7935 assert(DestTy->isVectorType() || SrcTy->isVectorType());
7936
7937 uint64_t SrcLen, DestLen;
7938 QualType SrcEltTy, DestEltTy;
7939 if (!breakDownVectorType(type: SrcTy, len&: SrcLen, eltType&: SrcEltTy))
7940 return false;
7941 if (!breakDownVectorType(type: DestTy, len&: DestLen, eltType&: DestEltTy))
7942 return false;
7943
7944 // ASTContext::getTypeSize will return the size rounded up to a
7945 // power of 2, so instead of using that, we need to use the raw
7946 // element size multiplied by the element count.
7947 uint64_t SrcEltSize = Context.getTypeSize(T: SrcEltTy);
7948 uint64_t DestEltSize = Context.getTypeSize(T: DestEltTy);
7949
7950 return (SrcLen * SrcEltSize == DestLen * DestEltSize);
7951}
7952
7953bool Sema::anyAltivecTypes(QualType SrcTy, QualType DestTy) {
7954 assert((DestTy->isVectorType() || SrcTy->isVectorType()) &&
7955 "expected at least one type to be a vector here");
7956
7957 bool IsSrcTyAltivec =
7958 SrcTy->isVectorType() && ((SrcTy->castAs<VectorType>()->getVectorKind() ==
7959 VectorKind::AltiVecVector) ||
7960 (SrcTy->castAs<VectorType>()->getVectorKind() ==
7961 VectorKind::AltiVecBool) ||
7962 (SrcTy->castAs<VectorType>()->getVectorKind() ==
7963 VectorKind::AltiVecPixel));
7964
7965 bool IsDestTyAltivec = DestTy->isVectorType() &&
7966 ((DestTy->castAs<VectorType>()->getVectorKind() ==
7967 VectorKind::AltiVecVector) ||
7968 (DestTy->castAs<VectorType>()->getVectorKind() ==
7969 VectorKind::AltiVecBool) ||
7970 (DestTy->castAs<VectorType>()->getVectorKind() ==
7971 VectorKind::AltiVecPixel));
7972
7973 return (IsSrcTyAltivec || IsDestTyAltivec);
7974}
7975
7976bool Sema::areLaxCompatibleVectorTypes(QualType srcTy, QualType destTy) {
7977 assert(destTy->isVectorType() || srcTy->isVectorType());
7978
7979 // Disallow lax conversions between scalars and ExtVectors (these
7980 // conversions are allowed for other vector types because common headers
7981 // depend on them). Most scalar OP ExtVector cases are handled by the
7982 // splat path anyway, which does what we want (convert, not bitcast).
7983 // What this rules out for ExtVectors is crazy things like char4*float.
7984 if (srcTy->isScalarType() && destTy->isExtVectorType()) return false;
7985 if (destTy->isScalarType() && srcTy->isExtVectorType()) return false;
7986
7987 return areVectorTypesSameSize(SrcTy: srcTy, DestTy: destTy);
7988}
7989
7990bool Sema::isLaxVectorConversion(QualType srcTy, QualType destTy) {
7991 assert(destTy->isVectorType() || srcTy->isVectorType());
7992
7993 switch (Context.getLangOpts().getLaxVectorConversions()) {
7994 case LangOptions::LaxVectorConversionKind::None:
7995 return false;
7996
7997 case LangOptions::LaxVectorConversionKind::Integer:
7998 if (!srcTy->isIntegralOrEnumerationType()) {
7999 auto *Vec = srcTy->getAs<VectorType>();
8000 if (!Vec || !Vec->getElementType()->isIntegralOrEnumerationType())
8001 return false;
8002 }
8003 if (!destTy->isIntegralOrEnumerationType()) {
8004 auto *Vec = destTy->getAs<VectorType>();
8005 if (!Vec || !Vec->getElementType()->isIntegralOrEnumerationType())
8006 return false;
8007 }
8008 // OK, integer (vector) -> integer (vector) bitcast.
8009 break;
8010
8011 case LangOptions::LaxVectorConversionKind::All:
8012 break;
8013 }
8014
8015 return areLaxCompatibleVectorTypes(srcTy, destTy);
8016}
8017
8018bool Sema::CheckMatrixCast(SourceRange R, QualType DestTy, QualType SrcTy,
8019 CastKind &Kind) {
8020 if (SrcTy->isMatrixType() && DestTy->isMatrixType()) {
8021 if (!areMatrixTypesOfTheSameDimension(srcTy: SrcTy, destTy: DestTy)) {
8022 return Diag(Loc: R.getBegin(), DiagID: diag::err_invalid_conversion_between_matrixes)
8023 << DestTy << SrcTy << R;
8024 }
8025 } else if (SrcTy->isMatrixType()) {
8026 return Diag(Loc: R.getBegin(),
8027 DiagID: diag::err_invalid_conversion_between_matrix_and_type)
8028 << SrcTy << DestTy << R;
8029 } else if (DestTy->isMatrixType()) {
8030 return Diag(Loc: R.getBegin(),
8031 DiagID: diag::err_invalid_conversion_between_matrix_and_type)
8032 << DestTy << SrcTy << R;
8033 }
8034
8035 Kind = CK_MatrixCast;
8036 return false;
8037}
8038
8039bool Sema::CheckVectorCast(SourceRange R, QualType VectorTy, QualType Ty,
8040 CastKind &Kind) {
8041 assert(VectorTy->isVectorType() && "Not a vector type!");
8042
8043 if (Ty->isVectorType() || Ty->isIntegralType(Ctx: Context)) {
8044 if (!areLaxCompatibleVectorTypes(srcTy: Ty, destTy: VectorTy))
8045 return Diag(Loc: R.getBegin(),
8046 DiagID: Ty->isVectorType() ?
8047 diag::err_invalid_conversion_between_vectors :
8048 diag::err_invalid_conversion_between_vector_and_integer)
8049 << VectorTy << Ty << R;
8050 } else
8051 return Diag(Loc: R.getBegin(),
8052 DiagID: diag::err_invalid_conversion_between_vector_and_scalar)
8053 << VectorTy << Ty << R;
8054
8055 Kind = CK_BitCast;
8056 return false;
8057}
8058
8059ExprResult Sema::prepareVectorSplat(QualType VectorTy, Expr *SplattedExpr) {
8060 QualType DestElemTy = VectorTy->castAs<VectorType>()->getElementType();
8061
8062 if (DestElemTy == SplattedExpr->getType())
8063 return SplattedExpr;
8064
8065 assert(DestElemTy->isFloatingType() ||
8066 DestElemTy->isIntegralOrEnumerationType());
8067
8068 CastKind CK;
8069 if (VectorTy->isExtVectorType() && SplattedExpr->getType()->isBooleanType()) {
8070 // OpenCL requires that we convert `true` boolean expressions to -1, but
8071 // only when splatting vectors.
8072 if (DestElemTy->isFloatingType()) {
8073 // To avoid having to have a CK_BooleanToSignedFloating cast kind, we cast
8074 // in two steps: boolean to signed integral, then to floating.
8075 ExprResult CastExprRes = ImpCastExprToType(E: SplattedExpr, Type: Context.IntTy,
8076 CK: CK_BooleanToSignedIntegral);
8077 SplattedExpr = CastExprRes.get();
8078 CK = CK_IntegralToFloating;
8079 } else {
8080 CK = CK_BooleanToSignedIntegral;
8081 }
8082 } else {
8083 ExprResult CastExprRes = SplattedExpr;
8084 CK = PrepareScalarCast(Src&: CastExprRes, DestTy: DestElemTy);
8085 if (CastExprRes.isInvalid())
8086 return ExprError();
8087 SplattedExpr = CastExprRes.get();
8088 }
8089 return ImpCastExprToType(E: SplattedExpr, Type: DestElemTy, CK);
8090}
8091
8092ExprResult Sema::prepareMatrixSplat(QualType MatrixTy, Expr *SplattedExpr) {
8093 QualType DestElemTy = MatrixTy->castAs<MatrixType>()->getElementType();
8094
8095 if (DestElemTy == SplattedExpr->getType())
8096 return SplattedExpr;
8097
8098 assert(DestElemTy->isFloatingType() ||
8099 DestElemTy->isIntegralOrEnumerationType());
8100
8101 ExprResult CastExprRes = SplattedExpr;
8102 CastKind CK = PrepareScalarCast(Src&: CastExprRes, DestTy: DestElemTy);
8103 if (CastExprRes.isInvalid())
8104 return ExprError();
8105 SplattedExpr = CastExprRes.get();
8106
8107 return ImpCastExprToType(E: SplattedExpr, Type: DestElemTy, CK);
8108}
8109
8110ExprResult Sema::CheckExtVectorCast(SourceRange R, QualType DestTy,
8111 Expr *CastExpr, CastKind &Kind) {
8112 assert(DestTy->isExtVectorType() && "Not an extended vector type!");
8113
8114 QualType SrcTy = CastExpr->getType();
8115
8116 // If SrcTy is a VectorType, the total size must match to explicitly cast to
8117 // an ExtVectorType.
8118 // In OpenCL, casts between vectors of different types are not allowed.
8119 // (See OpenCL 6.2).
8120 if (SrcTy->isVectorType()) {
8121 if (!areLaxCompatibleVectorTypes(srcTy: SrcTy, destTy: DestTy) ||
8122 (getLangOpts().OpenCL &&
8123 !Context.hasSameUnqualifiedType(T1: DestTy, T2: SrcTy) &&
8124 !Context.areCompatibleVectorTypes(FirstVec: DestTy, SecondVec: SrcTy))) {
8125 Diag(Loc: R.getBegin(),DiagID: diag::err_invalid_conversion_between_ext_vectors)
8126 << DestTy << SrcTy << R;
8127 return ExprError();
8128 }
8129 Kind = CK_BitCast;
8130 return CastExpr;
8131 }
8132
8133 // All non-pointer scalars can be cast to ExtVector type. The appropriate
8134 // conversion will take place first from scalar to elt type, and then
8135 // splat from elt type to vector.
8136 if (SrcTy->isPointerType())
8137 return Diag(Loc: R.getBegin(),
8138 DiagID: diag::err_invalid_conversion_between_vector_and_scalar)
8139 << DestTy << SrcTy << R;
8140
8141 Kind = CK_VectorSplat;
8142 return prepareVectorSplat(VectorTy: DestTy, SplattedExpr: CastExpr);
8143}
8144
8145/// Check that a call to alloc_size function specifies sufficient space for the
8146/// destination type.
8147static void CheckSufficientAllocSize(Sema &S, QualType DestType,
8148 const Expr *E) {
8149 QualType SourceType = E->getType();
8150 if (!DestType->isPointerType() || !SourceType->isPointerType() ||
8151 DestType == SourceType)
8152 return;
8153
8154 const auto *CE = dyn_cast<CallExpr>(Val: E->IgnoreParenCasts());
8155 if (!CE)
8156 return;
8157
8158 // Find the total size allocated by the function call.
8159 if (!CE->getCalleeAllocSizeAttr())
8160 return;
8161 std::optional<llvm::APInt> AllocSize =
8162 CE->evaluateBytesReturnedByAllocSizeCall(Ctx: S.Context);
8163 // Allocations of size zero are permitted as a special case. They are usually
8164 // done intentionally.
8165 if (!AllocSize || AllocSize->isZero())
8166 return;
8167 auto Size = CharUnits::fromQuantity(Quantity: AllocSize->getZExtValue());
8168
8169 QualType TargetType = DestType->getPointeeType();
8170 // Find the destination size. As a special case function types have size of
8171 // one byte to match the sizeof operator behavior.
8172 auto LhsSize = TargetType->isFunctionType()
8173 ? CharUnits::One()
8174 : S.Context.getTypeSizeInCharsIfKnown(Ty: TargetType);
8175 if (LhsSize && Size < LhsSize)
8176 S.Diag(Loc: E->getExprLoc(), DiagID: diag::warn_alloc_size)
8177 << Size.getQuantity() << TargetType << LhsSize->getQuantity();
8178}
8179
8180ExprResult
8181Sema::ActOnCastExpr(Scope *S, SourceLocation LParenLoc,
8182 Declarator &D, ParsedType &Ty,
8183 SourceLocation RParenLoc, Expr *CastExpr) {
8184 assert(!D.isInvalidType() && (CastExpr != nullptr) &&
8185 "ActOnCastExpr(): missing type or expr");
8186
8187 TypeSourceInfo *castTInfo = GetTypeForDeclaratorCast(D, FromTy: CastExpr->getType());
8188 if (D.isInvalidType())
8189 return ExprError();
8190
8191 if (getLangOpts().CPlusPlus) {
8192 // Check that there are no default arguments (C++ only).
8193 CheckExtraCXXDefaultArguments(D);
8194 }
8195
8196 checkUnusedDeclAttributes(D);
8197
8198 QualType castType = castTInfo->getType();
8199 Ty = CreateParsedType(T: castType, TInfo: castTInfo);
8200
8201 bool isVectorLiteral = false;
8202
8203 // Check for an altivec or OpenCL literal,
8204 // i.e. all the elements are integer constants.
8205 ParenExpr *PE = dyn_cast<ParenExpr>(Val: CastExpr);
8206 ParenListExpr *PLE = dyn_cast<ParenListExpr>(Val: CastExpr);
8207 if ((getLangOpts().AltiVec || getLangOpts().ZVector || getLangOpts().OpenCL)
8208 && castType->isVectorType() && (PE || PLE)) {
8209 if (PLE && PLE->getNumExprs() == 0) {
8210 Diag(Loc: PLE->getExprLoc(), DiagID: diag::err_altivec_empty_initializer);
8211 return ExprError();
8212 }
8213 if (PE || PLE->getNumExprs() == 1) {
8214 Expr *E = (PE ? PE->getSubExpr() : PLE->getExpr(Init: 0));
8215 if (!E->isTypeDependent() && !E->getType()->isVectorType())
8216 isVectorLiteral = true;
8217 }
8218 else
8219 isVectorLiteral = true;
8220 }
8221
8222 // If this is a vector initializer, '(' type ')' '(' init, ..., init ')'
8223 // then handle it as such.
8224 if (isVectorLiteral)
8225 return BuildVectorLiteral(LParenLoc, RParenLoc, E: CastExpr, TInfo: castTInfo);
8226
8227 // If the Expr being casted is a ParenListExpr, handle it specially.
8228 // This is not an AltiVec-style cast, so turn the ParenListExpr into a
8229 // sequence of BinOp comma operators.
8230 if (isa<ParenListExpr>(Val: CastExpr)) {
8231 ExprResult Result = MaybeConvertParenListExprToParenExpr(S, ME: CastExpr);
8232 if (Result.isInvalid()) return ExprError();
8233 CastExpr = Result.get();
8234 }
8235
8236 if (getLangOpts().CPlusPlus && !castType->isVoidType())
8237 Diag(Loc: LParenLoc, DiagID: diag::warn_old_style_cast) << CastExpr->getSourceRange();
8238
8239 ObjC().CheckTollFreeBridgeCast(castType, castExpr: CastExpr);
8240
8241 ObjC().CheckObjCBridgeRelatedCast(castType, castExpr: CastExpr);
8242
8243 DiscardMisalignedMemberAddress(T: castType.getTypePtr(), E: CastExpr);
8244
8245 CheckSufficientAllocSize(S&: *this, DestType: castType, E: CastExpr);
8246
8247 return BuildCStyleCastExpr(LParenLoc, Ty: castTInfo, RParenLoc, Op: CastExpr);
8248}
8249
8250ExprResult Sema::BuildVectorLiteral(SourceLocation LParenLoc,
8251 SourceLocation RParenLoc, Expr *E,
8252 TypeSourceInfo *TInfo) {
8253 assert((isa<ParenListExpr>(E) || isa<ParenExpr>(E)) &&
8254 "Expected paren or paren list expression");
8255
8256 Expr **exprs;
8257 unsigned numExprs;
8258 Expr *subExpr;
8259 SourceLocation LiteralLParenLoc, LiteralRParenLoc;
8260 if (ParenListExpr *PE = dyn_cast<ParenListExpr>(Val: E)) {
8261 LiteralLParenLoc = PE->getLParenLoc();
8262 LiteralRParenLoc = PE->getRParenLoc();
8263 exprs = PE->getExprs();
8264 numExprs = PE->getNumExprs();
8265 } else { // isa<ParenExpr> by assertion at function entrance
8266 LiteralLParenLoc = cast<ParenExpr>(Val: E)->getLParen();
8267 LiteralRParenLoc = cast<ParenExpr>(Val: E)->getRParen();
8268 subExpr = cast<ParenExpr>(Val: E)->getSubExpr();
8269 exprs = &subExpr;
8270 numExprs = 1;
8271 }
8272
8273 QualType Ty = TInfo->getType();
8274 assert(Ty->isVectorType() && "Expected vector type");
8275
8276 SmallVector<Expr *, 8> initExprs;
8277 const VectorType *VTy = Ty->castAs<VectorType>();
8278 unsigned numElems = VTy->getNumElements();
8279
8280 // '(...)' form of vector initialization in AltiVec: the number of
8281 // initializers must be one or must match the size of the vector.
8282 // If a single value is specified in the initializer then it will be
8283 // replicated to all the components of the vector
8284 if (CheckAltivecInitFromScalar(R: E->getSourceRange(), VecTy: Ty,
8285 SrcTy: VTy->getElementType()))
8286 return ExprError();
8287 if (ShouldSplatAltivecScalarInCast(VecTy: VTy)) {
8288 // The number of initializers must be one or must match the size of the
8289 // vector. If a single value is specified in the initializer then it will
8290 // be replicated to all the components of the vector
8291 if (numExprs == 1) {
8292 QualType ElemTy = VTy->getElementType();
8293 ExprResult Literal = DefaultLvalueConversion(E: exprs[0]);
8294 if (Literal.isInvalid())
8295 return ExprError();
8296 Literal = ImpCastExprToType(E: Literal.get(), Type: ElemTy,
8297 CK: PrepareScalarCast(Src&: Literal, DestTy: ElemTy));
8298 return BuildCStyleCastExpr(LParenLoc, Ty: TInfo, RParenLoc, Op: Literal.get());
8299 }
8300 else if (numExprs < numElems) {
8301 Diag(Loc: E->getExprLoc(),
8302 DiagID: diag::err_incorrect_number_of_vector_initializers);
8303 return ExprError();
8304 }
8305 else
8306 initExprs.append(in_start: exprs, in_end: exprs + numExprs);
8307 }
8308 else {
8309 // For OpenCL, when the number of initializers is a single value,
8310 // it will be replicated to all components of the vector.
8311 if (getLangOpts().OpenCL && VTy->getVectorKind() == VectorKind::Generic &&
8312 numExprs == 1) {
8313 QualType SrcTy = exprs[0]->getType();
8314 if (!SrcTy->isArithmeticType()) {
8315 Diag(Loc: exprs[0]->getBeginLoc(), DiagID: diag::err_typecheck_convert_incompatible)
8316 << Ty << SrcTy << AssignmentAction::Initializing << /*elidable=*/0
8317 << /*c_style=*/0 << /*cast_kind=*/"" << exprs[0]->getSourceRange();
8318 return ExprError();
8319 }
8320 QualType ElemTy = VTy->getElementType();
8321 ExprResult Literal = DefaultLvalueConversion(E: exprs[0]);
8322 if (Literal.isInvalid())
8323 return ExprError();
8324 Literal = ImpCastExprToType(E: Literal.get(), Type: ElemTy,
8325 CK: PrepareScalarCast(Src&: Literal, DestTy: ElemTy));
8326 return BuildCStyleCastExpr(LParenLoc, Ty: TInfo, RParenLoc, Op: Literal.get());
8327 }
8328
8329 initExprs.append(in_start: exprs, in_end: exprs + numExprs);
8330 }
8331 // FIXME: This means that pretty-printing the final AST will produce curly
8332 // braces instead of the original commas.
8333 InitListExpr *initE =
8334 new (Context) InitListExpr(Context, LiteralLParenLoc, initExprs,
8335 LiteralRParenLoc, /*isExplicit=*/false);
8336 initE->setType(Ty);
8337 return BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc, LiteralExpr: initE);
8338}
8339
8340ExprResult
8341Sema::MaybeConvertParenListExprToParenExpr(Scope *S, Expr *OrigExpr) {
8342 ParenListExpr *E = dyn_cast<ParenListExpr>(Val: OrigExpr);
8343 if (!E)
8344 return OrigExpr;
8345
8346 ExprResult Result(E->getExpr(Init: 0));
8347
8348 for (unsigned i = 1, e = E->getNumExprs(); i != e && !Result.isInvalid(); ++i)
8349 Result = ActOnBinOp(S, TokLoc: E->getExprLoc(), Kind: tok::comma, LHSExpr: Result.get(),
8350 RHSExpr: E->getExpr(Init: i));
8351
8352 if (Result.isInvalid()) return ExprError();
8353
8354 return ActOnParenExpr(L: E->getLParenLoc(), R: E->getRParenLoc(), E: Result.get());
8355}
8356
8357ExprResult Sema::ActOnParenListExpr(SourceLocation L,
8358 SourceLocation R,
8359 MultiExprArg Val) {
8360 return ParenListExpr::Create(Ctx: Context, LParenLoc: L, Exprs: Val, RParenLoc: R);
8361}
8362
8363ExprResult Sema::ActOnCXXParenListInitExpr(ArrayRef<Expr *> Args, QualType T,
8364 unsigned NumUserSpecifiedExprs,
8365 SourceLocation InitLoc,
8366 SourceLocation LParenLoc,
8367 SourceLocation RParenLoc) {
8368 return CXXParenListInitExpr::Create(C&: Context, Args, T, NumUserSpecifiedExprs,
8369 InitLoc, LParenLoc, RParenLoc);
8370}
8371
8372bool Sema::DiagnoseConditionalForNull(const Expr *LHSExpr, const Expr *RHSExpr,
8373 SourceLocation QuestionLoc) {
8374 const Expr *NullExpr = LHSExpr;
8375 const Expr *NonPointerExpr = RHSExpr;
8376 Expr::NullPointerConstantKind NullKind =
8377 NullExpr->isNullPointerConstant(Ctx&: Context,
8378 NPC: Expr::NPC_ValueDependentIsNotNull);
8379
8380 if (NullKind == Expr::NPCK_NotNull) {
8381 NullExpr = RHSExpr;
8382 NonPointerExpr = LHSExpr;
8383 NullKind =
8384 NullExpr->isNullPointerConstant(Ctx&: Context,
8385 NPC: Expr::NPC_ValueDependentIsNotNull);
8386 }
8387
8388 if (NullKind == Expr::NPCK_NotNull)
8389 return false;
8390
8391 if (NullKind == Expr::NPCK_ZeroExpression)
8392 return false;
8393
8394 if (NullKind == Expr::NPCK_ZeroLiteral) {
8395 // In this case, check to make sure that we got here from a "NULL"
8396 // string in the source code.
8397 NullExpr = NullExpr->IgnoreParenImpCasts();
8398 SourceLocation loc = NullExpr->getExprLoc();
8399 if (!findMacroSpelling(loc, name: "NULL"))
8400 return false;
8401 }
8402
8403 int DiagType = (NullKind == Expr::NPCK_CXX11_nullptr);
8404 Diag(Loc: QuestionLoc, DiagID: diag::err_typecheck_cond_incompatible_operands_null)
8405 << NonPointerExpr->getType() << DiagType
8406 << NonPointerExpr->getSourceRange();
8407 return true;
8408}
8409
8410/// Return false if the condition expression is valid, true otherwise.
8411static bool checkCondition(Sema &S, const Expr *Cond,
8412 SourceLocation QuestionLoc) {
8413 QualType CondTy = Cond->getType();
8414
8415 // OpenCL v1.1 s6.3.i says the condition cannot be a floating point type.
8416 if (S.getLangOpts().OpenCL && CondTy->isFloatingType()) {
8417 S.Diag(Loc: QuestionLoc, DiagID: diag::err_typecheck_cond_expect_nonfloat)
8418 << CondTy << Cond->getSourceRange();
8419 return true;
8420 }
8421
8422 // C99 6.5.15p2
8423 if (CondTy->isScalarType()) return false;
8424
8425 S.Diag(Loc: QuestionLoc, DiagID: diag::err_typecheck_cond_expect_scalar)
8426 << CondTy << Cond->getSourceRange();
8427 return true;
8428}
8429
8430/// Return false if the NullExpr can be promoted to PointerTy,
8431/// true otherwise.
8432static bool checkConditionalNullPointer(Sema &S, ExprResult &NullExpr,
8433 QualType PointerTy) {
8434 if ((!PointerTy->isAnyPointerType() && !PointerTy->isBlockPointerType()) ||
8435 !NullExpr.get()->isNullPointerConstant(Ctx&: S.Context,
8436 NPC: Expr::NPC_ValueDependentIsNull))
8437 return true;
8438
8439 NullExpr = S.ImpCastExprToType(E: NullExpr.get(), Type: PointerTy, CK: CK_NullToPointer);
8440 return false;
8441}
8442
8443/// Checks compatibility between two pointers and return the resulting
8444/// type.
8445static QualType checkConditionalPointerCompatibility(Sema &S, ExprResult &LHS,
8446 ExprResult &RHS,
8447 SourceLocation Loc) {
8448 QualType LHSTy = LHS.get()->getType();
8449 QualType RHSTy = RHS.get()->getType();
8450
8451 if (S.Context.hasSameType(T1: LHSTy, T2: RHSTy)) {
8452 // Two identical pointers types are always compatible.
8453 return S.Context.getCommonSugaredType(X: LHSTy, Y: RHSTy);
8454 }
8455
8456 QualType lhptee, rhptee;
8457
8458 // Get the pointee types.
8459 bool IsBlockPointer = false;
8460 if (const BlockPointerType *LHSBTy = LHSTy->getAs<BlockPointerType>()) {
8461 lhptee = LHSBTy->getPointeeType();
8462 rhptee = RHSTy->castAs<BlockPointerType>()->getPointeeType();
8463 IsBlockPointer = true;
8464 } else {
8465 lhptee = LHSTy->castAs<PointerType>()->getPointeeType();
8466 rhptee = RHSTy->castAs<PointerType>()->getPointeeType();
8467 }
8468
8469 // C99 6.5.15p6: If both operands are pointers to compatible types or to
8470 // differently qualified versions of compatible types, the result type is
8471 // a pointer to an appropriately qualified version of the composite
8472 // type.
8473
8474 // Only CVR-qualifiers exist in the standard, and the differently-qualified
8475 // clause doesn't make sense for our extensions. E.g. address space 2 should
8476 // be incompatible with address space 3: they may live on different devices or
8477 // anything.
8478 Qualifiers lhQual = lhptee.getQualifiers();
8479 Qualifiers rhQual = rhptee.getQualifiers();
8480
8481 LangAS ResultAddrSpace = LangAS::Default;
8482 LangAS LAddrSpace = lhQual.getAddressSpace();
8483 LangAS RAddrSpace = rhQual.getAddressSpace();
8484
8485 // OpenCL v1.1 s6.5 - Conversion between pointers to distinct address
8486 // spaces is disallowed.
8487 if (lhQual.isAddressSpaceSupersetOf(other: rhQual, Ctx: S.getASTContext()))
8488 ResultAddrSpace = LAddrSpace;
8489 else if (rhQual.isAddressSpaceSupersetOf(other: lhQual, Ctx: S.getASTContext()))
8490 ResultAddrSpace = RAddrSpace;
8491 else {
8492 S.Diag(Loc, DiagID: diag::err_typecheck_op_on_nonoverlapping_address_space_pointers)
8493 << LHSTy << RHSTy << 2 << LHS.get()->getSourceRange()
8494 << RHS.get()->getSourceRange();
8495 return QualType();
8496 }
8497
8498 unsigned MergedCVRQual = lhQual.getCVRQualifiers() | rhQual.getCVRQualifiers();
8499 auto LHSCastKind = CK_BitCast, RHSCastKind = CK_BitCast;
8500 lhQual.removeCVRQualifiers();
8501 rhQual.removeCVRQualifiers();
8502
8503 if (!lhQual.getPointerAuth().isEquivalent(Other: rhQual.getPointerAuth())) {
8504 S.Diag(Loc, DiagID: diag::err_typecheck_cond_incompatible_ptrauth)
8505 << LHSTy << RHSTy << LHS.get()->getSourceRange()
8506 << RHS.get()->getSourceRange();
8507 return QualType();
8508 }
8509
8510 // OpenCL v2.0 specification doesn't extend compatibility of type qualifiers
8511 // (C99 6.7.3) for address spaces. We assume that the check should behave in
8512 // the same manner as it's defined for CVR qualifiers, so for OpenCL two
8513 // qual types are compatible iff
8514 // * corresponded types are compatible
8515 // * CVR qualifiers are equal
8516 // * address spaces are equal
8517 // Thus for conditional operator we merge CVR and address space unqualified
8518 // pointees and if there is a composite type we return a pointer to it with
8519 // merged qualifiers.
8520 LHSCastKind =
8521 LAddrSpace == ResultAddrSpace ? CK_BitCast : CK_AddressSpaceConversion;
8522 RHSCastKind =
8523 RAddrSpace == ResultAddrSpace ? CK_BitCast : CK_AddressSpaceConversion;
8524 lhQual.removeAddressSpace();
8525 rhQual.removeAddressSpace();
8526
8527 lhptee = S.Context.getQualifiedType(T: lhptee.getUnqualifiedType(), Qs: lhQual);
8528 rhptee = S.Context.getQualifiedType(T: rhptee.getUnqualifiedType(), Qs: rhQual);
8529
8530 QualType CompositeTy = S.Context.mergeTypes(
8531 lhptee, rhptee, /*OfBlockPointer=*/false, /*Unqualified=*/false,
8532 /*BlockReturnType=*/false, /*IsConditionalOperator=*/true);
8533
8534 if (CompositeTy.isNull()) {
8535 // In this situation, we assume void* type. No especially good
8536 // reason, but this is what gcc does, and we do have to pick
8537 // to get a consistent AST.
8538 QualType incompatTy;
8539 incompatTy = S.Context.getPointerType(
8540 T: S.Context.getAddrSpaceQualType(T: S.Context.VoidTy, AddressSpace: ResultAddrSpace));
8541 LHS = S.ImpCastExprToType(E: LHS.get(), Type: incompatTy, CK: LHSCastKind);
8542 RHS = S.ImpCastExprToType(E: RHS.get(), Type: incompatTy, CK: RHSCastKind);
8543
8544 // FIXME: For OpenCL the warning emission and cast to void* leaves a room
8545 // for casts between types with incompatible address space qualifiers.
8546 // For the following code the compiler produces casts between global and
8547 // local address spaces of the corresponded innermost pointees:
8548 // local int *global *a;
8549 // global int *global *b;
8550 // a = (0 ? a : b); // see C99 6.5.16.1.p1.
8551 S.Diag(Loc, DiagID: diag::ext_typecheck_cond_incompatible_pointers)
8552 << LHSTy << RHSTy << LHS.get()->getSourceRange()
8553 << RHS.get()->getSourceRange();
8554
8555 return incompatTy;
8556 }
8557
8558 // The pointer types are compatible.
8559 // In case of OpenCL ResultTy should have the address space qualifier
8560 // which is a superset of address spaces of both the 2nd and the 3rd
8561 // operands of the conditional operator.
8562 QualType ResultTy = [&, ResultAddrSpace]() {
8563 if (S.getLangOpts().OpenCL) {
8564 Qualifiers CompositeQuals = CompositeTy.getQualifiers();
8565 CompositeQuals.setAddressSpace(ResultAddrSpace);
8566 return S.Context
8567 .getQualifiedType(T: CompositeTy.getUnqualifiedType(), Qs: CompositeQuals)
8568 .withCVRQualifiers(CVR: MergedCVRQual);
8569 }
8570 return CompositeTy.withCVRQualifiers(CVR: MergedCVRQual);
8571 }();
8572 if (IsBlockPointer)
8573 ResultTy = S.Context.getBlockPointerType(T: ResultTy);
8574 else
8575 ResultTy = S.Context.getPointerType(T: ResultTy);
8576
8577 LHS = S.ImpCastExprToType(E: LHS.get(), Type: ResultTy, CK: LHSCastKind);
8578 RHS = S.ImpCastExprToType(E: RHS.get(), Type: ResultTy, CK: RHSCastKind);
8579 return ResultTy;
8580}
8581
8582/// Return the resulting type when the operands are both block pointers.
8583static QualType checkConditionalBlockPointerCompatibility(Sema &S,
8584 ExprResult &LHS,
8585 ExprResult &RHS,
8586 SourceLocation Loc) {
8587 QualType LHSTy = LHS.get()->getType();
8588 QualType RHSTy = RHS.get()->getType();
8589
8590 if (!LHSTy->isBlockPointerType() || !RHSTy->isBlockPointerType()) {
8591 if (LHSTy->isVoidPointerType() || RHSTy->isVoidPointerType()) {
8592 QualType destType = S.Context.getPointerType(T: S.Context.VoidTy);
8593 LHS = S.ImpCastExprToType(E: LHS.get(), Type: destType, CK: CK_BitCast);
8594 RHS = S.ImpCastExprToType(E: RHS.get(), Type: destType, CK: CK_BitCast);
8595 return destType;
8596 }
8597 S.Diag(Loc, DiagID: diag::err_typecheck_cond_incompatible_operands)
8598 << LHSTy << RHSTy << LHS.get()->getSourceRange()
8599 << RHS.get()->getSourceRange();
8600 return QualType();
8601 }
8602
8603 // We have 2 block pointer types.
8604 return checkConditionalPointerCompatibility(S, LHS, RHS, Loc);
8605}
8606
8607/// Return the resulting type when the operands are both pointers.
8608static QualType
8609checkConditionalObjectPointersCompatibility(Sema &S, ExprResult &LHS,
8610 ExprResult &RHS,
8611 SourceLocation Loc) {
8612 // get the pointer types
8613 QualType LHSTy = LHS.get()->getType();
8614 QualType RHSTy = RHS.get()->getType();
8615
8616 // get the "pointed to" types
8617 QualType lhptee = LHSTy->castAs<PointerType>()->getPointeeType();
8618 QualType rhptee = RHSTy->castAs<PointerType>()->getPointeeType();
8619
8620 // ignore qualifiers on void (C99 6.5.15p3, clause 6)
8621 if (lhptee->isVoidType() && rhptee->isIncompleteOrObjectType()) {
8622 // Figure out necessary qualifiers (C99 6.5.15p6)
8623 QualType destPointee
8624 = S.Context.getQualifiedType(T: lhptee, Qs: rhptee.getQualifiers());
8625 QualType destType = S.Context.getPointerType(T: destPointee);
8626 // Add qualifiers if necessary.
8627 LHS = S.ImpCastExprToType(E: LHS.get(), Type: destType, CK: CK_NoOp);
8628 // Promote to void*.
8629 RHS = S.ImpCastExprToType(E: RHS.get(), Type: destType, CK: CK_BitCast);
8630 return destType;
8631 }
8632 if (rhptee->isVoidType() && lhptee->isIncompleteOrObjectType()) {
8633 QualType destPointee
8634 = S.Context.getQualifiedType(T: rhptee, Qs: lhptee.getQualifiers());
8635 QualType destType = S.Context.getPointerType(T: destPointee);
8636 // Add qualifiers if necessary.
8637 RHS = S.ImpCastExprToType(E: RHS.get(), Type: destType, CK: CK_NoOp);
8638 // Promote to void*.
8639 LHS = S.ImpCastExprToType(E: LHS.get(), Type: destType, CK: CK_BitCast);
8640 return destType;
8641 }
8642
8643 return checkConditionalPointerCompatibility(S, LHS, RHS, Loc);
8644}
8645
8646/// Return false if the first expression is not an integer and the second
8647/// expression is not a pointer, true otherwise.
8648static bool checkPointerIntegerMismatch(Sema &S, ExprResult &Int,
8649 Expr* PointerExpr, SourceLocation Loc,
8650 bool IsIntFirstExpr) {
8651 if (!PointerExpr->getType()->isPointerType() ||
8652 !Int.get()->getType()->isIntegerType())
8653 return false;
8654
8655 Expr *Expr1 = IsIntFirstExpr ? Int.get() : PointerExpr;
8656 Expr *Expr2 = IsIntFirstExpr ? PointerExpr : Int.get();
8657
8658 S.Diag(Loc, DiagID: diag::ext_typecheck_cond_pointer_integer_mismatch)
8659 << Expr1->getType() << Expr2->getType()
8660 << Expr1->getSourceRange() << Expr2->getSourceRange();
8661 Int = S.ImpCastExprToType(E: Int.get(), Type: PointerExpr->getType(),
8662 CK: CK_IntegralToPointer);
8663 return true;
8664}
8665
8666/// Simple conversion between integer and floating point types.
8667///
8668/// Used when handling the OpenCL conditional operator where the
8669/// condition is a vector while the other operands are scalar.
8670///
8671/// OpenCL v1.1 s6.3.i and s6.11.6 together require that the scalar
8672/// types are either integer or floating type. Between the two
8673/// operands, the type with the higher rank is defined as the "result
8674/// type". The other operand needs to be promoted to the same type. No
8675/// other type promotion is allowed. We cannot use
8676/// UsualArithmeticConversions() for this purpose, since it always
8677/// promotes promotable types.
8678static QualType OpenCLArithmeticConversions(Sema &S, ExprResult &LHS,
8679 ExprResult &RHS,
8680 SourceLocation QuestionLoc) {
8681 LHS = S.DefaultFunctionArrayLvalueConversion(E: LHS.get());
8682 if (LHS.isInvalid())
8683 return QualType();
8684 RHS = S.DefaultFunctionArrayLvalueConversion(E: RHS.get());
8685 if (RHS.isInvalid())
8686 return QualType();
8687
8688 // For conversion purposes, we ignore any qualifiers.
8689 // For example, "const float" and "float" are equivalent.
8690 QualType LHSType =
8691 S.Context.getCanonicalType(T: LHS.get()->getType()).getUnqualifiedType();
8692 QualType RHSType =
8693 S.Context.getCanonicalType(T: RHS.get()->getType()).getUnqualifiedType();
8694
8695 if (!LHSType->isIntegerType() && !LHSType->isRealFloatingType()) {
8696 S.Diag(Loc: QuestionLoc, DiagID: diag::err_typecheck_cond_expect_int_float)
8697 << LHSType << LHS.get()->getSourceRange();
8698 return QualType();
8699 }
8700
8701 if (!RHSType->isIntegerType() && !RHSType->isRealFloatingType()) {
8702 S.Diag(Loc: QuestionLoc, DiagID: diag::err_typecheck_cond_expect_int_float)
8703 << RHSType << RHS.get()->getSourceRange();
8704 return QualType();
8705 }
8706
8707 // If both types are identical, no conversion is needed.
8708 if (LHSType == RHSType)
8709 return LHSType;
8710
8711 // Now handle "real" floating types (i.e. float, double, long double).
8712 if (LHSType->isRealFloatingType() || RHSType->isRealFloatingType())
8713 return handleFloatConversion(S, LHS, RHS, LHSType, RHSType,
8714 /*IsCompAssign = */ false);
8715
8716 // Finally, we have two differing integer types.
8717 return handleIntegerConversion<doIntegralCast, doIntegralCast>
8718 (S, LHS, RHS, LHSType, RHSType, /*IsCompAssign = */ false);
8719}
8720
8721/// Convert scalar operands to a vector that matches the
8722/// condition in length.
8723///
8724/// Used when handling the OpenCL conditional operator where the
8725/// condition is a vector while the other operands are scalar.
8726///
8727/// We first compute the "result type" for the scalar operands
8728/// according to OpenCL v1.1 s6.3.i. Both operands are then converted
8729/// into a vector of that type where the length matches the condition
8730/// vector type. s6.11.6 requires that the element types of the result
8731/// and the condition must have the same number of bits.
8732static QualType
8733OpenCLConvertScalarsToVectors(Sema &S, ExprResult &LHS, ExprResult &RHS,
8734 QualType CondTy, SourceLocation QuestionLoc) {
8735 QualType ResTy = OpenCLArithmeticConversions(S, LHS, RHS, QuestionLoc);
8736 if (ResTy.isNull()) return QualType();
8737
8738 const VectorType *CV = CondTy->getAs<VectorType>();
8739 assert(CV);
8740
8741 // Determine the vector result type
8742 unsigned NumElements = CV->getNumElements();
8743 QualType VectorTy = S.Context.getExtVectorType(VectorType: ResTy, NumElts: NumElements);
8744
8745 // Ensure that all types have the same number of bits
8746 if (S.Context.getTypeSize(T: CV->getElementType())
8747 != S.Context.getTypeSize(T: ResTy)) {
8748 // Since VectorTy is created internally, it does not pretty print
8749 // with an OpenCL name. Instead, we just print a description.
8750 std::string EleTyName = ResTy.getUnqualifiedType().getAsString();
8751 SmallString<64> Str;
8752 llvm::raw_svector_ostream OS(Str);
8753 OS << "(vector of " << NumElements << " '" << EleTyName << "' values)";
8754 S.Diag(Loc: QuestionLoc, DiagID: diag::err_conditional_vector_element_size)
8755 << CondTy << OS.str();
8756 return QualType();
8757 }
8758
8759 // Convert operands to the vector result type
8760 LHS = S.ImpCastExprToType(E: LHS.get(), Type: VectorTy, CK: CK_VectorSplat);
8761 RHS = S.ImpCastExprToType(E: RHS.get(), Type: VectorTy, CK: CK_VectorSplat);
8762
8763 return VectorTy;
8764}
8765
8766/// Return false if this is a valid OpenCL condition vector
8767static bool checkOpenCLConditionVector(Sema &S, Expr *Cond,
8768 SourceLocation QuestionLoc) {
8769 // OpenCL v1.1 s6.11.6 says the elements of the vector must be of
8770 // integral type.
8771 const VectorType *CondTy = Cond->getType()->getAs<VectorType>();
8772 assert(CondTy);
8773 QualType EleTy = CondTy->getElementType();
8774 if (EleTy->isIntegerType()) return false;
8775
8776 S.Diag(Loc: QuestionLoc, DiagID: diag::err_typecheck_cond_expect_nonfloat)
8777 << Cond->getType() << Cond->getSourceRange();
8778 return true;
8779}
8780
8781/// Return false if the vector condition type and the vector
8782/// result type are compatible.
8783///
8784/// OpenCL v1.1 s6.11.6 requires that both vector types have the same
8785/// number of elements, and their element types have the same number
8786/// of bits.
8787static bool checkVectorResult(Sema &S, QualType CondTy, QualType VecResTy,
8788 SourceLocation QuestionLoc) {
8789 const VectorType *CV = CondTy->getAs<VectorType>();
8790 const VectorType *RV = VecResTy->getAs<VectorType>();
8791 assert(CV && RV);
8792
8793 if (CV->getNumElements() != RV->getNumElements()) {
8794 S.Diag(Loc: QuestionLoc, DiagID: diag::err_conditional_vector_size)
8795 << CondTy << VecResTy;
8796 return true;
8797 }
8798
8799 QualType CVE = CV->getElementType();
8800 QualType RVE = RV->getElementType();
8801
8802 // Boolean vectors are permitted outside of OpenCL mode.
8803 if (S.Context.getTypeSize(T: CVE) != S.Context.getTypeSize(T: RVE) &&
8804 (!CVE->isBooleanType() || S.LangOpts.OpenCL)) {
8805 S.Diag(Loc: QuestionLoc, DiagID: diag::err_conditional_vector_element_size)
8806 << CondTy << VecResTy;
8807 return true;
8808 }
8809
8810 return false;
8811}
8812
8813/// Return the resulting type for the conditional operator in
8814/// OpenCL (aka "ternary selection operator", OpenCL v1.1
8815/// s6.3.i) when the condition is a vector type.
8816static QualType
8817OpenCLCheckVectorConditional(Sema &S, ExprResult &Cond,
8818 ExprResult &LHS, ExprResult &RHS,
8819 SourceLocation QuestionLoc) {
8820 Cond = S.DefaultFunctionArrayLvalueConversion(E: Cond.get());
8821 if (Cond.isInvalid())
8822 return QualType();
8823 QualType CondTy = Cond.get()->getType();
8824
8825 if (checkOpenCLConditionVector(S, Cond: Cond.get(), QuestionLoc))
8826 return QualType();
8827
8828 // If either operand is a vector then find the vector type of the
8829 // result as specified in OpenCL v1.1 s6.3.i.
8830 if (LHS.get()->getType()->isVectorType() ||
8831 RHS.get()->getType()->isVectorType()) {
8832 bool IsBoolVecLang =
8833 !S.getLangOpts().OpenCL && !S.getLangOpts().OpenCLCPlusPlus;
8834 QualType VecResTy =
8835 S.CheckVectorOperands(LHS, RHS, Loc: QuestionLoc,
8836 /*isCompAssign*/ IsCompAssign: false,
8837 /*AllowBothBool*/ true,
8838 /*AllowBoolConversions*/ AllowBoolConversion: false,
8839 /*AllowBooleanOperation*/ AllowBoolOperation: IsBoolVecLang,
8840 /*ReportInvalid*/ true);
8841 if (VecResTy.isNull())
8842 return QualType();
8843 // The result type must match the condition type as specified in
8844 // OpenCL v1.1 s6.11.6.
8845 if (checkVectorResult(S, CondTy, VecResTy, QuestionLoc))
8846 return QualType();
8847 return VecResTy;
8848 }
8849
8850 // Both operands are scalar.
8851 return OpenCLConvertScalarsToVectors(S, LHS, RHS, CondTy, QuestionLoc);
8852}
8853
8854/// Return true if the Expr is block type
8855static bool checkBlockType(Sema &S, const Expr *E) {
8856 if (E->getType()->isBlockPointerType()) {
8857 S.Diag(Loc: E->getExprLoc(), DiagID: diag::err_opencl_ternary_with_block);
8858 return true;
8859 }
8860
8861 if (const CallExpr *CE = dyn_cast<CallExpr>(Val: E)) {
8862 QualType Ty = CE->getCallee()->getType();
8863 if (Ty->isBlockPointerType()) {
8864 S.Diag(Loc: E->getExprLoc(), DiagID: diag::err_opencl_ternary_with_block);
8865 return true;
8866 }
8867 }
8868 return false;
8869}
8870
8871/// Note that LHS is not null here, even if this is the gnu "x ?: y" extension.
8872/// In that case, LHS = cond.
8873/// C99 6.5.15
8874QualType Sema::CheckConditionalOperands(ExprResult &Cond, ExprResult &LHS,
8875 ExprResult &RHS, ExprValueKind &VK,
8876 ExprObjectKind &OK,
8877 SourceLocation QuestionLoc) {
8878
8879 ExprResult LHSResult = CheckPlaceholderExpr(E: LHS.get());
8880 if (!LHSResult.isUsable()) return QualType();
8881 LHS = LHSResult;
8882
8883 ExprResult RHSResult = CheckPlaceholderExpr(E: RHS.get());
8884 if (!RHSResult.isUsable()) return QualType();
8885 RHS = RHSResult;
8886
8887 // C++ is sufficiently different to merit its own checker.
8888 if (getLangOpts().CPlusPlus)
8889 return CXXCheckConditionalOperands(cond&: Cond, lhs&: LHS, rhs&: RHS, VK, OK, questionLoc: QuestionLoc);
8890
8891 VK = VK_PRValue;
8892 OK = OK_Ordinary;
8893
8894 if (Context.isDependenceAllowed() &&
8895 (Cond.get()->isTypeDependent() || LHS.get()->isTypeDependent() ||
8896 RHS.get()->isTypeDependent())) {
8897 assert(!getLangOpts().CPlusPlus);
8898 assert((Cond.get()->containsErrors() || LHS.get()->containsErrors() ||
8899 RHS.get()->containsErrors()) &&
8900 "should only occur in error-recovery path.");
8901 return Context.DependentTy;
8902 }
8903
8904 // The OpenCL operator with a vector condition is sufficiently
8905 // different to merit its own checker.
8906 if ((getLangOpts().OpenCL && Cond.get()->getType()->isVectorType()) ||
8907 Cond.get()->getType()->isExtVectorType())
8908 return OpenCLCheckVectorConditional(S&: *this, Cond, LHS, RHS, QuestionLoc);
8909
8910 // First, check the condition.
8911 Cond = UsualUnaryConversions(E: Cond.get());
8912 if (Cond.isInvalid())
8913 return QualType();
8914 if (checkCondition(S&: *this, Cond: Cond.get(), QuestionLoc))
8915 return QualType();
8916
8917 // Handle vectors.
8918 if (LHS.get()->getType()->isVectorType() ||
8919 RHS.get()->getType()->isVectorType())
8920 return CheckVectorOperands(LHS, RHS, Loc: QuestionLoc, /*isCompAssign*/ IsCompAssign: false,
8921 /*AllowBothBool*/ true,
8922 /*AllowBoolConversions*/ AllowBoolConversion: false,
8923 /*AllowBooleanOperation*/ AllowBoolOperation: false,
8924 /*ReportInvalid*/ true);
8925
8926 QualType ResTy = UsualArithmeticConversions(LHS, RHS, Loc: QuestionLoc,
8927 ACK: ArithConvKind::Conditional);
8928 if (LHS.isInvalid() || RHS.isInvalid())
8929 return QualType();
8930
8931 // WebAssembly tables are not allowed as conditional LHS or RHS.
8932 QualType LHSTy = LHS.get()->getType();
8933 QualType RHSTy = RHS.get()->getType();
8934 if (LHSTy->isWebAssemblyTableType() || RHSTy->isWebAssemblyTableType()) {
8935 Diag(Loc: QuestionLoc, DiagID: diag::err_wasm_table_conditional_expression)
8936 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
8937 return QualType();
8938 }
8939
8940 // Diagnose attempts to convert between __ibm128, __float128 and long double
8941 // where such conversions currently can't be handled.
8942 if (unsupportedTypeConversion(S: *this, LHSType: LHSTy, RHSType: RHSTy)) {
8943 Diag(Loc: QuestionLoc,
8944 DiagID: diag::err_typecheck_cond_incompatible_operands) << LHSTy << RHSTy
8945 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
8946 return QualType();
8947 }
8948
8949 // OpenCL v2.0 s6.12.5 - Blocks cannot be used as expressions of the ternary
8950 // selection operator (?:).
8951 if (getLangOpts().OpenCL &&
8952 ((int)checkBlockType(S&: *this, E: LHS.get()) | (int)checkBlockType(S&: *this, E: RHS.get()))) {
8953 return QualType();
8954 }
8955
8956 // If both operands have arithmetic type, do the usual arithmetic conversions
8957 // to find a common type: C99 6.5.15p3,5.
8958 if (LHSTy->isArithmeticType() && RHSTy->isArithmeticType()) {
8959 // Disallow invalid arithmetic conversions, such as those between bit-
8960 // precise integers types of different sizes, or between a bit-precise
8961 // integer and another type.
8962 if (ResTy.isNull() && (LHSTy->isBitIntType() || RHSTy->isBitIntType())) {
8963 Diag(Loc: QuestionLoc, DiagID: diag::err_typecheck_cond_incompatible_operands)
8964 << LHSTy << RHSTy << LHS.get()->getSourceRange()
8965 << RHS.get()->getSourceRange();
8966 return QualType();
8967 }
8968
8969 LHS = ImpCastExprToType(E: LHS.get(), Type: ResTy, CK: PrepareScalarCast(Src&: LHS, DestTy: ResTy));
8970 RHS = ImpCastExprToType(E: RHS.get(), Type: ResTy, CK: PrepareScalarCast(Src&: RHS, DestTy: ResTy));
8971
8972 return ResTy;
8973 }
8974
8975 // If both operands are the same structure or union type, the result is that
8976 // type.
8977 // FIXME: Type of conditional expression must be complete in C mode.
8978 if (LHSTy->isRecordType() &&
8979 Context.hasSameUnqualifiedType(T1: LHSTy, T2: RHSTy)) // C99 6.5.15p3
8980 return Context.getCommonSugaredType(X: LHSTy.getUnqualifiedType(),
8981 Y: RHSTy.getUnqualifiedType());
8982
8983 // C99 6.5.15p5: "If both operands have void type, the result has void type."
8984 // The following || allows only one side to be void (a GCC-ism).
8985 if (LHSTy->isVoidType() || RHSTy->isVoidType()) {
8986 if (LHSTy->isVoidType() && RHSTy->isVoidType()) {
8987 // UsualArithmeticConversions already handled the case where both sides
8988 // are the same type.
8989 } else if (RHSTy->isVoidType()) {
8990 ResTy = RHSTy;
8991 Diag(Loc: RHS.get()->getBeginLoc(), DiagID: diag::ext_typecheck_cond_one_void)
8992 << RHS.get()->getSourceRange();
8993 } else {
8994 ResTy = LHSTy;
8995 Diag(Loc: LHS.get()->getBeginLoc(), DiagID: diag::ext_typecheck_cond_one_void)
8996 << LHS.get()->getSourceRange();
8997 }
8998 LHS = ImpCastExprToType(E: LHS.get(), Type: ResTy, CK: CK_ToVoid);
8999 RHS = ImpCastExprToType(E: RHS.get(), Type: ResTy, CK: CK_ToVoid);
9000 return ResTy;
9001 }
9002
9003 // C23 6.5.15p7:
9004 // ... if both the second and third operands have nullptr_t type, the
9005 // result also has that type.
9006 if (LHSTy->isNullPtrType() && Context.hasSameType(T1: LHSTy, T2: RHSTy))
9007 return ResTy;
9008
9009 // C99 6.5.15p6 - "if one operand is a null pointer constant, the result has
9010 // the type of the other operand."
9011 if (!checkConditionalNullPointer(S&: *this, NullExpr&: RHS, PointerTy: LHSTy)) return LHSTy;
9012 if (!checkConditionalNullPointer(S&: *this, NullExpr&: LHS, PointerTy: RHSTy)) return RHSTy;
9013
9014 // All objective-c pointer type analysis is done here.
9015 QualType compositeType =
9016 ObjC().FindCompositeObjCPointerType(LHS, RHS, QuestionLoc);
9017 if (LHS.isInvalid() || RHS.isInvalid())
9018 return QualType();
9019 if (!compositeType.isNull())
9020 return compositeType;
9021
9022
9023 // Handle block pointer types.
9024 if (LHSTy->isBlockPointerType() || RHSTy->isBlockPointerType())
9025 return checkConditionalBlockPointerCompatibility(S&: *this, LHS, RHS,
9026 Loc: QuestionLoc);
9027
9028 // Check constraints for C object pointers types (C99 6.5.15p3,6).
9029 if (LHSTy->isPointerType() && RHSTy->isPointerType())
9030 return checkConditionalObjectPointersCompatibility(S&: *this, LHS, RHS,
9031 Loc: QuestionLoc);
9032
9033 // GCC compatibility: soften pointer/integer mismatch. Note that
9034 // null pointers have been filtered out by this point.
9035 if (checkPointerIntegerMismatch(S&: *this, Int&: LHS, PointerExpr: RHS.get(), Loc: QuestionLoc,
9036 /*IsIntFirstExpr=*/true))
9037 return RHSTy;
9038 if (checkPointerIntegerMismatch(S&: *this, Int&: RHS, PointerExpr: LHS.get(), Loc: QuestionLoc,
9039 /*IsIntFirstExpr=*/false))
9040 return LHSTy;
9041
9042 // Emit a better diagnostic if one of the expressions is a null pointer
9043 // constant and the other is not a pointer type. In this case, the user most
9044 // likely forgot to take the address of the other expression.
9045 if (DiagnoseConditionalForNull(LHSExpr: LHS.get(), RHSExpr: RHS.get(), QuestionLoc))
9046 return QualType();
9047
9048 // Finally, if the LHS and RHS types are canonically the same type, we can
9049 // use the common sugared type.
9050 if (Context.hasSameType(T1: LHSTy, T2: RHSTy))
9051 return Context.getCommonSugaredType(X: LHSTy, Y: RHSTy);
9052
9053 // Otherwise, the operands are not compatible.
9054 Diag(Loc: QuestionLoc, DiagID: diag::err_typecheck_cond_incompatible_operands)
9055 << LHSTy << RHSTy << LHS.get()->getSourceRange()
9056 << RHS.get()->getSourceRange();
9057 return QualType();
9058}
9059
9060/// SuggestParentheses - Emit a note with a fixit hint that wraps
9061/// ParenRange in parentheses.
9062static void SuggestParentheses(Sema &Self, SourceLocation Loc,
9063 const PartialDiagnostic &Note,
9064 SourceRange ParenRange) {
9065 SourceLocation EndLoc = Self.getLocForEndOfToken(Loc: ParenRange.getEnd());
9066 if (ParenRange.getBegin().isFileID() && ParenRange.getEnd().isFileID() &&
9067 EndLoc.isValid()) {
9068 Self.Diag(Loc, PD: Note)
9069 << FixItHint::CreateInsertion(InsertionLoc: ParenRange.getBegin(), Code: "(")
9070 << FixItHint::CreateInsertion(InsertionLoc: EndLoc, Code: ")");
9071 } else {
9072 // We can't display the parentheses, so just show the bare note.
9073 Self.Diag(Loc, PD: Note) << ParenRange;
9074 }
9075}
9076
9077static bool IsArithmeticOp(BinaryOperatorKind Opc) {
9078 return BinaryOperator::isAdditiveOp(Opc) ||
9079 BinaryOperator::isMultiplicativeOp(Opc) ||
9080 BinaryOperator::isShiftOp(Opc) || Opc == BO_And || Opc == BO_Or;
9081 // This only checks for bitwise-or and bitwise-and, but not bitwise-xor and
9082 // not any of the logical operators. Bitwise-xor is commonly used as a
9083 // logical-xor because there is no logical-xor operator. The logical
9084 // operators, including uses of xor, have a high false positive rate for
9085 // precedence warnings.
9086}
9087
9088/// IsArithmeticBinaryExpr - Returns true if E is an arithmetic binary
9089/// expression, either using a built-in or overloaded operator,
9090/// and sets *OpCode to the opcode and *RHSExprs to the right-hand side
9091/// expression.
9092static bool IsArithmeticBinaryExpr(const Expr *E, BinaryOperatorKind *Opcode,
9093 const Expr **RHSExprs) {
9094 // Don't strip parenthesis: we should not warn if E is in parenthesis.
9095 E = E->IgnoreImpCasts();
9096 E = E->IgnoreConversionOperatorSingleStep();
9097 E = E->IgnoreImpCasts();
9098 if (const auto *MTE = dyn_cast<MaterializeTemporaryExpr>(Val: E)) {
9099 E = MTE->getSubExpr();
9100 E = E->IgnoreImpCasts();
9101 }
9102
9103 // Built-in binary operator.
9104 if (const auto *OP = dyn_cast<BinaryOperator>(Val: E);
9105 OP && IsArithmeticOp(Opc: OP->getOpcode())) {
9106 *Opcode = OP->getOpcode();
9107 *RHSExprs = OP->getRHS();
9108 return true;
9109 }
9110
9111 // Overloaded operator.
9112 if (const auto *Call = dyn_cast<CXXOperatorCallExpr>(Val: E)) {
9113 if (Call->getNumArgs() != 2)
9114 return false;
9115
9116 // Make sure this is really a binary operator that is safe to pass into
9117 // BinaryOperator::getOverloadedOpcode(), e.g. it's not a subscript op.
9118 OverloadedOperatorKind OO = Call->getOperator();
9119 if (OO < OO_Plus || OO > OO_Arrow ||
9120 OO == OO_PlusPlus || OO == OO_MinusMinus)
9121 return false;
9122
9123 BinaryOperatorKind OpKind = BinaryOperator::getOverloadedOpcode(OO);
9124 if (IsArithmeticOp(Opc: OpKind)) {
9125 *Opcode = OpKind;
9126 *RHSExprs = Call->getArg(Arg: 1);
9127 return true;
9128 }
9129 }
9130
9131 return false;
9132}
9133
9134/// ExprLooksBoolean - Returns true if E looks boolean, i.e. it has boolean type
9135/// or is a logical expression such as (x==y) which has int type, but is
9136/// commonly interpreted as boolean.
9137static bool ExprLooksBoolean(const Expr *E) {
9138 E = E->IgnoreParenImpCasts();
9139
9140 if (E->getType()->isBooleanType())
9141 return true;
9142 if (const auto *OP = dyn_cast<BinaryOperator>(Val: E))
9143 return OP->isComparisonOp() || OP->isLogicalOp();
9144 if (const auto *OP = dyn_cast<UnaryOperator>(Val: E))
9145 return OP->getOpcode() == UO_LNot;
9146 if (E->getType()->isPointerType())
9147 return true;
9148 // FIXME: What about overloaded operator calls returning "unspecified boolean
9149 // type"s (commonly pointer-to-members)?
9150
9151 return false;
9152}
9153
9154/// DiagnoseConditionalPrecedence - Emit a warning when a conditional operator
9155/// and binary operator are mixed in a way that suggests the programmer assumed
9156/// the conditional operator has higher precedence, for example:
9157/// "int x = a + someBinaryCondition ? 1 : 2".
9158static void DiagnoseConditionalPrecedence(Sema &Self, SourceLocation OpLoc,
9159 Expr *Condition, const Expr *LHSExpr,
9160 const Expr *RHSExpr) {
9161 BinaryOperatorKind CondOpcode;
9162 const Expr *CondRHS;
9163
9164 if (!IsArithmeticBinaryExpr(E: Condition, Opcode: &CondOpcode, RHSExprs: &CondRHS))
9165 return;
9166 if (!ExprLooksBoolean(E: CondRHS))
9167 return;
9168
9169 // The condition is an arithmetic binary expression, with a right-
9170 // hand side that looks boolean, so warn.
9171
9172 unsigned DiagID = BinaryOperator::isBitwiseOp(Opc: CondOpcode)
9173 ? diag::warn_precedence_bitwise_conditional
9174 : diag::warn_precedence_conditional;
9175
9176 Self.Diag(Loc: OpLoc, DiagID)
9177 << Condition->getSourceRange()
9178 << BinaryOperator::getOpcodeStr(Op: CondOpcode);
9179
9180 SuggestParentheses(
9181 Self, Loc: OpLoc,
9182 Note: Self.PDiag(DiagID: diag::note_precedence_silence)
9183 << BinaryOperator::getOpcodeStr(Op: CondOpcode),
9184 ParenRange: SourceRange(Condition->getBeginLoc(), Condition->getEndLoc()));
9185
9186 SuggestParentheses(Self, Loc: OpLoc,
9187 Note: Self.PDiag(DiagID: diag::note_precedence_conditional_first),
9188 ParenRange: SourceRange(CondRHS->getBeginLoc(), RHSExpr->getEndLoc()));
9189}
9190
9191/// Compute the nullability of a conditional expression.
9192static QualType computeConditionalNullability(QualType ResTy, bool IsBin,
9193 QualType LHSTy, QualType RHSTy,
9194 ASTContext &Ctx) {
9195 if (!ResTy->isAnyPointerType())
9196 return ResTy;
9197
9198 auto GetNullability = [](QualType Ty) {
9199 NullabilityKindOrNone Kind = Ty->getNullability();
9200 if (Kind) {
9201 // For our purposes, treat _Nullable_result as _Nullable.
9202 if (*Kind == NullabilityKind::NullableResult)
9203 return NullabilityKind::Nullable;
9204 return *Kind;
9205 }
9206 return NullabilityKind::Unspecified;
9207 };
9208
9209 auto LHSKind = GetNullability(LHSTy), RHSKind = GetNullability(RHSTy);
9210 NullabilityKind MergedKind;
9211
9212 // Compute nullability of a binary conditional expression.
9213 if (IsBin) {
9214 if (LHSKind == NullabilityKind::NonNull)
9215 MergedKind = NullabilityKind::NonNull;
9216 else
9217 MergedKind = RHSKind;
9218 // Compute nullability of a normal conditional expression.
9219 } else {
9220 if (LHSKind == NullabilityKind::Nullable ||
9221 RHSKind == NullabilityKind::Nullable)
9222 MergedKind = NullabilityKind::Nullable;
9223 else if (LHSKind == NullabilityKind::NonNull)
9224 MergedKind = RHSKind;
9225 else if (RHSKind == NullabilityKind::NonNull)
9226 MergedKind = LHSKind;
9227 else
9228 MergedKind = NullabilityKind::Unspecified;
9229 }
9230
9231 // Return if ResTy already has the correct nullability.
9232 if (GetNullability(ResTy) == MergedKind)
9233 return ResTy;
9234
9235 // Strip all nullability from ResTy.
9236 while (ResTy->getNullability())
9237 ResTy = ResTy.getSingleStepDesugaredType(Context: Ctx);
9238
9239 // Create a new AttributedType with the new nullability kind.
9240 return Ctx.getAttributedType(nullability: MergedKind, modifiedType: ResTy, equivalentType: ResTy);
9241}
9242
9243ExprResult Sema::ActOnConditionalOp(SourceLocation QuestionLoc,
9244 SourceLocation ColonLoc,
9245 Expr *CondExpr, Expr *LHSExpr,
9246 Expr *RHSExpr) {
9247 // If this is the gnu "x ?: y" extension, analyze the types as though the LHS
9248 // was the condition.
9249 OpaqueValueExpr *opaqueValue = nullptr;
9250 Expr *commonExpr = nullptr;
9251 if (!LHSExpr) {
9252 commonExpr = CondExpr;
9253 // Lower out placeholder types first. This is important so that we don't
9254 // try to capture a placeholder. This happens in few cases in C++; such
9255 // as Objective-C++'s dictionary subscripting syntax.
9256 if (commonExpr->hasPlaceholderType()) {
9257 ExprResult result = CheckPlaceholderExpr(E: commonExpr);
9258 if (!result.isUsable()) return ExprError();
9259 commonExpr = result.get();
9260 }
9261 // We usually want to apply unary conversions *before* saving, except
9262 // in the special case of a C++ l-value conditional.
9263 if (!(getLangOpts().CPlusPlus
9264 && !commonExpr->isTypeDependent()
9265 && commonExpr->getValueKind() == RHSExpr->getValueKind()
9266 && commonExpr->isGLValue()
9267 && commonExpr->isOrdinaryOrBitFieldObject()
9268 && RHSExpr->isOrdinaryOrBitFieldObject()
9269 && Context.hasSameType(T1: commonExpr->getType(), T2: RHSExpr->getType()))) {
9270 ExprResult commonRes = UsualUnaryConversions(E: commonExpr);
9271 if (commonRes.isInvalid())
9272 return ExprError();
9273 commonExpr = commonRes.get();
9274 }
9275
9276 // If the common expression is a class or array prvalue, materialize it
9277 // so that we can safely refer to it multiple times.
9278 if (commonExpr->isPRValue() && (commonExpr->getType()->isRecordType() ||
9279 commonExpr->getType()->isArrayType())) {
9280 ExprResult MatExpr = TemporaryMaterializationConversion(E: commonExpr);
9281 if (MatExpr.isInvalid())
9282 return ExprError();
9283 commonExpr = MatExpr.get();
9284 }
9285
9286 opaqueValue = new (Context) OpaqueValueExpr(commonExpr->getExprLoc(),
9287 commonExpr->getType(),
9288 commonExpr->getValueKind(),
9289 commonExpr->getObjectKind(),
9290 commonExpr);
9291 LHSExpr = CondExpr = opaqueValue;
9292 }
9293
9294 QualType LHSTy = LHSExpr->getType(), RHSTy = RHSExpr->getType();
9295 ExprValueKind VK = VK_PRValue;
9296 ExprObjectKind OK = OK_Ordinary;
9297 ExprResult Cond = CondExpr, LHS = LHSExpr, RHS = RHSExpr;
9298 QualType result = CheckConditionalOperands(Cond, LHS, RHS,
9299 VK, OK, QuestionLoc);
9300 if (result.isNull() || Cond.isInvalid() || LHS.isInvalid() ||
9301 RHS.isInvalid())
9302 return ExprError();
9303
9304 DiagnoseConditionalPrecedence(Self&: *this, OpLoc: QuestionLoc, Condition: Cond.get(), LHSExpr: LHS.get(),
9305 RHSExpr: RHS.get());
9306
9307 CheckBoolLikeConversion(E: Cond.get(), CC: QuestionLoc);
9308
9309 result = computeConditionalNullability(ResTy: result, IsBin: commonExpr, LHSTy, RHSTy,
9310 Ctx&: Context);
9311
9312 if (!commonExpr)
9313 return new (Context)
9314 ConditionalOperator(Cond.get(), QuestionLoc, LHS.get(), ColonLoc,
9315 RHS.get(), result, VK, OK);
9316
9317 return new (Context) BinaryConditionalOperator(
9318 commonExpr, opaqueValue, Cond.get(), LHS.get(), RHS.get(), QuestionLoc,
9319 ColonLoc, result, VK, OK);
9320}
9321
9322bool Sema::IsInvalidSMECallConversion(QualType FromType, QualType ToType) {
9323 unsigned FromAttributes = 0, ToAttributes = 0;
9324 if (const auto *FromFn =
9325 dyn_cast<FunctionProtoType>(Val: Context.getCanonicalType(T: FromType)))
9326 FromAttributes =
9327 FromFn->getAArch64SMEAttributes() & FunctionType::SME_AttributeMask;
9328 if (const auto *ToFn =
9329 dyn_cast<FunctionProtoType>(Val: Context.getCanonicalType(T: ToType)))
9330 ToAttributes =
9331 ToFn->getAArch64SMEAttributes() & FunctionType::SME_AttributeMask;
9332
9333 return FromAttributes != ToAttributes;
9334}
9335
9336// checkPointerTypesForAssignment - This is a very tricky routine (despite
9337// being closely modeled after the C99 spec:-). The odd characteristic of this
9338// routine is it effectively iqnores the qualifiers on the top level pointee.
9339// This circumvents the usual type rules specified in 6.2.7p1 & 6.7.5.[1-3].
9340// FIXME: add a couple examples in this comment.
9341static AssignConvertType checkPointerTypesForAssignment(Sema &S,
9342 QualType LHSType,
9343 QualType RHSType,
9344 SourceLocation Loc) {
9345 assert(LHSType.isCanonical() && "LHS not canonicalized!");
9346 assert(RHSType.isCanonical() && "RHS not canonicalized!");
9347
9348 // get the "pointed to" type (ignoring qualifiers at the top level)
9349 const Type *lhptee, *rhptee;
9350 Qualifiers lhq, rhq;
9351 std::tie(args&: lhptee, args&: lhq) =
9352 cast<PointerType>(Val&: LHSType)->getPointeeType().split().asPair();
9353 std::tie(args&: rhptee, args&: rhq) =
9354 cast<PointerType>(Val&: RHSType)->getPointeeType().split().asPair();
9355
9356 AssignConvertType ConvTy = AssignConvertType::Compatible;
9357
9358 // C99 6.5.16.1p1: This following citation is common to constraints
9359 // 3 & 4 (below). ...and the type *pointed to* by the left has all the
9360 // qualifiers of the type *pointed to* by the right;
9361
9362 // As a special case, 'non-__weak A *' -> 'non-__weak const *' is okay.
9363 if (lhq.getObjCLifetime() != rhq.getObjCLifetime() &&
9364 lhq.compatiblyIncludesObjCLifetime(other: rhq)) {
9365 // Ignore lifetime for further calculation.
9366 lhq.removeObjCLifetime();
9367 rhq.removeObjCLifetime();
9368 }
9369
9370 if (!lhq.compatiblyIncludes(other: rhq, Ctx: S.getASTContext())) {
9371 // Treat address-space mismatches as fatal.
9372 if (!lhq.isAddressSpaceSupersetOf(other: rhq, Ctx: S.getASTContext()))
9373 return AssignConvertType::IncompatiblePointerDiscardsQualifiers;
9374
9375 // It's okay to add or remove GC or lifetime qualifiers when converting to
9376 // and from void*.
9377 else if (lhq.withoutObjCGCAttr().withoutObjCLifetime().compatiblyIncludes(
9378 other: rhq.withoutObjCGCAttr().withoutObjCLifetime(),
9379 Ctx: S.getASTContext()) &&
9380 (lhptee->isVoidType() || rhptee->isVoidType()))
9381 ; // keep old
9382
9383 // Treat lifetime mismatches as fatal.
9384 else if (lhq.getObjCLifetime() != rhq.getObjCLifetime())
9385 ConvTy = AssignConvertType::IncompatiblePointerDiscardsQualifiers;
9386
9387 // Treat pointer-auth mismatches as fatal.
9388 else if (!lhq.getPointerAuth().isEquivalent(Other: rhq.getPointerAuth()))
9389 ConvTy = AssignConvertType::IncompatiblePointerDiscardsQualifiers;
9390
9391 // For GCC/MS compatibility, other qualifier mismatches are treated
9392 // as still compatible in C.
9393 else
9394 ConvTy = AssignConvertType::CompatiblePointerDiscardsQualifiers;
9395 }
9396
9397 // C99 6.5.16.1p1 (constraint 4): If one operand is a pointer to an object or
9398 // incomplete type and the other is a pointer to a qualified or unqualified
9399 // version of void...
9400 if (lhptee->isVoidType()) {
9401 if (rhptee->isIncompleteOrObjectType())
9402 return ConvTy;
9403
9404 // As an extension, we allow cast to/from void* to function pointer.
9405 assert(rhptee->isFunctionType());
9406 return AssignConvertType::FunctionVoidPointer;
9407 }
9408
9409 if (rhptee->isVoidType()) {
9410 // In C, void * to another pointer type is compatible, but we want to note
9411 // that there will be an implicit conversion happening here.
9412 if (lhptee->isIncompleteOrObjectType())
9413 return ConvTy == AssignConvertType::Compatible &&
9414 !S.getLangOpts().CPlusPlus
9415 ? AssignConvertType::CompatibleVoidPtrToNonVoidPtr
9416 : ConvTy;
9417
9418 // As an extension, we allow cast to/from void* to function pointer.
9419 assert(lhptee->isFunctionType());
9420 return AssignConvertType::FunctionVoidPointer;
9421 }
9422
9423 if (!S.Diags.isIgnored(
9424 DiagID: diag::warn_typecheck_convert_incompatible_function_pointer_strict,
9425 Loc) &&
9426 RHSType->isFunctionPointerType() && LHSType->isFunctionPointerType() &&
9427 !S.TryFunctionConversion(FromType: RHSType, ToType: LHSType, ResultTy&: RHSType))
9428 return AssignConvertType::IncompatibleFunctionPointerStrict;
9429
9430 // C99 6.5.16.1p1 (constraint 3): both operands are pointers to qualified or
9431 // unqualified versions of compatible types, ...
9432 QualType ltrans = QualType(lhptee, 0), rtrans = QualType(rhptee, 0);
9433
9434 if (ltrans->isOverflowBehaviorType() || rtrans->isOverflowBehaviorType()) {
9435 if (!S.Context.hasSameType(T1: ltrans, T2: rtrans)) {
9436 QualType LUnderlying =
9437 ltrans->isOverflowBehaviorType()
9438 ? ltrans->castAs<OverflowBehaviorType>()->getUnderlyingType()
9439 : ltrans;
9440 QualType RUnderlying =
9441 rtrans->isOverflowBehaviorType()
9442 ? rtrans->castAs<OverflowBehaviorType>()->getUnderlyingType()
9443 : rtrans;
9444
9445 if (S.Context.hasSameType(T1: LUnderlying, T2: RUnderlying))
9446 return AssignConvertType::IncompatiblePointerDiscardsOverflowBehavior;
9447
9448 ltrans = LUnderlying;
9449 rtrans = RUnderlying;
9450 }
9451 }
9452
9453 if (!S.Context.typesAreCompatible(T1: ltrans, T2: rtrans)) {
9454 // Check if the pointee types are compatible ignoring the sign.
9455 // We explicitly check for char so that we catch "char" vs
9456 // "unsigned char" on systems where "char" is unsigned.
9457 if (lhptee->isCharType())
9458 ltrans = S.Context.UnsignedCharTy;
9459 else if (lhptee->hasSignedIntegerRepresentation())
9460 ltrans = S.Context.getCorrespondingUnsignedType(T: ltrans);
9461
9462 if (rhptee->isCharType())
9463 rtrans = S.Context.UnsignedCharTy;
9464 else if (rhptee->hasSignedIntegerRepresentation())
9465 rtrans = S.Context.getCorrespondingUnsignedType(T: rtrans);
9466
9467 if (ltrans == rtrans) {
9468 // Types are compatible ignoring the sign. Qualifier incompatibility
9469 // takes priority over sign incompatibility because the sign
9470 // warning can be disabled.
9471 if (!S.IsAssignConvertCompatible(ConvTy))
9472 return ConvTy;
9473
9474 return AssignConvertType::IncompatiblePointerSign;
9475 }
9476
9477 // If we are a multi-level pointer, it's possible that our issue is simply
9478 // one of qualification - e.g. char ** -> const char ** is not allowed. If
9479 // the eventual target type is the same and the pointers have the same
9480 // level of indirection, this must be the issue.
9481 if (isa<PointerType>(Val: lhptee) && isa<PointerType>(Val: rhptee)) {
9482 do {
9483 std::tie(args&: lhptee, args&: lhq) =
9484 cast<PointerType>(Val: lhptee)->getPointeeType().split().asPair();
9485 std::tie(args&: rhptee, args&: rhq) =
9486 cast<PointerType>(Val: rhptee)->getPointeeType().split().asPair();
9487
9488 // Inconsistent address spaces at this point is invalid, even if the
9489 // address spaces would be compatible.
9490 // FIXME: This doesn't catch address space mismatches for pointers of
9491 // different nesting levels, like:
9492 // __local int *** a;
9493 // int ** b = a;
9494 // It's not clear how to actually determine when such pointers are
9495 // invalidly incompatible.
9496 if (lhq.getAddressSpace() != rhq.getAddressSpace())
9497 return AssignConvertType::
9498 IncompatibleNestedPointerAddressSpaceMismatch;
9499
9500 } while (isa<PointerType>(Val: lhptee) && isa<PointerType>(Val: rhptee));
9501
9502 if (lhptee == rhptee)
9503 return AssignConvertType::IncompatibleNestedPointerQualifiers;
9504 }
9505
9506 // General pointer incompatibility takes priority over qualifiers.
9507 if (RHSType->isFunctionPointerType() && LHSType->isFunctionPointerType())
9508 return AssignConvertType::IncompatibleFunctionPointer;
9509 return AssignConvertType::IncompatiblePointer;
9510 }
9511 // Note: in C++, typesAreCompatible(ltrans, rtrans) will have guaranteed
9512 // hasSameType, so we can skip further checks.
9513 const auto *LFT = ltrans->getAs<FunctionType>();
9514 const auto *RFT = rtrans->getAs<FunctionType>();
9515 if (!S.getLangOpts().CPlusPlus && LFT && RFT) {
9516 // The invocation of IsFunctionConversion below will try to transform rtrans
9517 // to obtain an exact match for ltrans. This should not fail because of
9518 // mismatches in result type and parameter types, they were already checked
9519 // by typesAreCompatible above. So we will recreate rtrans (or where
9520 // appropriate ltrans) using the result type and parameter types from ltrans
9521 // (respectively rtrans), but keeping its ExtInfo/ExtProtoInfo.
9522 const auto *LFPT = dyn_cast<FunctionProtoType>(Val: LFT);
9523 const auto *RFPT = dyn_cast<FunctionProtoType>(Val: RFT);
9524 if (LFPT && RFPT) {
9525 rtrans = S.Context.getFunctionType(ResultTy: LFPT->getReturnType(),
9526 Args: LFPT->getParamTypes(),
9527 EPI: RFPT->getExtProtoInfo());
9528 } else if (LFPT) {
9529 FunctionProtoType::ExtProtoInfo EPI;
9530 EPI.ExtInfo = RFT->getExtInfo();
9531 rtrans = S.Context.getFunctionType(ResultTy: LFPT->getReturnType(),
9532 Args: LFPT->getParamTypes(), EPI);
9533 } else if (RFPT) {
9534 // In this case, we want to retain rtrans as a FunctionProtoType, to keep
9535 // all of its ExtProtoInfo. Transform ltrans instead.
9536 FunctionProtoType::ExtProtoInfo EPI;
9537 EPI.ExtInfo = LFT->getExtInfo();
9538 ltrans = S.Context.getFunctionType(ResultTy: RFPT->getReturnType(),
9539 Args: RFPT->getParamTypes(), EPI);
9540 } else {
9541 rtrans = S.Context.getFunctionNoProtoType(ResultTy: LFT->getReturnType(),
9542 Info: RFT->getExtInfo());
9543 }
9544 if (!S.Context.hasSameUnqualifiedType(T1: rtrans, T2: ltrans) &&
9545 !S.IsFunctionConversion(FromType: rtrans, ToType: ltrans))
9546 return AssignConvertType::IncompatibleFunctionPointer;
9547 }
9548 return ConvTy;
9549}
9550
9551/// checkBlockPointerTypesForAssignment - This routine determines whether two
9552/// block pointer types are compatible or whether a block and normal pointer
9553/// are compatible. It is more restrict than comparing two function pointer
9554// types.
9555static AssignConvertType checkBlockPointerTypesForAssignment(Sema &S,
9556 QualType LHSType,
9557 QualType RHSType) {
9558 assert(LHSType.isCanonical() && "LHS not canonicalized!");
9559 assert(RHSType.isCanonical() && "RHS not canonicalized!");
9560
9561 QualType lhptee, rhptee;
9562
9563 // get the "pointed to" type (ignoring qualifiers at the top level)
9564 lhptee = cast<BlockPointerType>(Val&: LHSType)->getPointeeType();
9565 rhptee = cast<BlockPointerType>(Val&: RHSType)->getPointeeType();
9566
9567 // In C++, the types have to match exactly.
9568 if (S.getLangOpts().CPlusPlus)
9569 return AssignConvertType::IncompatibleBlockPointer;
9570
9571 AssignConvertType ConvTy = AssignConvertType::Compatible;
9572
9573 // For blocks we enforce that qualifiers are identical.
9574 Qualifiers LQuals = lhptee.getLocalQualifiers();
9575 Qualifiers RQuals = rhptee.getLocalQualifiers();
9576 if (S.getLangOpts().OpenCL) {
9577 LQuals.removeAddressSpace();
9578 RQuals.removeAddressSpace();
9579 }
9580 if (LQuals != RQuals)
9581 ConvTy = AssignConvertType::CompatiblePointerDiscardsQualifiers;
9582
9583 // FIXME: OpenCL doesn't define the exact compile time semantics for a block
9584 // assignment.
9585 // The current behavior is similar to C++ lambdas. A block might be
9586 // assigned to a variable iff its return type and parameters are compatible
9587 // (C99 6.2.7) with the corresponding return type and parameters of the LHS of
9588 // an assignment. Presumably it should behave in way that a function pointer
9589 // assignment does in C, so for each parameter and return type:
9590 // * CVR and address space of LHS should be a superset of CVR and address
9591 // space of RHS.
9592 // * unqualified types should be compatible.
9593 if (S.getLangOpts().OpenCL) {
9594 if (!S.Context.typesAreBlockPointerCompatible(
9595 S.Context.getQualifiedType(T: LHSType.getUnqualifiedType(), Qs: LQuals),
9596 S.Context.getQualifiedType(T: RHSType.getUnqualifiedType(), Qs: RQuals)))
9597 return AssignConvertType::IncompatibleBlockPointer;
9598 } else if (!S.Context.typesAreBlockPointerCompatible(LHSType, RHSType))
9599 return AssignConvertType::IncompatibleBlockPointer;
9600
9601 return ConvTy;
9602}
9603
9604/// checkObjCPointerTypesForAssignment - Compares two objective-c pointer types
9605/// for assignment compatibility.
9606static AssignConvertType checkObjCPointerTypesForAssignment(Sema &S,
9607 QualType LHSType,
9608 QualType RHSType) {
9609 assert(LHSType.isCanonical() && "LHS was not canonicalized!");
9610 assert(RHSType.isCanonical() && "RHS was not canonicalized!");
9611
9612 if (LHSType->isObjCBuiltinType()) {
9613 // Class is not compatible with ObjC object pointers.
9614 if (LHSType->isObjCClassType() && !RHSType->isObjCBuiltinType() &&
9615 !RHSType->isObjCQualifiedClassType())
9616 return AssignConvertType::IncompatiblePointer;
9617 return AssignConvertType::Compatible;
9618 }
9619 if (RHSType->isObjCBuiltinType()) {
9620 if (RHSType->isObjCClassType() && !LHSType->isObjCBuiltinType() &&
9621 !LHSType->isObjCQualifiedClassType())
9622 return AssignConvertType::IncompatiblePointer;
9623 return AssignConvertType::Compatible;
9624 }
9625 QualType lhptee = LHSType->castAs<ObjCObjectPointerType>()->getPointeeType();
9626 QualType rhptee = RHSType->castAs<ObjCObjectPointerType>()->getPointeeType();
9627
9628 if (!lhptee.isAtLeastAsQualifiedAs(other: rhptee, Ctx: S.getASTContext()) &&
9629 // make an exception for id<P>
9630 !LHSType->isObjCQualifiedIdType())
9631 return AssignConvertType::CompatiblePointerDiscardsQualifiers;
9632
9633 if (S.Context.typesAreCompatible(T1: LHSType, T2: RHSType))
9634 return AssignConvertType::Compatible;
9635 if (LHSType->isObjCQualifiedIdType() || RHSType->isObjCQualifiedIdType())
9636 return AssignConvertType::IncompatibleObjCQualifiedId;
9637 return AssignConvertType::IncompatiblePointer;
9638}
9639
9640AssignConvertType Sema::CheckAssignmentConstraints(SourceLocation Loc,
9641 QualType LHSType,
9642 QualType RHSType) {
9643 // Fake up an opaque expression. We don't actually care about what
9644 // cast operations are required, so if CheckAssignmentConstraints
9645 // adds casts to this they'll be wasted, but fortunately that doesn't
9646 // usually happen on valid code.
9647 OpaqueValueExpr RHSExpr(Loc, RHSType, VK_PRValue);
9648 ExprResult RHSPtr = &RHSExpr;
9649 CastKind K;
9650
9651 return CheckAssignmentConstraints(LHSType, RHS&: RHSPtr, Kind&: K, /*ConvertRHS=*/false);
9652}
9653
9654/// This helper function returns true if QT is a vector type that has element
9655/// type ElementType.
9656static bool isVector(QualType QT, QualType ElementType) {
9657 if (const VectorType *VT = QT->getAs<VectorType>())
9658 return VT->getElementType().getCanonicalType() == ElementType;
9659 return false;
9660}
9661
9662/// CheckAssignmentConstraints (C99 6.5.16) - This routine currently
9663/// has code to accommodate several GCC extensions when type checking
9664/// pointers. Here are some objectionable examples that GCC considers warnings:
9665///
9666/// int a, *pint;
9667/// short *pshort;
9668/// struct foo *pfoo;
9669///
9670/// pint = pshort; // warning: assignment from incompatible pointer type
9671/// a = pint; // warning: assignment makes integer from pointer without a cast
9672/// pint = a; // warning: assignment makes pointer from integer without a cast
9673/// pint = pfoo; // warning: assignment from incompatible pointer type
9674///
9675/// As a result, the code for dealing with pointers is more complex than the
9676/// C99 spec dictates.
9677///
9678/// Sets 'Kind' for any result kind except Incompatible.
9679AssignConvertType Sema::CheckAssignmentConstraints(QualType LHSType,
9680 ExprResult &RHS,
9681 CastKind &Kind,
9682 bool ConvertRHS) {
9683 QualType RHSType = RHS.get()->getType();
9684 QualType OrigLHSType = LHSType;
9685
9686 // Get canonical types. We're not formatting these types, just comparing
9687 // them.
9688 LHSType = Context.getCanonicalType(T: LHSType).getUnqualifiedType();
9689 RHSType = Context.getCanonicalType(T: RHSType).getUnqualifiedType();
9690
9691 // Common case: no conversion required.
9692 if (LHSType == RHSType) {
9693 Kind = CK_NoOp;
9694 return AssignConvertType::Compatible;
9695 }
9696
9697 // If the LHS has an __auto_type, there are no additional type constraints
9698 // to be worried about.
9699 if (const auto *AT = dyn_cast<AutoType>(Val&: LHSType)) {
9700 if (AT->isGNUAutoType()) {
9701 Kind = CK_NoOp;
9702 return AssignConvertType::Compatible;
9703 }
9704 }
9705
9706 auto OBTResult = Context.checkOBTAssignmentCompatibility(LHS: LHSType, RHS: RHSType);
9707 switch (OBTResult) {
9708 case ASTContext::OBTAssignResult::IncompatibleKinds:
9709 Kind = CK_NoOp;
9710 return AssignConvertType::IncompatibleOBTKinds;
9711 case ASTContext::OBTAssignResult::Discards:
9712 Kind = LHSType->isBooleanType() ? CK_IntegralToBoolean : CK_IntegralCast;
9713 return AssignConvertType::CompatibleOBTDiscards;
9714 case ASTContext::OBTAssignResult::Compatible:
9715 case ASTContext::OBTAssignResult::NotApplicable:
9716 break;
9717 }
9718
9719 // Check for incompatible OBT types in pointer pointee types
9720 if (LHSType->isPointerType() && RHSType->isPointerType()) {
9721 QualType LHSPointee = LHSType->getPointeeType();
9722 QualType RHSPointee = RHSType->getPointeeType();
9723 if ((LHSPointee->isOverflowBehaviorType() ||
9724 RHSPointee->isOverflowBehaviorType()) &&
9725 !Context.areCompatibleOverflowBehaviorTypes(LHS: LHSPointee, RHS: RHSPointee)) {
9726 Kind = CK_NoOp;
9727 return AssignConvertType::IncompatibleOBTKinds;
9728 }
9729 }
9730
9731 // If we have an atomic type, try a non-atomic assignment, then just add an
9732 // atomic qualification step.
9733 if (const AtomicType *AtomicTy = dyn_cast<AtomicType>(Val&: LHSType)) {
9734 AssignConvertType Result =
9735 CheckAssignmentConstraints(LHSType: AtomicTy->getValueType(), RHS, Kind);
9736 if (!IsAssignConvertCompatible(ConvTy: Result))
9737 return Result;
9738 if (Kind != CK_NoOp && ConvertRHS)
9739 RHS = ImpCastExprToType(E: RHS.get(), Type: AtomicTy->getValueType(), CK: Kind);
9740 Kind = CK_NonAtomicToAtomic;
9741 return Result;
9742 }
9743
9744 // If the left-hand side is a reference type, then we are in a
9745 // (rare!) case where we've allowed the use of references in C,
9746 // e.g., as a parameter type in a built-in function. In this case,
9747 // just make sure that the type referenced is compatible with the
9748 // right-hand side type. The caller is responsible for adjusting
9749 // LHSType so that the resulting expression does not have reference
9750 // type.
9751 if (const ReferenceType *LHSTypeRef = LHSType->getAs<ReferenceType>()) {
9752 if (Context.typesAreCompatible(T1: LHSTypeRef->getPointeeType(), T2: RHSType)) {
9753 Kind = CK_LValueBitCast;
9754 return AssignConvertType::Compatible;
9755 }
9756 return AssignConvertType::Incompatible;
9757 }
9758
9759 // Allow scalar to ExtVector assignments, assignment to bool, and assignments
9760 // of an ExtVector type to the same ExtVector type.
9761 if (auto *LHSExtType = LHSType->getAs<ExtVectorType>()) {
9762 if (auto *RHSExtType = RHSType->getAs<ExtVectorType>()) {
9763 // Implicit conversions require the same number of elements.
9764 if (LHSExtType->getNumElements() != RHSExtType->getNumElements())
9765 return AssignConvertType::Incompatible;
9766
9767 if (LHSType->isExtVectorBoolType() &&
9768 RHSExtType->getElementType()->isIntegerType()) {
9769 Kind = CK_IntegralToBoolean;
9770 return AssignConvertType::Compatible;
9771 }
9772 // In OpenCL, allow compatible vector types (e.g. half to _Float16)
9773 if (Context.getLangOpts().OpenCL &&
9774 Context.areCompatibleVectorTypes(FirstVec: LHSType, SecondVec: RHSType)) {
9775 Kind = CK_BitCast;
9776 return AssignConvertType::Compatible;
9777 }
9778 return AssignConvertType::Incompatible;
9779 }
9780 if (RHSType->isArithmeticType()) {
9781 // CK_VectorSplat does T -> vector T, so first cast to the element type.
9782 if (ConvertRHS)
9783 RHS = prepareVectorSplat(VectorTy: LHSType, SplattedExpr: RHS.get());
9784 Kind = CK_VectorSplat;
9785 return AssignConvertType::Compatible;
9786 }
9787 }
9788
9789 // Conversions to or from vector type.
9790 if (LHSType->isVectorType() || RHSType->isVectorType()) {
9791 if (LHSType->isVectorType() && RHSType->isVectorType()) {
9792 // Allow assignments of an AltiVec vector type to an equivalent GCC
9793 // vector type and vice versa
9794 if (Context.areCompatibleVectorTypes(FirstVec: LHSType, SecondVec: RHSType)) {
9795 Kind = CK_BitCast;
9796 return AssignConvertType::Compatible;
9797 }
9798
9799 // If we are allowing lax vector conversions, and LHS and RHS are both
9800 // vectors, the total size only needs to be the same. This is a bitcast;
9801 // no bits are changed but the result type is different.
9802 if (isLaxVectorConversion(srcTy: RHSType, destTy: LHSType)) {
9803 // The default for lax vector conversions with Altivec vectors will
9804 // change, so if we are converting between vector types where
9805 // at least one is an Altivec vector, emit a warning.
9806 if (Context.getTargetInfo().getTriple().isPPC() &&
9807 anyAltivecTypes(SrcTy: RHSType, DestTy: LHSType) &&
9808 !Context.areCompatibleVectorTypes(FirstVec: RHSType, SecondVec: LHSType))
9809 Diag(Loc: RHS.get()->getExprLoc(), DiagID: diag::warn_deprecated_lax_vec_conv_all)
9810 << RHSType << LHSType;
9811 Kind = CK_BitCast;
9812 return AssignConvertType::IncompatibleVectors;
9813 }
9814 }
9815
9816 // When the RHS comes from another lax conversion (e.g. binops between
9817 // scalars and vectors) the result is canonicalized as a vector. When the
9818 // LHS is also a vector, the lax is allowed by the condition above. Handle
9819 // the case where LHS is a scalar.
9820 if (LHSType->isScalarType()) {
9821 const VectorType *VecType = RHSType->getAs<VectorType>();
9822 if (VecType && VecType->getNumElements() == 1 &&
9823 isLaxVectorConversion(srcTy: RHSType, destTy: LHSType)) {
9824 if (Context.getTargetInfo().getTriple().isPPC() &&
9825 (VecType->getVectorKind() == VectorKind::AltiVecVector ||
9826 VecType->getVectorKind() == VectorKind::AltiVecBool ||
9827 VecType->getVectorKind() == VectorKind::AltiVecPixel))
9828 Diag(Loc: RHS.get()->getExprLoc(), DiagID: diag::warn_deprecated_lax_vec_conv_all)
9829 << RHSType << LHSType;
9830 ExprResult *VecExpr = &RHS;
9831 *VecExpr = ImpCastExprToType(E: VecExpr->get(), Type: LHSType, CK: CK_BitCast);
9832 Kind = CK_BitCast;
9833 return AssignConvertType::Compatible;
9834 }
9835 }
9836
9837 // Allow assignments between fixed-length and sizeless SVE vectors.
9838 if ((LHSType->isSVESizelessBuiltinType() && RHSType->isVectorType()) ||
9839 (LHSType->isVectorType() && RHSType->isSVESizelessBuiltinType()))
9840 if (ARM().areCompatibleSveTypes(FirstType: LHSType, SecondType: RHSType) ||
9841 ARM().areLaxCompatibleSveTypes(FirstType: LHSType, SecondType: RHSType)) {
9842 Kind = CK_BitCast;
9843 return AssignConvertType::Compatible;
9844 }
9845
9846 // Allow assignments between fixed-length and sizeless RVV vectors.
9847 if ((LHSType->isRVVSizelessBuiltinType() && RHSType->isVectorType()) ||
9848 (LHSType->isVectorType() && RHSType->isRVVSizelessBuiltinType())) {
9849 if (Context.areCompatibleRVVTypes(FirstType: LHSType, SecondType: RHSType) ||
9850 Context.areLaxCompatibleRVVTypes(FirstType: LHSType, SecondType: RHSType)) {
9851 Kind = CK_BitCast;
9852 return AssignConvertType::Compatible;
9853 }
9854 }
9855
9856 return AssignConvertType::Incompatible;
9857 }
9858
9859 // Diagnose attempts to convert between __ibm128, __float128 and long double
9860 // where such conversions currently can't be handled.
9861 if (unsupportedTypeConversion(S: *this, LHSType, RHSType))
9862 return AssignConvertType::Incompatible;
9863
9864 // Disallow assigning a _Complex to a real type in C++ mode since it simply
9865 // discards the imaginary part.
9866 if (getLangOpts().CPlusPlus && RHSType->getAs<ComplexType>() &&
9867 !LHSType->getAs<ComplexType>())
9868 return AssignConvertType::Incompatible;
9869
9870 // Arithmetic conversions.
9871 if (LHSType->isArithmeticType() && RHSType->isArithmeticType() &&
9872 !(getLangOpts().CPlusPlus && LHSType->isEnumeralType())) {
9873 if (ConvertRHS)
9874 Kind = PrepareScalarCast(Src&: RHS, DestTy: LHSType);
9875 return AssignConvertType::Compatible;
9876 }
9877
9878 // Conversions to normal pointers.
9879 if (const PointerType *LHSPointer = dyn_cast<PointerType>(Val&: LHSType)) {
9880 // U* -> T*
9881 if (isa<PointerType>(Val: RHSType)) {
9882 LangAS AddrSpaceL = LHSPointer->getPointeeType().getAddressSpace();
9883 LangAS AddrSpaceR = RHSType->getPointeeType().getAddressSpace();
9884 if (AddrSpaceL != AddrSpaceR)
9885 Kind = CK_AddressSpaceConversion;
9886 else if (Context.hasCvrSimilarType(T1: RHSType, T2: LHSType))
9887 Kind = CK_NoOp;
9888 else
9889 Kind = CK_BitCast;
9890 return checkPointerTypesForAssignment(S&: *this, LHSType, RHSType,
9891 Loc: RHS.get()->getBeginLoc());
9892 }
9893
9894 // int -> T*
9895 if (RHSType->isIntegerType()) {
9896 Kind = CK_IntegralToPointer; // FIXME: null?
9897 return AssignConvertType::IntToPointer;
9898 }
9899
9900 // C pointers are not compatible with ObjC object pointers,
9901 // with two exceptions:
9902 if (isa<ObjCObjectPointerType>(Val: RHSType)) {
9903 // - conversions to void*
9904 if (LHSPointer->getPointeeType()->isVoidType()) {
9905 Kind = CK_BitCast;
9906 return AssignConvertType::Compatible;
9907 }
9908
9909 // - conversions from 'Class' to the redefinition type
9910 if (RHSType->isObjCClassType() &&
9911 Context.hasSameType(T1: LHSType,
9912 T2: Context.getObjCClassRedefinitionType())) {
9913 Kind = CK_BitCast;
9914 return AssignConvertType::Compatible;
9915 }
9916
9917 Kind = CK_BitCast;
9918 return AssignConvertType::IncompatiblePointer;
9919 }
9920
9921 // U^ -> void*
9922 if (RHSType->getAs<BlockPointerType>()) {
9923 if (LHSPointer->getPointeeType()->isVoidType()) {
9924 LangAS AddrSpaceL = LHSPointer->getPointeeType().getAddressSpace();
9925 LangAS AddrSpaceR = RHSType->getAs<BlockPointerType>()
9926 ->getPointeeType()
9927 .getAddressSpace();
9928 Kind =
9929 AddrSpaceL != AddrSpaceR ? CK_AddressSpaceConversion : CK_BitCast;
9930 return AssignConvertType::Compatible;
9931 }
9932 }
9933
9934 return AssignConvertType::Incompatible;
9935 }
9936
9937 // Conversions to block pointers.
9938 if (isa<BlockPointerType>(Val: LHSType)) {
9939 // U^ -> T^
9940 if (RHSType->isBlockPointerType()) {
9941 LangAS AddrSpaceL = LHSType->getAs<BlockPointerType>()
9942 ->getPointeeType()
9943 .getAddressSpace();
9944 LangAS AddrSpaceR = RHSType->getAs<BlockPointerType>()
9945 ->getPointeeType()
9946 .getAddressSpace();
9947 Kind = AddrSpaceL != AddrSpaceR ? CK_AddressSpaceConversion : CK_BitCast;
9948 return checkBlockPointerTypesForAssignment(S&: *this, LHSType, RHSType);
9949 }
9950
9951 // int or null -> T^
9952 if (RHSType->isIntegerType()) {
9953 Kind = CK_IntegralToPointer; // FIXME: null
9954 return AssignConvertType::IntToBlockPointer;
9955 }
9956
9957 // id -> T^
9958 if (getLangOpts().ObjC && RHSType->isObjCIdType()) {
9959 Kind = CK_AnyPointerToBlockPointerCast;
9960 return AssignConvertType::Compatible;
9961 }
9962
9963 // void* -> T^
9964 if (const PointerType *RHSPT = RHSType->getAs<PointerType>())
9965 if (RHSPT->getPointeeType()->isVoidType()) {
9966 Kind = CK_AnyPointerToBlockPointerCast;
9967 return AssignConvertType::Compatible;
9968 }
9969
9970 return AssignConvertType::Incompatible;
9971 }
9972
9973 // Conversions to Objective-C pointers.
9974 if (isa<ObjCObjectPointerType>(Val: LHSType)) {
9975 // A* -> B*
9976 if (RHSType->isObjCObjectPointerType()) {
9977 Kind = CK_BitCast;
9978 AssignConvertType result =
9979 checkObjCPointerTypesForAssignment(S&: *this, LHSType, RHSType);
9980 if (getLangOpts().allowsNonTrivialObjCLifetimeQualifiers() &&
9981 result == AssignConvertType::Compatible &&
9982 !ObjC().CheckObjCARCUnavailableWeakConversion(castType: OrigLHSType, ExprType: RHSType))
9983 result = AssignConvertType::IncompatibleObjCWeakRef;
9984 return result;
9985 }
9986
9987 // int or null -> A*
9988 if (RHSType->isIntegerType()) {
9989 Kind = CK_IntegralToPointer; // FIXME: null
9990 return AssignConvertType::IntToPointer;
9991 }
9992
9993 // In general, C pointers are not compatible with ObjC object pointers,
9994 // with two exceptions:
9995 if (isa<PointerType>(Val: RHSType)) {
9996 Kind = CK_CPointerToObjCPointerCast;
9997
9998 // - conversions from 'void*'
9999 if (RHSType->isVoidPointerType()) {
10000 return AssignConvertType::Compatible;
10001 }
10002
10003 // - conversions to 'Class' from its redefinition type
10004 if (LHSType->isObjCClassType() &&
10005 Context.hasSameType(T1: RHSType,
10006 T2: Context.getObjCClassRedefinitionType())) {
10007 return AssignConvertType::Compatible;
10008 }
10009
10010 return AssignConvertType::IncompatiblePointer;
10011 }
10012
10013 // Only under strict condition T^ is compatible with an Objective-C pointer.
10014 if (RHSType->isBlockPointerType() &&
10015 LHSType->isBlockCompatibleObjCPointerType(ctx&: Context)) {
10016 if (ConvertRHS)
10017 maybeExtendBlockObject(E&: RHS);
10018 Kind = CK_BlockPointerToObjCPointerCast;
10019 return AssignConvertType::Compatible;
10020 }
10021
10022 return AssignConvertType::Incompatible;
10023 }
10024
10025 // Conversion to nullptr_t (C23 only)
10026 if (getLangOpts().C23 && LHSType->isNullPtrType() &&
10027 RHS.get()->isNullPointerConstant(Ctx&: Context,
10028 NPC: Expr::NPC_ValueDependentIsNull)) {
10029 // null -> nullptr_t
10030 Kind = CK_NullToPointer;
10031 return AssignConvertType::Compatible;
10032 }
10033
10034 // Conversions from pointers that are not covered by the above.
10035 if (isa<PointerType>(Val: RHSType)) {
10036 // T* -> _Bool
10037 if (LHSType == Context.BoolTy) {
10038 Kind = CK_PointerToBoolean;
10039 return AssignConvertType::Compatible;
10040 }
10041
10042 // T* -> int
10043 if (LHSType->isIntegerType()) {
10044 Kind = CK_PointerToIntegral;
10045 return AssignConvertType::PointerToInt;
10046 }
10047
10048 return AssignConvertType::Incompatible;
10049 }
10050
10051 // Conversions from Objective-C pointers that are not covered by the above.
10052 if (isa<ObjCObjectPointerType>(Val: RHSType)) {
10053 // T* -> _Bool
10054 if (LHSType == Context.BoolTy) {
10055 Kind = CK_PointerToBoolean;
10056 return AssignConvertType::Compatible;
10057 }
10058
10059 // T* -> int
10060 if (LHSType->isIntegerType()) {
10061 Kind = CK_PointerToIntegral;
10062 return AssignConvertType::PointerToInt;
10063 }
10064
10065 return AssignConvertType::Incompatible;
10066 }
10067
10068 // struct A -> struct B
10069 if (isa<TagType>(Val: LHSType) && isa<TagType>(Val: RHSType)) {
10070 if (Context.typesAreCompatible(T1: LHSType, T2: RHSType)) {
10071 Kind = CK_NoOp;
10072 return AssignConvertType::Compatible;
10073 }
10074 }
10075
10076 if (LHSType->isSamplerT() && RHSType->isIntegerType()) {
10077 Kind = CK_IntToOCLSampler;
10078 return AssignConvertType::Compatible;
10079 }
10080
10081 return AssignConvertType::Incompatible;
10082}
10083
10084/// Constructs a transparent union from an expression that is
10085/// used to initialize the transparent union.
10086static void ConstructTransparentUnion(Sema &S, ASTContext &C,
10087 ExprResult &EResult, QualType UnionType,
10088 FieldDecl *Field) {
10089 // Build an initializer list that designates the appropriate member
10090 // of the transparent union.
10091 Expr *E = EResult.get();
10092 InitListExpr *Initializer = new (C) InitListExpr(
10093 C, SourceLocation(), E, SourceLocation(), /*isExplicit=*/false);
10094 Initializer->setType(UnionType);
10095 Initializer->setInitializedFieldInUnion(Field);
10096
10097 // Build a compound literal constructing a value of the transparent
10098 // union type from this initializer list.
10099 TypeSourceInfo *unionTInfo = C.getTrivialTypeSourceInfo(T: UnionType);
10100 EResult = new (C) CompoundLiteralExpr(SourceLocation(), unionTInfo, UnionType,
10101 VK_PRValue, Initializer, false);
10102}
10103
10104AssignConvertType
10105Sema::CheckTransparentUnionArgumentConstraints(QualType ArgType,
10106 ExprResult &RHS) {
10107 QualType RHSType = RHS.get()->getType();
10108
10109 // If the ArgType is a Union type, we want to handle a potential
10110 // transparent_union GCC extension.
10111 const RecordType *UT = ArgType->getAsUnionType();
10112 if (!UT)
10113 return AssignConvertType::Incompatible;
10114
10115 RecordDecl *UD = UT->getDecl()->getDefinitionOrSelf();
10116 if (!UD->hasAttr<TransparentUnionAttr>())
10117 return AssignConvertType::Incompatible;
10118
10119 // The field to initialize within the transparent union.
10120 FieldDecl *InitField = nullptr;
10121 // It's compatible if the expression matches any of the fields.
10122 for (auto *it : UD->fields()) {
10123 if (it->getType()->isPointerType()) {
10124 // If the transparent union contains a pointer type, we allow:
10125 // 1) void pointer
10126 // 2) null pointer constant
10127 if (RHSType->isPointerType())
10128 if (RHSType->castAs<PointerType>()->getPointeeType()->isVoidType()) {
10129 RHS = ImpCastExprToType(E: RHS.get(), Type: it->getType(), CK: CK_BitCast);
10130 InitField = it;
10131 break;
10132 }
10133
10134 if (RHS.get()->isNullPointerConstant(Ctx&: Context,
10135 NPC: Expr::NPC_ValueDependentIsNull)) {
10136 RHS = ImpCastExprToType(E: RHS.get(), Type: it->getType(),
10137 CK: CK_NullToPointer);
10138 InitField = it;
10139 break;
10140 }
10141 }
10142
10143 CastKind Kind;
10144 if (CheckAssignmentConstraints(LHSType: it->getType(), RHS, Kind) ==
10145 AssignConvertType::Compatible) {
10146 RHS = ImpCastExprToType(E: RHS.get(), Type: it->getType(), CK: Kind);
10147 InitField = it;
10148 break;
10149 }
10150 }
10151
10152 if (!InitField)
10153 return AssignConvertType::Incompatible;
10154
10155 ConstructTransparentUnion(S&: *this, C&: Context, EResult&: RHS, UnionType: ArgType, Field: InitField);
10156 return AssignConvertType::Compatible;
10157}
10158
10159AssignConvertType Sema::CheckSingleAssignmentConstraints(QualType LHSType,
10160 ExprResult &CallerRHS,
10161 bool Diagnose,
10162 bool DiagnoseCFAudited,
10163 bool ConvertRHS) {
10164 // We need to be able to tell the caller whether we diagnosed a problem, if
10165 // they ask us to issue diagnostics.
10166 assert((ConvertRHS || !Diagnose) && "can't indicate whether we diagnosed");
10167
10168 // If ConvertRHS is false, we want to leave the caller's RHS untouched. Sadly,
10169 // we can't avoid *all* modifications at the moment, so we need some somewhere
10170 // to put the updated value.
10171 ExprResult LocalRHS = CallerRHS;
10172 ExprResult &RHS = ConvertRHS ? CallerRHS : LocalRHS;
10173
10174 if (const auto *LHSPtrType = LHSType->getAs<PointerType>()) {
10175 if (const auto *RHSPtrType = RHS.get()->getType()->getAs<PointerType>()) {
10176 if (RHSPtrType->getPointeeType()->hasAttr(AK: attr::NoDeref) &&
10177 !LHSPtrType->getPointeeType()->hasAttr(AK: attr::NoDeref)) {
10178 Diag(Loc: RHS.get()->getExprLoc(),
10179 DiagID: diag::warn_noderef_to_dereferenceable_pointer)
10180 << RHS.get()->getSourceRange();
10181 }
10182 }
10183 }
10184
10185 if (getLangOpts().CPlusPlus) {
10186 if (!LHSType->isRecordType() && !LHSType->isAtomicType()) {
10187 // C++ 5.17p3: If the left operand is not of class type, the
10188 // expression is implicitly converted (C++ 4) to the
10189 // cv-unqualified type of the left operand.
10190 QualType RHSType = RHS.get()->getType();
10191 if (Diagnose) {
10192 RHS = PerformImplicitConversion(From: RHS.get(), ToType: LHSType.getUnqualifiedType(),
10193 Action: AssignmentAction::Assigning);
10194 } else {
10195 ImplicitConversionSequence ICS =
10196 TryImplicitConversion(From: RHS.get(), ToType: LHSType.getUnqualifiedType(),
10197 /*SuppressUserConversions=*/false,
10198 AllowExplicit: AllowedExplicit::None,
10199 /*InOverloadResolution=*/false,
10200 /*CStyle=*/false,
10201 /*AllowObjCWritebackConversion=*/false);
10202 if (ICS.isFailure())
10203 return AssignConvertType::Incompatible;
10204 RHS = PerformImplicitConversion(From: RHS.get(), ToType: LHSType.getUnqualifiedType(),
10205 ICS, Action: AssignmentAction::Assigning);
10206 }
10207 if (RHS.isInvalid())
10208 return AssignConvertType::Incompatible;
10209 AssignConvertType result = AssignConvertType::Compatible;
10210 if (getLangOpts().allowsNonTrivialObjCLifetimeQualifiers() &&
10211 !ObjC().CheckObjCARCUnavailableWeakConversion(castType: LHSType, ExprType: RHSType))
10212 result = AssignConvertType::IncompatibleObjCWeakRef;
10213
10214 // Check if OBT is being discarded during assignment
10215 // The RHS may have propagated OBT, but if LHS doesn't have it, warn
10216 if (RHSType->isOverflowBehaviorType() &&
10217 !LHSType->isOverflowBehaviorType()) {
10218 result = AssignConvertType::CompatibleOBTDiscards;
10219 }
10220
10221 return result;
10222 }
10223
10224 // FIXME: Currently, we fall through and treat C++ classes like C
10225 // structures.
10226 // FIXME: We also fall through for atomics; not sure what should
10227 // happen there, though.
10228 } else if (RHS.get()->getType() == Context.OverloadTy) {
10229 // As a set of extensions to C, we support overloading on functions. These
10230 // functions need to be resolved here.
10231 DeclAccessPair DAP;
10232 if (FunctionDecl *FD = ResolveAddressOfOverloadedFunction(
10233 AddressOfExpr: RHS.get(), TargetType: LHSType, /*Complain=*/false, Found&: DAP))
10234 RHS = FixOverloadedFunctionReference(E: RHS.get(), FoundDecl: DAP, Fn: FD);
10235 else
10236 return AssignConvertType::Incompatible;
10237 }
10238
10239 // For HLSL records, insert derived-to-base conversion if needed.
10240 if (getLangOpts().HLSL && LHSType->isRecordType()) {
10241 QualType RHSType = RHS.get()->getType();
10242 if (!Context.hasSameUnqualifiedType(T1: RHSType, T2: LHSType)) {
10243 CXXBasePaths Paths;
10244 if (IsDerivedFrom(Loc: RHS.get()->getBeginLoc(), Derived: RHSType, Base: LHSType, Paths)) {
10245 CXXCastPath CastPath;
10246 BuildBasePathArray(Paths, BasePath&: CastPath);
10247 RHS = ImpCastExprToType(E: RHS.get(), Type: LHSType, CK: CK_DerivedToBase, VK: VK_LValue,
10248 BasePath: &CastPath);
10249 }
10250 }
10251 }
10252
10253 // This check seems unnatural, however it is necessary to ensure the proper
10254 // conversion of functions/arrays. If the conversion were done for all
10255 // DeclExpr's (created by ActOnIdExpression), it would mess up the unary
10256 // expressions that suppress this implicit conversion (&, sizeof). This needs
10257 // to happen before we check for null pointer conversions because C does not
10258 // undergo the same implicit conversions as C++ does above (by the calls to
10259 // TryImplicitConversion() and PerformImplicitConversion()) which insert the
10260 // lvalue to rvalue cast before checking for null pointer constraints. This
10261 // addresses code like: nullptr_t val; int *ptr; ptr = val;
10262 //
10263 // Suppress this for references: C++ 8.5.3p5.
10264 if (!LHSType->isReferenceType()) {
10265 // FIXME: We potentially allocate here even if ConvertRHS is false.
10266 RHS = DefaultFunctionArrayLvalueConversion(E: RHS.get(), Diagnose);
10267 if (RHS.isInvalid())
10268 return AssignConvertType::Incompatible;
10269 }
10270
10271 // The constraints are expressed in terms of the atomic, qualified, or
10272 // unqualified type of the LHS.
10273 QualType LHSTypeAfterConversion = LHSType.getAtomicUnqualifiedType();
10274
10275 // C99 6.5.16.1p1: the left operand is a pointer and the right is
10276 // a null pointer constant <C23>or its type is nullptr_t;</C23>.
10277 if ((LHSTypeAfterConversion->isPointerType() ||
10278 LHSTypeAfterConversion->isObjCObjectPointerType() ||
10279 LHSTypeAfterConversion->isBlockPointerType()) &&
10280 ((getLangOpts().C23 && RHS.get()->getType()->isNullPtrType()) ||
10281 RHS.get()->isNullPointerConstant(Ctx&: Context,
10282 NPC: Expr::NPC_ValueDependentIsNull))) {
10283 AssignConvertType Ret = AssignConvertType::Compatible;
10284 if (Diagnose || ConvertRHS) {
10285 CastKind Kind;
10286 CXXCastPath Path;
10287 CheckPointerConversion(From: RHS.get(), ToType: LHSType, Kind, BasePath&: Path,
10288 /*IgnoreBaseAccess=*/false, Diagnose);
10289
10290 // If there is a conversion of some kind, check to see what kind of
10291 // pointer conversion happened so we can diagnose a C++ compatibility
10292 // diagnostic if the conversion is invalid. This only matters if the RHS
10293 // is some kind of void pointer. We have a carve-out when the RHS is from
10294 // a macro expansion because the use of a macro may indicate different
10295 // code between C and C++. Consider: char *s = NULL; where NULL is
10296 // defined as (void *)0 in C (which would be invalid in C++), but 0 in
10297 // C++, which is valid in C++.
10298 if (Kind != CK_NoOp && !getLangOpts().CPlusPlus &&
10299 !RHS.get()->getBeginLoc().isMacroID()) {
10300 QualType CanRHS =
10301 RHS.get()->getType().getCanonicalType().getUnqualifiedType();
10302 QualType CanLHS = LHSType.getCanonicalType().getUnqualifiedType();
10303 if (CanRHS->isVoidPointerType() && CanLHS->isPointerType()) {
10304 Ret = checkPointerTypesForAssignment(S&: *this, LHSType: CanLHS, RHSType: CanRHS,
10305 Loc: RHS.get()->getExprLoc());
10306 // Anything that's not considered perfectly compatible would be
10307 // incompatible in C++.
10308 if (Ret != AssignConvertType::Compatible)
10309 Ret = AssignConvertType::CompatibleVoidPtrToNonVoidPtr;
10310 }
10311 }
10312
10313 if (ConvertRHS)
10314 RHS = ImpCastExprToType(E: RHS.get(), Type: LHSType, CK: Kind, VK: VK_PRValue, BasePath: &Path);
10315 }
10316 return Ret;
10317 }
10318 // C23 6.5.16.1p1: the left operand has type atomic, qualified, or
10319 // unqualified bool, and the right operand is a pointer or its type is
10320 // nullptr_t.
10321 if (getLangOpts().C23 && LHSType->isBooleanType() &&
10322 RHS.get()->getType()->isNullPtrType()) {
10323 // NB: T* -> _Bool is handled in CheckAssignmentConstraints, this only
10324 // only handles nullptr -> _Bool due to needing an extra conversion
10325 // step.
10326 // We model this by converting from nullptr -> void * and then let the
10327 // conversion from void * -> _Bool happen naturally.
10328 if (Diagnose || ConvertRHS) {
10329 CastKind Kind;
10330 CXXCastPath Path;
10331 CheckPointerConversion(From: RHS.get(), ToType: Context.VoidPtrTy, Kind, BasePath&: Path,
10332 /*IgnoreBaseAccess=*/false, Diagnose);
10333 if (ConvertRHS)
10334 RHS = ImpCastExprToType(E: RHS.get(), Type: Context.VoidPtrTy, CK: Kind, VK: VK_PRValue,
10335 BasePath: &Path);
10336 }
10337 }
10338
10339 // OpenCL queue_t type assignment.
10340 if (LHSType->isQueueT() && RHS.get()->isNullPointerConstant(
10341 Ctx&: Context, NPC: Expr::NPC_ValueDependentIsNull)) {
10342 RHS = ImpCastExprToType(E: RHS.get(), Type: LHSType, CK: CK_NullToPointer);
10343 return AssignConvertType::Compatible;
10344 }
10345
10346 CastKind Kind;
10347 AssignConvertType result =
10348 CheckAssignmentConstraints(LHSType, RHS, Kind, ConvertRHS);
10349
10350 // If assigning a void * created by an allocation function call to some other
10351 // type, check that the allocated size is sufficient for that type.
10352 if (result != AssignConvertType::Incompatible &&
10353 RHS.get()->getType()->isVoidPointerType())
10354 CheckSufficientAllocSize(S&: *this, DestType: LHSType, E: RHS.get());
10355
10356 // C99 6.5.16.1p2: The value of the right operand is converted to the
10357 // type of the assignment expression.
10358 // CheckAssignmentConstraints allows the left-hand side to be a reference,
10359 // so that we can use references in built-in functions even in C.
10360 // The getNonReferenceType() call makes sure that the resulting expression
10361 // does not have reference type.
10362 if (result != AssignConvertType::Incompatible &&
10363 RHS.get()->getType() != LHSType) {
10364 QualType Ty = LHSType.getNonLValueExprType(Context);
10365 Expr *E = RHS.get();
10366
10367 // Check for various Objective-C errors. If we are not reporting
10368 // diagnostics and just checking for errors, e.g., during overload
10369 // resolution, return Incompatible to indicate the failure.
10370 if (getLangOpts().allowsNonTrivialObjCLifetimeQualifiers() &&
10371 ObjC().CheckObjCConversion(castRange: SourceRange(), castType: Ty, op&: E,
10372 CCK: CheckedConversionKind::Implicit, Diagnose,
10373 DiagnoseCFAudited) != SemaObjC::ACR_okay) {
10374 if (!Diagnose)
10375 return AssignConvertType::Incompatible;
10376 }
10377 if (getLangOpts().ObjC &&
10378 (ObjC().CheckObjCBridgeRelatedConversions(Loc: E->getBeginLoc(), DestType: LHSType,
10379 SrcType: E->getType(), SrcExpr&: E, Diagnose) ||
10380 ObjC().CheckConversionToObjCLiteral(DstType: LHSType, SrcExpr&: E, Diagnose))) {
10381 if (!Diagnose)
10382 return AssignConvertType::Incompatible;
10383 // Replace the expression with a corrected version and continue so we
10384 // can find further errors.
10385 RHS = E;
10386 return AssignConvertType::Compatible;
10387 }
10388
10389 if (ConvertRHS)
10390 RHS = ImpCastExprToType(E, Type: Ty, CK: Kind);
10391 }
10392
10393 return result;
10394}
10395
10396namespace {
10397/// The original operand to an operator, prior to the application of the usual
10398/// arithmetic conversions and converting the arguments of a builtin operator
10399/// candidate.
10400struct OriginalOperand {
10401 explicit OriginalOperand(Expr *Op) : Orig(Op), Conversion(nullptr) {
10402 if (auto *MTE = dyn_cast<MaterializeTemporaryExpr>(Val: Op))
10403 Op = MTE->getSubExpr();
10404 if (auto *BTE = dyn_cast<CXXBindTemporaryExpr>(Val: Op))
10405 Op = BTE->getSubExpr();
10406 if (auto *ICE = dyn_cast<ImplicitCastExpr>(Val: Op)) {
10407 Orig = ICE->getSubExprAsWritten();
10408 Conversion = ICE->getConversionFunction();
10409 }
10410 }
10411
10412 QualType getType() const { return Orig->getType(); }
10413
10414 Expr *Orig;
10415 NamedDecl *Conversion;
10416};
10417}
10418
10419QualType Sema::InvalidOperands(SourceLocation Loc, ExprResult &LHS,
10420 ExprResult &RHS) {
10421 OriginalOperand OrigLHS(LHS.get()), OrigRHS(RHS.get());
10422
10423 Diag(Loc, DiagID: diag::err_typecheck_invalid_operands)
10424 << OrigLHS.getType() << OrigRHS.getType()
10425 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
10426
10427 // If a user-defined conversion was applied to either of the operands prior
10428 // to applying the built-in operator rules, tell the user about it.
10429 if (OrigLHS.Conversion) {
10430 Diag(Loc: OrigLHS.Conversion->getLocation(),
10431 DiagID: diag::note_typecheck_invalid_operands_converted)
10432 << 0 << LHS.get()->getType();
10433 }
10434 if (OrigRHS.Conversion) {
10435 Diag(Loc: OrigRHS.Conversion->getLocation(),
10436 DiagID: diag::note_typecheck_invalid_operands_converted)
10437 << 1 << RHS.get()->getType();
10438 }
10439
10440 return QualType();
10441}
10442
10443QualType Sema::InvalidLogicalVectorOperands(SourceLocation Loc, ExprResult &LHS,
10444 ExprResult &RHS) {
10445 QualType LHSType = LHS.get()->IgnoreImpCasts()->getType();
10446 QualType RHSType = RHS.get()->IgnoreImpCasts()->getType();
10447
10448 bool LHSNatVec = LHSType->isVectorType();
10449 bool RHSNatVec = RHSType->isVectorType();
10450
10451 if (!(LHSNatVec && RHSNatVec)) {
10452 Expr *Vector = LHSNatVec ? LHS.get() : RHS.get();
10453 Expr *NonVector = !LHSNatVec ? LHS.get() : RHS.get();
10454 Diag(Loc, DiagID: diag::err_typecheck_logical_vector_expr_gnu_cpp_restrict)
10455 << 0 << Vector->getType() << NonVector->IgnoreImpCasts()->getType()
10456 << Vector->getSourceRange();
10457 return QualType();
10458 }
10459
10460 Diag(Loc, DiagID: diag::err_typecheck_logical_vector_expr_gnu_cpp_restrict)
10461 << 1 << LHSType << RHSType << LHS.get()->getSourceRange()
10462 << RHS.get()->getSourceRange();
10463
10464 return QualType();
10465}
10466
10467/// Try to convert a value of non-vector type to a vector type by converting
10468/// the type to the element type of the vector and then performing a splat.
10469/// If the language is OpenCL, we only use conversions that promote scalar
10470/// rank; for C, Obj-C, and C++ we allow any real scalar conversion except
10471/// for float->int.
10472///
10473/// OpenCL V2.0 6.2.6.p2:
10474/// An error shall occur if any scalar operand type has greater rank
10475/// than the type of the vector element.
10476///
10477/// \param scalar - if non-null, actually perform the conversions
10478/// \return true if the operation fails (but without diagnosing the failure)
10479static bool tryVectorConvertAndSplat(Sema &S, ExprResult *scalar,
10480 QualType scalarTy,
10481 QualType vectorEltTy,
10482 QualType vectorTy,
10483 unsigned &DiagID) {
10484 // The conversion to apply to the scalar before splatting it,
10485 // if necessary.
10486 CastKind scalarCast = CK_NoOp;
10487
10488 if (vectorEltTy->isBooleanType() && scalarTy->isIntegralType(Ctx: S.Context)) {
10489 scalarCast = CK_IntegralToBoolean;
10490 } else if (vectorEltTy->isIntegralType(Ctx: S.Context)) {
10491 if (S.getLangOpts().OpenCL && (scalarTy->isRealFloatingType() ||
10492 (scalarTy->isIntegerType() &&
10493 S.Context.getIntegerTypeOrder(LHS: vectorEltTy, RHS: scalarTy) < 0))) {
10494 DiagID = diag::err_opencl_scalar_type_rank_greater_than_vector_type;
10495 return true;
10496 }
10497 if (!scalarTy->isIntegralType(Ctx: S.Context))
10498 return true;
10499 scalarCast = CK_IntegralCast;
10500 } else if (vectorEltTy->isRealFloatingType()) {
10501 if (scalarTy->isRealFloatingType()) {
10502 if (S.getLangOpts().OpenCL &&
10503 S.Context.getFloatingTypeOrder(LHS: vectorEltTy, RHS: scalarTy) < 0) {
10504 DiagID = diag::err_opencl_scalar_type_rank_greater_than_vector_type;
10505 return true;
10506 }
10507 scalarCast = CK_FloatingCast;
10508 }
10509 else if (scalarTy->isIntegralType(Ctx: S.Context))
10510 scalarCast = CK_IntegralToFloating;
10511 else
10512 return true;
10513 } else {
10514 return true;
10515 }
10516
10517 // Adjust scalar if desired.
10518 if (scalar) {
10519 if (scalarCast != CK_NoOp)
10520 *scalar = S.ImpCastExprToType(E: scalar->get(), Type: vectorEltTy, CK: scalarCast);
10521 *scalar = S.ImpCastExprToType(E: scalar->get(), Type: vectorTy, CK: CK_VectorSplat);
10522 }
10523 return false;
10524}
10525
10526/// Convert vector E to a vector with the same number of elements but different
10527/// element type.
10528static ExprResult convertVector(Expr *E, QualType ElementType, Sema &S) {
10529 const auto *VecTy = E->getType()->getAs<VectorType>();
10530 assert(VecTy && "Expression E must be a vector");
10531 QualType NewVecTy =
10532 VecTy->isExtVectorType()
10533 ? S.Context.getExtVectorType(VectorType: ElementType, NumElts: VecTy->getNumElements())
10534 : S.Context.getVectorType(VectorType: ElementType, NumElts: VecTy->getNumElements(),
10535 VecKind: VecTy->getVectorKind());
10536
10537 // Look through the implicit cast. Return the subexpression if its type is
10538 // NewVecTy.
10539 if (auto *ICE = dyn_cast<ImplicitCastExpr>(Val: E))
10540 if (ICE->getSubExpr()->getType() == NewVecTy)
10541 return ICE->getSubExpr();
10542
10543 auto Cast = ElementType->isIntegerType() ? CK_IntegralCast : CK_FloatingCast;
10544 return S.ImpCastExprToType(E, Type: NewVecTy, CK: Cast);
10545}
10546
10547/// Test if a (constant) integer Int can be casted to another integer type
10548/// IntTy without losing precision.
10549static bool canConvertIntToOtherIntTy(Sema &S, ExprResult *Int,
10550 QualType OtherIntTy) {
10551 Expr *E = Int->get();
10552 if (E->containsErrors() || E->isInstantiationDependent())
10553 return false;
10554
10555 QualType IntTy = Int->get()->getType().getUnqualifiedType();
10556
10557 // Reject cases where the value of the Int is unknown as that would
10558 // possibly cause truncation, but accept cases where the scalar can be
10559 // demoted without loss of precision.
10560 Expr::EvalResult EVResult;
10561 bool CstInt = Int->get()->EvaluateAsInt(Result&: EVResult, Ctx: S.Context);
10562 int Order = S.Context.getIntegerTypeOrder(LHS: OtherIntTy, RHS: IntTy);
10563 bool IntSigned = IntTy->hasSignedIntegerRepresentation();
10564 bool OtherIntSigned = OtherIntTy->hasSignedIntegerRepresentation();
10565
10566 if (CstInt) {
10567 // If the scalar is constant and is of a higher order and has more active
10568 // bits that the vector element type, reject it.
10569 llvm::APSInt Result = EVResult.Val.getInt();
10570 unsigned NumBits = IntSigned
10571 ? (Result.isNegative() ? Result.getSignificantBits()
10572 : Result.getActiveBits())
10573 : Result.getActiveBits();
10574 if (Order < 0 && S.Context.getIntWidth(T: OtherIntTy) < NumBits)
10575 return true;
10576
10577 // If the signedness of the scalar type and the vector element type
10578 // differs and the number of bits is greater than that of the vector
10579 // element reject it.
10580 return (IntSigned != OtherIntSigned &&
10581 NumBits > S.Context.getIntWidth(T: OtherIntTy));
10582 }
10583
10584 // Reject cases where the value of the scalar is not constant and it's
10585 // order is greater than that of the vector element type.
10586 return (Order < 0);
10587}
10588
10589/// Test if a (constant) integer Int can be casted to floating point type
10590/// FloatTy without losing precision.
10591static bool canConvertIntTyToFloatTy(Sema &S, ExprResult *Int,
10592 QualType FloatTy) {
10593 if (Int->get()->containsErrors())
10594 return false;
10595
10596 QualType IntTy = Int->get()->getType().getUnqualifiedType();
10597
10598 // Determine if the integer constant can be expressed as a floating point
10599 // number of the appropriate type.
10600 Expr::EvalResult EVResult;
10601 bool CstInt = Int->get()->EvaluateAsInt(Result&: EVResult, Ctx: S.Context);
10602
10603 uint64_t Bits = 0;
10604 if (CstInt) {
10605 // Reject constants that would be truncated if they were converted to
10606 // the floating point type. Test by simple to/from conversion.
10607 // FIXME: Ideally the conversion to an APFloat and from an APFloat
10608 // could be avoided if there was a convertFromAPInt method
10609 // which could signal back if implicit truncation occurred.
10610 llvm::APSInt Result = EVResult.Val.getInt();
10611 llvm::APFloat Float(S.Context.getFloatTypeSemantics(T: FloatTy));
10612 Float.convertFromAPInt(Input: Result, IsSigned: IntTy->hasSignedIntegerRepresentation(),
10613 RM: llvm::APFloat::rmTowardZero);
10614 llvm::APSInt ConvertBack(S.Context.getIntWidth(T: IntTy),
10615 !IntTy->hasSignedIntegerRepresentation());
10616 bool Ignored = false;
10617 Float.convertToInteger(Result&: ConvertBack, RM: llvm::APFloat::rmNearestTiesToEven,
10618 IsExact: &Ignored);
10619 if (Result != ConvertBack)
10620 return true;
10621 } else {
10622 // Reject types that cannot be fully encoded into the mantissa of
10623 // the float.
10624 Bits = S.Context.getTypeSize(T: IntTy);
10625 unsigned FloatPrec = llvm::APFloat::semanticsPrecision(
10626 S.Context.getFloatTypeSemantics(T: FloatTy));
10627 if (Bits > FloatPrec)
10628 return true;
10629 }
10630
10631 return false;
10632}
10633
10634/// Attempt to convert and splat Scalar into a vector whose types matches
10635/// Vector following GCC conversion rules. The rule is that implicit
10636/// conversion can occur when Scalar can be casted to match Vector's element
10637/// type without causing truncation of Scalar.
10638static bool tryGCCVectorConvertAndSplat(Sema &S, ExprResult *Scalar,
10639 ExprResult *Vector) {
10640 QualType ScalarTy = Scalar->get()->getType().getUnqualifiedType();
10641 QualType VectorTy = Vector->get()->getType().getUnqualifiedType();
10642 QualType VectorEltTy;
10643
10644 if (const auto *VT = VectorTy->getAs<VectorType>()) {
10645 assert(!isa<ExtVectorType>(VT) &&
10646 "ExtVectorTypes should not be handled here!");
10647 VectorEltTy = VT->getElementType();
10648 } else if (VectorTy->isSveVLSBuiltinType()) {
10649 VectorEltTy =
10650 VectorTy->castAs<BuiltinType>()->getSveEltType(Ctx: S.getASTContext());
10651 } else {
10652 llvm_unreachable("Only Fixed-Length and SVE Vector types are handled here");
10653 }
10654
10655 // Reject cases where the vector element type or the scalar element type are
10656 // not integral or floating point types.
10657 if (!VectorEltTy->isArithmeticType() || !ScalarTy->isArithmeticType())
10658 return true;
10659
10660 // The conversion to apply to the scalar before splatting it,
10661 // if necessary.
10662 CastKind ScalarCast = CK_NoOp;
10663
10664 // Accept cases where the vector elements are integers and the scalar is
10665 // an integer.
10666 // FIXME: Notionally if the scalar was a floating point value with a precise
10667 // integral representation, we could cast it to an appropriate integer
10668 // type and then perform the rest of the checks here. GCC will perform
10669 // this conversion in some cases as determined by the input language.
10670 // We should accept it on a language independent basis.
10671 if (VectorEltTy->isIntegralType(Ctx: S.Context) &&
10672 ScalarTy->isIntegralType(Ctx: S.Context) &&
10673 S.Context.getIntegerTypeOrder(LHS: VectorEltTy, RHS: ScalarTy)) {
10674
10675 if (canConvertIntToOtherIntTy(S, Int: Scalar, OtherIntTy: VectorEltTy))
10676 return true;
10677
10678 ScalarCast = CK_IntegralCast;
10679 } else if (VectorEltTy->isIntegralType(Ctx: S.Context) &&
10680 ScalarTy->isRealFloatingType()) {
10681 if (S.Context.getTypeSize(T: VectorEltTy) == S.Context.getTypeSize(T: ScalarTy))
10682 ScalarCast = CK_FloatingToIntegral;
10683 else
10684 return true;
10685 } else if (VectorEltTy->isRealFloatingType()) {
10686 if (ScalarTy->isRealFloatingType()) {
10687
10688 // Reject cases where the scalar type is not a constant and has a higher
10689 // Order than the vector element type.
10690 llvm::APFloat Result(0.0);
10691
10692 // Determine whether this is a constant scalar. In the event that the
10693 // value is dependent (and thus cannot be evaluated by the constant
10694 // evaluator), skip the evaluation. This will then diagnose once the
10695 // expression is instantiated.
10696 bool CstScalar = Scalar->get()->isValueDependent() ||
10697 Scalar->get()->EvaluateAsFloat(Result, Ctx: S.Context);
10698 int Order = S.Context.getFloatingTypeOrder(LHS: VectorEltTy, RHS: ScalarTy);
10699 if (!CstScalar && Order < 0)
10700 return true;
10701
10702 // If the scalar cannot be safely casted to the vector element type,
10703 // reject it.
10704 if (CstScalar) {
10705 bool Truncated = false;
10706 Result.convert(ToSemantics: S.Context.getFloatTypeSemantics(T: VectorEltTy),
10707 RM: llvm::APFloat::rmNearestTiesToEven, losesInfo: &Truncated);
10708 if (Truncated)
10709 return true;
10710 }
10711
10712 ScalarCast = CK_FloatingCast;
10713 } else if (ScalarTy->isIntegralType(Ctx: S.Context)) {
10714 if (canConvertIntTyToFloatTy(S, Int: Scalar, FloatTy: VectorEltTy))
10715 return true;
10716
10717 ScalarCast = CK_IntegralToFloating;
10718 } else
10719 return true;
10720 } else if (ScalarTy->isEnumeralType())
10721 return true;
10722
10723 // Adjust scalar if desired.
10724 if (ScalarCast != CK_NoOp)
10725 *Scalar = S.ImpCastExprToType(E: Scalar->get(), Type: VectorEltTy, CK: ScalarCast);
10726 *Scalar = S.ImpCastExprToType(E: Scalar->get(), Type: VectorTy, CK: CK_VectorSplat);
10727 return false;
10728}
10729
10730QualType Sema::CheckVectorOperands(ExprResult &LHS, ExprResult &RHS,
10731 SourceLocation Loc, bool IsCompAssign,
10732 bool AllowBothBool,
10733 bool AllowBoolConversions,
10734 bool AllowBoolOperation,
10735 bool ReportInvalid) {
10736 if (!IsCompAssign) {
10737 LHS = DefaultFunctionArrayLvalueConversion(E: LHS.get());
10738 if (LHS.isInvalid())
10739 return QualType();
10740 }
10741 RHS = DefaultFunctionArrayLvalueConversion(E: RHS.get());
10742 if (RHS.isInvalid())
10743 return QualType();
10744
10745 // For conversion purposes, we ignore any qualifiers.
10746 // For example, "const float" and "float" are equivalent.
10747 QualType LHSType = LHS.get()->getType().getUnqualifiedType();
10748 QualType RHSType = RHS.get()->getType().getUnqualifiedType();
10749
10750 const VectorType *LHSVecType = LHSType->getAs<VectorType>();
10751 const VectorType *RHSVecType = RHSType->getAs<VectorType>();
10752 assert(LHSVecType || RHSVecType);
10753
10754 if (getLangOpts().HLSL)
10755 return HLSL().handleVectorBinOpConversion(LHS, RHS, LHSType, RHSType,
10756 IsCompAssign);
10757
10758 // Any operation with MFloat8 type is only possible with C intrinsics
10759 if ((LHSVecType && LHSVecType->getElementType()->isMFloat8Type()) ||
10760 (RHSVecType && RHSVecType->getElementType()->isMFloat8Type()))
10761 return InvalidOperands(Loc, LHS, RHS);
10762
10763 // AltiVec-style "vector bool op vector bool" combinations are allowed
10764 // for some operators but not others.
10765 if (!AllowBothBool && LHSVecType &&
10766 LHSVecType->getVectorKind() == VectorKind::AltiVecBool && RHSVecType &&
10767 RHSVecType->getVectorKind() == VectorKind::AltiVecBool)
10768 return ReportInvalid ? InvalidOperands(Loc, LHS, RHS) : QualType();
10769
10770 // This operation may not be performed on boolean vectors.
10771 if (!AllowBoolOperation &&
10772 (LHSType->isExtVectorBoolType() || RHSType->isExtVectorBoolType()))
10773 return ReportInvalid ? InvalidOperands(Loc, LHS, RHS) : QualType();
10774
10775 // If the vector types are identical, return.
10776 if (Context.hasSameType(T1: LHSType, T2: RHSType))
10777 return Context.getCommonSugaredType(X: LHSType, Y: RHSType);
10778
10779 // If we have compatible AltiVec and GCC vector types, use the AltiVec type.
10780 if (LHSVecType && RHSVecType &&
10781 Context.areCompatibleVectorTypes(FirstVec: LHSType, SecondVec: RHSType)) {
10782 if (isa<ExtVectorType>(Val: LHSVecType)) {
10783 RHS = ImpCastExprToType(E: RHS.get(), Type: LHSType, CK: CK_BitCast);
10784 return LHSType;
10785 }
10786
10787 if (!IsCompAssign)
10788 LHS = ImpCastExprToType(E: LHS.get(), Type: RHSType, CK: CK_BitCast);
10789 return RHSType;
10790 }
10791
10792 // AllowBoolConversions says that bool and non-bool AltiVec vectors
10793 // can be mixed, with the result being the non-bool type. The non-bool
10794 // operand must have integer element type.
10795 if (AllowBoolConversions && LHSVecType && RHSVecType &&
10796 LHSVecType->getNumElements() == RHSVecType->getNumElements() &&
10797 (Context.getTypeSize(T: LHSVecType->getElementType()) ==
10798 Context.getTypeSize(T: RHSVecType->getElementType()))) {
10799 if (LHSVecType->getVectorKind() == VectorKind::AltiVecVector &&
10800 LHSVecType->getElementType()->isIntegerType() &&
10801 RHSVecType->getVectorKind() == VectorKind::AltiVecBool) {
10802 RHS = ImpCastExprToType(E: RHS.get(), Type: LHSType, CK: CK_BitCast);
10803 return LHSType;
10804 }
10805 if (!IsCompAssign &&
10806 LHSVecType->getVectorKind() == VectorKind::AltiVecBool &&
10807 RHSVecType->getVectorKind() == VectorKind::AltiVecVector &&
10808 RHSVecType->getElementType()->isIntegerType()) {
10809 LHS = ImpCastExprToType(E: LHS.get(), Type: RHSType, CK: CK_BitCast);
10810 return RHSType;
10811 }
10812 }
10813
10814 // Expressions containing fixed-length and sizeless SVE/RVV vectors are
10815 // invalid since the ambiguity can affect the ABI.
10816 auto IsSveRVVConversion = [](QualType FirstType, QualType SecondType,
10817 unsigned &SVEorRVV) {
10818 const VectorType *VecType = SecondType->getAs<VectorType>();
10819 SVEorRVV = 0;
10820 if (FirstType->isSizelessBuiltinType() && VecType) {
10821 if (VecType->getVectorKind() == VectorKind::SveFixedLengthData ||
10822 VecType->getVectorKind() == VectorKind::SveFixedLengthPredicate)
10823 return true;
10824 if (VecType->getVectorKind() == VectorKind::RVVFixedLengthData ||
10825 VecType->getVectorKind() == VectorKind::RVVFixedLengthMask ||
10826 VecType->getVectorKind() == VectorKind::RVVFixedLengthMask_1 ||
10827 VecType->getVectorKind() == VectorKind::RVVFixedLengthMask_2 ||
10828 VecType->getVectorKind() == VectorKind::RVVFixedLengthMask_4) {
10829 SVEorRVV = 1;
10830 return true;
10831 }
10832 }
10833
10834 return false;
10835 };
10836
10837 unsigned SVEorRVV;
10838 if (IsSveRVVConversion(LHSType, RHSType, SVEorRVV) ||
10839 IsSveRVVConversion(RHSType, LHSType, SVEorRVV)) {
10840 Diag(Loc, DiagID: diag::err_typecheck_sve_rvv_ambiguous)
10841 << SVEorRVV << LHSType << RHSType;
10842 return QualType();
10843 }
10844
10845 // Expressions containing GNU and SVE or RVV (fixed or sizeless) vectors are
10846 // invalid since the ambiguity can affect the ABI.
10847 auto IsSveRVVGnuConversion = [](QualType FirstType, QualType SecondType,
10848 unsigned &SVEorRVV) {
10849 const VectorType *FirstVecType = FirstType->getAs<VectorType>();
10850 const VectorType *SecondVecType = SecondType->getAs<VectorType>();
10851
10852 SVEorRVV = 0;
10853 if (FirstVecType && SecondVecType) {
10854 if (FirstVecType->getVectorKind() == VectorKind::Generic) {
10855 if (SecondVecType->getVectorKind() == VectorKind::SveFixedLengthData ||
10856 SecondVecType->getVectorKind() ==
10857 VectorKind::SveFixedLengthPredicate)
10858 return true;
10859 if (SecondVecType->getVectorKind() == VectorKind::RVVFixedLengthData ||
10860 SecondVecType->getVectorKind() == VectorKind::RVVFixedLengthMask ||
10861 SecondVecType->getVectorKind() ==
10862 VectorKind::RVVFixedLengthMask_1 ||
10863 SecondVecType->getVectorKind() ==
10864 VectorKind::RVVFixedLengthMask_2 ||
10865 SecondVecType->getVectorKind() ==
10866 VectorKind::RVVFixedLengthMask_4) {
10867 SVEorRVV = 1;
10868 return true;
10869 }
10870 }
10871 return false;
10872 }
10873
10874 if (SecondVecType &&
10875 SecondVecType->getVectorKind() == VectorKind::Generic) {
10876 if (FirstType->isSVESizelessBuiltinType())
10877 return true;
10878 if (FirstType->isRVVSizelessBuiltinType()) {
10879 SVEorRVV = 1;
10880 return true;
10881 }
10882 }
10883
10884 return false;
10885 };
10886
10887 if (IsSveRVVGnuConversion(LHSType, RHSType, SVEorRVV) ||
10888 IsSveRVVGnuConversion(RHSType, LHSType, SVEorRVV)) {
10889 Diag(Loc, DiagID: diag::err_typecheck_sve_rvv_gnu_ambiguous)
10890 << SVEorRVV << LHSType << RHSType;
10891 return QualType();
10892 }
10893
10894 // If there's a vector type and a scalar, try to convert the scalar to
10895 // the vector element type and splat.
10896 unsigned DiagID = diag::err_typecheck_vector_not_convertable;
10897 if (!RHSVecType) {
10898 if (isa<ExtVectorType>(Val: LHSVecType)) {
10899 if (!tryVectorConvertAndSplat(S&: *this, scalar: &RHS, scalarTy: RHSType,
10900 vectorEltTy: LHSVecType->getElementType(), vectorTy: LHSType,
10901 DiagID))
10902 return LHSType;
10903 } else {
10904 if (!tryGCCVectorConvertAndSplat(S&: *this, Scalar: &RHS, Vector: &LHS))
10905 return LHSType;
10906 }
10907 }
10908 if (!LHSVecType) {
10909 if (isa<ExtVectorType>(Val: RHSVecType)) {
10910 if (!tryVectorConvertAndSplat(S&: *this, scalar: (IsCompAssign ? nullptr : &LHS),
10911 scalarTy: LHSType, vectorEltTy: RHSVecType->getElementType(),
10912 vectorTy: RHSType, DiagID))
10913 return RHSType;
10914 } else {
10915 if (LHS.get()->isLValue() ||
10916 !tryGCCVectorConvertAndSplat(S&: *this, Scalar: &LHS, Vector: &RHS))
10917 return RHSType;
10918 }
10919 }
10920
10921 // FIXME: The code below also handles conversion between vectors and
10922 // non-scalars, we should break this down into fine grained specific checks
10923 // and emit proper diagnostics.
10924 QualType VecType = LHSVecType ? LHSType : RHSType;
10925 const VectorType *VT = LHSVecType ? LHSVecType : RHSVecType;
10926 QualType OtherType = LHSVecType ? RHSType : LHSType;
10927 ExprResult *OtherExpr = LHSVecType ? &RHS : &LHS;
10928 if (isLaxVectorConversion(srcTy: OtherType, destTy: VecType)) {
10929 if (Context.getTargetInfo().getTriple().isPPC() &&
10930 anyAltivecTypes(SrcTy: RHSType, DestTy: LHSType) &&
10931 !Context.areCompatibleVectorTypes(FirstVec: RHSType, SecondVec: LHSType))
10932 Diag(Loc, DiagID: diag::warn_deprecated_lax_vec_conv_all) << RHSType << LHSType;
10933 // If we're allowing lax vector conversions, only the total (data) size
10934 // needs to be the same. For non compound assignment, if one of the types is
10935 // scalar, the result is always the vector type.
10936 if (!IsCompAssign) {
10937 *OtherExpr = ImpCastExprToType(E: OtherExpr->get(), Type: VecType, CK: CK_BitCast);
10938 return VecType;
10939 // In a compound assignment, lhs += rhs, 'lhs' is a lvalue src, forbidding
10940 // any implicit cast. Here, the 'rhs' should be implicit casted to 'lhs'
10941 // type. Note that this is already done by non-compound assignments in
10942 // CheckAssignmentConstraints. If it's a scalar type, only bitcast for
10943 // <1 x T> -> T. The result is also a vector type.
10944 } else if (OtherType->isExtVectorType() || OtherType->isVectorType() ||
10945 (OtherType->isScalarType() && VT->getNumElements() == 1)) {
10946 ExprResult *RHSExpr = &RHS;
10947 *RHSExpr = ImpCastExprToType(E: RHSExpr->get(), Type: LHSType, CK: CK_BitCast);
10948 return VecType;
10949 }
10950 }
10951
10952 // Okay, the expression is invalid.
10953
10954 // If there's a non-vector, non-real operand, diagnose that.
10955 if ((!RHSVecType && !RHSType->isRealType()) ||
10956 (!LHSVecType && !LHSType->isRealType())) {
10957 Diag(Loc, DiagID: diag::err_typecheck_vector_not_convertable_non_scalar)
10958 << LHSType << RHSType
10959 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
10960 return QualType();
10961 }
10962
10963 // OpenCL V1.1 6.2.6.p1:
10964 // If the operands are of more than one vector type, then an error shall
10965 // occur. Implicit conversions between vector types are not permitted, per
10966 // section 6.2.1.
10967 if (getLangOpts().OpenCL &&
10968 RHSVecType && isa<ExtVectorType>(Val: RHSVecType) &&
10969 LHSVecType && isa<ExtVectorType>(Val: LHSVecType)) {
10970 Diag(Loc, DiagID: diag::err_opencl_implicit_vector_conversion) << LHSType
10971 << RHSType;
10972 return QualType();
10973 }
10974
10975
10976 // If there is a vector type that is not a ExtVector and a scalar, we reach
10977 // this point if scalar could not be converted to the vector's element type
10978 // without truncation.
10979 if ((RHSVecType && !isa<ExtVectorType>(Val: RHSVecType)) ||
10980 (LHSVecType && !isa<ExtVectorType>(Val: LHSVecType))) {
10981 QualType Scalar = LHSVecType ? RHSType : LHSType;
10982 QualType Vector = LHSVecType ? LHSType : RHSType;
10983 unsigned ScalarOrVector = LHSVecType && RHSVecType ? 1 : 0;
10984 Diag(Loc,
10985 DiagID: diag::err_typecheck_vector_not_convertable_implict_truncation)
10986 << ScalarOrVector << Scalar << Vector;
10987
10988 return QualType();
10989 }
10990
10991 // Otherwise, use the generic diagnostic.
10992 Diag(Loc, DiagID)
10993 << LHSType << RHSType
10994 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
10995 return QualType();
10996}
10997
10998QualType Sema::CheckSizelessVectorOperands(ExprResult &LHS, ExprResult &RHS,
10999 SourceLocation Loc,
11000 bool IsCompAssign,
11001 ArithConvKind OperationKind) {
11002 if (!IsCompAssign) {
11003 LHS = DefaultFunctionArrayLvalueConversion(E: LHS.get());
11004 if (LHS.isInvalid())
11005 return QualType();
11006 }
11007 RHS = DefaultFunctionArrayLvalueConversion(E: RHS.get());
11008 if (RHS.isInvalid())
11009 return QualType();
11010
11011 QualType LHSType = LHS.get()->getType().getUnqualifiedType();
11012 QualType RHSType = RHS.get()->getType().getUnqualifiedType();
11013
11014 const BuiltinType *LHSBuiltinTy = LHSType->getAs<BuiltinType>();
11015 const BuiltinType *RHSBuiltinTy = RHSType->getAs<BuiltinType>();
11016
11017 unsigned DiagID = diag::err_typecheck_invalid_operands;
11018 if ((OperationKind == ArithConvKind::Arithmetic) &&
11019 ((LHSBuiltinTy && LHSBuiltinTy->isSVEBool()) ||
11020 (RHSBuiltinTy && RHSBuiltinTy->isSVEBool()))) {
11021 Diag(Loc, DiagID) << LHSType << RHSType << LHS.get()->getSourceRange()
11022 << RHS.get()->getSourceRange();
11023 return QualType();
11024 }
11025
11026 if (Context.hasSameType(T1: LHSType, T2: RHSType))
11027 return LHSType;
11028
11029 if (LHSType->isSveVLSBuiltinType() && !RHSType->isSveVLSBuiltinType()) {
11030 if (!tryGCCVectorConvertAndSplat(S&: *this, Scalar: &RHS, Vector: &LHS))
11031 return LHSType;
11032 }
11033 if (RHSType->isSveVLSBuiltinType() && !LHSType->isSveVLSBuiltinType()) {
11034 if (LHS.get()->isLValue() ||
11035 !tryGCCVectorConvertAndSplat(S&: *this, Scalar: &LHS, Vector: &RHS))
11036 return RHSType;
11037 }
11038
11039 if ((!LHSType->isSveVLSBuiltinType() && !LHSType->isRealType()) ||
11040 (!RHSType->isSveVLSBuiltinType() && !RHSType->isRealType())) {
11041 Diag(Loc, DiagID: diag::err_typecheck_vector_not_convertable_non_scalar)
11042 << LHSType << RHSType << LHS.get()->getSourceRange()
11043 << RHS.get()->getSourceRange();
11044 return QualType();
11045 }
11046
11047 if (LHSType->isSveVLSBuiltinType() && RHSType->isSveVLSBuiltinType() &&
11048 Context.getBuiltinVectorTypeInfo(VecTy: LHSBuiltinTy).EC !=
11049 Context.getBuiltinVectorTypeInfo(VecTy: RHSBuiltinTy).EC) {
11050 Diag(Loc, DiagID: diag::err_typecheck_vector_lengths_not_equal)
11051 << LHSType << RHSType << LHS.get()->getSourceRange()
11052 << RHS.get()->getSourceRange();
11053 return QualType();
11054 }
11055
11056 if (LHSType->isSveVLSBuiltinType() || RHSType->isSveVLSBuiltinType()) {
11057 QualType Scalar = LHSType->isSveVLSBuiltinType() ? RHSType : LHSType;
11058 QualType Vector = LHSType->isSveVLSBuiltinType() ? LHSType : RHSType;
11059 bool ScalarOrVector =
11060 LHSType->isSveVLSBuiltinType() && RHSType->isSveVLSBuiltinType();
11061
11062 Diag(Loc, DiagID: diag::err_typecheck_vector_not_convertable_implict_truncation)
11063 << ScalarOrVector << Scalar << Vector;
11064
11065 return QualType();
11066 }
11067
11068 Diag(Loc, DiagID) << LHSType << RHSType << LHS.get()->getSourceRange()
11069 << RHS.get()->getSourceRange();
11070 return QualType();
11071}
11072
11073// checkArithmeticNull - Detect when a NULL constant is used improperly in an
11074// expression. These are mainly cases where the null pointer is used as an
11075// integer instead of a pointer.
11076static void checkArithmeticNull(Sema &S, ExprResult &LHS, ExprResult &RHS,
11077 SourceLocation Loc, bool IsCompare) {
11078 // The canonical way to check for a GNU null is with isNullPointerConstant,
11079 // but we use a bit of a hack here for speed; this is a relatively
11080 // hot path, and isNullPointerConstant is slow.
11081 bool LHSNull = isa<GNUNullExpr>(Val: LHS.get()->IgnoreParenImpCasts());
11082 bool RHSNull = isa<GNUNullExpr>(Val: RHS.get()->IgnoreParenImpCasts());
11083
11084 QualType NonNullType = LHSNull ? RHS.get()->getType() : LHS.get()->getType();
11085
11086 // Avoid analyzing cases where the result will either be invalid (and
11087 // diagnosed as such) or entirely valid and not something to warn about.
11088 if ((!LHSNull && !RHSNull) || NonNullType->isBlockPointerType() ||
11089 NonNullType->isMemberPointerType() || NonNullType->isFunctionType())
11090 return;
11091
11092 // Comparison operations would not make sense with a null pointer no matter
11093 // what the other expression is.
11094 if (!IsCompare) {
11095 S.Diag(Loc, DiagID: diag::warn_null_in_arithmetic_operation)
11096 << (LHSNull ? LHS.get()->getSourceRange() : SourceRange())
11097 << (RHSNull ? RHS.get()->getSourceRange() : SourceRange());
11098 return;
11099 }
11100
11101 // The rest of the operations only make sense with a null pointer
11102 // if the other expression is a pointer.
11103 if (LHSNull == RHSNull || NonNullType->isAnyPointerType() ||
11104 NonNullType->canDecayToPointerType())
11105 return;
11106
11107 S.Diag(Loc, DiagID: diag::warn_null_in_comparison_operation)
11108 << LHSNull /* LHS is NULL */ << NonNullType
11109 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
11110}
11111
11112static void DetectPrecisionLossInComplexDivision(Sema &S, QualType DivisorTy,
11113 SourceLocation OpLoc) {
11114 // If the divisor is real, then this is real/real or complex/real division.
11115 // Either way there can be no precision loss.
11116 auto *CT = DivisorTy->getAs<ComplexType>();
11117 if (!CT)
11118 return;
11119
11120 QualType ElementType = CT->getElementType().getCanonicalType();
11121 bool IsComplexRangePromoted = S.getLangOpts().getComplexRange() ==
11122 LangOptions::ComplexRangeKind::CX_Promoted;
11123 if (!ElementType->isFloatingType() || !IsComplexRangePromoted)
11124 return;
11125
11126 ASTContext &Ctx = S.getASTContext();
11127 QualType HigherElementType = Ctx.GetHigherPrecisionFPType(ElementType);
11128 const llvm::fltSemantics &ElementTypeSemantics =
11129 Ctx.getFloatTypeSemantics(T: ElementType);
11130 const llvm::fltSemantics &HigherElementTypeSemantics =
11131 Ctx.getFloatTypeSemantics(T: HigherElementType);
11132
11133 if ((llvm::APFloat::semanticsMaxExponent(ElementTypeSemantics) * 2 + 1 >
11134 llvm::APFloat::semanticsMaxExponent(HigherElementTypeSemantics)) ||
11135 (HigherElementType == Ctx.LongDoubleTy &&
11136 !Ctx.getTargetInfo().hasLongDoubleType())) {
11137 // Retain the location of the first use of higher precision type.
11138 if (!S.LocationOfExcessPrecisionNotSatisfied.isValid())
11139 S.LocationOfExcessPrecisionNotSatisfied = OpLoc;
11140 for (auto &[Type, Num] : S.ExcessPrecisionNotSatisfied) {
11141 if (Type == HigherElementType) {
11142 Num++;
11143 return;
11144 }
11145 }
11146 S.ExcessPrecisionNotSatisfied.push_back(x: std::make_pair(
11147 x&: HigherElementType, y: S.ExcessPrecisionNotSatisfied.size()));
11148 }
11149}
11150
11151static void DiagnoseDivisionSizeofPointerOrArray(Sema &S, Expr *LHS, Expr *RHS,
11152 SourceLocation Loc) {
11153 const auto *LUE = dyn_cast<UnaryExprOrTypeTraitExpr>(Val: LHS);
11154 const auto *RUE = dyn_cast<UnaryExprOrTypeTraitExpr>(Val: RHS);
11155 if (!LUE || !RUE)
11156 return;
11157 if (LUE->getKind() != UETT_SizeOf || LUE->isArgumentType() ||
11158 RUE->getKind() != UETT_SizeOf)
11159 return;
11160
11161 const Expr *LHSArg = LUE->getArgumentExpr()->IgnoreParens();
11162 QualType LHSTy = LHSArg->getType();
11163 QualType RHSTy;
11164
11165 if (RUE->isArgumentType())
11166 RHSTy = RUE->getArgumentType().getNonReferenceType();
11167 else
11168 RHSTy = RUE->getArgumentExpr()->IgnoreParens()->getType();
11169
11170 if (LHSTy->isPointerType() && !RHSTy->isPointerType()) {
11171 if (!S.Context.hasSameUnqualifiedType(T1: LHSTy->getPointeeType(), T2: RHSTy))
11172 return;
11173
11174 S.Diag(Loc, DiagID: diag::warn_division_sizeof_ptr) << LHS << LHS->getSourceRange();
11175 if (const auto *DRE = dyn_cast<DeclRefExpr>(Val: LHSArg)) {
11176 if (const ValueDecl *LHSArgDecl = DRE->getDecl())
11177 S.Diag(Loc: LHSArgDecl->getLocation(), DiagID: diag::note_pointer_declared_here)
11178 << LHSArgDecl;
11179 }
11180 } else if (const auto *ArrayTy = S.Context.getAsArrayType(T: LHSTy)) {
11181 QualType ArrayElemTy = ArrayTy->getElementType();
11182 if (ArrayElemTy != S.Context.getBaseElementType(VAT: ArrayTy) ||
11183 ArrayElemTy->isDependentType() || RHSTy->isDependentType() ||
11184 RHSTy->isReferenceType() || ArrayElemTy->isCharType() ||
11185 S.Context.getTypeSize(T: ArrayElemTy) == S.Context.getTypeSize(T: RHSTy))
11186 return;
11187 S.Diag(Loc, DiagID: diag::warn_division_sizeof_array)
11188 << LHSArg->getSourceRange() << ArrayElemTy << RHSTy;
11189 if (const auto *DRE = dyn_cast<DeclRefExpr>(Val: LHSArg)) {
11190 if (const ValueDecl *LHSArgDecl = DRE->getDecl())
11191 S.Diag(Loc: LHSArgDecl->getLocation(), DiagID: diag::note_array_declared_here)
11192 << LHSArgDecl;
11193 }
11194
11195 S.Diag(Loc, DiagID: diag::note_precedence_silence) << RHS;
11196 }
11197}
11198
11199static void DiagnoseBadDivideOrRemainderValues(Sema& S, ExprResult &LHS,
11200 ExprResult &RHS,
11201 SourceLocation Loc, bool IsDiv) {
11202 // Check for division/remainder by zero.
11203 Expr::EvalResult RHSValue;
11204 if (!RHS.get()->isValueDependent() &&
11205 RHS.get()->EvaluateAsInt(Result&: RHSValue, Ctx: S.Context) &&
11206 RHSValue.Val.getInt() == 0)
11207 S.DiagRuntimeBehavior(Loc, Statement: RHS.get(),
11208 PD: S.PDiag(DiagID: diag::warn_remainder_division_by_zero)
11209 << IsDiv << RHS.get()->getSourceRange());
11210}
11211
11212static void diagnoseScopedEnums(Sema &S, const SourceLocation Loc,
11213 const ExprResult &LHS, const ExprResult &RHS,
11214 BinaryOperatorKind Opc) {
11215 if (!LHS.isUsable() || !RHS.isUsable())
11216 return;
11217 const Expr *LHSExpr = LHS.get();
11218 const Expr *RHSExpr = RHS.get();
11219 const QualType LHSType = LHSExpr->getType();
11220 const QualType RHSType = RHSExpr->getType();
11221 const bool LHSIsScoped = LHSType->isScopedEnumeralType();
11222 const bool RHSIsScoped = RHSType->isScopedEnumeralType();
11223 if (!LHSIsScoped && !RHSIsScoped)
11224 return;
11225 if (BinaryOperator::isAssignmentOp(Opc) && LHSIsScoped)
11226 return;
11227 if (!LHSIsScoped && !LHSType->isIntegralOrUnscopedEnumerationType())
11228 return;
11229 if (!RHSIsScoped && !RHSType->isIntegralOrUnscopedEnumerationType())
11230 return;
11231 auto DiagnosticHelper = [&S](const Expr *expr, const QualType type) {
11232 SourceLocation BeginLoc = expr->getBeginLoc();
11233 QualType IntType = type->castAs<EnumType>()
11234 ->getDecl()
11235 ->getDefinitionOrSelf()
11236 ->getIntegerType();
11237 std::string InsertionString = "static_cast<" + IntType.getAsString() + ">(";
11238 S.Diag(Loc: BeginLoc, DiagID: diag::note_no_implicit_conversion_for_scoped_enum)
11239 << FixItHint::CreateInsertion(InsertionLoc: BeginLoc, Code: InsertionString)
11240 << FixItHint::CreateInsertion(InsertionLoc: expr->getEndLoc(), Code: ")");
11241 };
11242 if (LHSIsScoped) {
11243 DiagnosticHelper(LHSExpr, LHSType);
11244 }
11245 if (RHSIsScoped) {
11246 DiagnosticHelper(RHSExpr, RHSType);
11247 }
11248}
11249
11250QualType Sema::CheckMultiplyDivideOperands(ExprResult &LHS, ExprResult &RHS,
11251 SourceLocation Loc,
11252 BinaryOperatorKind Opc) {
11253 bool IsCompAssign = Opc == BO_MulAssign || Opc == BO_DivAssign;
11254 bool IsDiv = Opc == BO_Div || Opc == BO_DivAssign;
11255
11256 checkArithmeticNull(S&: *this, LHS, RHS, Loc, /*IsCompare=*/false);
11257
11258 QualType LHSTy = LHS.get()->getType();
11259 QualType RHSTy = RHS.get()->getType();
11260 if (LHSTy->isVectorType() || RHSTy->isVectorType())
11261 return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign,
11262 /*AllowBothBool*/ getLangOpts().AltiVec,
11263 /*AllowBoolConversions*/ false,
11264 /*AllowBooleanOperation*/ AllowBoolOperation: false,
11265 /*ReportInvalid*/ true);
11266 if (LHSTy->isSveVLSBuiltinType() || RHSTy->isSveVLSBuiltinType())
11267 return CheckSizelessVectorOperands(LHS, RHS, Loc, IsCompAssign,
11268 OperationKind: ArithConvKind::Arithmetic);
11269 if (!IsDiv &&
11270 (LHSTy->isConstantMatrixType() || RHSTy->isConstantMatrixType()))
11271 return CheckMatrixMultiplyOperands(LHS, RHS, Loc, IsCompAssign);
11272 // For division, only matrix-by-scalar is supported. Other combinations with
11273 // matrix types are invalid.
11274 if (IsDiv && LHSTy->isConstantMatrixType() && RHSTy->isArithmeticType())
11275 return CheckMatrixElementwiseOperands(LHS, RHS, Loc, IsCompAssign);
11276
11277 QualType compType = UsualArithmeticConversions(
11278 LHS, RHS, Loc,
11279 ACK: IsCompAssign ? ArithConvKind::CompAssign : ArithConvKind::Arithmetic);
11280 if (LHS.isInvalid() || RHS.isInvalid())
11281 return QualType();
11282
11283 if (compType.isNull() || !compType->isArithmeticType()) {
11284 QualType ResultTy = InvalidOperands(Loc, LHS, RHS);
11285 diagnoseScopedEnums(S&: *this, Loc, LHS, RHS, Opc);
11286 return ResultTy;
11287 }
11288 if (IsDiv) {
11289 DetectPrecisionLossInComplexDivision(S&: *this, DivisorTy: RHS.get()->getType(), OpLoc: Loc);
11290 DiagnoseBadDivideOrRemainderValues(S&: *this, LHS, RHS, Loc, IsDiv);
11291 DiagnoseDivisionSizeofPointerOrArray(S&: *this, LHS: LHS.get(), RHS: RHS.get(), Loc);
11292 }
11293 return compType;
11294}
11295
11296QualType Sema::CheckRemainderOperands(
11297 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, bool IsCompAssign) {
11298 checkArithmeticNull(S&: *this, LHS, RHS, Loc, /*IsCompare=*/false);
11299
11300 // Note: This check is here to simplify the double exclusions of
11301 // scalar and vector HLSL checks. No getLangOpts().HLSL
11302 // is needed since all languages exlcude doubles.
11303 if (LHS.get()->getType()->isDoubleType() ||
11304 RHS.get()->getType()->isDoubleType() ||
11305 (LHS.get()->getType()->isVectorType() && LHS.get()
11306 ->getType()
11307 ->getAs<VectorType>()
11308 ->getElementType()
11309 ->isDoubleType()) ||
11310 (RHS.get()->getType()->isVectorType() && RHS.get()
11311 ->getType()
11312 ->getAs<VectorType>()
11313 ->getElementType()
11314 ->isDoubleType()))
11315 return InvalidOperands(Loc, LHS, RHS);
11316
11317 if (LHS.get()->getType()->isVectorType() ||
11318 RHS.get()->getType()->isVectorType()) {
11319 if ((LHS.get()->getType()->hasIntegerRepresentation() &&
11320 RHS.get()->getType()->hasIntegerRepresentation()) ||
11321 (getLangOpts().HLSL &&
11322 (LHS.get()->getType()->hasFloatingRepresentation() ||
11323 RHS.get()->getType()->hasFloatingRepresentation())))
11324 return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign,
11325 /*AllowBothBool*/ getLangOpts().AltiVec,
11326 /*AllowBoolConversions*/ false,
11327 /*AllowBooleanOperation*/ AllowBoolOperation: false,
11328 /*ReportInvalid*/ true);
11329 return InvalidOperands(Loc, LHS, RHS);
11330 }
11331
11332 if (LHS.get()->getType()->isSveVLSBuiltinType() ||
11333 RHS.get()->getType()->isSveVLSBuiltinType()) {
11334 if (LHS.get()->getType()->hasIntegerRepresentation() &&
11335 RHS.get()->getType()->hasIntegerRepresentation())
11336 return CheckSizelessVectorOperands(LHS, RHS, Loc, IsCompAssign,
11337 OperationKind: ArithConvKind::Arithmetic);
11338
11339 return InvalidOperands(Loc, LHS, RHS);
11340 }
11341
11342 QualType compType = UsualArithmeticConversions(
11343 LHS, RHS, Loc,
11344 ACK: IsCompAssign ? ArithConvKind::CompAssign : ArithConvKind::Arithmetic);
11345 if (LHS.isInvalid() || RHS.isInvalid())
11346 return QualType();
11347
11348 if (compType.isNull() ||
11349 (!compType->isIntegerType() &&
11350 !(getLangOpts().HLSL && compType->isFloatingType()))) {
11351 QualType ResultTy = InvalidOperands(Loc, LHS, RHS);
11352 diagnoseScopedEnums(S&: *this, Loc, LHS, RHS,
11353 Opc: IsCompAssign ? BO_RemAssign : BO_Rem);
11354 return ResultTy;
11355 }
11356 DiagnoseBadDivideOrRemainderValues(S&: *this, LHS, RHS, Loc, IsDiv: false /* IsDiv */);
11357 return compType;
11358}
11359
11360/// Diagnose invalid arithmetic on two void pointers.
11361static void diagnoseArithmeticOnTwoVoidPointers(Sema &S, SourceLocation Loc,
11362 Expr *LHSExpr, Expr *RHSExpr) {
11363 S.Diag(Loc, DiagID: S.getLangOpts().CPlusPlus
11364 ? diag::err_typecheck_pointer_arith_void_type
11365 : diag::ext_gnu_void_ptr)
11366 << 1 /* two pointers */ << LHSExpr->getSourceRange()
11367 << RHSExpr->getSourceRange();
11368}
11369
11370/// Diagnose invalid arithmetic on a void pointer.
11371static void diagnoseArithmeticOnVoidPointer(Sema &S, SourceLocation Loc,
11372 Expr *Pointer) {
11373 S.Diag(Loc, DiagID: S.getLangOpts().CPlusPlus
11374 ? diag::err_typecheck_pointer_arith_void_type
11375 : diag::ext_gnu_void_ptr)
11376 << 0 /* one pointer */ << Pointer->getSourceRange();
11377}
11378
11379/// Diagnose invalid arithmetic on a null pointer.
11380///
11381/// If \p IsGNUIdiom is true, the operation is using the 'p = (i8*)nullptr + n'
11382/// idiom, which we recognize as a GNU extension.
11383///
11384static void diagnoseArithmeticOnNullPointer(Sema &S, SourceLocation Loc,
11385 Expr *Pointer, bool IsGNUIdiom) {
11386 if (IsGNUIdiom)
11387 S.Diag(Loc, DiagID: diag::warn_gnu_null_ptr_arith)
11388 << Pointer->getSourceRange();
11389 else
11390 S.Diag(Loc, DiagID: diag::warn_pointer_arith_null_ptr)
11391 << S.getLangOpts().CPlusPlus << Pointer->getSourceRange();
11392}
11393
11394/// Diagnose invalid subraction on a null pointer.
11395///
11396static void diagnoseSubtractionOnNullPointer(Sema &S, SourceLocation Loc,
11397 Expr *Pointer, bool BothNull) {
11398 // Null - null is valid in C++ [expr.add]p7
11399 if (BothNull && S.getLangOpts().CPlusPlus)
11400 return;
11401
11402 // Is this s a macro from a system header?
11403 if (S.Diags.getSuppressSystemWarnings() && S.SourceMgr.isInSystemMacro(loc: Loc))
11404 return;
11405
11406 S.DiagRuntimeBehavior(Loc, Statement: Pointer,
11407 PD: S.PDiag(DiagID: diag::warn_pointer_sub_null_ptr)
11408 << S.getLangOpts().CPlusPlus
11409 << Pointer->getSourceRange());
11410}
11411
11412/// Diagnose invalid arithmetic on two function pointers.
11413static void diagnoseArithmeticOnTwoFunctionPointers(Sema &S, SourceLocation Loc,
11414 Expr *LHS, Expr *RHS) {
11415 assert(LHS->getType()->isAnyPointerType());
11416 assert(RHS->getType()->isAnyPointerType());
11417 S.Diag(Loc, DiagID: S.getLangOpts().CPlusPlus
11418 ? diag::err_typecheck_pointer_arith_function_type
11419 : diag::ext_gnu_ptr_func_arith)
11420 << 1 /* two pointers */ << LHS->getType()->getPointeeType()
11421 // We only show the second type if it differs from the first.
11422 << (unsigned)!S.Context.hasSameUnqualifiedType(T1: LHS->getType(),
11423 T2: RHS->getType())
11424 << RHS->getType()->getPointeeType()
11425 << LHS->getSourceRange() << RHS->getSourceRange();
11426}
11427
11428/// Diagnose invalid arithmetic on a function pointer.
11429static void diagnoseArithmeticOnFunctionPointer(Sema &S, SourceLocation Loc,
11430 Expr *Pointer) {
11431 assert(Pointer->getType()->isAnyPointerType());
11432 S.Diag(Loc, DiagID: S.getLangOpts().CPlusPlus
11433 ? diag::err_typecheck_pointer_arith_function_type
11434 : diag::ext_gnu_ptr_func_arith)
11435 << 0 /* one pointer */ << Pointer->getType()->getPointeeType()
11436 << 0 /* one pointer, so only one type */
11437 << Pointer->getSourceRange();
11438}
11439
11440/// Emit error if Operand is incomplete pointer type
11441///
11442/// \returns True if pointer has incomplete type
11443static bool checkArithmeticIncompletePointerType(Sema &S, SourceLocation Loc,
11444 Expr *Operand) {
11445 QualType ResType = Operand->getType();
11446 if (const AtomicType *ResAtomicType = ResType->getAs<AtomicType>())
11447 ResType = ResAtomicType->getValueType();
11448
11449 assert(ResType->isAnyPointerType());
11450 QualType PointeeTy = ResType->getPointeeType();
11451 return S.RequireCompleteSizedType(
11452 Loc, T: PointeeTy,
11453 DiagID: diag::err_typecheck_arithmetic_incomplete_or_sizeless_type,
11454 Args: Operand->getSourceRange());
11455}
11456
11457/// Check the validity of an arithmetic pointer operand.
11458///
11459/// If the operand has pointer type, this code will check for pointer types
11460/// which are invalid in arithmetic operations. These will be diagnosed
11461/// appropriately, including whether or not the use is supported as an
11462/// extension.
11463///
11464/// \returns True when the operand is valid to use (even if as an extension).
11465static bool checkArithmeticOpPointerOperand(Sema &S, SourceLocation Loc,
11466 Expr *Operand) {
11467 QualType ResType = Operand->getType();
11468 if (const AtomicType *ResAtomicType = ResType->getAs<AtomicType>())
11469 ResType = ResAtomicType->getValueType();
11470
11471 if (!ResType->isAnyPointerType()) return true;
11472
11473 QualType PointeeTy = ResType->getPointeeType();
11474 if (PointeeTy->isVoidType()) {
11475 diagnoseArithmeticOnVoidPointer(S, Loc, Pointer: Operand);
11476 return !S.getLangOpts().CPlusPlus;
11477 }
11478 if (PointeeTy->isFunctionType()) {
11479 diagnoseArithmeticOnFunctionPointer(S, Loc, Pointer: Operand);
11480 return !S.getLangOpts().CPlusPlus;
11481 }
11482
11483 if (checkArithmeticIncompletePointerType(S, Loc, Operand)) return false;
11484
11485 return true;
11486}
11487
11488/// Check the validity of a binary arithmetic operation w.r.t. pointer
11489/// operands.
11490///
11491/// This routine will diagnose any invalid arithmetic on pointer operands much
11492/// like \see checkArithmeticOpPointerOperand. However, it has special logic
11493/// for emitting a single diagnostic even for operations where both LHS and RHS
11494/// are (potentially problematic) pointers.
11495///
11496/// \returns True when the operand is valid to use (even if as an extension).
11497static bool checkArithmeticBinOpPointerOperands(Sema &S, SourceLocation Loc,
11498 Expr *LHSExpr, Expr *RHSExpr) {
11499 bool isLHSPointer = LHSExpr->getType()->isAnyPointerType();
11500 bool isRHSPointer = RHSExpr->getType()->isAnyPointerType();
11501 if (!isLHSPointer && !isRHSPointer) return true;
11502
11503 QualType LHSPointeeTy, RHSPointeeTy;
11504 if (isLHSPointer) LHSPointeeTy = LHSExpr->getType()->getPointeeType();
11505 if (isRHSPointer) RHSPointeeTy = RHSExpr->getType()->getPointeeType();
11506
11507 // if both are pointers check if operation is valid wrt address spaces
11508 if (isLHSPointer && isRHSPointer) {
11509 if (!LHSPointeeTy.isAddressSpaceOverlapping(T: RHSPointeeTy,
11510 Ctx: S.getASTContext())) {
11511 S.Diag(Loc,
11512 DiagID: diag::err_typecheck_op_on_nonoverlapping_address_space_pointers)
11513 << LHSExpr->getType() << RHSExpr->getType() << 1 /*arithmetic op*/
11514 << LHSExpr->getSourceRange() << RHSExpr->getSourceRange();
11515 return false;
11516 }
11517 }
11518
11519 // Check for arithmetic on pointers to incomplete types.
11520 bool isLHSVoidPtr = isLHSPointer && LHSPointeeTy->isVoidType();
11521 bool isRHSVoidPtr = isRHSPointer && RHSPointeeTy->isVoidType();
11522 if (isLHSVoidPtr || isRHSVoidPtr) {
11523 if (!isRHSVoidPtr) diagnoseArithmeticOnVoidPointer(S, Loc, Pointer: LHSExpr);
11524 else if (!isLHSVoidPtr) diagnoseArithmeticOnVoidPointer(S, Loc, Pointer: RHSExpr);
11525 else diagnoseArithmeticOnTwoVoidPointers(S, Loc, LHSExpr, RHSExpr);
11526
11527 return !S.getLangOpts().CPlusPlus;
11528 }
11529
11530 bool isLHSFuncPtr = isLHSPointer && LHSPointeeTy->isFunctionType();
11531 bool isRHSFuncPtr = isRHSPointer && RHSPointeeTy->isFunctionType();
11532 if (isLHSFuncPtr || isRHSFuncPtr) {
11533 if (!isRHSFuncPtr) diagnoseArithmeticOnFunctionPointer(S, Loc, Pointer: LHSExpr);
11534 else if (!isLHSFuncPtr) diagnoseArithmeticOnFunctionPointer(S, Loc,
11535 Pointer: RHSExpr);
11536 else diagnoseArithmeticOnTwoFunctionPointers(S, Loc, LHS: LHSExpr, RHS: RHSExpr);
11537
11538 return !S.getLangOpts().CPlusPlus;
11539 }
11540
11541 if (isLHSPointer && checkArithmeticIncompletePointerType(S, Loc, Operand: LHSExpr))
11542 return false;
11543 if (isRHSPointer && checkArithmeticIncompletePointerType(S, Loc, Operand: RHSExpr))
11544 return false;
11545
11546 return true;
11547}
11548
11549/// diagnoseStringPlusInt - Emit a warning when adding an integer to a string
11550/// literal.
11551static void diagnoseStringPlusInt(Sema &Self, SourceLocation OpLoc,
11552 Expr *LHSExpr, Expr *RHSExpr) {
11553 StringLiteral* StrExpr = dyn_cast<StringLiteral>(Val: LHSExpr->IgnoreImpCasts());
11554 Expr* IndexExpr = RHSExpr;
11555 if (!StrExpr) {
11556 StrExpr = dyn_cast<StringLiteral>(Val: RHSExpr->IgnoreImpCasts());
11557 IndexExpr = LHSExpr;
11558 }
11559
11560 bool IsStringPlusInt = StrExpr &&
11561 IndexExpr->getType()->isIntegralOrUnscopedEnumerationType();
11562 if (!IsStringPlusInt || IndexExpr->isValueDependent())
11563 return;
11564
11565 SourceRange DiagRange(LHSExpr->getBeginLoc(), RHSExpr->getEndLoc());
11566 Self.Diag(Loc: OpLoc, DiagID: diag::warn_string_plus_int)
11567 << DiagRange << IndexExpr->IgnoreImpCasts()->getType();
11568
11569 // Only print a fixit for "str" + int, not for int + "str".
11570 if (IndexExpr == RHSExpr) {
11571 SourceLocation EndLoc = Self.getLocForEndOfToken(Loc: RHSExpr->getEndLoc());
11572 Self.Diag(Loc: OpLoc, DiagID: diag::note_string_plus_scalar_silence)
11573 << FixItHint::CreateInsertion(InsertionLoc: LHSExpr->getBeginLoc(), Code: "&")
11574 << FixItHint::CreateReplacement(RemoveRange: SourceRange(OpLoc), Code: "[")
11575 << FixItHint::CreateInsertion(InsertionLoc: EndLoc, Code: "]");
11576 } else
11577 Self.Diag(Loc: OpLoc, DiagID: diag::note_string_plus_scalar_silence);
11578}
11579
11580/// Emit a warning when adding a char literal to a string.
11581static void diagnoseStringPlusChar(Sema &Self, SourceLocation OpLoc,
11582 Expr *LHSExpr, Expr *RHSExpr) {
11583 const Expr *StringRefExpr = LHSExpr;
11584 const CharacterLiteral *CharExpr =
11585 dyn_cast<CharacterLiteral>(Val: RHSExpr->IgnoreImpCasts());
11586
11587 if (!CharExpr) {
11588 CharExpr = dyn_cast<CharacterLiteral>(Val: LHSExpr->IgnoreImpCasts());
11589 StringRefExpr = RHSExpr;
11590 }
11591
11592 if (!CharExpr || !StringRefExpr)
11593 return;
11594
11595 const QualType StringType = StringRefExpr->getType();
11596
11597 // Return if not a PointerType.
11598 if (!StringType->isAnyPointerType())
11599 return;
11600
11601 // Return if not a CharacterType.
11602 if (!StringType->getPointeeType()->isAnyCharacterType())
11603 return;
11604
11605 ASTContext &Ctx = Self.getASTContext();
11606 SourceRange DiagRange(LHSExpr->getBeginLoc(), RHSExpr->getEndLoc());
11607
11608 const QualType CharType = CharExpr->getType();
11609 if (!CharType->isAnyCharacterType() &&
11610 CharType->isIntegerType() &&
11611 llvm::isUIntN(N: Ctx.getCharWidth(), x: CharExpr->getValue())) {
11612 Self.Diag(Loc: OpLoc, DiagID: diag::warn_string_plus_char)
11613 << DiagRange << Ctx.CharTy;
11614 } else {
11615 Self.Diag(Loc: OpLoc, DiagID: diag::warn_string_plus_char)
11616 << DiagRange << CharExpr->getType();
11617 }
11618
11619 // Only print a fixit for str + char, not for char + str.
11620 if (isa<CharacterLiteral>(Val: RHSExpr->IgnoreImpCasts())) {
11621 SourceLocation EndLoc = Self.getLocForEndOfToken(Loc: RHSExpr->getEndLoc());
11622 Self.Diag(Loc: OpLoc, DiagID: diag::note_string_plus_scalar_silence)
11623 << FixItHint::CreateInsertion(InsertionLoc: LHSExpr->getBeginLoc(), Code: "&")
11624 << FixItHint::CreateReplacement(RemoveRange: SourceRange(OpLoc), Code: "[")
11625 << FixItHint::CreateInsertion(InsertionLoc: EndLoc, Code: "]");
11626 } else {
11627 Self.Diag(Loc: OpLoc, DiagID: diag::note_string_plus_scalar_silence);
11628 }
11629}
11630
11631/// Emit error when two pointers are incompatible.
11632static void diagnosePointerIncompatibility(Sema &S, SourceLocation Loc,
11633 Expr *LHSExpr, Expr *RHSExpr) {
11634 assert(LHSExpr->getType()->isAnyPointerType());
11635 assert(RHSExpr->getType()->isAnyPointerType());
11636 S.Diag(Loc, DiagID: diag::err_typecheck_sub_ptr_compatible)
11637 << LHSExpr->getType() << RHSExpr->getType() << LHSExpr->getSourceRange()
11638 << RHSExpr->getSourceRange();
11639}
11640
11641// C99 6.5.6
11642QualType Sema::CheckAdditionOperands(ExprResult &LHS, ExprResult &RHS,
11643 SourceLocation Loc, BinaryOperatorKind Opc,
11644 QualType* CompLHSTy) {
11645 checkArithmeticNull(S&: *this, LHS, RHS, Loc, /*IsCompare=*/false);
11646
11647 if (LHS.get()->getType()->isVectorType() ||
11648 RHS.get()->getType()->isVectorType()) {
11649 QualType compType =
11650 CheckVectorOperands(LHS, RHS, Loc, IsCompAssign: CompLHSTy,
11651 /*AllowBothBool*/ getLangOpts().AltiVec,
11652 /*AllowBoolConversions*/ getLangOpts().ZVector,
11653 /*AllowBooleanOperation*/ AllowBoolOperation: false,
11654 /*ReportInvalid*/ true);
11655 if (CompLHSTy) *CompLHSTy = compType;
11656 return compType;
11657 }
11658
11659 if (LHS.get()->getType()->isSveVLSBuiltinType() ||
11660 RHS.get()->getType()->isSveVLSBuiltinType()) {
11661 QualType compType = CheckSizelessVectorOperands(LHS, RHS, Loc, IsCompAssign: CompLHSTy,
11662 OperationKind: ArithConvKind::Arithmetic);
11663 if (CompLHSTy)
11664 *CompLHSTy = compType;
11665 return compType;
11666 }
11667
11668 if (LHS.get()->getType()->isConstantMatrixType() ||
11669 RHS.get()->getType()->isConstantMatrixType()) {
11670 QualType compType =
11671 CheckMatrixElementwiseOperands(LHS, RHS, Loc, IsCompAssign: CompLHSTy);
11672 if (CompLHSTy)
11673 *CompLHSTy = compType;
11674 return compType;
11675 }
11676
11677 QualType compType = UsualArithmeticConversions(
11678 LHS, RHS, Loc,
11679 ACK: CompLHSTy ? ArithConvKind::CompAssign : ArithConvKind::Arithmetic);
11680 if (LHS.isInvalid() || RHS.isInvalid())
11681 return QualType();
11682
11683 // Diagnose "string literal" '+' int and string '+' "char literal".
11684 if (Opc == BO_Add) {
11685 diagnoseStringPlusInt(Self&: *this, OpLoc: Loc, LHSExpr: LHS.get(), RHSExpr: RHS.get());
11686 diagnoseStringPlusChar(Self&: *this, OpLoc: Loc, LHSExpr: LHS.get(), RHSExpr: RHS.get());
11687 }
11688
11689 // handle the common case first (both operands are arithmetic).
11690 if (!compType.isNull() && compType->isArithmeticType()) {
11691 if (CompLHSTy) *CompLHSTy = compType;
11692 return compType;
11693 }
11694
11695 // Type-checking. Ultimately the pointer's going to be in PExp;
11696 // note that we bias towards the LHS being the pointer.
11697 Expr *PExp = LHS.get(), *IExp = RHS.get();
11698
11699 bool isObjCPointer;
11700 if (PExp->getType()->isPointerType()) {
11701 isObjCPointer = false;
11702 } else if (PExp->getType()->isObjCObjectPointerType()) {
11703 isObjCPointer = true;
11704 } else {
11705 std::swap(a&: PExp, b&: IExp);
11706 if (PExp->getType()->isPointerType()) {
11707 isObjCPointer = false;
11708 } else if (PExp->getType()->isObjCObjectPointerType()) {
11709 isObjCPointer = true;
11710 } else {
11711 QualType ResultTy = InvalidOperands(Loc, LHS, RHS);
11712 diagnoseScopedEnums(S&: *this, Loc, LHS, RHS, Opc);
11713 return ResultTy;
11714 }
11715 }
11716 assert(PExp->getType()->isAnyPointerType());
11717
11718 if (!IExp->getType()->isIntegerType())
11719 return InvalidOperands(Loc, LHS, RHS);
11720
11721 // Adding to a null pointer results in undefined behavior.
11722 if (PExp->IgnoreParenCasts()->isNullPointerConstant(
11723 Ctx&: Context, NPC: Expr::NPC_ValueDependentIsNotNull)) {
11724 // In C++ adding zero to a null pointer is defined.
11725 Expr::EvalResult KnownVal;
11726 if (!getLangOpts().CPlusPlus ||
11727 (!IExp->isValueDependent() &&
11728 (!IExp->EvaluateAsInt(Result&: KnownVal, Ctx: Context) ||
11729 KnownVal.Val.getInt() != 0))) {
11730 // Check the conditions to see if this is the 'p = nullptr + n' idiom.
11731 bool IsGNUIdiom = BinaryOperator::isNullPointerArithmeticExtension(
11732 Ctx&: Context, Opc: BO_Add, LHS: PExp, RHS: IExp);
11733 diagnoseArithmeticOnNullPointer(S&: *this, Loc, Pointer: PExp, IsGNUIdiom);
11734 }
11735 }
11736
11737 if (!checkArithmeticOpPointerOperand(S&: *this, Loc, Operand: PExp))
11738 return QualType();
11739
11740 if (isObjCPointer && checkArithmeticOnObjCPointer(S&: *this, opLoc: Loc, op: PExp))
11741 return QualType();
11742
11743 // Arithmetic on label addresses is normally allowed, except when we add
11744 // a ptrauth signature to the addresses.
11745 if (isa<AddrLabelExpr>(Val: PExp) && getLangOpts().PointerAuthIndirectGotos) {
11746 Diag(Loc, DiagID: diag::err_ptrauth_indirect_goto_addrlabel_arithmetic)
11747 << /*addition*/ 1;
11748 return QualType();
11749 }
11750
11751 // Check array bounds for pointer arithemtic
11752 CheckArrayAccess(BaseExpr: PExp, IndexExpr: IExp);
11753
11754 if (CompLHSTy) {
11755 QualType LHSTy = Context.isPromotableBitField(E: LHS.get());
11756 if (LHSTy.isNull()) {
11757 LHSTy = LHS.get()->getType();
11758 if (Context.isPromotableIntegerType(T: LHSTy))
11759 LHSTy = Context.getPromotedIntegerType(PromotableType: LHSTy);
11760 }
11761 *CompLHSTy = LHSTy;
11762 }
11763
11764 return PExp->getType();
11765}
11766
11767// C99 6.5.6
11768QualType Sema::CheckSubtractionOperands(ExprResult &LHS, ExprResult &RHS,
11769 SourceLocation Loc,
11770 BinaryOperatorKind Opc,
11771 QualType *CompLHSTy) {
11772 checkArithmeticNull(S&: *this, LHS, RHS, Loc, /*IsCompare=*/false);
11773
11774 if (LHS.get()->getType()->isVectorType() ||
11775 RHS.get()->getType()->isVectorType()) {
11776 QualType compType =
11777 CheckVectorOperands(LHS, RHS, Loc, IsCompAssign: CompLHSTy,
11778 /*AllowBothBool*/ getLangOpts().AltiVec,
11779 /*AllowBoolConversions*/ getLangOpts().ZVector,
11780 /*AllowBooleanOperation*/ AllowBoolOperation: false,
11781 /*ReportInvalid*/ true);
11782 if (CompLHSTy) *CompLHSTy = compType;
11783 return compType;
11784 }
11785
11786 if (LHS.get()->getType()->isSveVLSBuiltinType() ||
11787 RHS.get()->getType()->isSveVLSBuiltinType()) {
11788 QualType compType = CheckSizelessVectorOperands(LHS, RHS, Loc, IsCompAssign: CompLHSTy,
11789 OperationKind: ArithConvKind::Arithmetic);
11790 if (CompLHSTy)
11791 *CompLHSTy = compType;
11792 return compType;
11793 }
11794
11795 if (LHS.get()->getType()->isConstantMatrixType() ||
11796 RHS.get()->getType()->isConstantMatrixType()) {
11797 QualType compType =
11798 CheckMatrixElementwiseOperands(LHS, RHS, Loc, IsCompAssign: CompLHSTy);
11799 if (CompLHSTy)
11800 *CompLHSTy = compType;
11801 return compType;
11802 }
11803
11804 QualType compType = UsualArithmeticConversions(
11805 LHS, RHS, Loc,
11806 ACK: CompLHSTy ? ArithConvKind::CompAssign : ArithConvKind::Arithmetic);
11807 if (LHS.isInvalid() || RHS.isInvalid())
11808 return QualType();
11809
11810 // Enforce type constraints: C99 6.5.6p3.
11811
11812 // Handle the common case first (both operands are arithmetic).
11813 if (!compType.isNull() && compType->isArithmeticType()) {
11814 if (CompLHSTy) *CompLHSTy = compType;
11815 return compType;
11816 }
11817
11818 // Either ptr - int or ptr - ptr.
11819 if (LHS.get()->getType()->isAnyPointerType()) {
11820 QualType lpointee = LHS.get()->getType()->getPointeeType();
11821
11822 // Diagnose bad cases where we step over interface counts.
11823 if (LHS.get()->getType()->isObjCObjectPointerType() &&
11824 checkArithmeticOnObjCPointer(S&: *this, opLoc: Loc, op: LHS.get()))
11825 return QualType();
11826
11827 // Arithmetic on label addresses is normally allowed, except when we add
11828 // a ptrauth signature to the addresses.
11829 if (isa<AddrLabelExpr>(Val: LHS.get()) &&
11830 getLangOpts().PointerAuthIndirectGotos) {
11831 Diag(Loc, DiagID: diag::err_ptrauth_indirect_goto_addrlabel_arithmetic)
11832 << /*subtraction*/ 0;
11833 return QualType();
11834 }
11835
11836 // The result type of a pointer-int computation is the pointer type.
11837 if (RHS.get()->getType()->isIntegerType()) {
11838 // Subtracting from a null pointer should produce a warning.
11839 // The last argument to the diagnose call says this doesn't match the
11840 // GNU int-to-pointer idiom.
11841 if (LHS.get()->IgnoreParenCasts()->isNullPointerConstant(Ctx&: Context,
11842 NPC: Expr::NPC_ValueDependentIsNotNull)) {
11843 // In C++ adding zero to a null pointer is defined.
11844 Expr::EvalResult KnownVal;
11845 if (!getLangOpts().CPlusPlus ||
11846 (!RHS.get()->isValueDependent() &&
11847 (!RHS.get()->EvaluateAsInt(Result&: KnownVal, Ctx: Context) ||
11848 KnownVal.Val.getInt() != 0))) {
11849 diagnoseArithmeticOnNullPointer(S&: *this, Loc, Pointer: LHS.get(), IsGNUIdiom: false);
11850 }
11851 }
11852
11853 if (!checkArithmeticOpPointerOperand(S&: *this, Loc, Operand: LHS.get()))
11854 return QualType();
11855
11856 // Check array bounds for pointer arithemtic
11857 CheckArrayAccess(BaseExpr: LHS.get(), IndexExpr: RHS.get(), /*ArraySubscriptExpr*/ASE: nullptr,
11858 /*AllowOnePastEnd*/true, /*IndexNegated*/true);
11859
11860 if (CompLHSTy) *CompLHSTy = LHS.get()->getType();
11861 return LHS.get()->getType();
11862 }
11863
11864 // Handle pointer-pointer subtractions.
11865 if (const PointerType *RHSPTy
11866 = RHS.get()->getType()->getAs<PointerType>()) {
11867 QualType rpointee = RHSPTy->getPointeeType();
11868
11869 if (getLangOpts().CPlusPlus) {
11870 // Pointee types must be the same: C++ [expr.add]
11871 if (!Context.hasSameUnqualifiedType(T1: lpointee, T2: rpointee)) {
11872 diagnosePointerIncompatibility(S&: *this, Loc, LHSExpr: LHS.get(), RHSExpr: RHS.get());
11873 }
11874 } else {
11875 // Pointee types must be compatible C99 6.5.6p3
11876 if (!Context.typesAreCompatible(
11877 T1: Context.getCanonicalType(T: lpointee).getUnqualifiedType(),
11878 T2: Context.getCanonicalType(T: rpointee).getUnqualifiedType())) {
11879 diagnosePointerIncompatibility(S&: *this, Loc, LHSExpr: LHS.get(), RHSExpr: RHS.get());
11880 return QualType();
11881 }
11882 }
11883
11884 if (!checkArithmeticBinOpPointerOperands(S&: *this, Loc,
11885 LHSExpr: LHS.get(), RHSExpr: RHS.get()))
11886 return QualType();
11887
11888 bool LHSIsNullPtr = LHS.get()->IgnoreParenCasts()->isNullPointerConstant(
11889 Ctx&: Context, NPC: Expr::NPC_ValueDependentIsNotNull);
11890 bool RHSIsNullPtr = RHS.get()->IgnoreParenCasts()->isNullPointerConstant(
11891 Ctx&: Context, NPC: Expr::NPC_ValueDependentIsNotNull);
11892
11893 // Subtracting nullptr or from nullptr is suspect
11894 if (LHSIsNullPtr)
11895 diagnoseSubtractionOnNullPointer(S&: *this, Loc, Pointer: LHS.get(), BothNull: RHSIsNullPtr);
11896 if (RHSIsNullPtr)
11897 diagnoseSubtractionOnNullPointer(S&: *this, Loc, Pointer: RHS.get(), BothNull: LHSIsNullPtr);
11898
11899 // The pointee type may have zero size. As an extension, a structure or
11900 // union may have zero size or an array may have zero length. In this
11901 // case subtraction does not make sense.
11902 if (!rpointee->isVoidType() && !rpointee->isFunctionType()) {
11903 CharUnits ElementSize = Context.getTypeSizeInChars(T: rpointee);
11904 if (ElementSize.isZero()) {
11905 Diag(Loc,DiagID: diag::warn_sub_ptr_zero_size_types)
11906 << rpointee.getUnqualifiedType()
11907 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
11908 }
11909 }
11910
11911 if (CompLHSTy) *CompLHSTy = LHS.get()->getType();
11912 return Context.getPointerDiffType();
11913 }
11914 }
11915
11916 QualType ResultTy = InvalidOperands(Loc, LHS, RHS);
11917 diagnoseScopedEnums(S&: *this, Loc, LHS, RHS, Opc);
11918 return ResultTy;
11919}
11920
11921static bool isScopedEnumerationType(QualType T) {
11922 if (const EnumType *ET = T->getAsCanonical<EnumType>())
11923 return ET->getDecl()->isScoped();
11924 return false;
11925}
11926
11927static void DiagnoseBadShiftValues(Sema& S, ExprResult &LHS, ExprResult &RHS,
11928 SourceLocation Loc, BinaryOperatorKind Opc,
11929 QualType LHSType) {
11930 // OpenCL 6.3j: shift values are effectively % word size of LHS (more defined),
11931 // so skip remaining warnings as we don't want to modify values within Sema.
11932 if (S.getLangOpts().OpenCL)
11933 return;
11934
11935 if (Opc == BO_Shr &&
11936 LHS.get()->IgnoreParenImpCasts()->getType()->isBooleanType())
11937 S.Diag(Loc, DiagID: diag::warn_shift_bool) << LHS.get()->getSourceRange();
11938
11939 // Check right/shifter operand
11940 Expr::EvalResult RHSResult;
11941 if (RHS.get()->isValueDependent() ||
11942 !RHS.get()->EvaluateAsInt(Result&: RHSResult, Ctx: S.Context))
11943 return;
11944 llvm::APSInt Right = RHSResult.Val.getInt();
11945
11946 if (Right.isNegative()) {
11947 S.DiagRuntimeBehavior(Loc, Statement: RHS.get(),
11948 PD: S.PDiag(DiagID: diag::warn_shift_negative)
11949 << RHS.get()->getSourceRange());
11950 return;
11951 }
11952
11953 QualType LHSExprType = LHS.get()->getType();
11954 uint64_t LeftSize = S.Context.getTypeSize(T: LHSExprType);
11955 if (LHSExprType->isBitIntType())
11956 LeftSize = S.Context.getIntWidth(T: LHSExprType);
11957 else if (LHSExprType->isFixedPointType()) {
11958 auto FXSema = S.Context.getFixedPointSemantics(Ty: LHSExprType);
11959 LeftSize = FXSema.getWidth() - (unsigned)FXSema.hasUnsignedPadding();
11960 }
11961 if (Right.uge(RHS: LeftSize)) {
11962 S.DiagRuntimeBehavior(Loc, Statement: RHS.get(),
11963 PD: S.PDiag(DiagID: diag::warn_shift_gt_typewidth)
11964 << RHS.get()->getSourceRange());
11965 return;
11966 }
11967
11968 // FIXME: We probably need to handle fixed point types specially here.
11969 if (Opc != BO_Shl || LHSExprType->isFixedPointType())
11970 return;
11971
11972 // When left shifting an ICE which is signed, we can check for overflow which
11973 // according to C++ standards prior to C++2a has undefined behavior
11974 // ([expr.shift] 5.8/2). Unsigned integers have defined behavior modulo one
11975 // more than the maximum value representable in the result type, so never
11976 // warn for those. (FIXME: Unsigned left-shift overflow in a constant
11977 // expression is still probably a bug.)
11978 Expr::EvalResult LHSResult;
11979 if (LHS.get()->isValueDependent() ||
11980 LHSType->hasUnsignedIntegerRepresentation() ||
11981 !LHS.get()->EvaluateAsInt(Result&: LHSResult, Ctx: S.Context))
11982 return;
11983 llvm::APSInt Left = LHSResult.Val.getInt();
11984
11985 // Don't warn if signed overflow is defined, then all the rest of the
11986 // diagnostics will not be triggered because the behavior is defined.
11987 // Also don't warn in C++20 mode (and newer), as signed left shifts
11988 // always wrap and never overflow.
11989 if (S.getLangOpts().isSignedOverflowDefined() || S.getLangOpts().CPlusPlus20)
11990 return;
11991
11992 // If LHS does not have a non-negative value then, the
11993 // behavior is undefined before C++2a. Warn about it.
11994 if (Left.isNegative()) {
11995 S.DiagRuntimeBehavior(Loc, Statement: LHS.get(),
11996 PD: S.PDiag(DiagID: diag::warn_shift_lhs_negative)
11997 << LHS.get()->getSourceRange());
11998 return;
11999 }
12000
12001 llvm::APInt ResultBits =
12002 static_cast<llvm::APInt &>(Right) + Left.getSignificantBits();
12003 if (ResultBits.ule(RHS: LeftSize))
12004 return;
12005 llvm::APSInt Result = Left.extend(width: ResultBits.getLimitedValue());
12006 Result = Result.shl(ShiftAmt: Right);
12007
12008 // Print the bit representation of the signed integer as an unsigned
12009 // hexadecimal number.
12010 SmallString<40> HexResult;
12011 Result.toString(Str&: HexResult, Radix: 16, /*Signed =*/false, /*Literal =*/formatAsCLiteral: true);
12012
12013 // If we are only missing a sign bit, this is less likely to result in actual
12014 // bugs -- if the result is cast back to an unsigned type, it will have the
12015 // expected value. Thus we place this behind a different warning that can be
12016 // turned off separately if needed.
12017 if (ResultBits - 1 == LeftSize) {
12018 S.Diag(Loc, DiagID: diag::warn_shift_result_sets_sign_bit)
12019 << HexResult << LHSType
12020 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
12021 return;
12022 }
12023
12024 S.Diag(Loc, DiagID: diag::warn_shift_result_gt_typewidth)
12025 << HexResult.str() << Result.getSignificantBits() << LHSType
12026 << Left.getBitWidth() << LHS.get()->getSourceRange()
12027 << RHS.get()->getSourceRange();
12028}
12029
12030/// Return the resulting type when a vector is shifted
12031/// by a scalar or vector shift amount.
12032static QualType checkVectorShift(Sema &S, ExprResult &LHS, ExprResult &RHS,
12033 SourceLocation Loc, bool IsCompAssign) {
12034 // OpenCL v1.1 s6.3.j says RHS can be a vector only if LHS is a vector.
12035 if ((S.LangOpts.OpenCL || S.LangOpts.ZVector) &&
12036 !LHS.get()->getType()->isVectorType()) {
12037 S.Diag(Loc, DiagID: diag::err_shift_rhs_only_vector)
12038 << RHS.get()->getType() << LHS.get()->getType()
12039 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
12040 return QualType();
12041 }
12042
12043 if (!IsCompAssign) {
12044 LHS = S.UsualUnaryConversions(E: LHS.get());
12045 if (LHS.isInvalid()) return QualType();
12046 }
12047
12048 RHS = S.UsualUnaryConversions(E: RHS.get());
12049 if (RHS.isInvalid()) return QualType();
12050
12051 QualType LHSType = LHS.get()->getType();
12052 // Note that LHS might be a scalar because the routine calls not only in
12053 // OpenCL case.
12054 const VectorType *LHSVecTy = LHSType->getAs<VectorType>();
12055 QualType LHSEleType = LHSVecTy ? LHSVecTy->getElementType() : LHSType;
12056
12057 // Note that RHS might not be a vector.
12058 QualType RHSType = RHS.get()->getType();
12059 const VectorType *RHSVecTy = RHSType->getAs<VectorType>();
12060 QualType RHSEleType = RHSVecTy ? RHSVecTy->getElementType() : RHSType;
12061
12062 // Do not allow shifts for boolean vectors.
12063 if ((LHSVecTy && LHSVecTy->isExtVectorBoolType()) ||
12064 (RHSVecTy && RHSVecTy->isExtVectorBoolType())) {
12065 S.Diag(Loc, DiagID: diag::err_typecheck_invalid_operands)
12066 << LHS.get()->getType() << RHS.get()->getType()
12067 << LHS.get()->getSourceRange();
12068 return QualType();
12069 }
12070
12071 // The operands need to be integers.
12072 if (!LHSEleType->isIntegerType()) {
12073 S.Diag(Loc, DiagID: diag::err_typecheck_expect_int)
12074 << LHS.get()->getType() << LHS.get()->getSourceRange();
12075 return QualType();
12076 }
12077
12078 if (!RHSEleType->isIntegerType()) {
12079 S.Diag(Loc, DiagID: diag::err_typecheck_expect_int)
12080 << RHS.get()->getType() << RHS.get()->getSourceRange();
12081 return QualType();
12082 }
12083
12084 if (!LHSVecTy) {
12085 assert(RHSVecTy);
12086 if (IsCompAssign)
12087 return RHSType;
12088 if (LHSEleType != RHSEleType) {
12089 LHS = S.ImpCastExprToType(E: LHS.get(),Type: RHSEleType, CK: CK_IntegralCast);
12090 LHSEleType = RHSEleType;
12091 }
12092 QualType VecTy =
12093 S.Context.getExtVectorType(VectorType: LHSEleType, NumElts: RHSVecTy->getNumElements());
12094 LHS = S.ImpCastExprToType(E: LHS.get(), Type: VecTy, CK: CK_VectorSplat);
12095 LHSType = VecTy;
12096 } else if (RHSVecTy) {
12097 // OpenCL v1.1 s6.3.j says that for vector types, the operators
12098 // are applied component-wise. So if RHS is a vector, then ensure
12099 // that the number of elements is the same as LHS...
12100 if (RHSVecTy->getNumElements() != LHSVecTy->getNumElements()) {
12101 S.Diag(Loc, DiagID: diag::err_typecheck_vector_lengths_not_equal)
12102 << LHS.get()->getType() << RHS.get()->getType()
12103 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
12104 return QualType();
12105 }
12106 if (!S.LangOpts.OpenCL && !S.LangOpts.ZVector) {
12107 const BuiltinType *LHSBT = LHSEleType->getAs<clang::BuiltinType>();
12108 const BuiltinType *RHSBT = RHSEleType->getAs<clang::BuiltinType>();
12109 if (LHSBT != RHSBT &&
12110 S.Context.getTypeSize(T: LHSBT) != S.Context.getTypeSize(T: RHSBT)) {
12111 S.Diag(Loc, DiagID: diag::warn_typecheck_vector_element_sizes_not_equal)
12112 << LHS.get()->getType() << RHS.get()->getType()
12113 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
12114 }
12115 }
12116 } else {
12117 // ...else expand RHS to match the number of elements in LHS.
12118 QualType VecTy =
12119 S.Context.getExtVectorType(VectorType: RHSEleType, NumElts: LHSVecTy->getNumElements());
12120 RHS = S.ImpCastExprToType(E: RHS.get(), Type: VecTy, CK: CK_VectorSplat);
12121 }
12122
12123 return LHSType;
12124}
12125
12126static QualType checkSizelessVectorShift(Sema &S, ExprResult &LHS,
12127 ExprResult &RHS, SourceLocation Loc,
12128 bool IsCompAssign) {
12129 if (!IsCompAssign) {
12130 LHS = S.UsualUnaryConversions(E: LHS.get());
12131 if (LHS.isInvalid())
12132 return QualType();
12133 }
12134
12135 RHS = S.UsualUnaryConversions(E: RHS.get());
12136 if (RHS.isInvalid())
12137 return QualType();
12138
12139 QualType LHSType = LHS.get()->getType();
12140 const BuiltinType *LHSBuiltinTy = LHSType->castAs<BuiltinType>();
12141 QualType LHSEleType = LHSType->isSveVLSBuiltinType()
12142 ? LHSBuiltinTy->getSveEltType(Ctx: S.getASTContext())
12143 : LHSType;
12144
12145 // Note that RHS might not be a vector
12146 QualType RHSType = RHS.get()->getType();
12147 const BuiltinType *RHSBuiltinTy = RHSType->castAs<BuiltinType>();
12148 QualType RHSEleType = RHSType->isSveVLSBuiltinType()
12149 ? RHSBuiltinTy->getSveEltType(Ctx: S.getASTContext())
12150 : RHSType;
12151
12152 if ((LHSBuiltinTy && LHSBuiltinTy->isSVEBool()) ||
12153 (RHSBuiltinTy && RHSBuiltinTy->isSVEBool())) {
12154 S.Diag(Loc, DiagID: diag::err_typecheck_invalid_operands)
12155 << LHSType << RHSType << LHS.get()->getSourceRange();
12156 return QualType();
12157 }
12158
12159 if (!LHSEleType->isIntegerType()) {
12160 S.Diag(Loc, DiagID: diag::err_typecheck_expect_int)
12161 << LHS.get()->getType() << LHS.get()->getSourceRange();
12162 return QualType();
12163 }
12164
12165 if (!RHSEleType->isIntegerType()) {
12166 S.Diag(Loc, DiagID: diag::err_typecheck_expect_int)
12167 << RHS.get()->getType() << RHS.get()->getSourceRange();
12168 return QualType();
12169 }
12170
12171 if (LHSType->isSveVLSBuiltinType() && RHSType->isSveVLSBuiltinType() &&
12172 (S.Context.getBuiltinVectorTypeInfo(VecTy: LHSBuiltinTy).EC !=
12173 S.Context.getBuiltinVectorTypeInfo(VecTy: RHSBuiltinTy).EC)) {
12174 S.Diag(Loc, DiagID: diag::err_typecheck_invalid_operands)
12175 << LHSType << RHSType << LHS.get()->getSourceRange()
12176 << RHS.get()->getSourceRange();
12177 return QualType();
12178 }
12179
12180 if (!LHSType->isSveVLSBuiltinType()) {
12181 assert(RHSType->isSveVLSBuiltinType());
12182 if (IsCompAssign)
12183 return RHSType;
12184 if (LHSEleType != RHSEleType) {
12185 LHS = S.ImpCastExprToType(E: LHS.get(), Type: RHSEleType, CK: clang::CK_IntegralCast);
12186 LHSEleType = RHSEleType;
12187 }
12188 const llvm::ElementCount VecSize =
12189 S.Context.getBuiltinVectorTypeInfo(VecTy: RHSBuiltinTy).EC;
12190 QualType VecTy =
12191 S.Context.getScalableVectorType(EltTy: LHSEleType, NumElts: VecSize.getKnownMinValue());
12192 LHS = S.ImpCastExprToType(E: LHS.get(), Type: VecTy, CK: clang::CK_VectorSplat);
12193 LHSType = VecTy;
12194 } else if (RHSBuiltinTy && RHSBuiltinTy->isSveVLSBuiltinType()) {
12195 if (S.Context.getTypeSize(T: RHSBuiltinTy) !=
12196 S.Context.getTypeSize(T: LHSBuiltinTy)) {
12197 S.Diag(Loc, DiagID: diag::err_typecheck_vector_lengths_not_equal)
12198 << LHSType << RHSType << LHS.get()->getSourceRange()
12199 << RHS.get()->getSourceRange();
12200 return QualType();
12201 }
12202 } else {
12203 const llvm::ElementCount VecSize =
12204 S.Context.getBuiltinVectorTypeInfo(VecTy: LHSBuiltinTy).EC;
12205 if (LHSEleType != RHSEleType) {
12206 RHS = S.ImpCastExprToType(E: RHS.get(), Type: LHSEleType, CK: clang::CK_IntegralCast);
12207 RHSEleType = LHSEleType;
12208 }
12209 QualType VecTy =
12210 S.Context.getScalableVectorType(EltTy: RHSEleType, NumElts: VecSize.getKnownMinValue());
12211 RHS = S.ImpCastExprToType(E: RHS.get(), Type: VecTy, CK: CK_VectorSplat);
12212 }
12213
12214 return LHSType;
12215}
12216
12217// C99 6.5.7
12218QualType Sema::CheckShiftOperands(ExprResult &LHS, ExprResult &RHS,
12219 SourceLocation Loc, BinaryOperatorKind Opc,
12220 bool IsCompAssign) {
12221 checkArithmeticNull(S&: *this, LHS, RHS, Loc, /*IsCompare=*/false);
12222
12223 // Vector shifts promote their scalar inputs to vector type.
12224 if (LHS.get()->getType()->isVectorType() ||
12225 RHS.get()->getType()->isVectorType()) {
12226 if (LangOpts.ZVector) {
12227 // The shift operators for the z vector extensions work basically
12228 // like general shifts, except that neither the LHS nor the RHS is
12229 // allowed to be a "vector bool".
12230 if (auto LHSVecType = LHS.get()->getType()->getAs<VectorType>())
12231 if (LHSVecType->getVectorKind() == VectorKind::AltiVecBool)
12232 return InvalidOperands(Loc, LHS, RHS);
12233 if (auto RHSVecType = RHS.get()->getType()->getAs<VectorType>())
12234 if (RHSVecType->getVectorKind() == VectorKind::AltiVecBool)
12235 return InvalidOperands(Loc, LHS, RHS);
12236 }
12237 return checkVectorShift(S&: *this, LHS, RHS, Loc, IsCompAssign);
12238 }
12239
12240 if (LHS.get()->getType()->isSveVLSBuiltinType() ||
12241 RHS.get()->getType()->isSveVLSBuiltinType())
12242 return checkSizelessVectorShift(S&: *this, LHS, RHS, Loc, IsCompAssign);
12243
12244 // Shifts don't perform usual arithmetic conversions, they just do integer
12245 // promotions on each operand. C99 6.5.7p3
12246
12247 // For the LHS, do usual unary conversions, but then reset them away
12248 // if this is a compound assignment.
12249 ExprResult OldLHS = LHS;
12250 LHS = UsualUnaryConversions(E: LHS.get());
12251 if (LHS.isInvalid())
12252 return QualType();
12253 QualType LHSType = LHS.get()->getType();
12254 if (IsCompAssign) LHS = OldLHS;
12255
12256 // The RHS is simpler.
12257 RHS = UsualUnaryConversions(E: RHS.get());
12258 if (RHS.isInvalid())
12259 return QualType();
12260 QualType RHSType = RHS.get()->getType();
12261
12262 // C99 6.5.7p2: Each of the operands shall have integer type.
12263 // Embedded-C 4.1.6.2.2: The LHS may also be fixed-point.
12264 if ((!LHSType->isFixedPointOrIntegerType() &&
12265 !LHSType->hasIntegerRepresentation()) ||
12266 !RHSType->hasIntegerRepresentation()) {
12267 QualType ResultTy = InvalidOperands(Loc, LHS, RHS);
12268 diagnoseScopedEnums(S&: *this, Loc, LHS, RHS, Opc);
12269 return ResultTy;
12270 }
12271
12272 DiagnoseBadShiftValues(S&: *this, LHS, RHS, Loc, Opc, LHSType);
12273
12274 // "The type of the result is that of the promoted left operand."
12275 return LHSType;
12276}
12277
12278/// Diagnose bad pointer comparisons.
12279static void diagnoseDistinctPointerComparison(Sema &S, SourceLocation Loc,
12280 ExprResult &LHS, ExprResult &RHS,
12281 bool IsError) {
12282 S.Diag(Loc, DiagID: IsError ? diag::err_typecheck_comparison_of_distinct_pointers
12283 : diag::ext_typecheck_comparison_of_distinct_pointers)
12284 << LHS.get()->getType() << RHS.get()->getType()
12285 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
12286}
12287
12288/// Returns false if the pointers are converted to a composite type,
12289/// true otherwise.
12290static bool convertPointersToCompositeType(Sema &S, SourceLocation Loc,
12291 ExprResult &LHS, ExprResult &RHS) {
12292 // C++ [expr.rel]p2:
12293 // [...] Pointer conversions (4.10) and qualification
12294 // conversions (4.4) are performed on pointer operands (or on
12295 // a pointer operand and a null pointer constant) to bring
12296 // them to their composite pointer type. [...]
12297 //
12298 // C++ [expr.eq]p1 uses the same notion for (in)equality
12299 // comparisons of pointers.
12300
12301 QualType LHSType = LHS.get()->getType();
12302 QualType RHSType = RHS.get()->getType();
12303 assert(LHSType->isPointerType() || RHSType->isPointerType() ||
12304 LHSType->isMemberPointerType() || RHSType->isMemberPointerType());
12305
12306 QualType T = S.FindCompositePointerType(Loc, E1&: LHS, E2&: RHS);
12307 if (T.isNull()) {
12308 if ((LHSType->isAnyPointerType() || LHSType->isMemberPointerType()) &&
12309 (RHSType->isAnyPointerType() || RHSType->isMemberPointerType()))
12310 diagnoseDistinctPointerComparison(S, Loc, LHS, RHS, /*isError*/IsError: true);
12311 else
12312 S.InvalidOperands(Loc, LHS, RHS);
12313 return true;
12314 }
12315
12316 return false;
12317}
12318
12319static void diagnoseFunctionPointerToVoidComparison(Sema &S, SourceLocation Loc,
12320 ExprResult &LHS,
12321 ExprResult &RHS,
12322 bool IsError) {
12323 S.Diag(Loc, DiagID: IsError ? diag::err_typecheck_comparison_of_fptr_to_void
12324 : diag::ext_typecheck_comparison_of_fptr_to_void)
12325 << LHS.get()->getType() << RHS.get()->getType()
12326 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
12327}
12328
12329static bool isObjCObjectLiteral(ExprResult &E) {
12330 switch (E.get()->IgnoreParenImpCasts()->getStmtClass()) {
12331 case Stmt::ObjCArrayLiteralClass:
12332 case Stmt::ObjCDictionaryLiteralClass:
12333 case Stmt::ObjCStringLiteralClass:
12334 case Stmt::ObjCBoxedExprClass:
12335 return true;
12336 default:
12337 // Note that ObjCBoolLiteral is NOT an object literal!
12338 return false;
12339 }
12340}
12341
12342static bool hasIsEqualMethod(Sema &S, const Expr *LHS, const Expr *RHS) {
12343 const ObjCObjectPointerType *Type =
12344 LHS->getType()->getAs<ObjCObjectPointerType>();
12345
12346 // If this is not actually an Objective-C object, bail out.
12347 if (!Type)
12348 return false;
12349
12350 // Get the LHS object's interface type.
12351 QualType InterfaceType = Type->getPointeeType();
12352
12353 // If the RHS isn't an Objective-C object, bail out.
12354 if (!RHS->getType()->isObjCObjectPointerType())
12355 return false;
12356
12357 // Try to find the -isEqual: method.
12358 Selector IsEqualSel = S.ObjC().NSAPIObj->getIsEqualSelector();
12359 ObjCMethodDecl *Method =
12360 S.ObjC().LookupMethodInObjectType(Sel: IsEqualSel, Ty: InterfaceType,
12361 /*IsInstance=*/true);
12362 if (!Method) {
12363 if (Type->isObjCIdType()) {
12364 // For 'id', just check the global pool.
12365 Method =
12366 S.ObjC().LookupInstanceMethodInGlobalPool(Sel: IsEqualSel, R: SourceRange(),
12367 /*receiverId=*/receiverIdOrClass: true);
12368 } else {
12369 // Check protocols.
12370 Method = S.ObjC().LookupMethodInQualifiedType(Sel: IsEqualSel, OPT: Type,
12371 /*IsInstance=*/true);
12372 }
12373 }
12374
12375 if (!Method)
12376 return false;
12377
12378 QualType T = Method->parameters()[0]->getType();
12379 if (!T->isObjCObjectPointerType())
12380 return false;
12381
12382 QualType R = Method->getReturnType();
12383 if (!R->isScalarType())
12384 return false;
12385
12386 return true;
12387}
12388
12389static void diagnoseObjCLiteralComparison(Sema &S, SourceLocation Loc,
12390 ExprResult &LHS, ExprResult &RHS,
12391 BinaryOperator::Opcode Opc){
12392 Expr *Literal;
12393 Expr *Other;
12394 if (isObjCObjectLiteral(E&: LHS)) {
12395 Literal = LHS.get();
12396 Other = RHS.get();
12397 } else {
12398 Literal = RHS.get();
12399 Other = LHS.get();
12400 }
12401
12402 // Don't warn on comparisons against nil.
12403 Other = Other->IgnoreParenCasts();
12404 if (Other->isNullPointerConstant(Ctx&: S.getASTContext(),
12405 NPC: Expr::NPC_ValueDependentIsNotNull))
12406 return;
12407
12408 // This should be kept in sync with warn_objc_literal_comparison.
12409 // LK_String should always be after the other literals, since it has its own
12410 // warning flag.
12411 SemaObjC::ObjCLiteralKind LiteralKind = S.ObjC().CheckLiteralKind(FromE: Literal);
12412 assert(LiteralKind != SemaObjC::LK_Block);
12413 if (LiteralKind == SemaObjC::LK_None) {
12414 llvm_unreachable("Unknown Objective-C object literal kind");
12415 }
12416
12417 if (LiteralKind == SemaObjC::LK_String)
12418 S.Diag(Loc, DiagID: diag::warn_objc_string_literal_comparison)
12419 << Literal->getSourceRange();
12420 else
12421 S.Diag(Loc, DiagID: diag::warn_objc_literal_comparison)
12422 << LiteralKind << Literal->getSourceRange();
12423
12424 if (BinaryOperator::isEqualityOp(Opc) &&
12425 hasIsEqualMethod(S, LHS: LHS.get(), RHS: RHS.get())) {
12426 SourceLocation Start = LHS.get()->getBeginLoc();
12427 SourceLocation End = S.getLocForEndOfToken(Loc: RHS.get()->getEndLoc());
12428 CharSourceRange OpRange =
12429 CharSourceRange::getCharRange(B: Loc, E: S.getLocForEndOfToken(Loc));
12430
12431 S.Diag(Loc, DiagID: diag::note_objc_literal_comparison_isequal)
12432 << FixItHint::CreateInsertion(InsertionLoc: Start, Code: Opc == BO_EQ ? "[" : "![")
12433 << FixItHint::CreateReplacement(RemoveRange: OpRange, Code: " isEqual:")
12434 << FixItHint::CreateInsertion(InsertionLoc: End, Code: "]");
12435 }
12436}
12437
12438/// Warns on !x < y, !x & y where !(x < y), !(x & y) was probably intended.
12439static void diagnoseLogicalNotOnLHSofCheck(Sema &S, ExprResult &LHS,
12440 ExprResult &RHS, SourceLocation Loc,
12441 BinaryOperatorKind Opc) {
12442 // Check that left hand side is !something.
12443 UnaryOperator *UO = dyn_cast<UnaryOperator>(Val: LHS.get()->IgnoreImpCasts());
12444 if (!UO || UO->getOpcode() != UO_LNot) return;
12445
12446 // Only check if the right hand side is non-bool arithmetic type.
12447 if (RHS.get()->isKnownToHaveBooleanValue()) return;
12448
12449 // Make sure that the something in !something is not bool.
12450 Expr *SubExpr = UO->getSubExpr()->IgnoreImpCasts();
12451 if (SubExpr->isKnownToHaveBooleanValue()) return;
12452
12453 // Emit warning.
12454 bool IsBitwiseOp = Opc == BO_And || Opc == BO_Or || Opc == BO_Xor;
12455 S.Diag(Loc: UO->getOperatorLoc(), DiagID: diag::warn_logical_not_on_lhs_of_check)
12456 << Loc << IsBitwiseOp;
12457
12458 // First note suggest !(x < y)
12459 SourceLocation FirstOpen = SubExpr->getBeginLoc();
12460 SourceLocation FirstClose = RHS.get()->getEndLoc();
12461 FirstClose = S.getLocForEndOfToken(Loc: FirstClose);
12462 if (FirstClose.isInvalid())
12463 FirstOpen = SourceLocation();
12464 S.Diag(Loc: UO->getOperatorLoc(), DiagID: diag::note_logical_not_fix)
12465 << IsBitwiseOp
12466 << FixItHint::CreateInsertion(InsertionLoc: FirstOpen, Code: "(")
12467 << FixItHint::CreateInsertion(InsertionLoc: FirstClose, Code: ")");
12468
12469 // Second note suggests (!x) < y
12470 SourceLocation SecondOpen = LHS.get()->getBeginLoc();
12471 SourceLocation SecondClose = LHS.get()->getEndLoc();
12472 SecondClose = S.getLocForEndOfToken(Loc: SecondClose);
12473 if (SecondClose.isInvalid())
12474 SecondOpen = SourceLocation();
12475 S.Diag(Loc: UO->getOperatorLoc(), DiagID: diag::note_logical_not_silence_with_parens)
12476 << FixItHint::CreateInsertion(InsertionLoc: SecondOpen, Code: "(")
12477 << FixItHint::CreateInsertion(InsertionLoc: SecondClose, Code: ")");
12478}
12479
12480// Returns true if E refers to a non-weak array.
12481static bool checkForArray(const Expr *E) {
12482 const ValueDecl *D = nullptr;
12483 if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Val: E)) {
12484 D = DR->getDecl();
12485 } else if (const MemberExpr *Mem = dyn_cast<MemberExpr>(Val: E)) {
12486 if (Mem->isImplicitAccess())
12487 D = Mem->getMemberDecl();
12488 }
12489 if (!D)
12490 return false;
12491 return D->getType()->isArrayType() && !D->isWeak();
12492}
12493
12494/// Detect patterns ptr + size >= ptr and ptr + size < ptr, where ptr is a
12495/// pointer and size is an unsigned integer. Return whether the result is
12496/// always true/false.
12497static std::optional<bool> isTautologicalBoundsCheck(Sema &S, const Expr *LHS,
12498 const Expr *RHS,
12499 BinaryOperatorKind Opc) {
12500 if (!LHS->getType()->isPointerType() ||
12501 S.getLangOpts().PointerOverflowDefined)
12502 return std::nullopt;
12503
12504 // Canonicalize to >= or < predicate.
12505 switch (Opc) {
12506 case BO_GE:
12507 case BO_LT:
12508 break;
12509 case BO_GT:
12510 std::swap(a&: LHS, b&: RHS);
12511 Opc = BO_LT;
12512 break;
12513 case BO_LE:
12514 std::swap(a&: LHS, b&: RHS);
12515 Opc = BO_GE;
12516 break;
12517 default:
12518 return std::nullopt;
12519 }
12520
12521 auto *BO = dyn_cast<BinaryOperator>(Val: LHS);
12522 if (!BO || BO->getOpcode() != BO_Add)
12523 return std::nullopt;
12524
12525 Expr *Other;
12526 if (Expr::isSameComparisonOperand(E1: BO->getLHS(), E2: RHS))
12527 Other = BO->getRHS();
12528 else if (Expr::isSameComparisonOperand(E1: BO->getRHS(), E2: RHS))
12529 Other = BO->getLHS();
12530 else
12531 return std::nullopt;
12532
12533 if (!Other->getType()->isUnsignedIntegerType())
12534 return std::nullopt;
12535
12536 return Opc == BO_GE;
12537}
12538
12539/// Diagnose some forms of syntactically-obvious tautological comparison.
12540static void diagnoseTautologicalComparison(Sema &S, SourceLocation Loc,
12541 Expr *LHS, Expr *RHS,
12542 BinaryOperatorKind Opc) {
12543 Expr *LHSStripped = LHS->IgnoreParenImpCasts();
12544 Expr *RHSStripped = RHS->IgnoreParenImpCasts();
12545
12546 QualType LHSType = LHS->getType();
12547 QualType RHSType = RHS->getType();
12548 if (LHSType->hasFloatingRepresentation() ||
12549 (LHSType->isBlockPointerType() && !BinaryOperator::isEqualityOp(Opc)) ||
12550 S.inTemplateInstantiation())
12551 return;
12552
12553 // WebAssembly Tables cannot be compared, therefore shouldn't emit
12554 // Tautological diagnostics.
12555 if (LHSType->isWebAssemblyTableType() || RHSType->isWebAssemblyTableType())
12556 return;
12557
12558 // Comparisons between two array types are ill-formed for operator<=>, so
12559 // we shouldn't emit any additional warnings about it.
12560 if (Opc == BO_Cmp && LHSType->isArrayType() && RHSType->isArrayType())
12561 return;
12562
12563 // For non-floating point types, check for self-comparisons of the form
12564 // x == x, x != x, x < x, etc. These always evaluate to a constant, and
12565 // often indicate logic errors in the program.
12566 //
12567 // NOTE: Don't warn about comparison expressions resulting from macro
12568 // expansion. Also don't warn about comparisons which are only self
12569 // comparisons within a template instantiation. The warnings should catch
12570 // obvious cases in the definition of the template anyways. The idea is to
12571 // warn when the typed comparison operator will always evaluate to the same
12572 // result.
12573
12574 // Used for indexing into %select in warn_comparison_always
12575 enum {
12576 AlwaysConstant,
12577 AlwaysTrue,
12578 AlwaysFalse,
12579 AlwaysEqual, // std::strong_ordering::equal from operator<=>
12580 };
12581
12582 // C++1a [array.comp]:
12583 // Equality and relational comparisons ([expr.eq], [expr.rel]) between two
12584 // operands of array type.
12585 // C++2a [depr.array.comp]:
12586 // Equality and relational comparisons ([expr.eq], [expr.rel]) between two
12587 // operands of array type are deprecated.
12588 if (S.getLangOpts().CPlusPlus && LHSStripped->getType()->isArrayType() &&
12589 RHSStripped->getType()->isArrayType()) {
12590 auto IsDeprArrayComparionIgnored =
12591 S.getDiagnostics().isIgnored(DiagID: diag::warn_depr_array_comparison, Loc);
12592 auto DiagID = S.getLangOpts().CPlusPlus26
12593 ? diag::warn_array_comparison_cxx26
12594 : !S.getLangOpts().CPlusPlus20 || IsDeprArrayComparionIgnored
12595 ? diag::warn_array_comparison
12596 : diag::warn_depr_array_comparison;
12597 S.Diag(Loc, DiagID) << LHS->getSourceRange() << RHS->getSourceRange()
12598 << LHSStripped->getType() << RHSStripped->getType();
12599 // Carry on to produce the tautological comparison warning, if this
12600 // expression is potentially-evaluated, we can resolve the array to a
12601 // non-weak declaration, and so on.
12602 }
12603
12604 if (!LHS->getBeginLoc().isMacroID() && !RHS->getBeginLoc().isMacroID()) {
12605 if (Expr::isSameComparisonOperand(E1: LHS, E2: RHS)) {
12606 unsigned Result;
12607 switch (Opc) {
12608 case BO_EQ:
12609 case BO_LE:
12610 case BO_GE:
12611 Result = AlwaysTrue;
12612 break;
12613 case BO_NE:
12614 case BO_LT:
12615 case BO_GT:
12616 Result = AlwaysFalse;
12617 break;
12618 case BO_Cmp:
12619 Result = AlwaysEqual;
12620 break;
12621 default:
12622 Result = AlwaysConstant;
12623 break;
12624 }
12625 S.DiagRuntimeBehavior(Loc, Statement: nullptr,
12626 PD: S.PDiag(DiagID: diag::warn_comparison_always)
12627 << 0 /*self-comparison*/
12628 << Result);
12629 } else if (checkForArray(E: LHSStripped) && checkForArray(E: RHSStripped)) {
12630 // What is it always going to evaluate to?
12631 unsigned Result;
12632 switch (Opc) {
12633 case BO_EQ: // e.g. array1 == array2
12634 Result = AlwaysFalse;
12635 break;
12636 case BO_NE: // e.g. array1 != array2
12637 Result = AlwaysTrue;
12638 break;
12639 default: // e.g. array1 <= array2
12640 // The best we can say is 'a constant'
12641 Result = AlwaysConstant;
12642 break;
12643 }
12644 S.DiagRuntimeBehavior(Loc, Statement: nullptr,
12645 PD: S.PDiag(DiagID: diag::warn_comparison_always)
12646 << 1 /*array comparison*/
12647 << Result);
12648 } else if (std::optional<bool> Res =
12649 isTautologicalBoundsCheck(S, LHS, RHS, Opc)) {
12650 S.DiagRuntimeBehavior(Loc, Statement: nullptr,
12651 PD: S.PDiag(DiagID: diag::warn_comparison_always)
12652 << 2 /*pointer comparison*/
12653 << (*Res ? AlwaysTrue : AlwaysFalse));
12654 }
12655 }
12656
12657 if (isa<CastExpr>(Val: LHSStripped))
12658 LHSStripped = LHSStripped->IgnoreParenCasts();
12659 if (isa<CastExpr>(Val: RHSStripped))
12660 RHSStripped = RHSStripped->IgnoreParenCasts();
12661
12662 // Warn about comparisons against a string constant (unless the other
12663 // operand is null); the user probably wants string comparison function.
12664 Expr *LiteralString = nullptr;
12665 Expr *LiteralStringStripped = nullptr;
12666 if ((isa<StringLiteral>(Val: LHSStripped) || isa<ObjCEncodeExpr>(Val: LHSStripped)) &&
12667 !RHSStripped->isNullPointerConstant(Ctx&: S.Context,
12668 NPC: Expr::NPC_ValueDependentIsNull)) {
12669 LiteralString = LHS;
12670 LiteralStringStripped = LHSStripped;
12671 } else if ((isa<StringLiteral>(Val: RHSStripped) ||
12672 isa<ObjCEncodeExpr>(Val: RHSStripped)) &&
12673 !LHSStripped->isNullPointerConstant(Ctx&: S.Context,
12674 NPC: Expr::NPC_ValueDependentIsNull)) {
12675 LiteralString = RHS;
12676 LiteralStringStripped = RHSStripped;
12677 }
12678
12679 if (LiteralString) {
12680 S.DiagRuntimeBehavior(Loc, Statement: nullptr,
12681 PD: S.PDiag(DiagID: diag::warn_stringcompare)
12682 << isa<ObjCEncodeExpr>(Val: LiteralStringStripped)
12683 << LiteralString->getSourceRange());
12684 }
12685}
12686
12687static ImplicitConversionKind castKindToImplicitConversionKind(CastKind CK) {
12688 switch (CK) {
12689 default: {
12690#ifndef NDEBUG
12691 llvm::errs() << "unhandled cast kind: " << CastExpr::getCastKindName(CK)
12692 << "\n";
12693#endif
12694 llvm_unreachable("unhandled cast kind");
12695 }
12696 case CK_UserDefinedConversion:
12697 return ICK_Identity;
12698 case CK_LValueToRValue:
12699 return ICK_Lvalue_To_Rvalue;
12700 case CK_ArrayToPointerDecay:
12701 return ICK_Array_To_Pointer;
12702 case CK_FunctionToPointerDecay:
12703 return ICK_Function_To_Pointer;
12704 case CK_IntegralCast:
12705 return ICK_Integral_Conversion;
12706 case CK_FloatingCast:
12707 return ICK_Floating_Conversion;
12708 case CK_IntegralToFloating:
12709 case CK_FloatingToIntegral:
12710 return ICK_Floating_Integral;
12711 case CK_IntegralComplexCast:
12712 case CK_FloatingComplexCast:
12713 case CK_FloatingComplexToIntegralComplex:
12714 case CK_IntegralComplexToFloatingComplex:
12715 return ICK_Complex_Conversion;
12716 case CK_FloatingComplexToReal:
12717 case CK_FloatingRealToComplex:
12718 case CK_IntegralComplexToReal:
12719 case CK_IntegralRealToComplex:
12720 return ICK_Complex_Real;
12721 case CK_HLSLArrayRValue:
12722 return ICK_HLSL_Array_RValue;
12723 }
12724}
12725
12726static bool checkThreeWayNarrowingConversion(Sema &S, QualType ToType, Expr *E,
12727 QualType FromType,
12728 SourceLocation Loc) {
12729 // Check for a narrowing implicit conversion.
12730 StandardConversionSequence SCS;
12731 SCS.setAsIdentityConversion();
12732 SCS.setToType(Idx: 0, T: FromType);
12733 SCS.setToType(Idx: 1, T: ToType);
12734 if (const auto *ICE = dyn_cast<ImplicitCastExpr>(Val: E))
12735 SCS.Second = castKindToImplicitConversionKind(CK: ICE->getCastKind());
12736
12737 APValue PreNarrowingValue;
12738 QualType PreNarrowingType;
12739 switch (SCS.getNarrowingKind(Context&: S.Context, Converted: E, ConstantValue&: PreNarrowingValue,
12740 ConstantType&: PreNarrowingType,
12741 /*IgnoreFloatToIntegralConversion*/ true)) {
12742 case NK_Dependent_Narrowing:
12743 // Implicit conversion to a narrower type, but the expression is
12744 // value-dependent so we can't tell whether it's actually narrowing.
12745 case NK_Not_Narrowing:
12746 return false;
12747
12748 case NK_Constant_Narrowing:
12749 // Implicit conversion to a narrower type, and the value is not a constant
12750 // expression.
12751 S.Diag(Loc: E->getBeginLoc(), DiagID: diag::err_spaceship_argument_narrowing)
12752 << /*Constant*/ 1
12753 << PreNarrowingValue.getAsString(Ctx: S.Context, Ty: PreNarrowingType) << ToType;
12754 return true;
12755
12756 case NK_Variable_Narrowing:
12757 // Implicit conversion to a narrower type, and the value is not a constant
12758 // expression.
12759 case NK_Type_Narrowing:
12760 S.Diag(Loc: E->getBeginLoc(), DiagID: diag::err_spaceship_argument_narrowing)
12761 << /*Constant*/ 0 << FromType << ToType;
12762 // TODO: It's not a constant expression, but what if the user intended it
12763 // to be? Can we produce notes to help them figure out why it isn't?
12764 return true;
12765 }
12766 llvm_unreachable("unhandled case in switch");
12767}
12768
12769static QualType checkArithmeticOrEnumeralThreeWayCompare(Sema &S,
12770 ExprResult &LHS,
12771 ExprResult &RHS,
12772 SourceLocation Loc) {
12773 QualType LHSType = LHS.get()->getType();
12774 QualType RHSType = RHS.get()->getType();
12775 // Dig out the original argument type and expression before implicit casts
12776 // were applied. These are the types/expressions we need to check the
12777 // [expr.spaceship] requirements against.
12778 ExprResult LHSStripped = LHS.get()->IgnoreParenImpCasts();
12779 ExprResult RHSStripped = RHS.get()->IgnoreParenImpCasts();
12780 QualType LHSStrippedType = LHSStripped.get()->getType();
12781 QualType RHSStrippedType = RHSStripped.get()->getType();
12782
12783 // C++2a [expr.spaceship]p3: If one of the operands is of type bool and the
12784 // other is not, the program is ill-formed.
12785 if (LHSStrippedType->isBooleanType() != RHSStrippedType->isBooleanType()) {
12786 S.InvalidOperands(Loc, LHS&: LHSStripped, RHS&: RHSStripped);
12787 return QualType();
12788 }
12789
12790 // FIXME: Consider combining this with checkEnumArithmeticConversions.
12791 int NumEnumArgs = (int)LHSStrippedType->isEnumeralType() +
12792 RHSStrippedType->isEnumeralType();
12793 if (NumEnumArgs == 1) {
12794 bool LHSIsEnum = LHSStrippedType->isEnumeralType();
12795 QualType OtherTy = LHSIsEnum ? RHSStrippedType : LHSStrippedType;
12796 if (OtherTy->hasFloatingRepresentation()) {
12797 S.InvalidOperands(Loc, LHS&: LHSStripped, RHS&: RHSStripped);
12798 return QualType();
12799 }
12800 }
12801 if (NumEnumArgs == 2) {
12802 // C++2a [expr.spaceship]p5: If both operands have the same enumeration
12803 // type E, the operator yields the result of converting the operands
12804 // to the underlying type of E and applying <=> to the converted operands.
12805 if (!S.Context.hasSameUnqualifiedType(T1: LHSStrippedType, T2: RHSStrippedType)) {
12806 S.InvalidOperands(Loc, LHS, RHS);
12807 return QualType();
12808 }
12809 QualType IntType = LHSStrippedType->castAsEnumDecl()->getIntegerType();
12810 assert(IntType->isArithmeticType());
12811
12812 // We can't use `CK_IntegralCast` when the underlying type is 'bool', so we
12813 // promote the boolean type, and all other promotable integer types, to
12814 // avoid this.
12815 if (S.Context.isPromotableIntegerType(T: IntType))
12816 IntType = S.Context.getPromotedIntegerType(PromotableType: IntType);
12817
12818 LHS = S.ImpCastExprToType(E: LHS.get(), Type: IntType, CK: CK_IntegralCast);
12819 RHS = S.ImpCastExprToType(E: RHS.get(), Type: IntType, CK: CK_IntegralCast);
12820 LHSType = RHSType = IntType;
12821 }
12822
12823 // C++2a [expr.spaceship]p4: If both operands have arithmetic types, the
12824 // usual arithmetic conversions are applied to the operands.
12825 QualType Type =
12826 S.UsualArithmeticConversions(LHS, RHS, Loc, ACK: ArithConvKind::Comparison);
12827 if (LHS.isInvalid() || RHS.isInvalid())
12828 return QualType();
12829 if (Type.isNull()) {
12830 QualType ResultTy = S.InvalidOperands(Loc, LHS, RHS);
12831 diagnoseScopedEnums(S, Loc, LHS, RHS, Opc: BO_Cmp);
12832 return ResultTy;
12833 }
12834
12835 std::optional<ComparisonCategoryType> CCT =
12836 getComparisonCategoryForBuiltinCmp(T: Type);
12837 if (!CCT)
12838 return S.InvalidOperands(Loc, LHS, RHS);
12839
12840 bool HasNarrowing = checkThreeWayNarrowingConversion(
12841 S, ToType: Type, E: LHS.get(), FromType: LHSType, Loc: LHS.get()->getBeginLoc());
12842 HasNarrowing |= checkThreeWayNarrowingConversion(S, ToType: Type, E: RHS.get(), FromType: RHSType,
12843 Loc: RHS.get()->getBeginLoc());
12844 if (HasNarrowing)
12845 return QualType();
12846
12847 assert(!Type.isNull() && "composite type for <=> has not been set");
12848
12849 return S.CheckComparisonCategoryType(
12850 Kind: *CCT, Loc, Usage: Sema::ComparisonCategoryUsage::OperatorInExpression);
12851}
12852
12853static QualType checkArithmeticOrEnumeralCompare(Sema &S, ExprResult &LHS,
12854 ExprResult &RHS,
12855 SourceLocation Loc,
12856 BinaryOperatorKind Opc) {
12857 if (Opc == BO_Cmp)
12858 return checkArithmeticOrEnumeralThreeWayCompare(S, LHS, RHS, Loc);
12859
12860 // C99 6.5.8p3 / C99 6.5.9p4
12861 QualType Type =
12862 S.UsualArithmeticConversions(LHS, RHS, Loc, ACK: ArithConvKind::Comparison);
12863 if (LHS.isInvalid() || RHS.isInvalid())
12864 return QualType();
12865 if (Type.isNull()) {
12866 QualType ResultTy = S.InvalidOperands(Loc, LHS, RHS);
12867 diagnoseScopedEnums(S, Loc, LHS, RHS, Opc);
12868 return ResultTy;
12869 }
12870 assert(Type->isArithmeticType() || Type->isEnumeralType());
12871
12872 if (Type->isAnyComplexType() && BinaryOperator::isRelationalOp(Opc))
12873 return S.InvalidOperands(Loc, LHS, RHS);
12874
12875 // Check for comparisons of floating point operands using != and ==.
12876 if (Type->hasFloatingRepresentation())
12877 S.CheckFloatComparison(Loc, LHS: LHS.get(), RHS: RHS.get(), Opcode: Opc);
12878
12879 // The result of comparisons is 'bool' in C++, 'int' in C.
12880 return S.Context.getLogicalOperationType();
12881}
12882
12883void Sema::CheckPtrComparisonWithNullChar(ExprResult &E, ExprResult &NullE) {
12884 if (!NullE.get()->getType()->isAnyPointerType())
12885 return;
12886 int NullValue = PP.isMacroDefined(Id: "NULL") ? 0 : 1;
12887 if (!E.get()->getType()->isAnyPointerType() &&
12888 E.get()->isNullPointerConstant(Ctx&: Context,
12889 NPC: Expr::NPC_ValueDependentIsNotNull) ==
12890 Expr::NPCK_ZeroExpression) {
12891 if (const auto *CL = dyn_cast<CharacterLiteral>(Val: E.get())) {
12892 if (CL->getValue() == 0)
12893 Diag(Loc: E.get()->getExprLoc(), DiagID: diag::warn_pointer_compare)
12894 << NullValue
12895 << FixItHint::CreateReplacement(RemoveRange: E.get()->getExprLoc(),
12896 Code: NullValue ? "NULL" : "(void *)0");
12897 } else if (const auto *CE = dyn_cast<CStyleCastExpr>(Val: E.get())) {
12898 TypeSourceInfo *TI = CE->getTypeInfoAsWritten();
12899 QualType T = Context.getCanonicalType(T: TI->getType()).getUnqualifiedType();
12900 if (T == Context.CharTy)
12901 Diag(Loc: E.get()->getExprLoc(), DiagID: diag::warn_pointer_compare)
12902 << NullValue
12903 << FixItHint::CreateReplacement(RemoveRange: E.get()->getExprLoc(),
12904 Code: NullValue ? "NULL" : "(void *)0");
12905 }
12906 }
12907}
12908
12909// C99 6.5.8, C++ [expr.rel]
12910QualType Sema::CheckCompareOperands(ExprResult &LHS, ExprResult &RHS,
12911 SourceLocation Loc,
12912 BinaryOperatorKind Opc) {
12913 bool IsRelational = BinaryOperator::isRelationalOp(Opc);
12914 bool IsThreeWay = Opc == BO_Cmp;
12915 bool IsOrdered = IsRelational || IsThreeWay;
12916 auto IsAnyPointerType = [](ExprResult E) {
12917 QualType Ty = E.get()->getType();
12918 return Ty->isPointerType() || Ty->isMemberPointerType();
12919 };
12920
12921 // C++2a [expr.spaceship]p6: If at least one of the operands is of pointer
12922 // type, array-to-pointer, ..., conversions are performed on both operands to
12923 // bring them to their composite type.
12924 // Otherwise, all comparisons expect an rvalue, so convert to rvalue before
12925 // any type-related checks.
12926 if (!IsThreeWay || IsAnyPointerType(LHS) || IsAnyPointerType(RHS)) {
12927 LHS = DefaultFunctionArrayLvalueConversion(E: LHS.get());
12928 if (LHS.isInvalid())
12929 return QualType();
12930 RHS = DefaultFunctionArrayLvalueConversion(E: RHS.get());
12931 if (RHS.isInvalid())
12932 return QualType();
12933 } else {
12934 LHS = DefaultLvalueConversion(E: LHS.get());
12935 if (LHS.isInvalid())
12936 return QualType();
12937 RHS = DefaultLvalueConversion(E: RHS.get());
12938 if (RHS.isInvalid())
12939 return QualType();
12940 }
12941
12942 checkArithmeticNull(S&: *this, LHS, RHS, Loc, /*IsCompare=*/true);
12943 if (!getLangOpts().CPlusPlus && BinaryOperator::isEqualityOp(Opc)) {
12944 CheckPtrComparisonWithNullChar(E&: LHS, NullE&: RHS);
12945 CheckPtrComparisonWithNullChar(E&: RHS, NullE&: LHS);
12946 }
12947
12948 // Handle vector comparisons separately.
12949 if (LHS.get()->getType()->isVectorType() ||
12950 RHS.get()->getType()->isVectorType())
12951 return CheckVectorCompareOperands(LHS, RHS, Loc, Opc);
12952
12953 if (LHS.get()->getType()->isSveVLSBuiltinType() ||
12954 RHS.get()->getType()->isSveVLSBuiltinType())
12955 return CheckSizelessVectorCompareOperands(LHS, RHS, Loc, Opc);
12956
12957 diagnoseLogicalNotOnLHSofCheck(S&: *this, LHS, RHS, Loc, Opc);
12958 diagnoseTautologicalComparison(S&: *this, Loc, LHS: LHS.get(), RHS: RHS.get(), Opc);
12959
12960 QualType LHSType = LHS.get()->getType();
12961 QualType RHSType = RHS.get()->getType();
12962 if ((LHSType->isArithmeticType() || LHSType->isEnumeralType()) &&
12963 (RHSType->isArithmeticType() || RHSType->isEnumeralType()))
12964 return checkArithmeticOrEnumeralCompare(S&: *this, LHS, RHS, Loc, Opc);
12965
12966 if ((LHSType->isPointerType() &&
12967 LHSType->getPointeeType().isWebAssemblyReferenceType()) ||
12968 (RHSType->isPointerType() &&
12969 RHSType->getPointeeType().isWebAssemblyReferenceType()))
12970 return InvalidOperands(Loc, LHS, RHS);
12971
12972 const Expr::NullPointerConstantKind LHSNullKind =
12973 LHS.get()->isNullPointerConstant(Ctx&: Context, NPC: Expr::NPC_ValueDependentIsNull);
12974 const Expr::NullPointerConstantKind RHSNullKind =
12975 RHS.get()->isNullPointerConstant(Ctx&: Context, NPC: Expr::NPC_ValueDependentIsNull);
12976 bool LHSIsNull = LHSNullKind != Expr::NPCK_NotNull;
12977 bool RHSIsNull = RHSNullKind != Expr::NPCK_NotNull;
12978
12979 auto computeResultTy = [&]() {
12980 if (Opc != BO_Cmp)
12981 return QualType(Context.getLogicalOperationType());
12982 assert(getLangOpts().CPlusPlus);
12983 assert(Context.hasSameType(LHS.get()->getType(), RHS.get()->getType()));
12984
12985 QualType CompositeTy = LHS.get()->getType();
12986 assert(!CompositeTy->isReferenceType());
12987
12988 std::optional<ComparisonCategoryType> CCT =
12989 getComparisonCategoryForBuiltinCmp(T: CompositeTy);
12990 if (!CCT)
12991 return InvalidOperands(Loc, LHS, RHS);
12992
12993 if (CompositeTy->isPointerType() && LHSIsNull != RHSIsNull) {
12994 // P0946R0: Comparisons between a null pointer constant and an object
12995 // pointer result in std::strong_equality, which is ill-formed under
12996 // P1959R0.
12997 Diag(Loc, DiagID: diag::err_typecheck_three_way_comparison_of_pointer_and_zero)
12998 << (LHSIsNull ? LHS.get()->getSourceRange()
12999 : RHS.get()->getSourceRange());
13000 return QualType();
13001 }
13002
13003 return CheckComparisonCategoryType(
13004 Kind: *CCT, Loc, Usage: ComparisonCategoryUsage::OperatorInExpression);
13005 };
13006
13007 if (!IsOrdered && LHSIsNull != RHSIsNull) {
13008 bool IsEquality = Opc == BO_EQ;
13009 if (RHSIsNull)
13010 DiagnoseAlwaysNonNullPointer(E: LHS.get(), NullType: RHSNullKind, IsEqual: IsEquality,
13011 Range: RHS.get()->getSourceRange());
13012 else
13013 DiagnoseAlwaysNonNullPointer(E: RHS.get(), NullType: LHSNullKind, IsEqual: IsEquality,
13014 Range: LHS.get()->getSourceRange());
13015 }
13016
13017 if (IsOrdered && LHSType->isFunctionPointerType() &&
13018 RHSType->isFunctionPointerType()) {
13019 // Valid unless a relational comparison of function pointers
13020 bool IsError = Opc == BO_Cmp;
13021 auto DiagID =
13022 IsError ? diag::err_typecheck_ordered_comparison_of_function_pointers
13023 : getLangOpts().CPlusPlus
13024 ? diag::warn_typecheck_ordered_comparison_of_function_pointers
13025 : diag::ext_typecheck_ordered_comparison_of_function_pointers;
13026 Diag(Loc, DiagID) << LHSType << RHSType << LHS.get()->getSourceRange()
13027 << RHS.get()->getSourceRange();
13028 if (IsError)
13029 return QualType();
13030 }
13031
13032 if ((LHSType->isIntegerType() && !LHSIsNull) ||
13033 (RHSType->isIntegerType() && !RHSIsNull)) {
13034 // Skip normal pointer conversion checks in this case; we have better
13035 // diagnostics for this below.
13036 } else if (getLangOpts().CPlusPlus) {
13037 // Equality comparison of a function pointer to a void pointer is invalid,
13038 // but we allow it as an extension.
13039 // FIXME: If we really want to allow this, should it be part of composite
13040 // pointer type computation so it works in conditionals too?
13041 if (!IsOrdered &&
13042 ((LHSType->isFunctionPointerType() && RHSType->isVoidPointerType()) ||
13043 (RHSType->isFunctionPointerType() && LHSType->isVoidPointerType()))) {
13044 // This is a gcc extension compatibility comparison.
13045 // In a SFINAE context, we treat this as a hard error to maintain
13046 // conformance with the C++ standard.
13047 bool IsError = isSFINAEContext();
13048 diagnoseFunctionPointerToVoidComparison(S&: *this, Loc, LHS, RHS, IsError);
13049
13050 if (IsError)
13051 return QualType();
13052
13053 RHS = ImpCastExprToType(E: RHS.get(), Type: LHSType, CK: CK_BitCast);
13054 return computeResultTy();
13055 }
13056
13057 // C++ [expr.eq]p2:
13058 // If at least one operand is a pointer [...] bring them to their
13059 // composite pointer type.
13060 // C++ [expr.spaceship]p6
13061 // If at least one of the operands is of pointer type, [...] bring them
13062 // to their composite pointer type.
13063 // C++ [expr.rel]p2:
13064 // If both operands are pointers, [...] bring them to their composite
13065 // pointer type.
13066 // For <=>, the only valid non-pointer types are arrays and functions, and
13067 // we already decayed those, so this is really the same as the relational
13068 // comparison rule.
13069 if ((int)LHSType->isPointerType() + (int)RHSType->isPointerType() >=
13070 (IsOrdered ? 2 : 1) &&
13071 (!LangOpts.ObjCAutoRefCount || !(LHSType->isObjCObjectPointerType() ||
13072 RHSType->isObjCObjectPointerType()))) {
13073 if (convertPointersToCompositeType(S&: *this, Loc, LHS, RHS))
13074 return QualType();
13075 return computeResultTy();
13076 }
13077 } else if (LHSType->isPointerType() &&
13078 RHSType->isPointerType()) { // C99 6.5.8p2
13079 // All of the following pointer-related warnings are GCC extensions, except
13080 // when handling null pointer constants.
13081 QualType LCanPointeeTy =
13082 LHSType->castAs<PointerType>()->getPointeeType().getCanonicalType();
13083 QualType RCanPointeeTy =
13084 RHSType->castAs<PointerType>()->getPointeeType().getCanonicalType();
13085
13086 // C99 6.5.9p2 and C99 6.5.8p2
13087 if (Context.typesAreCompatible(T1: LCanPointeeTy.getUnqualifiedType(),
13088 T2: RCanPointeeTy.getUnqualifiedType())) {
13089 if (IsRelational) {
13090 // Pointers both need to point to complete or incomplete types
13091 if ((LCanPointeeTy->isIncompleteType() !=
13092 RCanPointeeTy->isIncompleteType()) &&
13093 !getLangOpts().C11) {
13094 Diag(Loc, DiagID: diag::ext_typecheck_compare_complete_incomplete_pointers)
13095 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange()
13096 << LHSType << RHSType << LCanPointeeTy->isIncompleteType()
13097 << RCanPointeeTy->isIncompleteType();
13098 }
13099 }
13100 } else if (!IsRelational &&
13101 (LCanPointeeTy->isVoidType() || RCanPointeeTy->isVoidType())) {
13102 // Valid unless comparison between non-null pointer and function pointer
13103 if ((LCanPointeeTy->isFunctionType() || RCanPointeeTy->isFunctionType())
13104 && !LHSIsNull && !RHSIsNull)
13105 diagnoseFunctionPointerToVoidComparison(S&: *this, Loc, LHS, RHS,
13106 /*isError*/IsError: false);
13107 } else {
13108 // Invalid
13109 diagnoseDistinctPointerComparison(S&: *this, Loc, LHS, RHS, /*isError*/IsError: false);
13110 }
13111 if (LCanPointeeTy != RCanPointeeTy) {
13112 // Treat NULL constant as a special case in OpenCL.
13113 if (getLangOpts().OpenCL && !LHSIsNull && !RHSIsNull) {
13114 if (!LCanPointeeTy.isAddressSpaceOverlapping(T: RCanPointeeTy,
13115 Ctx: getASTContext())) {
13116 Diag(Loc,
13117 DiagID: diag::err_typecheck_op_on_nonoverlapping_address_space_pointers)
13118 << LHSType << RHSType << 0 /* comparison */
13119 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
13120 }
13121 }
13122 LangAS AddrSpaceL = LCanPointeeTy.getAddressSpace();
13123 LangAS AddrSpaceR = RCanPointeeTy.getAddressSpace();
13124 CastKind Kind = AddrSpaceL != AddrSpaceR ? CK_AddressSpaceConversion
13125 : CK_BitCast;
13126
13127 const FunctionType *LFn = LCanPointeeTy->getAs<FunctionType>();
13128 const FunctionType *RFn = RCanPointeeTy->getAs<FunctionType>();
13129 bool LHSHasCFIUncheckedCallee = LFn && LFn->getCFIUncheckedCalleeAttr();
13130 bool RHSHasCFIUncheckedCallee = RFn && RFn->getCFIUncheckedCalleeAttr();
13131 bool ChangingCFIUncheckedCallee =
13132 LHSHasCFIUncheckedCallee != RHSHasCFIUncheckedCallee;
13133
13134 if (LHSIsNull && !RHSIsNull)
13135 LHS = ImpCastExprToType(E: LHS.get(), Type: RHSType, CK: Kind);
13136 else if (!ChangingCFIUncheckedCallee)
13137 RHS = ImpCastExprToType(E: RHS.get(), Type: LHSType, CK: Kind);
13138 }
13139 return computeResultTy();
13140 }
13141
13142
13143 // C++ [expr.eq]p4:
13144 // Two operands of type std::nullptr_t or one operand of type
13145 // std::nullptr_t and the other a null pointer constant compare
13146 // equal.
13147 // C23 6.5.9p5:
13148 // If both operands have type nullptr_t or one operand has type nullptr_t
13149 // and the other is a null pointer constant, they compare equal if the
13150 // former is a null pointer.
13151 if (!IsOrdered && LHSIsNull && RHSIsNull) {
13152 if (LHSType->isNullPtrType()) {
13153 RHS = ImpCastExprToType(E: RHS.get(), Type: LHSType, CK: CK_NullToPointer);
13154 return computeResultTy();
13155 }
13156 if (RHSType->isNullPtrType()) {
13157 LHS = ImpCastExprToType(E: LHS.get(), Type: RHSType, CK: CK_NullToPointer);
13158 return computeResultTy();
13159 }
13160 }
13161
13162 if (!getLangOpts().CPlusPlus && !IsOrdered && (LHSIsNull || RHSIsNull)) {
13163 // C23 6.5.9p6:
13164 // Otherwise, at least one operand is a pointer. If one is a pointer and
13165 // the other is a null pointer constant or has type nullptr_t, they
13166 // compare equal
13167 if (LHSIsNull && RHSType->isPointerType()) {
13168 LHS = ImpCastExprToType(E: LHS.get(), Type: RHSType, CK: CK_NullToPointer);
13169 return computeResultTy();
13170 }
13171 if (RHSIsNull && LHSType->isPointerType()) {
13172 RHS = ImpCastExprToType(E: RHS.get(), Type: LHSType, CK: CK_NullToPointer);
13173 return computeResultTy();
13174 }
13175 }
13176
13177 // Comparison of Objective-C pointers and block pointers against nullptr_t.
13178 // These aren't covered by the composite pointer type rules.
13179 if (!IsOrdered && RHSType->isNullPtrType() &&
13180 (LHSType->isObjCObjectPointerType() || LHSType->isBlockPointerType())) {
13181 RHS = ImpCastExprToType(E: RHS.get(), Type: LHSType, CK: CK_NullToPointer);
13182 return computeResultTy();
13183 }
13184 if (!IsOrdered && LHSType->isNullPtrType() &&
13185 (RHSType->isObjCObjectPointerType() || RHSType->isBlockPointerType())) {
13186 LHS = ImpCastExprToType(E: LHS.get(), Type: RHSType, CK: CK_NullToPointer);
13187 return computeResultTy();
13188 }
13189
13190 if (getLangOpts().CPlusPlus) {
13191 if (IsRelational &&
13192 ((LHSType->isNullPtrType() && RHSType->isPointerType()) ||
13193 (RHSType->isNullPtrType() && LHSType->isPointerType()))) {
13194 // HACK: Relational comparison of nullptr_t against a pointer type is
13195 // invalid per DR583, but we allow it within std::less<> and friends,
13196 // since otherwise common uses of it break.
13197 // FIXME: Consider removing this hack once LWG fixes std::less<> and
13198 // friends to have std::nullptr_t overload candidates.
13199 DeclContext *DC = CurContext;
13200 if (isa<FunctionDecl>(Val: DC))
13201 DC = DC->getParent();
13202 if (auto *CTSD = dyn_cast<ClassTemplateSpecializationDecl>(Val: DC)) {
13203 if (CTSD->isInStdNamespace() &&
13204 llvm::StringSwitch<bool>(CTSD->getName())
13205 .Cases(CaseStrings: {"less", "less_equal", "greater", "greater_equal"}, Value: true)
13206 .Default(Value: false)) {
13207 if (RHSType->isNullPtrType())
13208 RHS = ImpCastExprToType(E: RHS.get(), Type: LHSType, CK: CK_NullToPointer);
13209 else
13210 LHS = ImpCastExprToType(E: LHS.get(), Type: RHSType, CK: CK_NullToPointer);
13211 return computeResultTy();
13212 }
13213 }
13214 }
13215
13216 // C++ [expr.eq]p2:
13217 // If at least one operand is a pointer to member, [...] bring them to
13218 // their composite pointer type.
13219 if (!IsOrdered &&
13220 (LHSType->isMemberPointerType() || RHSType->isMemberPointerType())) {
13221 if (convertPointersToCompositeType(S&: *this, Loc, LHS, RHS))
13222 return QualType();
13223 else
13224 return computeResultTy();
13225 }
13226 }
13227
13228 // Handle block pointer types.
13229 if (!IsOrdered && LHSType->isBlockPointerType() &&
13230 RHSType->isBlockPointerType()) {
13231 QualType lpointee = LHSType->castAs<BlockPointerType>()->getPointeeType();
13232 QualType rpointee = RHSType->castAs<BlockPointerType>()->getPointeeType();
13233
13234 if (!LHSIsNull && !RHSIsNull &&
13235 !Context.typesAreCompatible(T1: lpointee, T2: rpointee)) {
13236 Diag(Loc, DiagID: diag::err_typecheck_comparison_of_distinct_blocks)
13237 << LHSType << RHSType << LHS.get()->getSourceRange()
13238 << RHS.get()->getSourceRange();
13239 }
13240 RHS = ImpCastExprToType(E: RHS.get(), Type: LHSType, CK: CK_BitCast);
13241 return computeResultTy();
13242 }
13243
13244 // Allow block pointers to be compared with null pointer constants.
13245 if (!IsOrdered
13246 && ((LHSType->isBlockPointerType() && RHSType->isPointerType())
13247 || (LHSType->isPointerType() && RHSType->isBlockPointerType()))) {
13248 if (!LHSIsNull && !RHSIsNull) {
13249 if (!((RHSType->isPointerType() && RHSType->castAs<PointerType>()
13250 ->getPointeeType()->isVoidType())
13251 || (LHSType->isPointerType() && LHSType->castAs<PointerType>()
13252 ->getPointeeType()->isVoidType())))
13253 Diag(Loc, DiagID: diag::err_typecheck_comparison_of_distinct_blocks)
13254 << LHSType << RHSType << LHS.get()->getSourceRange()
13255 << RHS.get()->getSourceRange();
13256 }
13257 if (LHSIsNull && !RHSIsNull)
13258 LHS = ImpCastExprToType(E: LHS.get(), Type: RHSType,
13259 CK: RHSType->isPointerType() ? CK_BitCast
13260 : CK_AnyPointerToBlockPointerCast);
13261 else
13262 RHS = ImpCastExprToType(E: RHS.get(), Type: LHSType,
13263 CK: LHSType->isPointerType() ? CK_BitCast
13264 : CK_AnyPointerToBlockPointerCast);
13265 return computeResultTy();
13266 }
13267
13268 if (LHSType->isObjCObjectPointerType() ||
13269 RHSType->isObjCObjectPointerType()) {
13270 const PointerType *LPT = LHSType->getAs<PointerType>();
13271 const PointerType *RPT = RHSType->getAs<PointerType>();
13272 if (LPT || RPT) {
13273 bool LPtrToVoid = LPT ? LPT->getPointeeType()->isVoidType() : false;
13274 bool RPtrToVoid = RPT ? RPT->getPointeeType()->isVoidType() : false;
13275
13276 if (!LPtrToVoid && !RPtrToVoid &&
13277 !Context.typesAreCompatible(T1: LHSType, T2: RHSType)) {
13278 diagnoseDistinctPointerComparison(S&: *this, Loc, LHS, RHS,
13279 /*isError*/IsError: false);
13280 }
13281 // FIXME: If LPtrToVoid, we should presumably convert the LHS rather than
13282 // the RHS, but we have test coverage for this behavior.
13283 // FIXME: Consider using convertPointersToCompositeType in C++.
13284 if (LHSIsNull && !RHSIsNull) {
13285 Expr *E = LHS.get();
13286 if (getLangOpts().ObjCAutoRefCount)
13287 ObjC().CheckObjCConversion(castRange: SourceRange(), castType: RHSType, op&: E,
13288 CCK: CheckedConversionKind::Implicit);
13289 LHS = ImpCastExprToType(E, Type: RHSType,
13290 CK: RPT ? CK_BitCast :CK_CPointerToObjCPointerCast);
13291 }
13292 else {
13293 Expr *E = RHS.get();
13294 if (getLangOpts().ObjCAutoRefCount)
13295 ObjC().CheckObjCConversion(castRange: SourceRange(), castType: LHSType, op&: E,
13296 CCK: CheckedConversionKind::Implicit,
13297 /*Diagnose=*/true,
13298 /*DiagnoseCFAudited=*/false, Opc);
13299 RHS = ImpCastExprToType(E, Type: LHSType,
13300 CK: LPT ? CK_BitCast :CK_CPointerToObjCPointerCast);
13301 }
13302 return computeResultTy();
13303 }
13304 if (LHSType->isObjCObjectPointerType() &&
13305 RHSType->isObjCObjectPointerType()) {
13306 if (!Context.areComparableObjCPointerTypes(LHS: LHSType, RHS: RHSType))
13307 diagnoseDistinctPointerComparison(S&: *this, Loc, LHS, RHS,
13308 /*isError*/IsError: false);
13309 if (isObjCObjectLiteral(E&: LHS) || isObjCObjectLiteral(E&: RHS))
13310 diagnoseObjCLiteralComparison(S&: *this, Loc, LHS, RHS, Opc);
13311
13312 if (LHSIsNull && !RHSIsNull)
13313 LHS = ImpCastExprToType(E: LHS.get(), Type: RHSType, CK: CK_BitCast);
13314 else
13315 RHS = ImpCastExprToType(E: RHS.get(), Type: LHSType, CK: CK_BitCast);
13316 return computeResultTy();
13317 }
13318
13319 if (!IsOrdered && LHSType->isBlockPointerType() &&
13320 RHSType->isBlockCompatibleObjCPointerType(ctx&: Context)) {
13321 LHS = ImpCastExprToType(E: LHS.get(), Type: RHSType,
13322 CK: CK_BlockPointerToObjCPointerCast);
13323 return computeResultTy();
13324 } else if (!IsOrdered &&
13325 LHSType->isBlockCompatibleObjCPointerType(ctx&: Context) &&
13326 RHSType->isBlockPointerType()) {
13327 RHS = ImpCastExprToType(E: RHS.get(), Type: LHSType,
13328 CK: CK_BlockPointerToObjCPointerCast);
13329 return computeResultTy();
13330 }
13331 }
13332 if ((LHSType->isAnyPointerType() && RHSType->isIntegerType()) ||
13333 (LHSType->isIntegerType() && RHSType->isAnyPointerType())) {
13334 unsigned DiagID = 0;
13335 bool isError = false;
13336 if (LangOpts.DebuggerSupport) {
13337 // Under a debugger, allow the comparison of pointers to integers,
13338 // since users tend to want to compare addresses.
13339 } else if ((LHSIsNull && LHSType->isIntegerType()) ||
13340 (RHSIsNull && RHSType->isIntegerType())) {
13341 if (IsOrdered) {
13342 isError = getLangOpts().CPlusPlus;
13343 DiagID =
13344 isError ? diag::err_typecheck_ordered_comparison_of_pointer_and_zero
13345 : diag::ext_typecheck_ordered_comparison_of_pointer_and_zero;
13346 }
13347 } else if (getLangOpts().CPlusPlus) {
13348 DiagID = diag::err_typecheck_comparison_of_pointer_integer;
13349 isError = true;
13350 } else if (IsOrdered)
13351 DiagID = diag::ext_typecheck_ordered_comparison_of_pointer_integer;
13352 else
13353 DiagID = diag::ext_typecheck_comparison_of_pointer_integer;
13354
13355 if (DiagID) {
13356 Diag(Loc, DiagID)
13357 << LHSType << RHSType << LHS.get()->getSourceRange()
13358 << RHS.get()->getSourceRange();
13359 if (isError)
13360 return QualType();
13361 }
13362
13363 if (LHSType->isIntegerType())
13364 LHS = ImpCastExprToType(E: LHS.get(), Type: RHSType,
13365 CK: LHSIsNull ? CK_NullToPointer : CK_IntegralToPointer);
13366 else
13367 RHS = ImpCastExprToType(E: RHS.get(), Type: LHSType,
13368 CK: RHSIsNull ? CK_NullToPointer : CK_IntegralToPointer);
13369 return computeResultTy();
13370 }
13371
13372 // Handle block pointers.
13373 if (!IsOrdered && RHSIsNull
13374 && LHSType->isBlockPointerType() && RHSType->isIntegerType()) {
13375 RHS = ImpCastExprToType(E: RHS.get(), Type: LHSType, CK: CK_NullToPointer);
13376 return computeResultTy();
13377 }
13378 if (!IsOrdered && LHSIsNull
13379 && LHSType->isIntegerType() && RHSType->isBlockPointerType()) {
13380 LHS = ImpCastExprToType(E: LHS.get(), Type: RHSType, CK: CK_NullToPointer);
13381 return computeResultTy();
13382 }
13383
13384 if (getLangOpts().getOpenCLCompatibleVersion() >= 200) {
13385 if (LHSType->isClkEventT() && RHSType->isClkEventT()) {
13386 return computeResultTy();
13387 }
13388
13389 if (LHSType->isQueueT() && RHSType->isQueueT()) {
13390 return computeResultTy();
13391 }
13392
13393 if (LHSIsNull && RHSType->isQueueT()) {
13394 LHS = ImpCastExprToType(E: LHS.get(), Type: RHSType, CK: CK_NullToPointer);
13395 return computeResultTy();
13396 }
13397
13398 if (LHSType->isQueueT() && RHSIsNull) {
13399 RHS = ImpCastExprToType(E: RHS.get(), Type: LHSType, CK: CK_NullToPointer);
13400 return computeResultTy();
13401 }
13402 }
13403
13404 return InvalidOperands(Loc, LHS, RHS);
13405}
13406
13407QualType Sema::GetSignedVectorType(QualType V) {
13408 const VectorType *VTy = V->castAs<VectorType>();
13409 unsigned TypeSize = Context.getTypeSize(T: VTy->getElementType());
13410
13411 if (isa<ExtVectorType>(Val: VTy)) {
13412 if (VTy->isExtVectorBoolType())
13413 return Context.getExtVectorType(VectorType: Context.BoolTy, NumElts: VTy->getNumElements());
13414 if (TypeSize == Context.getTypeSize(T: Context.CharTy))
13415 return Context.getExtVectorType(VectorType: Context.CharTy, NumElts: VTy->getNumElements());
13416 if (TypeSize == Context.getTypeSize(T: Context.ShortTy))
13417 return Context.getExtVectorType(VectorType: Context.ShortTy, NumElts: VTy->getNumElements());
13418 if (TypeSize == Context.getTypeSize(T: Context.IntTy))
13419 return Context.getExtVectorType(VectorType: Context.IntTy, NumElts: VTy->getNumElements());
13420 if (TypeSize == Context.getTypeSize(T: Context.Int128Ty))
13421 return Context.getExtVectorType(VectorType: Context.Int128Ty, NumElts: VTy->getNumElements());
13422 if (TypeSize == Context.getTypeSize(T: Context.LongTy))
13423 return Context.getExtVectorType(VectorType: Context.LongTy, NumElts: VTy->getNumElements());
13424 assert(TypeSize == Context.getTypeSize(Context.LongLongTy) &&
13425 "Unhandled vector element size in vector compare");
13426 return Context.getExtVectorType(VectorType: Context.LongLongTy, NumElts: VTy->getNumElements());
13427 }
13428
13429 if (TypeSize == Context.getTypeSize(T: Context.Int128Ty))
13430 return Context.getVectorType(VectorType: Context.Int128Ty, NumElts: VTy->getNumElements(),
13431 VecKind: VectorKind::Generic);
13432 if (TypeSize == Context.getTypeSize(T: Context.LongLongTy))
13433 return Context.getVectorType(VectorType: Context.LongLongTy, NumElts: VTy->getNumElements(),
13434 VecKind: VectorKind::Generic);
13435 if (TypeSize == Context.getTypeSize(T: Context.LongTy))
13436 return Context.getVectorType(VectorType: Context.LongTy, NumElts: VTy->getNumElements(),
13437 VecKind: VectorKind::Generic);
13438 if (TypeSize == Context.getTypeSize(T: Context.IntTy))
13439 return Context.getVectorType(VectorType: Context.IntTy, NumElts: VTy->getNumElements(),
13440 VecKind: VectorKind::Generic);
13441 if (TypeSize == Context.getTypeSize(T: Context.ShortTy))
13442 return Context.getVectorType(VectorType: Context.ShortTy, NumElts: VTy->getNumElements(),
13443 VecKind: VectorKind::Generic);
13444 assert(TypeSize == Context.getTypeSize(Context.CharTy) &&
13445 "Unhandled vector element size in vector compare");
13446 return Context.getVectorType(VectorType: Context.CharTy, NumElts: VTy->getNumElements(),
13447 VecKind: VectorKind::Generic);
13448}
13449
13450QualType Sema::GetSignedSizelessVectorType(QualType V) {
13451 const BuiltinType *VTy = V->castAs<BuiltinType>();
13452 assert(VTy->isSizelessBuiltinType() && "expected sizeless type");
13453
13454 const QualType ETy = V->getSveEltType(Ctx: Context);
13455 const auto TypeSize = Context.getTypeSize(T: ETy);
13456
13457 const QualType IntTy = Context.getIntTypeForBitwidth(DestWidth: TypeSize, Signed: true);
13458 const llvm::ElementCount VecSize = Context.getBuiltinVectorTypeInfo(VecTy: VTy).EC;
13459 return Context.getScalableVectorType(EltTy: IntTy, NumElts: VecSize.getKnownMinValue());
13460}
13461
13462QualType Sema::CheckVectorCompareOperands(ExprResult &LHS, ExprResult &RHS,
13463 SourceLocation Loc,
13464 BinaryOperatorKind Opc) {
13465 if (Opc == BO_Cmp) {
13466 Diag(Loc, DiagID: diag::err_three_way_vector_comparison);
13467 return QualType();
13468 }
13469
13470 // Check to make sure we're operating on vectors of the same type and width,
13471 // Allowing one side to be a scalar of element type.
13472 QualType vType =
13473 CheckVectorOperands(LHS, RHS, Loc, /*isCompAssign*/ IsCompAssign: false,
13474 /*AllowBothBool*/ true,
13475 /*AllowBoolConversions*/ getLangOpts().ZVector,
13476 /*AllowBooleanOperation*/ AllowBoolOperation: true,
13477 /*ReportInvalid*/ true);
13478 if (vType.isNull())
13479 return vType;
13480
13481 QualType LHSType = LHS.get()->getType();
13482
13483 // Determine the return type of a vector compare. By default clang will return
13484 // a scalar for all vector compares except vector bool and vector pixel.
13485 // With the gcc compiler we will always return a vector type and with the xl
13486 // compiler we will always return a scalar type. This switch allows choosing
13487 // which behavior is prefered.
13488 if (getLangOpts().AltiVec) {
13489 switch (getLangOpts().getAltivecSrcCompat()) {
13490 case LangOptions::AltivecSrcCompatKind::Mixed:
13491 // If AltiVec, the comparison results in a numeric type, i.e.
13492 // bool for C++, int for C
13493 if (vType->castAs<VectorType>()->getVectorKind() ==
13494 VectorKind::AltiVecVector)
13495 return Context.getLogicalOperationType();
13496 else
13497 Diag(Loc, DiagID: diag::warn_deprecated_altivec_src_compat);
13498 break;
13499 case LangOptions::AltivecSrcCompatKind::GCC:
13500 // For GCC we always return the vector type.
13501 break;
13502 case LangOptions::AltivecSrcCompatKind::XL:
13503 return Context.getLogicalOperationType();
13504 break;
13505 }
13506 }
13507
13508 // For non-floating point types, check for self-comparisons of the form
13509 // x == x, x != x, x < x, etc. These always evaluate to a constant, and
13510 // often indicate logic errors in the program.
13511 diagnoseTautologicalComparison(S&: *this, Loc, LHS: LHS.get(), RHS: RHS.get(), Opc);
13512
13513 // Check for comparisons of floating point operands using != and ==.
13514 if (LHSType->hasFloatingRepresentation()) {
13515 assert(RHS.get()->getType()->hasFloatingRepresentation());
13516 CheckFloatComparison(Loc, LHS: LHS.get(), RHS: RHS.get(), Opcode: Opc);
13517 }
13518
13519 // Return a signed type for the vector.
13520 return GetSignedVectorType(V: vType);
13521}
13522
13523QualType Sema::CheckSizelessVectorCompareOperands(ExprResult &LHS,
13524 ExprResult &RHS,
13525 SourceLocation Loc,
13526 BinaryOperatorKind Opc) {
13527 if (Opc == BO_Cmp) {
13528 Diag(Loc, DiagID: diag::err_three_way_vector_comparison);
13529 return QualType();
13530 }
13531
13532 // Check to make sure we're operating on vectors of the same type and width,
13533 // Allowing one side to be a scalar of element type.
13534 QualType vType = CheckSizelessVectorOperands(
13535 LHS, RHS, Loc, /*isCompAssign*/ IsCompAssign: false, OperationKind: ArithConvKind::Comparison);
13536
13537 if (vType.isNull())
13538 return vType;
13539
13540 QualType LHSType = LHS.get()->getType();
13541
13542 // For non-floating point types, check for self-comparisons of the form
13543 // x == x, x != x, x < x, etc. These always evaluate to a constant, and
13544 // often indicate logic errors in the program.
13545 diagnoseTautologicalComparison(S&: *this, Loc, LHS: LHS.get(), RHS: RHS.get(), Opc);
13546
13547 // Check for comparisons of floating point operands using != and ==.
13548 if (LHSType->hasFloatingRepresentation()) {
13549 assert(RHS.get()->getType()->hasFloatingRepresentation());
13550 CheckFloatComparison(Loc, LHS: LHS.get(), RHS: RHS.get(), Opcode: Opc);
13551 }
13552
13553 const BuiltinType *LHSBuiltinTy = LHSType->getAs<BuiltinType>();
13554 const BuiltinType *RHSBuiltinTy = RHS.get()->getType()->getAs<BuiltinType>();
13555
13556 if (LHSBuiltinTy && RHSBuiltinTy && LHSBuiltinTy->isSVEBool() &&
13557 RHSBuiltinTy->isSVEBool())
13558 return LHSType;
13559
13560 // Return a signed type for the vector.
13561 return GetSignedSizelessVectorType(V: vType);
13562}
13563
13564static void diagnoseXorMisusedAsPow(Sema &S, const ExprResult &XorLHS,
13565 const ExprResult &XorRHS,
13566 const SourceLocation Loc) {
13567 // Do not diagnose macros.
13568 if (Loc.isMacroID())
13569 return;
13570
13571 // Do not diagnose if both LHS and RHS are macros.
13572 if (XorLHS.get()->getExprLoc().isMacroID() &&
13573 XorRHS.get()->getExprLoc().isMacroID())
13574 return;
13575
13576 bool Negative = false;
13577 bool ExplicitPlus = false;
13578 const auto *LHSInt = dyn_cast<IntegerLiteral>(Val: XorLHS.get());
13579 const auto *RHSInt = dyn_cast<IntegerLiteral>(Val: XorRHS.get());
13580
13581 if (!LHSInt)
13582 return;
13583 if (!RHSInt) {
13584 // Check negative literals.
13585 if (const auto *UO = dyn_cast<UnaryOperator>(Val: XorRHS.get())) {
13586 UnaryOperatorKind Opc = UO->getOpcode();
13587 if (Opc != UO_Minus && Opc != UO_Plus)
13588 return;
13589 RHSInt = dyn_cast<IntegerLiteral>(Val: UO->getSubExpr());
13590 if (!RHSInt)
13591 return;
13592 Negative = (Opc == UO_Minus);
13593 ExplicitPlus = !Negative;
13594 } else {
13595 return;
13596 }
13597 }
13598
13599 const llvm::APInt &LeftSideValue = LHSInt->getValue();
13600 llvm::APInt RightSideValue = RHSInt->getValue();
13601 if (LeftSideValue != 2 && LeftSideValue != 10)
13602 return;
13603
13604 if (LeftSideValue.getBitWidth() != RightSideValue.getBitWidth())
13605 return;
13606
13607 CharSourceRange ExprRange = CharSourceRange::getCharRange(
13608 B: LHSInt->getBeginLoc(), E: S.getLocForEndOfToken(Loc: RHSInt->getLocation()));
13609 llvm::StringRef ExprStr =
13610 Lexer::getSourceText(Range: ExprRange, SM: S.getSourceManager(), LangOpts: S.getLangOpts());
13611
13612 CharSourceRange XorRange =
13613 CharSourceRange::getCharRange(B: Loc, E: S.getLocForEndOfToken(Loc));
13614 llvm::StringRef XorStr =
13615 Lexer::getSourceText(Range: XorRange, SM: S.getSourceManager(), LangOpts: S.getLangOpts());
13616 // Do not diagnose if xor keyword/macro is used.
13617 if (XorStr == "xor")
13618 return;
13619
13620 std::string LHSStr = std::string(Lexer::getSourceText(
13621 Range: CharSourceRange::getTokenRange(R: LHSInt->getSourceRange()),
13622 SM: S.getSourceManager(), LangOpts: S.getLangOpts()));
13623 std::string RHSStr = std::string(Lexer::getSourceText(
13624 Range: CharSourceRange::getTokenRange(R: RHSInt->getSourceRange()),
13625 SM: S.getSourceManager(), LangOpts: S.getLangOpts()));
13626
13627 if (Negative) {
13628 RightSideValue = -RightSideValue;
13629 RHSStr = "-" + RHSStr;
13630 } else if (ExplicitPlus) {
13631 RHSStr = "+" + RHSStr;
13632 }
13633
13634 StringRef LHSStrRef = LHSStr;
13635 StringRef RHSStrRef = RHSStr;
13636 // Do not diagnose literals with digit separators, binary, hexadecimal, octal
13637 // literals.
13638 if (LHSStrRef.starts_with(Prefix: "0b") || LHSStrRef.starts_with(Prefix: "0B") ||
13639 RHSStrRef.starts_with(Prefix: "0b") || RHSStrRef.starts_with(Prefix: "0B") ||
13640 LHSStrRef.starts_with(Prefix: "0x") || LHSStrRef.starts_with(Prefix: "0X") ||
13641 RHSStrRef.starts_with(Prefix: "0x") || RHSStrRef.starts_with(Prefix: "0X") ||
13642 (LHSStrRef.size() > 1 && LHSStrRef.starts_with(Prefix: "0")) ||
13643 (RHSStrRef.size() > 1 && RHSStrRef.starts_with(Prefix: "0")) ||
13644 LHSStrRef.contains(C: '\'') || RHSStrRef.contains(C: '\''))
13645 return;
13646
13647 bool SuggestXor =
13648 S.getLangOpts().CPlusPlus || S.getPreprocessor().isMacroDefined(Id: "xor");
13649 const llvm::APInt XorValue = LeftSideValue ^ RightSideValue;
13650 int64_t RightSideIntValue = RightSideValue.getSExtValue();
13651 if (LeftSideValue == 2 && RightSideIntValue >= 0) {
13652 std::string SuggestedExpr = "1 << " + RHSStr;
13653 bool Overflow = false;
13654 llvm::APInt One = (LeftSideValue - 1);
13655 llvm::APInt PowValue = One.sshl_ov(Amt: RightSideValue, Overflow);
13656 if (Overflow) {
13657 if (RightSideIntValue < 64)
13658 S.Diag(Loc, DiagID: diag::warn_xor_used_as_pow_base)
13659 << ExprStr << toString(I: XorValue, Radix: 10, Signed: true) << ("1LL << " + RHSStr)
13660 << FixItHint::CreateReplacement(RemoveRange: ExprRange, Code: "1LL << " + RHSStr);
13661 else if (RightSideIntValue == 64)
13662 S.Diag(Loc, DiagID: diag::warn_xor_used_as_pow)
13663 << ExprStr << toString(I: XorValue, Radix: 10, Signed: true);
13664 else
13665 return;
13666 } else {
13667 S.Diag(Loc, DiagID: diag::warn_xor_used_as_pow_base_extra)
13668 << ExprStr << toString(I: XorValue, Radix: 10, Signed: true) << SuggestedExpr
13669 << toString(I: PowValue, Radix: 10, Signed: true)
13670 << FixItHint::CreateReplacement(
13671 RemoveRange: ExprRange, Code: (RightSideIntValue == 0) ? "1" : SuggestedExpr);
13672 }
13673
13674 S.Diag(Loc, DiagID: diag::note_xor_used_as_pow_silence)
13675 << ("0x2 ^ " + RHSStr) << SuggestXor;
13676 } else if (LeftSideValue == 10) {
13677 std::string SuggestedValue = "1e" + std::to_string(val: RightSideIntValue);
13678 S.Diag(Loc, DiagID: diag::warn_xor_used_as_pow_base)
13679 << ExprStr << toString(I: XorValue, Radix: 10, Signed: true) << SuggestedValue
13680 << FixItHint::CreateReplacement(RemoveRange: ExprRange, Code: SuggestedValue);
13681 S.Diag(Loc, DiagID: diag::note_xor_used_as_pow_silence)
13682 << ("0xA ^ " + RHSStr) << SuggestXor;
13683 }
13684}
13685
13686QualType Sema::CheckVectorLogicalOperands(ExprResult &LHS, ExprResult &RHS,
13687 SourceLocation Loc,
13688 BinaryOperatorKind Opc) {
13689 // Ensure that either both operands are of the same vector type, or
13690 // one operand is of a vector type and the other is of its element type.
13691 QualType vType = CheckVectorOperands(LHS, RHS, Loc, IsCompAssign: false,
13692 /*AllowBothBool*/ true,
13693 /*AllowBoolConversions*/ false,
13694 /*AllowBooleanOperation*/ AllowBoolOperation: false,
13695 /*ReportInvalid*/ false);
13696 if (vType.isNull())
13697 return InvalidOperands(Loc, LHS, RHS);
13698 if (getLangOpts().OpenCL &&
13699 getLangOpts().getOpenCLCompatibleVersion() < 120 &&
13700 vType->hasFloatingRepresentation())
13701 return InvalidOperands(Loc, LHS, RHS);
13702 // FIXME: The check for C++ here is for GCC compatibility. GCC rejects the
13703 // usage of the logical operators && and || with vectors in C. This
13704 // check could be notionally dropped.
13705 if (!getLangOpts().CPlusPlus &&
13706 !(isa<ExtVectorType>(Val: vType->getAs<VectorType>())))
13707 return InvalidLogicalVectorOperands(Loc, LHS, RHS);
13708 // Beginning with HLSL 2021, HLSL disallows logical operators on vector
13709 // operands and instead requires the use of the `and`, `or`, `any`, `all`, and
13710 // `select` functions.
13711 if (getLangOpts().HLSL &&
13712 getLangOpts().getHLSLVersion() >= LangOptionsBase::HLSL_2021) {
13713 (void)InvalidOperands(Loc, LHS, RHS);
13714 HLSL().emitLogicalOperatorFixIt(LHS: LHS.get(), RHS: RHS.get(), Opc);
13715 return QualType();
13716 }
13717
13718 return GetSignedVectorType(V: LHS.get()->getType());
13719}
13720
13721QualType Sema::CheckMatrixLogicalOperands(ExprResult &LHS, ExprResult &RHS,
13722 SourceLocation Loc,
13723 BinaryOperatorKind Opc) {
13724
13725 if (!getLangOpts().HLSL) {
13726 assert(false && "Logical operands are not supported in C\\C++");
13727 return QualType();
13728 }
13729
13730 if (getLangOpts().getHLSLVersion() >= LangOptionsBase::HLSL_2021) {
13731 (void)InvalidOperands(Loc, LHS, RHS);
13732 HLSL().emitLogicalOperatorFixIt(LHS: LHS.get(), RHS: RHS.get(), Opc);
13733 return QualType();
13734 }
13735 SemaRef.Diag(Loc: LHS.get()->getBeginLoc(), DiagID: diag::err_hlsl_langstd_unimplemented)
13736 << getLangOpts().getHLSLVersion();
13737 return QualType();
13738}
13739
13740QualType Sema::CheckMatrixElementwiseOperands(ExprResult &LHS, ExprResult &RHS,
13741 SourceLocation Loc,
13742 bool IsCompAssign) {
13743 if (!IsCompAssign) {
13744 LHS = DefaultFunctionArrayLvalueConversion(E: LHS.get());
13745 if (LHS.isInvalid())
13746 return QualType();
13747 }
13748 RHS = DefaultFunctionArrayLvalueConversion(E: RHS.get());
13749 if (RHS.isInvalid())
13750 return QualType();
13751
13752 // For conversion purposes, we ignore any qualifiers.
13753 // For example, "const float" and "float" are equivalent.
13754 QualType LHSType = LHS.get()->getType().getUnqualifiedType();
13755 QualType RHSType = RHS.get()->getType().getUnqualifiedType();
13756
13757 const MatrixType *LHSMatType = LHSType->getAs<MatrixType>();
13758 const MatrixType *RHSMatType = RHSType->getAs<MatrixType>();
13759 assert((LHSMatType || RHSMatType) && "At least one operand must be a matrix");
13760
13761 if (Context.hasSameType(T1: LHSType, T2: RHSType))
13762 return Context.getCommonSugaredType(X: LHSType, Y: RHSType);
13763
13764 // Type conversion may change LHS/RHS. Keep copies to the original results, in
13765 // case we have to return InvalidOperands.
13766 ExprResult OriginalLHS = LHS;
13767 ExprResult OriginalRHS = RHS;
13768 if (LHSMatType && !RHSMatType) {
13769 RHS = tryConvertExprToType(E: RHS.get(), Ty: LHSMatType->getElementType());
13770 if (!RHS.isInvalid())
13771 return LHSType;
13772
13773 return InvalidOperands(Loc, LHS&: OriginalLHS, RHS&: OriginalRHS);
13774 }
13775
13776 if (!LHSMatType && RHSMatType) {
13777 LHS = tryConvertExprToType(E: LHS.get(), Ty: RHSMatType->getElementType());
13778 if (!LHS.isInvalid())
13779 return RHSType;
13780 return InvalidOperands(Loc, LHS&: OriginalLHS, RHS&: OriginalRHS);
13781 }
13782
13783 return InvalidOperands(Loc, LHS, RHS);
13784}
13785
13786QualType Sema::CheckMatrixMultiplyOperands(ExprResult &LHS, ExprResult &RHS,
13787 SourceLocation Loc,
13788 bool IsCompAssign) {
13789 if (!IsCompAssign) {
13790 LHS = DefaultFunctionArrayLvalueConversion(E: LHS.get());
13791 if (LHS.isInvalid())
13792 return QualType();
13793 }
13794 RHS = DefaultFunctionArrayLvalueConversion(E: RHS.get());
13795 if (RHS.isInvalid())
13796 return QualType();
13797
13798 auto *LHSMatType = LHS.get()->getType()->getAs<ConstantMatrixType>();
13799 auto *RHSMatType = RHS.get()->getType()->getAs<ConstantMatrixType>();
13800 assert((LHSMatType || RHSMatType) && "At least one operand must be a matrix");
13801
13802 if (LHSMatType && RHSMatType) {
13803 if (LHSMatType->getNumColumns() != RHSMatType->getNumRows())
13804 return InvalidOperands(Loc, LHS, RHS);
13805
13806 if (Context.hasSameType(T1: LHSMatType, T2: RHSMatType))
13807 return Context.getCommonSugaredType(
13808 X: LHS.get()->getType().getUnqualifiedType(),
13809 Y: RHS.get()->getType().getUnqualifiedType());
13810
13811 QualType LHSELTy = LHSMatType->getElementType(),
13812 RHSELTy = RHSMatType->getElementType();
13813 if (!Context.hasSameType(T1: LHSELTy, T2: RHSELTy))
13814 return InvalidOperands(Loc, LHS, RHS);
13815
13816 return Context.getConstantMatrixType(
13817 ElementType: Context.getCommonSugaredType(X: LHSELTy, Y: RHSELTy),
13818 NumRows: LHSMatType->getNumRows(), NumColumns: RHSMatType->getNumColumns());
13819 }
13820 return CheckMatrixElementwiseOperands(LHS, RHS, Loc, IsCompAssign);
13821}
13822
13823static bool isLegalBoolVectorBinaryOp(BinaryOperatorKind Opc) {
13824 switch (Opc) {
13825 default:
13826 return false;
13827 case BO_And:
13828 case BO_AndAssign:
13829 case BO_Or:
13830 case BO_OrAssign:
13831 case BO_Xor:
13832 case BO_XorAssign:
13833 return true;
13834 }
13835}
13836
13837inline QualType Sema::CheckBitwiseOperands(ExprResult &LHS, ExprResult &RHS,
13838 SourceLocation Loc,
13839 BinaryOperatorKind Opc) {
13840 checkArithmeticNull(S&: *this, LHS, RHS, Loc, /*IsCompare=*/false);
13841
13842 bool IsCompAssign =
13843 Opc == BO_AndAssign || Opc == BO_OrAssign || Opc == BO_XorAssign;
13844
13845 bool LegalBoolVecOperator = isLegalBoolVectorBinaryOp(Opc);
13846
13847 if (LHS.get()->getType()->isVectorType() ||
13848 RHS.get()->getType()->isVectorType()) {
13849 if (LHS.get()->getType()->hasIntegerRepresentation() &&
13850 RHS.get()->getType()->hasIntegerRepresentation())
13851 return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign,
13852 /*AllowBothBool*/ true,
13853 /*AllowBoolConversions*/ getLangOpts().ZVector,
13854 /*AllowBooleanOperation*/ AllowBoolOperation: LegalBoolVecOperator,
13855 /*ReportInvalid*/ true);
13856 return InvalidOperands(Loc, LHS, RHS);
13857 }
13858
13859 if (LHS.get()->getType()->isSveVLSBuiltinType() ||
13860 RHS.get()->getType()->isSveVLSBuiltinType()) {
13861 if (LHS.get()->getType()->hasIntegerRepresentation() &&
13862 RHS.get()->getType()->hasIntegerRepresentation())
13863 return CheckSizelessVectorOperands(LHS, RHS, Loc, IsCompAssign,
13864 OperationKind: ArithConvKind::BitwiseOp);
13865 return InvalidOperands(Loc, LHS, RHS);
13866 }
13867
13868 if (LHS.get()->getType()->isSveVLSBuiltinType() ||
13869 RHS.get()->getType()->isSveVLSBuiltinType()) {
13870 if (LHS.get()->getType()->hasIntegerRepresentation() &&
13871 RHS.get()->getType()->hasIntegerRepresentation())
13872 return CheckSizelessVectorOperands(LHS, RHS, Loc, IsCompAssign,
13873 OperationKind: ArithConvKind::BitwiseOp);
13874 return InvalidOperands(Loc, LHS, RHS);
13875 }
13876
13877 if (Opc == BO_And)
13878 diagnoseLogicalNotOnLHSofCheck(S&: *this, LHS, RHS, Loc, Opc);
13879
13880 if (LHS.get()->getType()->hasFloatingRepresentation() ||
13881 RHS.get()->getType()->hasFloatingRepresentation())
13882 return InvalidOperands(Loc, LHS, RHS);
13883
13884 ExprResult LHSResult = LHS, RHSResult = RHS;
13885 QualType compType = UsualArithmeticConversions(
13886 LHS&: LHSResult, RHS&: RHSResult, Loc,
13887 ACK: IsCompAssign ? ArithConvKind::CompAssign : ArithConvKind::BitwiseOp);
13888 if (LHSResult.isInvalid() || RHSResult.isInvalid())
13889 return QualType();
13890 LHS = LHSResult.get();
13891 RHS = RHSResult.get();
13892
13893 if (Opc == BO_Xor)
13894 diagnoseXorMisusedAsPow(S&: *this, XorLHS: LHS, XorRHS: RHS, Loc);
13895
13896 if (!compType.isNull() && compType->isIntegralOrUnscopedEnumerationType())
13897 return compType;
13898 QualType ResultTy = InvalidOperands(Loc, LHS, RHS);
13899 diagnoseScopedEnums(S&: *this, Loc, LHS, RHS, Opc);
13900 return ResultTy;
13901}
13902
13903// C99 6.5.[13,14]
13904inline QualType Sema::CheckLogicalOperands(ExprResult &LHS, ExprResult &RHS,
13905 SourceLocation Loc,
13906 BinaryOperatorKind Opc) {
13907 // Check vector operands differently.
13908 if (LHS.get()->getType()->isVectorType() ||
13909 RHS.get()->getType()->isVectorType())
13910 return CheckVectorLogicalOperands(LHS, RHS, Loc, Opc);
13911
13912 if (LHS.get()->getType()->isConstantMatrixType() ||
13913 RHS.get()->getType()->isConstantMatrixType())
13914 return CheckMatrixLogicalOperands(LHS, RHS, Loc, Opc);
13915
13916 bool EnumConstantInBoolContext = false;
13917 for (const ExprResult &HS : {LHS, RHS}) {
13918 if (const auto *DREHS = dyn_cast<DeclRefExpr>(Val: HS.get())) {
13919 const auto *ECDHS = dyn_cast<EnumConstantDecl>(Val: DREHS->getDecl());
13920 if (ECDHS && ECDHS->getInitVal() != 0 && ECDHS->getInitVal() != 1)
13921 EnumConstantInBoolContext = true;
13922 }
13923 }
13924
13925 if (EnumConstantInBoolContext)
13926 Diag(Loc, DiagID: diag::warn_enum_constant_in_bool_context);
13927
13928 // WebAssembly tables can't be used with logical operators.
13929 QualType LHSTy = LHS.get()->getType();
13930 QualType RHSTy = RHS.get()->getType();
13931 const auto *LHSATy = dyn_cast<ArrayType>(Val&: LHSTy);
13932 const auto *RHSATy = dyn_cast<ArrayType>(Val&: RHSTy);
13933 if ((LHSATy && LHSATy->getElementType().isWebAssemblyReferenceType()) ||
13934 (RHSATy && RHSATy->getElementType().isWebAssemblyReferenceType())) {
13935 return InvalidOperands(Loc, LHS, RHS);
13936 }
13937
13938 // Diagnose cases where the user write a logical and/or but probably meant a
13939 // bitwise one. We do this when the LHS is a non-bool integer and the RHS
13940 // is a constant.
13941 if (!EnumConstantInBoolContext && LHS.get()->getType()->isIntegerType() &&
13942 !LHS.get()->getType()->isBooleanType() &&
13943 RHS.get()->getType()->isIntegerType() && !RHS.get()->isValueDependent() &&
13944 // Don't warn in macros or template instantiations.
13945 !Loc.isMacroID() && !inTemplateInstantiation()) {
13946 // If the RHS can be constant folded, and if it constant folds to something
13947 // that isn't 0 or 1 (which indicate a potential logical operation that
13948 // happened to fold to true/false) then warn.
13949 // Parens on the RHS are ignored.
13950 Expr::EvalResult EVResult;
13951 if (RHS.get()->EvaluateAsInt(Result&: EVResult, Ctx: Context)) {
13952 llvm::APSInt Result = EVResult.Val.getInt();
13953 if ((getLangOpts().CPlusPlus && !RHS.get()->getType()->isBooleanType() &&
13954 !RHS.get()->getExprLoc().isMacroID()) ||
13955 (Result != 0 && Result != 1)) {
13956 Diag(Loc, DiagID: diag::warn_logical_instead_of_bitwise)
13957 << RHS.get()->getSourceRange() << (Opc == BO_LAnd ? "&&" : "||");
13958 // Suggest replacing the logical operator with the bitwise version
13959 Diag(Loc, DiagID: diag::note_logical_instead_of_bitwise_change_operator)
13960 << (Opc == BO_LAnd ? "&" : "|")
13961 << FixItHint::CreateReplacement(
13962 RemoveRange: SourceRange(Loc, getLocForEndOfToken(Loc)),
13963 Code: Opc == BO_LAnd ? "&" : "|");
13964 if (Opc == BO_LAnd)
13965 // Suggest replacing "Foo() && kNonZero" with "Foo()"
13966 Diag(Loc, DiagID: diag::note_logical_instead_of_bitwise_remove_constant)
13967 << FixItHint::CreateRemoval(
13968 RemoveRange: SourceRange(getLocForEndOfToken(Loc: LHS.get()->getEndLoc()),
13969 RHS.get()->getEndLoc()));
13970 }
13971 }
13972 }
13973
13974 if (!Context.getLangOpts().CPlusPlus) {
13975 // OpenCL v1.1 s6.3.g: The logical operators and (&&), or (||) do
13976 // not operate on the built-in scalar and vector float types.
13977 if (Context.getLangOpts().OpenCL &&
13978 Context.getLangOpts().OpenCLVersion < 120) {
13979 if (LHS.get()->getType()->isFloatingType() ||
13980 RHS.get()->getType()->isFloatingType())
13981 return InvalidOperands(Loc, LHS, RHS);
13982 }
13983
13984 LHS = UsualUnaryConversions(E: LHS.get());
13985 if (LHS.isInvalid())
13986 return QualType();
13987
13988 RHS = UsualUnaryConversions(E: RHS.get());
13989 if (RHS.isInvalid())
13990 return QualType();
13991
13992 if (LHS.get()->getType() == Context.AMDGPUFeaturePredicateTy)
13993 LHS = AMDGPU().ExpandAMDGPUPredicateBuiltIn(CE: LHS.get());
13994 if (RHS.get()->getType() == Context.AMDGPUFeaturePredicateTy)
13995 RHS = AMDGPU().ExpandAMDGPUPredicateBuiltIn(CE: RHS.get());
13996
13997 if (!LHS.get()->getType()->isScalarType() ||
13998 !RHS.get()->getType()->isScalarType())
13999 return InvalidOperands(Loc, LHS, RHS);
14000
14001 return Context.IntTy;
14002 }
14003
14004 // The following is safe because we only use this method for
14005 // non-overloadable operands.
14006
14007 // C++ [expr.log.and]p1
14008 // C++ [expr.log.or]p1
14009 // The operands are both contextually converted to type bool.
14010 ExprResult LHSRes = PerformContextuallyConvertToBool(From: LHS.get());
14011 if (LHSRes.isInvalid()) {
14012 QualType ResultTy = InvalidOperands(Loc, LHS, RHS);
14013 diagnoseScopedEnums(S&: *this, Loc, LHS, RHS, Opc);
14014 return ResultTy;
14015 }
14016 LHS = LHSRes;
14017
14018 ExprResult RHSRes = PerformContextuallyConvertToBool(From: RHS.get());
14019 if (RHSRes.isInvalid()) {
14020 QualType ResultTy = InvalidOperands(Loc, LHS, RHS);
14021 diagnoseScopedEnums(S&: *this, Loc, LHS, RHS, Opc);
14022 return ResultTy;
14023 }
14024 RHS = RHSRes;
14025
14026 // C++ [expr.log.and]p2
14027 // C++ [expr.log.or]p2
14028 // The result is a bool.
14029 return Context.BoolTy;
14030}
14031
14032static bool IsReadonlyMessage(Expr *E, Sema &S) {
14033 const MemberExpr *ME = dyn_cast<MemberExpr>(Val: E);
14034 if (!ME) return false;
14035 if (!isa<FieldDecl>(Val: ME->getMemberDecl())) return false;
14036 ObjCMessageExpr *Base = dyn_cast<ObjCMessageExpr>(
14037 Val: ME->getBase()->IgnoreImplicit()->IgnoreParenImpCasts());
14038 if (!Base) return false;
14039 return Base->getMethodDecl() != nullptr;
14040}
14041
14042/// Is the given expression (which must be 'const') a reference to a
14043/// variable which was originally non-const, but which has become
14044/// 'const' due to being captured within a block?
14045enum NonConstCaptureKind { NCCK_None, NCCK_Block, NCCK_Lambda };
14046static NonConstCaptureKind isReferenceToNonConstCapture(Sema &S, Expr *E) {
14047 assert(E->isLValue() && E->getType().isConstQualified());
14048 E = E->IgnoreParens();
14049
14050 // Must be a reference to a declaration from an enclosing scope.
14051 DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Val: E);
14052 if (!DRE) return NCCK_None;
14053 if (!DRE->refersToEnclosingVariableOrCapture()) return NCCK_None;
14054
14055 ValueDecl *Value = DRE->getDecl();
14056
14057 // The declaration must be a value which is not declared 'const'.
14058 if (Value->getType().isConstQualified())
14059 return NCCK_None;
14060
14061 BindingDecl *Binding = dyn_cast<BindingDecl>(Val: Value);
14062 if (Binding) {
14063 assert(S.getLangOpts().CPlusPlus && "BindingDecl outside of C++?");
14064 assert(!isa<BlockDecl>(Binding->getDeclContext()));
14065 return NCCK_Lambda;
14066 }
14067
14068 VarDecl *Var = dyn_cast<VarDecl>(Val: Value);
14069 if (!Var)
14070 return NCCK_None;
14071 if (Var->getType()->isReferenceType())
14072 return NCCK_None;
14073
14074 assert(Var->hasLocalStorage() && "capture added 'const' to non-local?");
14075
14076 // Decide whether the first capture was for a block or a lambda.
14077 DeclContext *DC = S.CurContext, *Prev = nullptr;
14078 // Decide whether the first capture was for a block or a lambda.
14079 while (DC) {
14080 // For init-capture, it is possible that the variable belongs to the
14081 // template pattern of the current context.
14082 if (auto *FD = dyn_cast<FunctionDecl>(Val: DC))
14083 if (Var->isInitCapture() &&
14084 FD->getTemplateInstantiationPattern() == Var->getDeclContext())
14085 break;
14086 if (DC == Var->getDeclContext())
14087 break;
14088 Prev = DC;
14089 DC = DC->getParent();
14090 }
14091 // Unless we have an init-capture, we've gone one step too far.
14092 if (!Var->isInitCapture())
14093 DC = Prev;
14094 return (isa<BlockDecl>(Val: DC) ? NCCK_Block : NCCK_Lambda);
14095}
14096
14097static bool IsTypeModifiable(QualType Ty, bool IsDereference) {
14098 Ty = Ty.getNonReferenceType();
14099 if (IsDereference && Ty->isPointerType())
14100 Ty = Ty->getPointeeType();
14101 return !Ty.isConstQualified();
14102}
14103
14104// Update err_typecheck_assign_const and note_typecheck_assign_const
14105// when this enum is changed.
14106enum {
14107 ConstFunction,
14108 ConstVariable,
14109 ConstMember,
14110 NestedConstMember,
14111 ConstUnknown, // Keep as last element
14112};
14113
14114/// Emit the "read-only variable not assignable" error and print notes to give
14115/// more information about why the variable is not assignable, such as pointing
14116/// to the declaration of a const variable, showing that a method is const, or
14117/// that the function is returning a const reference.
14118static void DiagnoseConstAssignment(Sema &S, const Expr *E,
14119 SourceLocation Loc) {
14120 SourceRange ExprRange = E->getSourceRange();
14121
14122 // Only emit one error on the first const found. All other consts will emit
14123 // a note to the error.
14124 bool DiagnosticEmitted = false;
14125
14126 // Track if the current expression is the result of a dereference, and if the
14127 // next checked expression is the result of a dereference.
14128 bool IsDereference = false;
14129 bool NextIsDereference = false;
14130
14131 // Loop to process MemberExpr chains.
14132 while (true) {
14133 IsDereference = NextIsDereference;
14134
14135 E = E->IgnoreImplicit()->IgnoreParenImpCasts();
14136 if (const MemberExpr *ME = dyn_cast<MemberExpr>(Val: E)) {
14137 NextIsDereference = ME->isArrow();
14138 const ValueDecl *VD = ME->getMemberDecl();
14139 if (const FieldDecl *Field = dyn_cast<FieldDecl>(Val: VD)) {
14140 // Mutable fields can be modified even if the class is const.
14141 if (Field->isMutable()) {
14142 assert(DiagnosticEmitted && "Expected diagnostic not emitted.");
14143 break;
14144 }
14145
14146 if (!IsTypeModifiable(Ty: Field->getType(), IsDereference)) {
14147 if (!DiagnosticEmitted) {
14148 S.Diag(Loc, DiagID: diag::err_typecheck_assign_const)
14149 << ExprRange << ConstMember << false /*static*/ << Field
14150 << Field->getType();
14151 DiagnosticEmitted = true;
14152 }
14153 S.Diag(Loc: VD->getLocation(), DiagID: diag::note_typecheck_assign_const)
14154 << ConstMember << false /*static*/ << Field << Field->getType()
14155 << Field->getSourceRange();
14156 }
14157 E = ME->getBase();
14158 continue;
14159 } else if (const VarDecl *VDecl = dyn_cast<VarDecl>(Val: VD)) {
14160 if (VDecl->getType().isConstQualified()) {
14161 if (!DiagnosticEmitted) {
14162 S.Diag(Loc, DiagID: diag::err_typecheck_assign_const)
14163 << ExprRange << ConstMember << true /*static*/ << VDecl
14164 << VDecl->getType();
14165 DiagnosticEmitted = true;
14166 }
14167 S.Diag(Loc: VD->getLocation(), DiagID: diag::note_typecheck_assign_const)
14168 << ConstMember << true /*static*/ << VDecl << VDecl->getType()
14169 << VDecl->getSourceRange();
14170 }
14171 // Static fields do not inherit constness from parents.
14172 break;
14173 }
14174 break; // End MemberExpr
14175 } else if (const ArraySubscriptExpr *ASE =
14176 dyn_cast<ArraySubscriptExpr>(Val: E)) {
14177 E = ASE->getBase()->IgnoreParenImpCasts();
14178 continue;
14179 } else if (const ExtVectorElementExpr *EVE =
14180 dyn_cast<ExtVectorElementExpr>(Val: E)) {
14181 E = EVE->getBase()->IgnoreParenImpCasts();
14182 continue;
14183 }
14184 break;
14185 }
14186
14187 if (const CallExpr *CE = dyn_cast<CallExpr>(Val: E)) {
14188 // Function calls
14189 const FunctionDecl *FD = CE->getDirectCallee();
14190 if (FD && !IsTypeModifiable(Ty: FD->getReturnType(), IsDereference)) {
14191 if (!DiagnosticEmitted) {
14192 S.Diag(Loc, DiagID: diag::err_typecheck_assign_const) << ExprRange
14193 << ConstFunction << FD;
14194 DiagnosticEmitted = true;
14195 }
14196 S.Diag(Loc: FD->getReturnTypeSourceRange().getBegin(),
14197 DiagID: diag::note_typecheck_assign_const)
14198 << ConstFunction << FD << FD->getReturnType()
14199 << FD->getReturnTypeSourceRange();
14200 }
14201 } else if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Val: E)) {
14202 // Point to variable declaration.
14203 if (const ValueDecl *VD = DRE->getDecl()) {
14204 if (!IsTypeModifiable(Ty: VD->getType(), IsDereference)) {
14205 if (!DiagnosticEmitted) {
14206 S.Diag(Loc, DiagID: diag::err_typecheck_assign_const)
14207 << ExprRange << ConstVariable << VD << VD->getType();
14208 DiagnosticEmitted = true;
14209 }
14210 S.Diag(Loc: VD->getLocation(), DiagID: diag::note_typecheck_assign_const)
14211 << ConstVariable << VD << VD->getType() << VD->getSourceRange();
14212 }
14213 }
14214 } else if (isa<CXXThisExpr>(Val: E)) {
14215 if (const DeclContext *DC = S.getFunctionLevelDeclContext()) {
14216 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Val: DC)) {
14217 if (MD->isConst()) {
14218 if (!DiagnosticEmitted) {
14219 S.Diag(Loc, DiagID: diag::err_typecheck_assign_const_method)
14220 << ExprRange << MD;
14221 DiagnosticEmitted = true;
14222 }
14223 S.Diag(Loc: MD->getLocation(), DiagID: diag::note_typecheck_assign_const_method)
14224 << MD << MD->getSourceRange();
14225 }
14226 }
14227 }
14228 }
14229
14230 if (DiagnosticEmitted)
14231 return;
14232
14233 // Can't determine a more specific message, so display the generic error.
14234 S.Diag(Loc, DiagID: diag::err_typecheck_assign_const) << ExprRange << ConstUnknown;
14235}
14236
14237enum OriginalExprKind {
14238 OEK_Variable,
14239 OEK_Member,
14240 OEK_LValue
14241};
14242
14243static void DiagnoseRecursiveConstFields(Sema &S, const ValueDecl *VD,
14244 const RecordType *Ty,
14245 SourceLocation Loc, SourceRange Range,
14246 OriginalExprKind OEK,
14247 bool &DiagnosticEmitted) {
14248 std::vector<const RecordType *> RecordTypeList;
14249 RecordTypeList.push_back(x: Ty);
14250 unsigned NextToCheckIndex = 0;
14251 // We walk the record hierarchy breadth-first to ensure that we print
14252 // diagnostics in field nesting order.
14253 while (RecordTypeList.size() > NextToCheckIndex) {
14254 bool IsNested = NextToCheckIndex > 0;
14255 for (const FieldDecl *Field : RecordTypeList[NextToCheckIndex]
14256 ->getDecl()
14257 ->getDefinitionOrSelf()
14258 ->fields()) {
14259 // First, check every field for constness.
14260 QualType FieldTy = Field->getType();
14261 if (FieldTy.isConstQualified()) {
14262 if (!DiagnosticEmitted) {
14263 S.Diag(Loc, DiagID: diag::err_typecheck_assign_const)
14264 << Range << NestedConstMember << OEK << VD
14265 << IsNested << Field;
14266 DiagnosticEmitted = true;
14267 }
14268 S.Diag(Loc: Field->getLocation(), DiagID: diag::note_typecheck_assign_const)
14269 << NestedConstMember << IsNested << Field
14270 << FieldTy << Field->getSourceRange();
14271 }
14272
14273 // Then we append it to the list to check next in order.
14274 FieldTy = FieldTy.getCanonicalType();
14275 if (const auto *FieldRecTy = FieldTy->getAsCanonical<RecordType>()) {
14276 if (!llvm::is_contained(Range&: RecordTypeList, Element: FieldRecTy))
14277 RecordTypeList.push_back(x: FieldRecTy);
14278 }
14279 }
14280 ++NextToCheckIndex;
14281 }
14282}
14283
14284/// Emit an error for the case where a record we are trying to assign to has a
14285/// const-qualified field somewhere in its hierarchy.
14286static void DiagnoseRecursiveConstFields(Sema &S, const Expr *E,
14287 SourceLocation Loc) {
14288 QualType Ty = E->getType();
14289 assert(Ty->isRecordType() && "lvalue was not record?");
14290 SourceRange Range = E->getSourceRange();
14291 const auto *RTy = Ty->getAsCanonical<RecordType>();
14292 bool DiagEmitted = false;
14293
14294 if (const MemberExpr *ME = dyn_cast<MemberExpr>(Val: E))
14295 DiagnoseRecursiveConstFields(S, VD: ME->getMemberDecl(), Ty: RTy, Loc,
14296 Range, OEK: OEK_Member, DiagnosticEmitted&: DiagEmitted);
14297 else if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Val: E))
14298 DiagnoseRecursiveConstFields(S, VD: DRE->getDecl(), Ty: RTy, Loc,
14299 Range, OEK: OEK_Variable, DiagnosticEmitted&: DiagEmitted);
14300 else
14301 DiagnoseRecursiveConstFields(S, VD: nullptr, Ty: RTy, Loc,
14302 Range, OEK: OEK_LValue, DiagnosticEmitted&: DiagEmitted);
14303 if (!DiagEmitted)
14304 DiagnoseConstAssignment(S, E, Loc);
14305}
14306
14307/// CheckForModifiableLvalue - Verify that E is a modifiable lvalue. If not,
14308/// emit an error and return true. If so, return false.
14309static bool CheckForModifiableLvalue(Expr *E, SourceLocation Loc, Sema &S) {
14310 assert(!E->hasPlaceholderType(BuiltinType::PseudoObject));
14311
14312 S.CheckShadowingDeclModification(E, Loc);
14313
14314 SourceLocation OrigLoc = Loc;
14315 Expr::isModifiableLvalueResult IsLV = E->isModifiableLvalue(Ctx&: S.Context,
14316 Loc: &Loc);
14317 if (IsLV == Expr::MLV_ClassTemporary && IsReadonlyMessage(E, S))
14318 IsLV = Expr::MLV_InvalidMessageExpression;
14319 if (IsLV == Expr::MLV_Valid)
14320 return false;
14321
14322 unsigned DiagID = 0;
14323 bool NeedType = false;
14324 switch (IsLV) { // C99 6.5.16p2
14325 case Expr::MLV_ConstQualified:
14326 // Use a specialized diagnostic when we're assigning to an object
14327 // from an enclosing function or block.
14328 if (NonConstCaptureKind NCCK = isReferenceToNonConstCapture(S, E)) {
14329 if (NCCK == NCCK_Block)
14330 DiagID = diag::err_block_decl_ref_not_modifiable_lvalue;
14331 else
14332 DiagID = diag::err_lambda_decl_ref_not_modifiable_lvalue;
14333 break;
14334 }
14335
14336 // In ARC, use some specialized diagnostics for occasions where we
14337 // infer 'const'. These are always pseudo-strong variables.
14338 if (S.getLangOpts().ObjCAutoRefCount) {
14339 DeclRefExpr *declRef = dyn_cast<DeclRefExpr>(Val: E->IgnoreParenCasts());
14340 if (declRef && isa<VarDecl>(Val: declRef->getDecl())) {
14341 VarDecl *var = cast<VarDecl>(Val: declRef->getDecl());
14342
14343 // Use the normal diagnostic if it's pseudo-__strong but the
14344 // user actually wrote 'const'.
14345 if (var->isARCPseudoStrong() &&
14346 (!var->getTypeSourceInfo() ||
14347 !var->getTypeSourceInfo()->getType().isConstQualified())) {
14348 // There are three pseudo-strong cases:
14349 // - self
14350 ObjCMethodDecl *method = S.getCurMethodDecl();
14351 if (method && var == method->getSelfDecl()) {
14352 DiagID = method->isClassMethod()
14353 ? diag::err_typecheck_arc_assign_self_class_method
14354 : diag::err_typecheck_arc_assign_self;
14355
14356 // - Objective-C externally_retained attribute.
14357 } else if (var->hasAttr<ObjCExternallyRetainedAttr>() ||
14358 isa<ParmVarDecl>(Val: var)) {
14359 DiagID = diag::err_typecheck_arc_assign_externally_retained;
14360
14361 // - fast enumeration variables
14362 } else {
14363 DiagID = diag::err_typecheck_arr_assign_enumeration;
14364 }
14365
14366 SourceRange Assign;
14367 if (Loc != OrigLoc)
14368 Assign = SourceRange(OrigLoc, OrigLoc);
14369 S.Diag(Loc, DiagID) << E->getSourceRange() << Assign;
14370 // We need to preserve the AST regardless, so migration tool
14371 // can do its job.
14372 return false;
14373 }
14374 }
14375 }
14376
14377 // If none of the special cases above are triggered, then this is a
14378 // simple const assignment.
14379 if (DiagID == 0) {
14380 DiagnoseConstAssignment(S, E, Loc);
14381 return true;
14382 }
14383
14384 break;
14385 case Expr::MLV_ConstAddrSpace:
14386 DiagnoseConstAssignment(S, E, Loc);
14387 return true;
14388 case Expr::MLV_ConstQualifiedField:
14389 DiagnoseRecursiveConstFields(S, E, Loc);
14390 return true;
14391 case Expr::MLV_ArrayType:
14392 case Expr::MLV_ArrayTemporary:
14393 DiagID = diag::err_typecheck_array_not_modifiable_lvalue;
14394 NeedType = true;
14395 break;
14396 case Expr::MLV_NotObjectType:
14397 DiagID = diag::err_typecheck_non_object_not_modifiable_lvalue;
14398 NeedType = true;
14399 break;
14400 case Expr::MLV_LValueCast:
14401 DiagID = diag::err_typecheck_lvalue_casts_not_supported;
14402 break;
14403 case Expr::MLV_Valid:
14404 llvm_unreachable("did not take early return for MLV_Valid");
14405 case Expr::MLV_InvalidExpression:
14406 case Expr::MLV_MemberFunction:
14407 case Expr::MLV_ClassTemporary:
14408 DiagID = diag::err_typecheck_expression_not_modifiable_lvalue;
14409 break;
14410 case Expr::MLV_IncompleteType:
14411 case Expr::MLV_IncompleteVoidType:
14412 return S.RequireCompleteType(Loc, T: E->getType(),
14413 DiagID: diag::err_typecheck_incomplete_type_not_modifiable_lvalue, Args: E);
14414 case Expr::MLV_DuplicateVectorComponents:
14415 DiagID = diag::err_typecheck_duplicate_vector_components_not_mlvalue;
14416 break;
14417 case Expr::MLV_DuplicateMatrixComponents:
14418 DiagID = diag::err_typecheck_duplicate_matrix_components_not_mlvalue;
14419 break;
14420 case Expr::MLV_NoSetterProperty:
14421 llvm_unreachable("readonly properties should be processed differently");
14422 case Expr::MLV_InvalidMessageExpression:
14423 DiagID = diag::err_readonly_message_assignment;
14424 break;
14425 case Expr::MLV_SubObjCPropertySetting:
14426 DiagID = diag::err_no_subobject_property_setting;
14427 break;
14428 }
14429
14430 SourceRange Assign;
14431 if (Loc != OrigLoc)
14432 Assign = SourceRange(OrigLoc, OrigLoc);
14433 if (NeedType)
14434 S.Diag(Loc, DiagID) << E->getType() << E->getSourceRange() << Assign;
14435 else
14436 S.Diag(Loc, DiagID) << E->getSourceRange() << Assign;
14437 return true;
14438}
14439
14440static void CheckIdentityFieldAssignment(Expr *LHSExpr, Expr *RHSExpr,
14441 SourceLocation Loc,
14442 Sema &Sema) {
14443 if (Sema.inTemplateInstantiation())
14444 return;
14445 if (Sema.isUnevaluatedContext())
14446 return;
14447 if (Loc.isInvalid() || Loc.isMacroID())
14448 return;
14449 if (LHSExpr->getExprLoc().isMacroID() || RHSExpr->getExprLoc().isMacroID())
14450 return;
14451
14452 // C / C++ fields
14453 MemberExpr *ML = dyn_cast<MemberExpr>(Val: LHSExpr);
14454 MemberExpr *MR = dyn_cast<MemberExpr>(Val: RHSExpr);
14455 if (ML && MR) {
14456 if (!(isa<CXXThisExpr>(Val: ML->getBase()) && isa<CXXThisExpr>(Val: MR->getBase())))
14457 return;
14458 const ValueDecl *LHSDecl =
14459 cast<ValueDecl>(Val: ML->getMemberDecl()->getCanonicalDecl());
14460 const ValueDecl *RHSDecl =
14461 cast<ValueDecl>(Val: MR->getMemberDecl()->getCanonicalDecl());
14462 if (LHSDecl != RHSDecl)
14463 return;
14464 if (LHSDecl->getType().isVolatileQualified())
14465 return;
14466 if (const ReferenceType *RefTy = LHSDecl->getType()->getAs<ReferenceType>())
14467 if (RefTy->getPointeeType().isVolatileQualified())
14468 return;
14469
14470 Sema.Diag(Loc, DiagID: diag::warn_identity_field_assign) << 0;
14471 }
14472
14473 // Objective-C instance variables
14474 ObjCIvarRefExpr *OL = dyn_cast<ObjCIvarRefExpr>(Val: LHSExpr);
14475 ObjCIvarRefExpr *OR = dyn_cast<ObjCIvarRefExpr>(Val: RHSExpr);
14476 if (OL && OR && OL->getDecl() == OR->getDecl()) {
14477 DeclRefExpr *RL = dyn_cast<DeclRefExpr>(Val: OL->getBase()->IgnoreImpCasts());
14478 DeclRefExpr *RR = dyn_cast<DeclRefExpr>(Val: OR->getBase()->IgnoreImpCasts());
14479 if (RL && RR && RL->getDecl() == RR->getDecl())
14480 Sema.Diag(Loc, DiagID: diag::warn_identity_field_assign) << 1;
14481 }
14482}
14483
14484// C99 6.5.16.1
14485QualType Sema::CheckAssignmentOperands(Expr *LHSExpr, ExprResult &RHS,
14486 SourceLocation Loc,
14487 QualType CompoundType,
14488 BinaryOperatorKind Opc) {
14489 assert(!LHSExpr->hasPlaceholderType(BuiltinType::PseudoObject));
14490
14491 // Verify that LHS is a modifiable lvalue, and emit error if not.
14492 if (CheckForModifiableLvalue(E: LHSExpr, Loc, S&: *this))
14493 return QualType();
14494
14495 QualType LHSType = LHSExpr->getType();
14496 QualType RHSType = CompoundType.isNull() ? RHS.get()->getType() :
14497 CompoundType;
14498
14499 if (RHS.isUsable()) {
14500 // Even if this check fails don't return early to allow the best
14501 // possible error recovery and to allow any subsequent diagnostics to
14502 // work.
14503 const ValueDecl *Assignee = nullptr;
14504 bool ShowFullyQualifiedAssigneeName = false;
14505 // In simple cases describe what is being assigned to
14506 if (auto *DR = dyn_cast<DeclRefExpr>(Val: LHSExpr->IgnoreParenCasts())) {
14507 Assignee = DR->getDecl();
14508 } else if (auto *ME = dyn_cast<MemberExpr>(Val: LHSExpr->IgnoreParenCasts())) {
14509 Assignee = ME->getMemberDecl();
14510 ShowFullyQualifiedAssigneeName = true;
14511 }
14512
14513 BoundsSafetyCheckAssignmentToCountAttrPtr(
14514 LHSTy: LHSType, RHSExpr: RHS.get(), Action: AssignmentAction::Assigning, Loc, Assignee,
14515 ShowFullyQualifiedAssigneeName);
14516 }
14517
14518 // OpenCL v1.2 s6.1.1.1 p2:
14519 // The half data type can only be used to declare a pointer to a buffer that
14520 // contains half values
14521 if (getLangOpts().OpenCL &&
14522 !getOpenCLOptions().isAvailableOption(Ext: "cl_khr_fp16", LO: getLangOpts()) &&
14523 LHSType->isHalfType()) {
14524 Diag(Loc, DiagID: diag::err_opencl_half_load_store) << 1
14525 << LHSType.getUnqualifiedType();
14526 return QualType();
14527 }
14528
14529 // WebAssembly tables can't be used on RHS of an assignment expression.
14530 if (RHSType->isWebAssemblyTableType()) {
14531 Diag(Loc, DiagID: diag::err_wasm_table_art) << 0;
14532 return QualType();
14533 }
14534
14535 AssignConvertType ConvTy;
14536 if (CompoundType.isNull()) {
14537 Expr *RHSCheck = RHS.get();
14538
14539 CheckIdentityFieldAssignment(LHSExpr, RHSExpr: RHSCheck, Loc, Sema&: *this);
14540
14541 QualType LHSTy(LHSType);
14542 ConvTy = CheckSingleAssignmentConstraints(LHSType: LHSTy, CallerRHS&: RHS);
14543 if (RHS.isInvalid())
14544 return QualType();
14545 // Special case of NSObject attributes on c-style pointer types.
14546 if (ConvTy == AssignConvertType::IncompatiblePointer &&
14547 ((Context.isObjCNSObjectType(Ty: LHSType) &&
14548 RHSType->isObjCObjectPointerType()) ||
14549 (Context.isObjCNSObjectType(Ty: RHSType) &&
14550 LHSType->isObjCObjectPointerType())))
14551 ConvTy = AssignConvertType::Compatible;
14552
14553 if (IsAssignConvertCompatible(ConvTy) && LHSType->isObjCObjectType())
14554 Diag(Loc, DiagID: diag::err_objc_object_assignment) << LHSType;
14555
14556 // If the RHS is a unary plus or minus, check to see if they = and + are
14557 // right next to each other. If so, the user may have typo'd "x =+ 4"
14558 // instead of "x += 4".
14559 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Val: RHSCheck))
14560 RHSCheck = ICE->getSubExpr();
14561 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(Val: RHSCheck)) {
14562 if ((UO->getOpcode() == UO_Plus || UO->getOpcode() == UO_Minus) &&
14563 Loc.isFileID() && UO->getOperatorLoc().isFileID() &&
14564 // Only if the two operators are exactly adjacent.
14565 Loc.getLocWithOffset(Offset: 1) == UO->getOperatorLoc() &&
14566 // And there is a space or other character before the subexpr of the
14567 // unary +/-. We don't want to warn on "x=-1".
14568 Loc.getLocWithOffset(Offset: 2) != UO->getSubExpr()->getBeginLoc() &&
14569 UO->getSubExpr()->getBeginLoc().isFileID()) {
14570 Diag(Loc, DiagID: diag::warn_not_compound_assign)
14571 << (UO->getOpcode() == UO_Plus ? "+" : "-")
14572 << SourceRange(UO->getOperatorLoc(), UO->getOperatorLoc());
14573 }
14574 }
14575
14576 if (IsAssignConvertCompatible(ConvTy)) {
14577 if (LHSType.getObjCLifetime() == Qualifiers::OCL_Strong) {
14578 // Warn about retain cycles where a block captures the LHS, but
14579 // not if the LHS is a simple variable into which the block is
14580 // being stored...unless that variable can be captured by reference!
14581 const Expr *InnerLHS = LHSExpr->IgnoreParenCasts();
14582 const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Val: InnerLHS);
14583 if (!DRE || DRE->getDecl()->hasAttr<BlocksAttr>())
14584 ObjC().checkRetainCycles(receiver: LHSExpr, argument: RHS.get());
14585 }
14586
14587 if (LHSType.getObjCLifetime() == Qualifiers::OCL_Strong ||
14588 LHSType.isNonWeakInMRRWithObjCWeak(Context)) {
14589 // It is safe to assign a weak reference into a strong variable.
14590 // Although this code can still have problems:
14591 // id x = self.weakProp;
14592 // id y = self.weakProp;
14593 // we do not warn to warn spuriously when 'x' and 'y' are on separate
14594 // paths through the function. This should be revisited if
14595 // -Wrepeated-use-of-weak is made flow-sensitive.
14596 // For ObjCWeak only, we do not warn if the assign is to a non-weak
14597 // variable, which will be valid for the current autorelease scope.
14598 if (!Diags.isIgnored(DiagID: diag::warn_arc_repeated_use_of_weak,
14599 Loc: RHS.get()->getBeginLoc()))
14600 getCurFunction()->markSafeWeakUse(E: RHS.get());
14601
14602 } else if (getLangOpts().ObjCAutoRefCount || getLangOpts().ObjCWeak) {
14603 checkUnsafeExprAssigns(Loc, LHS: LHSExpr, RHS: RHS.get());
14604 }
14605 }
14606 } else {
14607 // Compound assignment "x += y"
14608 ConvTy = CheckAssignmentConstraints(Loc, LHSType, RHSType);
14609 }
14610
14611 if (DiagnoseAssignmentResult(ConvTy, Loc, DstType: LHSType, SrcType: RHSType, SrcExpr: RHS.get(),
14612 Action: AssignmentAction::Assigning))
14613 return QualType();
14614
14615 CheckForNullPointerDereference(S&: *this, E: LHSExpr);
14616
14617 AssignedEntity AE{.LHS: LHSExpr};
14618 checkAssignmentLifetime(SemaRef&: *this, Entity: AE, Init: RHS.get());
14619
14620 if (getLangOpts().CPlusPlus20 && LHSType.isVolatileQualified()) {
14621 if (CompoundType.isNull()) {
14622 // C++2a [expr.ass]p5:
14623 // A simple-assignment whose left operand is of a volatile-qualified
14624 // type is deprecated unless the assignment is either a discarded-value
14625 // expression or an unevaluated operand
14626 ExprEvalContexts.back().VolatileAssignmentLHSs.push_back(Elt: LHSExpr);
14627 }
14628 }
14629
14630 // C11 6.5.16p3: The type of an assignment expression is the type of the
14631 // left operand would have after lvalue conversion.
14632 // C11 6.3.2.1p2: ...this is called lvalue conversion. If the lvalue has
14633 // qualified type, the value has the unqualified version of the type of the
14634 // lvalue; additionally, if the lvalue has atomic type, the value has the
14635 // non-atomic version of the type of the lvalue.
14636 // C++ 5.17p1: the type of the assignment expression is that of its left
14637 // operand.
14638 return getLangOpts().CPlusPlus ? LHSType : LHSType.getAtomicUnqualifiedType();
14639}
14640
14641// Scenarios to ignore if expression E is:
14642// 1. an explicit cast expression into void
14643// 2. a function call expression that returns void
14644static bool IgnoreCommaOperand(const Expr *E, const ASTContext &Context) {
14645 E = E->IgnoreParens();
14646
14647 if (const CastExpr *CE = dyn_cast<CastExpr>(Val: E)) {
14648 if (CE->getCastKind() == CK_ToVoid) {
14649 return true;
14650 }
14651
14652 // static_cast<void> on a dependent type will not show up as CK_ToVoid.
14653 if (CE->getCastKind() == CK_Dependent && E->getType()->isVoidType() &&
14654 CE->getSubExpr()->getType()->isDependentType()) {
14655 return true;
14656 }
14657 }
14658
14659 if (const auto *CE = dyn_cast<CallExpr>(Val: E))
14660 return CE->getCallReturnType(Ctx: Context)->isVoidType();
14661 return false;
14662}
14663
14664void Sema::DiagnoseCommaOperator(const Expr *LHS, SourceLocation Loc) {
14665 // No warnings in macros
14666 if (Loc.isMacroID())
14667 return;
14668
14669 // Don't warn in template instantiations.
14670 if (inTemplateInstantiation())
14671 return;
14672
14673 // Scope isn't fine-grained enough to explicitly list the specific cases, so
14674 // instead, skip more than needed, then call back into here with the
14675 // CommaVisitor in SemaStmt.cpp.
14676 // The listed locations are the initialization and increment portions
14677 // of a for loop. The additional checks are on the condition of
14678 // if statements, do/while loops, and for loops.
14679 if (getCurScope()->isControlScope())
14680 return;
14681
14682 // If there are multiple comma operators used together, get the RHS of the
14683 // of the comma operator as the LHS.
14684 while (const BinaryOperator *BO = dyn_cast<BinaryOperator>(Val: LHS)) {
14685 if (BO->getOpcode() != BO_Comma)
14686 break;
14687 LHS = BO->getRHS();
14688 }
14689
14690 // Only allow some expressions on LHS to not warn.
14691 if (IgnoreCommaOperand(E: LHS, Context))
14692 return;
14693
14694 Diag(Loc, DiagID: diag::warn_comma_operator);
14695 Diag(Loc: LHS->getBeginLoc(), DiagID: diag::note_cast_to_void)
14696 << LHS->getSourceRange()
14697 << FixItHint::CreateInsertion(InsertionLoc: LHS->getBeginLoc(),
14698 Code: LangOpts.CPlusPlus ? "static_cast<void>("
14699 : "(void)(")
14700 << FixItHint::CreateInsertion(InsertionLoc: PP.getLocForEndOfToken(Loc: LHS->getEndLoc()),
14701 Code: ")");
14702}
14703
14704// C99 6.5.17
14705static QualType CheckCommaOperands(Sema &S, ExprResult &LHS, ExprResult &RHS,
14706 SourceLocation Loc) {
14707 LHS = S.CheckPlaceholderExpr(E: LHS.get());
14708 RHS = S.CheckPlaceholderExpr(E: RHS.get());
14709 if (LHS.isInvalid() || RHS.isInvalid())
14710 return QualType();
14711
14712 // C's comma performs lvalue conversion (C99 6.3.2.1) on both its
14713 // operands, but not unary promotions.
14714 // C++'s comma does not do any conversions at all (C++ [expr.comma]p1).
14715
14716 // So we treat the LHS as a ignored value, and in C++ we allow the
14717 // containing site to determine what should be done with the RHS.
14718 LHS = S.IgnoredValueConversions(E: LHS.get());
14719 if (LHS.isInvalid())
14720 return QualType();
14721
14722 S.DiagnoseUnusedExprResult(S: LHS.get(), DiagID: diag::warn_unused_comma_left_operand);
14723
14724 if (!S.getLangOpts().CPlusPlus) {
14725 RHS = S.DefaultFunctionArrayLvalueConversion(E: RHS.get());
14726 if (RHS.isInvalid())
14727 return QualType();
14728 if (!RHS.get()->getType()->isVoidType())
14729 S.RequireCompleteType(Loc, T: RHS.get()->getType(),
14730 DiagID: diag::err_incomplete_type);
14731 }
14732
14733 if (!S.getDiagnostics().isIgnored(DiagID: diag::warn_comma_operator, Loc))
14734 S.DiagnoseCommaOperator(LHS: LHS.get(), Loc);
14735
14736 return RHS.get()->getType();
14737}
14738
14739/// CheckIncrementDecrementOperand - unlike most "Check" methods, this routine
14740/// doesn't need to call UsualUnaryConversions or UsualArithmeticConversions.
14741static QualType CheckIncrementDecrementOperand(Sema &S, Expr *Op,
14742 ExprValueKind &VK,
14743 ExprObjectKind &OK,
14744 SourceLocation OpLoc, bool IsInc,
14745 bool IsPrefix) {
14746 QualType ResType = Op->getType();
14747 // Atomic types can be used for increment / decrement where the non-atomic
14748 // versions can, so ignore the _Atomic() specifier for the purpose of
14749 // checking.
14750 if (const AtomicType *ResAtomicType = ResType->getAs<AtomicType>())
14751 ResType = ResAtomicType->getValueType();
14752
14753 assert(!ResType.isNull() && "no type for increment/decrement expression");
14754
14755 if (S.getLangOpts().CPlusPlus && ResType->isBooleanType()) {
14756 // Decrement of bool is not allowed.
14757 if (!IsInc) {
14758 S.Diag(Loc: OpLoc, DiagID: diag::err_decrement_bool) << Op->getSourceRange();
14759 return QualType();
14760 }
14761 // Increment of bool sets it to true, but is deprecated.
14762 S.Diag(Loc: OpLoc, DiagID: S.getLangOpts().CPlusPlus17 ? diag::ext_increment_bool
14763 : diag::warn_increment_bool)
14764 << Op->getSourceRange();
14765 } else if (S.getLangOpts().CPlusPlus && ResType->isEnumeralType()) {
14766 // Error on enum increments and decrements in C++ mode
14767 S.Diag(Loc: OpLoc, DiagID: diag::err_increment_decrement_enum) << IsInc << ResType;
14768 return QualType();
14769 } else if (ResType->isRealType()) {
14770 // OK!
14771 } else if (ResType->isPointerType()) {
14772 // C99 6.5.2.4p2, 6.5.6p2
14773 if (!checkArithmeticOpPointerOperand(S, Loc: OpLoc, Operand: Op))
14774 return QualType();
14775 } else if (ResType->isOverflowBehaviorType()) {
14776 // OK!
14777 } else if (ResType->isObjCObjectPointerType()) {
14778 // On modern runtimes, ObjC pointer arithmetic is forbidden.
14779 // Otherwise, we just need a complete type.
14780 if (checkArithmeticIncompletePointerType(S, Loc: OpLoc, Operand: Op) ||
14781 checkArithmeticOnObjCPointer(S, opLoc: OpLoc, op: Op))
14782 return QualType();
14783 } else if (ResType->isAnyComplexType()) {
14784 // C99 does not support ++/-- on complex types, we allow as an extension.
14785 S.Diag(Loc: OpLoc, DiagID: S.getLangOpts().C2y ? diag::warn_c2y_compat_increment_complex
14786 : diag::ext_c2y_increment_complex)
14787 << IsInc << Op->getSourceRange();
14788 } else if (ResType->isPlaceholderType()) {
14789 ExprResult PR = S.CheckPlaceholderExpr(E: Op);
14790 if (PR.isInvalid()) return QualType();
14791 return CheckIncrementDecrementOperand(S, Op: PR.get(), VK, OK, OpLoc,
14792 IsInc, IsPrefix);
14793 } else if (S.getLangOpts().AltiVec && ResType->isVectorType()) {
14794 // OK! ( C/C++ Language Extensions for CBEA(Version 2.6) 10.3 )
14795 } else if (S.getLangOpts().ZVector && ResType->isVectorType() &&
14796 (ResType->castAs<VectorType>()->getVectorKind() !=
14797 VectorKind::AltiVecBool)) {
14798 // The z vector extensions allow ++ and -- for non-bool vectors.
14799 } else if (S.getLangOpts().OpenCL && ResType->isVectorType() &&
14800 ResType->castAs<VectorType>()->getElementType()->isIntegerType()) {
14801 // OpenCL V1.2 6.3 says dec/inc ops operate on integer vector types.
14802 } else {
14803 S.Diag(Loc: OpLoc, DiagID: diag::err_typecheck_illegal_increment_decrement)
14804 << ResType << int(IsInc) << Op->getSourceRange();
14805 return QualType();
14806 }
14807 // At this point, we know we have a real, complex or pointer type.
14808 // Now make sure the operand is a modifiable lvalue.
14809 if (CheckForModifiableLvalue(E: Op, Loc: OpLoc, S))
14810 return QualType();
14811 if (S.getLangOpts().CPlusPlus20 && ResType.isVolatileQualified()) {
14812 // C++2a [expr.pre.inc]p1, [expr.post.inc]p1:
14813 // An operand with volatile-qualified type is deprecated
14814 S.Diag(Loc: OpLoc, DiagID: diag::warn_deprecated_increment_decrement_volatile)
14815 << IsInc << ResType;
14816 }
14817 // In C++, a prefix increment is the same type as the operand. Otherwise
14818 // (in C or with postfix), the increment is the unqualified type of the
14819 // operand.
14820 if (IsPrefix && S.getLangOpts().CPlusPlus) {
14821 VK = VK_LValue;
14822 OK = Op->getObjectKind();
14823 return ResType;
14824 } else {
14825 VK = VK_PRValue;
14826 return ResType.getUnqualifiedType();
14827 }
14828}
14829
14830/// getPrimaryDecl - Helper function for CheckAddressOfOperand().
14831/// This routine allows us to typecheck complex/recursive expressions
14832/// where the declaration is needed for type checking. We only need to
14833/// handle cases when the expression references a function designator
14834/// or is an lvalue. Here are some examples:
14835/// - &(x) => x
14836/// - &*****f => f for f a function designator.
14837/// - &s.xx => s
14838/// - &s.zz[1].yy -> s, if zz is an array
14839/// - *(x + 1) -> x, if x is an array
14840/// - &"123"[2] -> 0
14841/// - & __real__ x -> x
14842///
14843/// FIXME: We don't recurse to the RHS of a comma, nor handle pointers to
14844/// members.
14845static ValueDecl *getPrimaryDecl(Expr *E) {
14846 switch (E->getStmtClass()) {
14847 case Stmt::DeclRefExprClass:
14848 return cast<DeclRefExpr>(Val: E)->getDecl();
14849 case Stmt::MemberExprClass:
14850 // If this is an arrow operator, the address is an offset from
14851 // the base's value, so the object the base refers to is
14852 // irrelevant.
14853 if (cast<MemberExpr>(Val: E)->isArrow())
14854 return nullptr;
14855 // Otherwise, the expression refers to a part of the base
14856 return getPrimaryDecl(E: cast<MemberExpr>(Val: E)->getBase());
14857 case Stmt::ArraySubscriptExprClass: {
14858 // FIXME: This code shouldn't be necessary! We should catch the implicit
14859 // promotion of register arrays earlier.
14860 Expr* Base = cast<ArraySubscriptExpr>(Val: E)->getBase();
14861 if (ImplicitCastExpr* ICE = dyn_cast<ImplicitCastExpr>(Val: Base)) {
14862 if (ICE->getSubExpr()->getType()->isArrayType())
14863 return getPrimaryDecl(E: ICE->getSubExpr());
14864 }
14865 return nullptr;
14866 }
14867 case Stmt::UnaryOperatorClass: {
14868 UnaryOperator *UO = cast<UnaryOperator>(Val: E);
14869
14870 switch(UO->getOpcode()) {
14871 case UO_Real:
14872 case UO_Imag:
14873 case UO_Extension:
14874 return getPrimaryDecl(E: UO->getSubExpr());
14875 default:
14876 return nullptr;
14877 }
14878 }
14879 case Stmt::ParenExprClass:
14880 return getPrimaryDecl(E: cast<ParenExpr>(Val: E)->getSubExpr());
14881 case Stmt::ImplicitCastExprClass:
14882 // If the result of an implicit cast is an l-value, we care about
14883 // the sub-expression; otherwise, the result here doesn't matter.
14884 return getPrimaryDecl(E: cast<ImplicitCastExpr>(Val: E)->getSubExpr());
14885 case Stmt::CXXUuidofExprClass:
14886 return cast<CXXUuidofExpr>(Val: E)->getGuidDecl();
14887 default:
14888 return nullptr;
14889 }
14890}
14891
14892namespace {
14893enum {
14894 AO_Bit_Field = 0,
14895 AO_Vector_Element = 1,
14896 AO_Property_Expansion = 2,
14897 AO_Register_Variable = 3,
14898 AO_Matrix_Element = 4,
14899 AO_No_Error = 5
14900};
14901}
14902/// Diagnose invalid operand for address of operations.
14903///
14904/// \param Type The type of operand which cannot have its address taken.
14905static void diagnoseAddressOfInvalidType(Sema &S, SourceLocation Loc,
14906 Expr *E, unsigned Type) {
14907 S.Diag(Loc, DiagID: diag::err_typecheck_address_of) << Type << E->getSourceRange();
14908}
14909
14910bool Sema::CheckUseOfCXXMethodAsAddressOfOperand(SourceLocation OpLoc,
14911 const Expr *Op,
14912 const CXXMethodDecl *MD) {
14913 const auto *DRE = cast<DeclRefExpr>(Val: Op->IgnoreParens());
14914
14915 if (Op != DRE)
14916 return Diag(Loc: OpLoc, DiagID: diag::err_parens_pointer_member_function)
14917 << Op->getSourceRange();
14918
14919 // Taking the address of a dtor is illegal per C++ [class.dtor]p2.
14920 if (isa<CXXDestructorDecl>(Val: MD))
14921 return Diag(Loc: OpLoc, DiagID: diag::err_typecheck_addrof_dtor)
14922 << DRE->getSourceRange();
14923
14924 if (DRE->getQualifier())
14925 return false;
14926
14927 if (MD->getParent()->getName().empty())
14928 return Diag(Loc: OpLoc, DiagID: diag::err_unqualified_pointer_member_function)
14929 << DRE->getSourceRange();
14930
14931 SmallString<32> Str;
14932 StringRef Qual = (MD->getParent()->getName() + "::").toStringRef(Out&: Str);
14933 return Diag(Loc: OpLoc, DiagID: diag::err_unqualified_pointer_member_function)
14934 << DRE->getSourceRange()
14935 << FixItHint::CreateInsertion(InsertionLoc: DRE->getSourceRange().getBegin(), Code: Qual);
14936}
14937
14938QualType Sema::CheckAddressOfOperand(ExprResult &OrigOp, SourceLocation OpLoc) {
14939 if (const BuiltinType *PTy = OrigOp.get()->getType()->getAsPlaceholderType()){
14940 if (PTy->getKind() == BuiltinType::Overload) {
14941 Expr *E = OrigOp.get()->IgnoreParens();
14942 if (!isa<OverloadExpr>(Val: E)) {
14943 assert(cast<UnaryOperator>(E)->getOpcode() == UO_AddrOf);
14944 Diag(Loc: OpLoc, DiagID: diag::err_typecheck_invalid_lvalue_addrof_addrof_function)
14945 << OrigOp.get()->getSourceRange();
14946 return QualType();
14947 }
14948
14949 OverloadExpr *Ovl = cast<OverloadExpr>(Val: E);
14950 if (isa<UnresolvedMemberExpr>(Val: Ovl))
14951 if (!ResolveSingleFunctionTemplateSpecialization(ovl: Ovl)) {
14952 Diag(Loc: OpLoc, DiagID: diag::err_invalid_form_pointer_member_function)
14953 << OrigOp.get()->getSourceRange();
14954 return QualType();
14955 }
14956
14957 return Context.OverloadTy;
14958 }
14959
14960 if (PTy->getKind() == BuiltinType::UnknownAny)
14961 return Context.UnknownAnyTy;
14962
14963 if (PTy->getKind() == BuiltinType::BoundMember) {
14964 Diag(Loc: OpLoc, DiagID: diag::err_invalid_form_pointer_member_function)
14965 << OrigOp.get()->getSourceRange();
14966 return QualType();
14967 }
14968
14969 OrigOp = CheckPlaceholderExpr(E: OrigOp.get());
14970 if (OrigOp.isInvalid()) return QualType();
14971 }
14972
14973 if (OrigOp.get()->isTypeDependent())
14974 return Context.DependentTy;
14975
14976 assert(!OrigOp.get()->hasPlaceholderType());
14977
14978 // Make sure to ignore parentheses in subsequent checks
14979 Expr *op = OrigOp.get()->IgnoreParens();
14980
14981 // In OpenCL captures for blocks called as lambda functions
14982 // are located in the private address space. Blocks used in
14983 // enqueue_kernel can be located in a different address space
14984 // depending on a vendor implementation. Thus preventing
14985 // taking an address of the capture to avoid invalid AS casts.
14986 if (LangOpts.OpenCL) {
14987 auto* VarRef = dyn_cast<DeclRefExpr>(Val: op);
14988 if (VarRef && VarRef->refersToEnclosingVariableOrCapture()) {
14989 Diag(Loc: op->getExprLoc(), DiagID: diag::err_opencl_taking_address_capture);
14990 return QualType();
14991 }
14992 }
14993
14994 if (getLangOpts().C99) {
14995 // Implement C99-only parts of addressof rules.
14996 if (UnaryOperator* uOp = dyn_cast<UnaryOperator>(Val: op)) {
14997 if (uOp->getOpcode() == UO_Deref)
14998 // Per C99 6.5.3.2, the address of a deref always returns a valid result
14999 // (assuming the deref expression is valid).
15000 return uOp->getSubExpr()->getType();
15001 }
15002 // Technically, there should be a check for array subscript
15003 // expressions here, but the result of one is always an lvalue anyway.
15004 }
15005 ValueDecl *dcl = getPrimaryDecl(E: op);
15006
15007 if (auto *FD = dyn_cast_or_null<FunctionDecl>(Val: dcl))
15008 if (!checkAddressOfFunctionIsAvailable(Function: FD, /*Complain=*/true,
15009 Loc: op->getBeginLoc()))
15010 return QualType();
15011
15012 Expr::LValueClassification lval = op->ClassifyLValue(Ctx&: Context);
15013 unsigned AddressOfError = AO_No_Error;
15014
15015 if (lval == Expr::LV_ClassTemporary || lval == Expr::LV_ArrayTemporary) {
15016 bool IsError = isSFINAEContext();
15017 Diag(Loc: OpLoc, DiagID: IsError ? diag::err_typecheck_addrof_temporary
15018 : diag::ext_typecheck_addrof_temporary)
15019 << op->getType() << op->getSourceRange();
15020 if (IsError)
15021 return QualType();
15022 // Materialize the temporary as an lvalue so that we can take its address.
15023 OrigOp = op =
15024 CreateMaterializeTemporaryExpr(T: op->getType(), Temporary: OrigOp.get(), BoundToLvalueReference: true);
15025 } else if (isa<ObjCSelectorExpr>(Val: op)) {
15026 return Context.getPointerType(T: op->getType());
15027 } else if (lval == Expr::LV_MemberFunction) {
15028 // If it's an instance method, make a member pointer.
15029 // The expression must have exactly the form &A::foo.
15030
15031 // If the underlying expression isn't a decl ref, give up.
15032 if (!isa<DeclRefExpr>(Val: op)) {
15033 Diag(Loc: OpLoc, DiagID: diag::err_invalid_form_pointer_member_function)
15034 << OrigOp.get()->getSourceRange();
15035 return QualType();
15036 }
15037 DeclRefExpr *DRE = cast<DeclRefExpr>(Val: op);
15038 CXXMethodDecl *MD = cast<CXXMethodDecl>(Val: DRE->getDecl());
15039
15040 CheckUseOfCXXMethodAsAddressOfOperand(OpLoc, Op: OrigOp.get(), MD);
15041 QualType MPTy = Context.getMemberPointerType(
15042 T: op->getType(), Qualifier: DRE->getQualifier(), Cls: MD->getParent());
15043
15044 if (getLangOpts().PointerAuthCalls && MD->isVirtual() &&
15045 !isUnevaluatedContext() && !MPTy->isDependentType()) {
15046 // When pointer authentication is enabled, argument and return types of
15047 // vitual member functions must be complete. This is because vitrual
15048 // member function pointers are implemented using virtual dispatch
15049 // thunks and the thunks cannot be emitted if the argument or return
15050 // types are incomplete.
15051 auto ReturnOrParamTypeIsIncomplete = [&](QualType T,
15052 SourceLocation DeclRefLoc,
15053 SourceLocation RetArgTypeLoc) {
15054 if (RequireCompleteType(Loc: DeclRefLoc, T, DiagID: diag::err_incomplete_type)) {
15055 Diag(Loc: DeclRefLoc,
15056 DiagID: diag::note_ptrauth_virtual_function_pointer_incomplete_arg_ret);
15057 Diag(Loc: RetArgTypeLoc,
15058 DiagID: diag::note_ptrauth_virtual_function_incomplete_arg_ret_type)
15059 << T;
15060 return true;
15061 }
15062 return false;
15063 };
15064 QualType RetTy = MD->getReturnType();
15065 bool IsIncomplete =
15066 !RetTy->isVoidType() &&
15067 ReturnOrParamTypeIsIncomplete(
15068 RetTy, OpLoc, MD->getReturnTypeSourceRange().getBegin());
15069 for (auto *PVD : MD->parameters())
15070 IsIncomplete |= ReturnOrParamTypeIsIncomplete(PVD->getType(), OpLoc,
15071 PVD->getBeginLoc());
15072 if (IsIncomplete)
15073 return QualType();
15074 }
15075
15076 // Under the MS ABI, lock down the inheritance model now.
15077 if (Context.getTargetInfo().getCXXABI().isMicrosoft())
15078 (void)isCompleteType(Loc: OpLoc, T: MPTy);
15079 return MPTy;
15080 } else if (lval != Expr::LV_Valid && lval != Expr::LV_IncompleteVoidType) {
15081 // C99 6.5.3.2p1
15082 // The operand must be either an l-value or a function designator
15083 if (!op->getType()->isFunctionType()) {
15084 // Use a special diagnostic for loads from property references.
15085 if (isa<PseudoObjectExpr>(Val: op)) {
15086 AddressOfError = AO_Property_Expansion;
15087 } else {
15088 Diag(Loc: OpLoc, DiagID: diag::err_typecheck_invalid_lvalue_addrof)
15089 << op->getType() << op->getSourceRange();
15090 return QualType();
15091 }
15092 } else if (const auto *DRE = dyn_cast<DeclRefExpr>(Val: op)) {
15093 if (const auto *MD = dyn_cast_or_null<CXXMethodDecl>(Val: DRE->getDecl()))
15094 CheckUseOfCXXMethodAsAddressOfOperand(OpLoc, Op: OrigOp.get(), MD);
15095 }
15096
15097 } else if (op->getObjectKind() == OK_BitField) { // C99 6.5.3.2p1
15098 // The operand cannot be a bit-field
15099 AddressOfError = AO_Bit_Field;
15100 } else if (op->getObjectKind() == OK_VectorComponent) {
15101 // The operand cannot be an element of a vector
15102 AddressOfError = AO_Vector_Element;
15103 } else if (op->getObjectKind() == OK_MatrixComponent) {
15104 // The operand cannot be an element of a matrix.
15105 AddressOfError = AO_Matrix_Element;
15106 } else if (dcl) { // C99 6.5.3.2p1
15107 // We have an lvalue with a decl. Make sure the decl is not declared
15108 // with the register storage-class specifier.
15109 if (const VarDecl *vd = dyn_cast<VarDecl>(Val: dcl)) {
15110 // in C++ it is not error to take address of a register
15111 // variable (c++03 7.1.1P3)
15112 if (vd->getStorageClass() == SC_Register &&
15113 !getLangOpts().CPlusPlus) {
15114 AddressOfError = AO_Register_Variable;
15115 }
15116 } else if (isa<MSPropertyDecl>(Val: dcl)) {
15117 AddressOfError = AO_Property_Expansion;
15118 } else if (isa<FunctionTemplateDecl>(Val: dcl)) {
15119 return Context.OverloadTy;
15120 } else if (isa<FieldDecl>(Val: dcl) || isa<IndirectFieldDecl>(Val: dcl)) {
15121 // Okay: we can take the address of a field.
15122 // Could be a pointer to member, though, if there is an explicit
15123 // scope qualifier for the class.
15124
15125 // [C++26] [expr.prim.id.general]
15126 // If an id-expression E denotes a non-static non-type member
15127 // of some class C [...] and if E is a qualified-id, E is
15128 // not the un-parenthesized operand of the unary & operator [...]
15129 // the id-expression is transformed into a class member access expression.
15130 if (auto *DRE = dyn_cast<DeclRefExpr>(Val: op);
15131 DRE && DRE->getQualifier() && !isa<ParenExpr>(Val: OrigOp.get())) {
15132 DeclContext *Ctx = dcl->getDeclContext();
15133 if (Ctx && Ctx->isRecord()) {
15134 if (dcl->getType()->isReferenceType()) {
15135 Diag(Loc: OpLoc,
15136 DiagID: diag::err_cannot_form_pointer_to_member_of_reference_type)
15137 << dcl->getDeclName() << dcl->getType();
15138 return QualType();
15139 }
15140
15141 while (cast<RecordDecl>(Val: Ctx)->isAnonymousStructOrUnion())
15142 Ctx = Ctx->getParent();
15143
15144 QualType MPTy = Context.getMemberPointerType(
15145 T: op->getType(), Qualifier: DRE->getQualifier(), Cls: cast<CXXRecordDecl>(Val: Ctx));
15146 // Under the MS ABI, lock down the inheritance model now.
15147 if (Context.getTargetInfo().getCXXABI().isMicrosoft())
15148 (void)isCompleteType(Loc: OpLoc, T: MPTy);
15149 return MPTy;
15150 }
15151 }
15152 } else if (!isa<FunctionDecl, TemplateParamObjectDecl,
15153 NonTypeTemplateParmDecl, BindingDecl, MSGuidDecl,
15154 UnnamedGlobalConstantDecl>(Val: dcl))
15155 llvm_unreachable("Unknown/unexpected decl type");
15156 }
15157
15158 if (AddressOfError != AO_No_Error) {
15159 diagnoseAddressOfInvalidType(S&: *this, Loc: OpLoc, E: op, Type: AddressOfError);
15160 return QualType();
15161 }
15162
15163 if (lval == Expr::LV_IncompleteVoidType) {
15164 // Taking the address of a void variable is technically illegal, but we
15165 // allow it in cases which are otherwise valid.
15166 // Example: "extern void x; void* y = &x;".
15167 Diag(Loc: OpLoc, DiagID: diag::ext_typecheck_addrof_void) << op->getSourceRange();
15168 }
15169
15170 // If the operand has type "type", the result has type "pointer to type".
15171 if (op->getType()->isObjCObjectType())
15172 return Context.getObjCObjectPointerType(OIT: op->getType());
15173
15174 // Cannot take the address of WebAssembly references or tables.
15175 if (Context.getTargetInfo().getTriple().isWasm()) {
15176 QualType OpTy = op->getType();
15177 if (OpTy.isWebAssemblyReferenceType()) {
15178 Diag(Loc: OpLoc, DiagID: diag::err_wasm_ca_reference)
15179 << 1 << OrigOp.get()->getSourceRange();
15180 return QualType();
15181 }
15182 if (OpTy->isWebAssemblyTableType()) {
15183 Diag(Loc: OpLoc, DiagID: diag::err_wasm_table_pr)
15184 << 1 << OrigOp.get()->getSourceRange();
15185 return QualType();
15186 }
15187 }
15188
15189 CheckAddressOfPackedMember(rhs: op);
15190
15191 return Context.getPointerType(T: op->getType());
15192}
15193
15194static void RecordModifiableNonNullParam(Sema &S, const Expr *Exp) {
15195 const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Val: Exp);
15196 if (!DRE)
15197 return;
15198 const Decl *D = DRE->getDecl();
15199 if (!D)
15200 return;
15201 const ParmVarDecl *Param = dyn_cast<ParmVarDecl>(Val: D);
15202 if (!Param)
15203 return;
15204 if (const FunctionDecl* FD = dyn_cast<FunctionDecl>(Val: Param->getDeclContext()))
15205 if (!FD->hasAttr<NonNullAttr>() && !Param->hasAttr<NonNullAttr>())
15206 return;
15207 if (FunctionScopeInfo *FD = S.getCurFunction())
15208 FD->ModifiedNonNullParams.insert(Ptr: Param);
15209}
15210
15211/// CheckIndirectionOperand - Type check unary indirection (prefix '*').
15212static QualType CheckIndirectionOperand(Sema &S, Expr *Op, ExprValueKind &VK,
15213 SourceLocation OpLoc,
15214 bool IsAfterAmp = false) {
15215 ExprResult ConvResult = S.UsualUnaryConversions(E: Op);
15216 if (ConvResult.isInvalid())
15217 return QualType();
15218 Op = ConvResult.get();
15219 QualType OpTy = Op->getType();
15220 QualType Result;
15221
15222 if (isa<CXXReinterpretCastExpr>(Val: Op->IgnoreParens())) {
15223 QualType OpOrigType = Op->IgnoreParenCasts()->getType();
15224 S.CheckCompatibleReinterpretCast(SrcType: OpOrigType, DestType: OpTy, /*IsDereference*/true,
15225 Range: Op->getSourceRange());
15226 }
15227
15228 if (const PointerType *PT = OpTy->getAs<PointerType>())
15229 {
15230 Result = PT->getPointeeType();
15231 }
15232 else if (const ObjCObjectPointerType *OPT =
15233 OpTy->getAs<ObjCObjectPointerType>())
15234 Result = OPT->getPointeeType();
15235 else {
15236 ExprResult PR = S.CheckPlaceholderExpr(E: Op);
15237 if (PR.isInvalid()) return QualType();
15238 if (PR.get() != Op)
15239 return CheckIndirectionOperand(S, Op: PR.get(), VK, OpLoc);
15240 }
15241
15242 if (Result.isNull()) {
15243 S.Diag(Loc: OpLoc, DiagID: diag::err_typecheck_indirection_requires_pointer)
15244 << OpTy << Op->getSourceRange();
15245 return QualType();
15246 }
15247
15248 if (Result->isVoidType()) {
15249 // C++ [expr.unary.op]p1:
15250 // [...] the expression to which [the unary * operator] is applied shall
15251 // be a pointer to an object type, or a pointer to a function type
15252 LangOptions LO = S.getLangOpts();
15253 if (LO.CPlusPlus)
15254 S.Diag(Loc: OpLoc, DiagID: diag::err_typecheck_indirection_through_void_pointer_cpp)
15255 << OpTy << Op->getSourceRange();
15256 else if (!(LO.C99 && IsAfterAmp) && !S.isUnevaluatedContext())
15257 S.Diag(Loc: OpLoc, DiagID: diag::ext_typecheck_indirection_through_void_pointer)
15258 << OpTy << Op->getSourceRange();
15259 }
15260
15261 // Dereferences are usually l-values...
15262 VK = VK_LValue;
15263
15264 // ...except that certain expressions are never l-values in C.
15265 if (!S.getLangOpts().CPlusPlus && Result.isCForbiddenLValueType())
15266 VK = VK_PRValue;
15267
15268 return Result;
15269}
15270
15271BinaryOperatorKind Sema::ConvertTokenKindToBinaryOpcode(tok::TokenKind Kind) {
15272 BinaryOperatorKind Opc;
15273 switch (Kind) {
15274 default: llvm_unreachable("Unknown binop!");
15275 case tok::periodstar: Opc = BO_PtrMemD; break;
15276 case tok::arrowstar: Opc = BO_PtrMemI; break;
15277 case tok::star: Opc = BO_Mul; break;
15278 case tok::slash: Opc = BO_Div; break;
15279 case tok::percent: Opc = BO_Rem; break;
15280 case tok::plus: Opc = BO_Add; break;
15281 case tok::minus: Opc = BO_Sub; break;
15282 case tok::lessless: Opc = BO_Shl; break;
15283 case tok::greatergreater: Opc = BO_Shr; break;
15284 case tok::lessequal: Opc = BO_LE; break;
15285 case tok::less: Opc = BO_LT; break;
15286 case tok::greaterequal: Opc = BO_GE; break;
15287 case tok::greater: Opc = BO_GT; break;
15288 case tok::exclaimequal: Opc = BO_NE; break;
15289 case tok::equalequal: Opc = BO_EQ; break;
15290 case tok::spaceship: Opc = BO_Cmp; break;
15291 case tok::amp: Opc = BO_And; break;
15292 case tok::caret: Opc = BO_Xor; break;
15293 case tok::pipe: Opc = BO_Or; break;
15294 case tok::ampamp: Opc = BO_LAnd; break;
15295 case tok::pipepipe: Opc = BO_LOr; break;
15296 case tok::equal: Opc = BO_Assign; break;
15297 case tok::starequal: Opc = BO_MulAssign; break;
15298 case tok::slashequal: Opc = BO_DivAssign; break;
15299 case tok::percentequal: Opc = BO_RemAssign; break;
15300 case tok::plusequal: Opc = BO_AddAssign; break;
15301 case tok::minusequal: Opc = BO_SubAssign; break;
15302 case tok::lesslessequal: Opc = BO_ShlAssign; break;
15303 case tok::greatergreaterequal: Opc = BO_ShrAssign; break;
15304 case tok::ampequal: Opc = BO_AndAssign; break;
15305 case tok::caretequal: Opc = BO_XorAssign; break;
15306 case tok::pipeequal: Opc = BO_OrAssign; break;
15307 case tok::comma: Opc = BO_Comma; break;
15308 }
15309 return Opc;
15310}
15311
15312static inline UnaryOperatorKind ConvertTokenKindToUnaryOpcode(
15313 tok::TokenKind Kind) {
15314 UnaryOperatorKind Opc;
15315 switch (Kind) {
15316 default: llvm_unreachable("Unknown unary op!");
15317 case tok::plusplus: Opc = UO_PreInc; break;
15318 case tok::minusminus: Opc = UO_PreDec; break;
15319 case tok::amp: Opc = UO_AddrOf; break;
15320 case tok::star: Opc = UO_Deref; break;
15321 case tok::plus: Opc = UO_Plus; break;
15322 case tok::minus: Opc = UO_Minus; break;
15323 case tok::tilde: Opc = UO_Not; break;
15324 case tok::exclaim: Opc = UO_LNot; break;
15325 case tok::kw___real: Opc = UO_Real; break;
15326 case tok::kw___imag: Opc = UO_Imag; break;
15327 case tok::kw___extension__: Opc = UO_Extension; break;
15328 }
15329 return Opc;
15330}
15331
15332const FieldDecl *
15333Sema::getSelfAssignmentClassMemberCandidate(const ValueDecl *SelfAssigned) {
15334 // Explore the case for adding 'this->' to the LHS of a self assignment, very
15335 // common for setters.
15336 // struct A {
15337 // int X;
15338 // -void setX(int X) { X = X; }
15339 // +void setX(int X) { this->X = X; }
15340 // };
15341
15342 // Only consider parameters for self assignment fixes.
15343 if (!isa<ParmVarDecl>(Val: SelfAssigned))
15344 return nullptr;
15345 const auto *Method =
15346 dyn_cast_or_null<CXXMethodDecl>(Val: getCurFunctionDecl(AllowLambda: true));
15347 if (!Method)
15348 return nullptr;
15349
15350 const CXXRecordDecl *Parent = Method->getParent();
15351 // In theory this is fixable if the lambda explicitly captures this, but
15352 // that's added complexity that's rarely going to be used.
15353 if (Parent->isLambda())
15354 return nullptr;
15355
15356 // FIXME: Use an actual Lookup operation instead of just traversing fields
15357 // in order to get base class fields.
15358 auto Field =
15359 llvm::find_if(Range: Parent->fields(),
15360 P: [Name(SelfAssigned->getDeclName())](const FieldDecl *F) {
15361 return F->getDeclName() == Name;
15362 });
15363 return (Field != Parent->field_end()) ? *Field : nullptr;
15364}
15365
15366/// DiagnoseSelfAssignment - Emits a warning if a value is assigned to itself.
15367/// This warning suppressed in the event of macro expansions.
15368static void DiagnoseSelfAssignment(Sema &S, Expr *LHSExpr, Expr *RHSExpr,
15369 SourceLocation OpLoc, bool IsBuiltin) {
15370 if (S.inTemplateInstantiation())
15371 return;
15372 if (S.isUnevaluatedContext())
15373 return;
15374 if (OpLoc.isInvalid() || OpLoc.isMacroID())
15375 return;
15376 LHSExpr = LHSExpr->IgnoreParenImpCasts();
15377 RHSExpr = RHSExpr->IgnoreParenImpCasts();
15378 const DeclRefExpr *LHSDeclRef = dyn_cast<DeclRefExpr>(Val: LHSExpr);
15379 const DeclRefExpr *RHSDeclRef = dyn_cast<DeclRefExpr>(Val: RHSExpr);
15380 if (!LHSDeclRef || !RHSDeclRef ||
15381 LHSDeclRef->getLocation().isMacroID() ||
15382 RHSDeclRef->getLocation().isMacroID())
15383 return;
15384 const ValueDecl *LHSDecl =
15385 cast<ValueDecl>(Val: LHSDeclRef->getDecl()->getCanonicalDecl());
15386 const ValueDecl *RHSDecl =
15387 cast<ValueDecl>(Val: RHSDeclRef->getDecl()->getCanonicalDecl());
15388 if (LHSDecl != RHSDecl)
15389 return;
15390 if (LHSDecl->getType().isVolatileQualified())
15391 return;
15392 if (const ReferenceType *RefTy = LHSDecl->getType()->getAs<ReferenceType>())
15393 if (RefTy->getPointeeType().isVolatileQualified())
15394 return;
15395
15396 auto Diag = S.Diag(Loc: OpLoc, DiagID: IsBuiltin ? diag::warn_self_assignment_builtin
15397 : diag::warn_self_assignment_overloaded)
15398 << LHSDeclRef->getType() << LHSExpr->getSourceRange()
15399 << RHSExpr->getSourceRange();
15400 if (const FieldDecl *SelfAssignField =
15401 S.getSelfAssignmentClassMemberCandidate(SelfAssigned: RHSDecl))
15402 Diag << 1 << SelfAssignField
15403 << FixItHint::CreateInsertion(InsertionLoc: LHSDeclRef->getBeginLoc(), Code: "this->");
15404 else
15405 Diag << 0;
15406}
15407
15408/// Check if a bitwise-& is performed on an Objective-C pointer. This
15409/// is usually indicative of introspection within the Objective-C pointer.
15410static void checkObjCPointerIntrospection(Sema &S, ExprResult &L, ExprResult &R,
15411 SourceLocation OpLoc) {
15412 if (!S.getLangOpts().ObjC)
15413 return;
15414
15415 const Expr *ObjCPointerExpr = nullptr, *OtherExpr = nullptr;
15416 const Expr *LHS = L.get();
15417 const Expr *RHS = R.get();
15418
15419 if (LHS->IgnoreParenCasts()->getType()->isObjCObjectPointerType()) {
15420 ObjCPointerExpr = LHS;
15421 OtherExpr = RHS;
15422 }
15423 else if (RHS->IgnoreParenCasts()->getType()->isObjCObjectPointerType()) {
15424 ObjCPointerExpr = RHS;
15425 OtherExpr = LHS;
15426 }
15427
15428 // This warning is deliberately made very specific to reduce false
15429 // positives with logic that uses '&' for hashing. This logic mainly
15430 // looks for code trying to introspect into tagged pointers, which
15431 // code should generally never do.
15432 if (ObjCPointerExpr && isa<IntegerLiteral>(Val: OtherExpr->IgnoreParenCasts())) {
15433 unsigned Diag = diag::warn_objc_pointer_masking;
15434 // Determine if we are introspecting the result of performSelectorXXX.
15435 const Expr *Ex = ObjCPointerExpr->IgnoreParenCasts();
15436 // Special case messages to -performSelector and friends, which
15437 // can return non-pointer values boxed in a pointer value.
15438 // Some clients may wish to silence warnings in this subcase.
15439 if (const ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(Val: Ex)) {
15440 Selector S = ME->getSelector();
15441 StringRef SelArg0 = S.getNameForSlot(argIndex: 0);
15442 if (SelArg0.starts_with(Prefix: "performSelector"))
15443 Diag = diag::warn_objc_pointer_masking_performSelector;
15444 }
15445
15446 S.Diag(Loc: OpLoc, DiagID: Diag)
15447 << ObjCPointerExpr->getSourceRange();
15448 }
15449}
15450
15451// This helper function promotes a binary operator's operands (which are of a
15452// half vector type) to a vector of floats and then truncates the result to
15453// a vector of either half or short.
15454static ExprResult convertHalfVecBinOp(Sema &S, ExprResult LHS, ExprResult RHS,
15455 BinaryOperatorKind Opc, QualType ResultTy,
15456 ExprValueKind VK, ExprObjectKind OK,
15457 bool IsCompAssign, SourceLocation OpLoc,
15458 FPOptionsOverride FPFeatures) {
15459 auto &Context = S.getASTContext();
15460 assert((isVector(ResultTy, Context.HalfTy) ||
15461 isVector(ResultTy, Context.ShortTy)) &&
15462 "Result must be a vector of half or short");
15463 assert(isVector(LHS.get()->getType(), Context.HalfTy) &&
15464 isVector(RHS.get()->getType(), Context.HalfTy) &&
15465 "both operands expected to be a half vector");
15466
15467 RHS = convertVector(E: RHS.get(), ElementType: Context.FloatTy, S);
15468 QualType BinOpResTy = RHS.get()->getType();
15469
15470 // If Opc is a comparison, ResultType is a vector of shorts. In that case,
15471 // change BinOpResTy to a vector of ints.
15472 if (isVector(QT: ResultTy, ElementType: Context.ShortTy))
15473 BinOpResTy = S.GetSignedVectorType(V: BinOpResTy);
15474
15475 if (IsCompAssign)
15476 return CompoundAssignOperator::Create(C: Context, lhs: LHS.get(), rhs: RHS.get(), opc: Opc,
15477 ResTy: ResultTy, VK, OK, opLoc: OpLoc, FPFeatures,
15478 CompLHSType: BinOpResTy, CompResultType: BinOpResTy);
15479
15480 LHS = convertVector(E: LHS.get(), ElementType: Context.FloatTy, S);
15481 auto *BO = BinaryOperator::Create(C: Context, lhs: LHS.get(), rhs: RHS.get(), opc: Opc,
15482 ResTy: BinOpResTy, VK, OK, opLoc: OpLoc, FPFeatures);
15483 return convertVector(E: BO, ElementType: ResultTy->castAs<VectorType>()->getElementType(), S);
15484}
15485
15486/// Returns true if conversion between vectors of halfs and vectors of floats
15487/// is needed.
15488static bool needsConversionOfHalfVec(bool OpRequiresConversion, ASTContext &Ctx,
15489 Expr *E0, Expr *E1 = nullptr) {
15490 if (!OpRequiresConversion || Ctx.getLangOpts().NativeHalfType ||
15491 Ctx.getTargetInfo().useFP16ConversionIntrinsics())
15492 return false;
15493
15494 auto HasVectorOfHalfType = [&Ctx](Expr *E) {
15495 QualType Ty = E->IgnoreImplicit()->getType();
15496
15497 // Don't promote half precision neon vectors like float16x4_t in arm_neon.h
15498 // to vectors of floats. Although the element type of the vectors is __fp16,
15499 // the vectors shouldn't be treated as storage-only types. See the
15500 // discussion here: https://reviews.llvm.org/rG825235c140e7
15501 if (const VectorType *VT = Ty->getAs<VectorType>()) {
15502 if (VT->getVectorKind() == VectorKind::Neon)
15503 return false;
15504 return VT->getElementType().getCanonicalType() == Ctx.HalfTy;
15505 }
15506 return false;
15507 };
15508
15509 return HasVectorOfHalfType(E0) && (!E1 || HasVectorOfHalfType(E1));
15510}
15511
15512ExprResult Sema::CreateBuiltinBinOp(SourceLocation OpLoc,
15513 BinaryOperatorKind Opc, Expr *LHSExpr,
15514 Expr *RHSExpr, bool ForFoldExpression) {
15515 if (getLangOpts().CPlusPlus11 && isa<InitListExpr>(Val: RHSExpr)) {
15516 // The syntax only allows initializer lists on the RHS of assignment,
15517 // so we don't need to worry about accepting invalid code for
15518 // non-assignment operators.
15519 // C++11 5.17p9:
15520 // The meaning of x = {v} [...] is that of x = T(v) [...]. The meaning
15521 // of x = {} is x = T().
15522 InitializationKind Kind = InitializationKind::CreateDirectList(
15523 InitLoc: RHSExpr->getBeginLoc(), LBraceLoc: RHSExpr->getBeginLoc(), RBraceLoc: RHSExpr->getEndLoc());
15524 InitializedEntity Entity =
15525 InitializedEntity::InitializeTemporary(Type: LHSExpr->getType());
15526 InitializationSequence InitSeq(*this, Entity, Kind, RHSExpr);
15527 ExprResult Init = InitSeq.Perform(S&: *this, Entity, Kind, Args: RHSExpr);
15528 if (Init.isInvalid())
15529 return Init;
15530 RHSExpr = Init.get();
15531 }
15532
15533 ExprResult LHS = LHSExpr, RHS = RHSExpr;
15534 QualType ResultTy; // Result type of the binary operator.
15535 // The following two variables are used for compound assignment operators
15536 QualType CompLHSTy; // Type of LHS after promotions for computation
15537 QualType CompResultTy; // Type of computation result
15538 ExprValueKind VK = VK_PRValue;
15539 ExprObjectKind OK = OK_Ordinary;
15540 bool ConvertHalfVec = false;
15541
15542 if (!LHS.isUsable() || !RHS.isUsable())
15543 return ExprError();
15544
15545 if (getLangOpts().OpenCL) {
15546 QualType LHSTy = LHSExpr->getType();
15547 QualType RHSTy = RHSExpr->getType();
15548 // OpenCLC v2.0 s6.13.11.1 allows atomic variables to be initialized by
15549 // the ATOMIC_VAR_INIT macro.
15550 if (LHSTy->isAtomicType() || RHSTy->isAtomicType()) {
15551 SourceRange SR(LHSExpr->getBeginLoc(), RHSExpr->getEndLoc());
15552 if (BO_Assign == Opc)
15553 Diag(Loc: OpLoc, DiagID: diag::err_opencl_atomic_init) << 0 << SR;
15554 else
15555 ResultTy = InvalidOperands(Loc: OpLoc, LHS, RHS);
15556 return ExprError();
15557 }
15558
15559 // OpenCL special types - image, sampler, pipe, and blocks are to be used
15560 // only with a builtin functions and therefore should be disallowed here.
15561 if (LHSTy->isImageType() || RHSTy->isImageType() ||
15562 LHSTy->isSamplerT() || RHSTy->isSamplerT() ||
15563 LHSTy->isPipeType() || RHSTy->isPipeType() ||
15564 LHSTy->isBlockPointerType() || RHSTy->isBlockPointerType()) {
15565 ResultTy = InvalidOperands(Loc: OpLoc, LHS, RHS);
15566 return ExprError();
15567 }
15568 }
15569
15570 checkTypeSupport(Ty: LHSExpr->getType(), Loc: OpLoc, /*ValueDecl*/ D: nullptr);
15571 checkTypeSupport(Ty: RHSExpr->getType(), Loc: OpLoc, /*ValueDecl*/ D: nullptr);
15572
15573 switch (Opc) {
15574 case BO_Assign:
15575 ResultTy = CheckAssignmentOperands(LHSExpr: LHS.get(), RHS, Loc: OpLoc, CompoundType: QualType(), Opc);
15576 if (getLangOpts().CPlusPlus &&
15577 LHS.get()->getObjectKind() != OK_ObjCProperty) {
15578 VK = LHS.get()->getValueKind();
15579 OK = LHS.get()->getObjectKind();
15580 }
15581 if (!ResultTy.isNull()) {
15582 DiagnoseSelfAssignment(S&: *this, LHSExpr: LHS.get(), RHSExpr: RHS.get(), OpLoc, IsBuiltin: true);
15583 DiagnoseSelfMove(LHSExpr: LHS.get(), RHSExpr: RHS.get(), OpLoc);
15584
15585 // Avoid copying a block to the heap if the block is assigned to a local
15586 // auto variable that is declared in the same scope as the block. This
15587 // optimization is unsafe if the local variable is declared in an outer
15588 // scope. For example:
15589 //
15590 // BlockTy b;
15591 // {
15592 // b = ^{...};
15593 // }
15594 // // It is unsafe to invoke the block here if it wasn't copied to the
15595 // // heap.
15596 // b();
15597
15598 if (auto *BE = dyn_cast<BlockExpr>(Val: RHS.get()->IgnoreParens()))
15599 if (auto *DRE = dyn_cast<DeclRefExpr>(Val: LHS.get()->IgnoreParens()))
15600 if (auto *VD = dyn_cast<VarDecl>(Val: DRE->getDecl()))
15601 if (VD->hasLocalStorage() && getCurScope()->isDeclScope(D: VD))
15602 BE->getBlockDecl()->setCanAvoidCopyToHeap();
15603
15604 if (LHS.get()->getType().hasNonTrivialToPrimitiveCopyCUnion())
15605 checkNonTrivialCUnion(QT: LHS.get()->getType(), Loc: LHS.get()->getExprLoc(),
15606 UseContext: NonTrivialCUnionContext::Assignment, NonTrivialKind: NTCUK_Copy);
15607 }
15608 RecordModifiableNonNullParam(S&: *this, Exp: LHS.get());
15609 break;
15610 case BO_PtrMemD:
15611 case BO_PtrMemI:
15612 ResultTy = CheckPointerToMemberOperands(LHS, RHS, VK, OpLoc,
15613 isIndirect: Opc == BO_PtrMemI);
15614 break;
15615 case BO_Mul:
15616 case BO_Div:
15617 ConvertHalfVec = true;
15618 ResultTy = CheckMultiplyDivideOperands(LHS, RHS, Loc: OpLoc, Opc);
15619 break;
15620 case BO_Rem:
15621 ResultTy = CheckRemainderOperands(LHS, RHS, Loc: OpLoc);
15622 break;
15623 case BO_Add:
15624 ConvertHalfVec = true;
15625 ResultTy = CheckAdditionOperands(LHS, RHS, Loc: OpLoc, Opc);
15626 break;
15627 case BO_Sub:
15628 ConvertHalfVec = true;
15629 ResultTy = CheckSubtractionOperands(LHS, RHS, Loc: OpLoc, Opc);
15630 break;
15631 case BO_Shl:
15632 case BO_Shr:
15633 ResultTy = CheckShiftOperands(LHS, RHS, Loc: OpLoc, Opc);
15634 break;
15635 case BO_LE:
15636 case BO_LT:
15637 case BO_GE:
15638 case BO_GT:
15639 ConvertHalfVec = true;
15640 ResultTy = CheckCompareOperands(LHS, RHS, Loc: OpLoc, Opc);
15641
15642 if (const auto *BI = dyn_cast<BinaryOperator>(Val: LHSExpr);
15643 !ForFoldExpression && BI && BI->isComparisonOp())
15644 Diag(Loc: OpLoc, DiagID: diag::warn_consecutive_comparison)
15645 << BI->getOpcodeStr() << BinaryOperator::getOpcodeStr(Op: Opc);
15646
15647 break;
15648 case BO_EQ:
15649 case BO_NE:
15650 ConvertHalfVec = true;
15651 ResultTy = CheckCompareOperands(LHS, RHS, Loc: OpLoc, Opc);
15652 break;
15653 case BO_Cmp:
15654 ConvertHalfVec = true;
15655 ResultTy = CheckCompareOperands(LHS, RHS, Loc: OpLoc, Opc);
15656 assert(ResultTy.isNull() || ResultTy->getAsCXXRecordDecl());
15657 break;
15658 case BO_And:
15659 checkObjCPointerIntrospection(S&: *this, L&: LHS, R&: RHS, OpLoc);
15660 [[fallthrough]];
15661 case BO_Xor:
15662 case BO_Or:
15663 ResultTy = CheckBitwiseOperands(LHS, RHS, Loc: OpLoc, Opc);
15664 break;
15665 case BO_LAnd:
15666 case BO_LOr:
15667 ConvertHalfVec = true;
15668 ResultTy = CheckLogicalOperands(LHS, RHS, Loc: OpLoc, Opc);
15669 break;
15670 case BO_MulAssign:
15671 case BO_DivAssign:
15672 ConvertHalfVec = true;
15673 CompResultTy = CheckMultiplyDivideOperands(LHS, RHS, Loc: OpLoc, Opc);
15674 CompLHSTy = CompResultTy;
15675 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
15676 ResultTy =
15677 CheckAssignmentOperands(LHSExpr: LHS.get(), RHS, Loc: OpLoc, CompoundType: CompResultTy, Opc);
15678 break;
15679 case BO_RemAssign:
15680 CompResultTy = CheckRemainderOperands(LHS, RHS, Loc: OpLoc, IsCompAssign: true);
15681 CompLHSTy = CompResultTy;
15682 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
15683 ResultTy =
15684 CheckAssignmentOperands(LHSExpr: LHS.get(), RHS, Loc: OpLoc, CompoundType: CompResultTy, Opc);
15685 break;
15686 case BO_AddAssign:
15687 ConvertHalfVec = true;
15688 CompResultTy = CheckAdditionOperands(LHS, RHS, Loc: OpLoc, Opc, CompLHSTy: &CompLHSTy);
15689 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
15690 ResultTy =
15691 CheckAssignmentOperands(LHSExpr: LHS.get(), RHS, Loc: OpLoc, CompoundType: CompResultTy, Opc);
15692 break;
15693 case BO_SubAssign:
15694 ConvertHalfVec = true;
15695 CompResultTy = CheckSubtractionOperands(LHS, RHS, Loc: OpLoc, Opc, CompLHSTy: &CompLHSTy);
15696 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
15697 ResultTy =
15698 CheckAssignmentOperands(LHSExpr: LHS.get(), RHS, Loc: OpLoc, CompoundType: CompResultTy, Opc);
15699 break;
15700 case BO_ShlAssign:
15701 case BO_ShrAssign:
15702 CompResultTy = CheckShiftOperands(LHS, RHS, Loc: OpLoc, Opc, IsCompAssign: true);
15703 CompLHSTy = CompResultTy;
15704 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
15705 ResultTy =
15706 CheckAssignmentOperands(LHSExpr: LHS.get(), RHS, Loc: OpLoc, CompoundType: CompResultTy, Opc);
15707 break;
15708 case BO_AndAssign:
15709 case BO_OrAssign: // fallthrough
15710 DiagnoseSelfAssignment(S&: *this, LHSExpr: LHS.get(), RHSExpr: RHS.get(), OpLoc, IsBuiltin: true);
15711 [[fallthrough]];
15712 case BO_XorAssign:
15713 CompResultTy = CheckBitwiseOperands(LHS, RHS, Loc: OpLoc, Opc);
15714 CompLHSTy = CompResultTy;
15715 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
15716 ResultTy =
15717 CheckAssignmentOperands(LHSExpr: LHS.get(), RHS, Loc: OpLoc, CompoundType: CompResultTy, Opc);
15718 break;
15719 case BO_Comma:
15720 ResultTy = CheckCommaOperands(S&: *this, LHS, RHS, Loc: OpLoc);
15721 if (getLangOpts().CPlusPlus && !RHS.isInvalid()) {
15722 VK = RHS.get()->getValueKind();
15723 OK = RHS.get()->getObjectKind();
15724 }
15725 break;
15726 }
15727 if (ResultTy.isNull() || LHS.isInvalid() || RHS.isInvalid())
15728 return ExprError();
15729
15730 // Some of the binary operations require promoting operands of half vector to
15731 // float vectors and truncating the result back to half vector. For now, we do
15732 // this only when HalfArgsAndReturn is set (that is, when the target is arm or
15733 // arm64).
15734 assert(
15735 (Opc == BO_Comma || isVector(RHS.get()->getType(), Context.HalfTy) ==
15736 isVector(LHS.get()->getType(), Context.HalfTy)) &&
15737 "both sides are half vectors or neither sides are");
15738 ConvertHalfVec =
15739 needsConversionOfHalfVec(OpRequiresConversion: ConvertHalfVec, Ctx&: Context, E0: LHS.get(), E1: RHS.get());
15740
15741 // Check for array bounds violations for both sides of the BinaryOperator
15742 CheckArrayAccess(E: LHS.get());
15743 CheckArrayAccess(E: RHS.get());
15744
15745 if (const ObjCIsaExpr *OISA = dyn_cast<ObjCIsaExpr>(Val: LHS.get()->IgnoreParenCasts())) {
15746 NamedDecl *ObjectSetClass = LookupSingleName(S: TUScope,
15747 Name: &Context.Idents.get(Name: "object_setClass"),
15748 Loc: SourceLocation(), NameKind: LookupOrdinaryName);
15749 if (ObjectSetClass && isa<ObjCIsaExpr>(Val: LHS.get())) {
15750 SourceLocation RHSLocEnd = getLocForEndOfToken(Loc: RHS.get()->getEndLoc());
15751 Diag(Loc: LHS.get()->getExprLoc(), DiagID: diag::warn_objc_isa_assign)
15752 << FixItHint::CreateInsertion(InsertionLoc: LHS.get()->getBeginLoc(),
15753 Code: "object_setClass(")
15754 << FixItHint::CreateReplacement(RemoveRange: SourceRange(OISA->getOpLoc(), OpLoc),
15755 Code: ",")
15756 << FixItHint::CreateInsertion(InsertionLoc: RHSLocEnd, Code: ")");
15757 }
15758 else
15759 Diag(Loc: LHS.get()->getExprLoc(), DiagID: diag::warn_objc_isa_assign);
15760 }
15761 else if (const ObjCIvarRefExpr *OIRE =
15762 dyn_cast<ObjCIvarRefExpr>(Val: LHS.get()->IgnoreParenCasts()))
15763 DiagnoseDirectIsaAccess(S&: *this, OIRE, AssignLoc: OpLoc, RHS: RHS.get());
15764
15765 // Opc is not a compound assignment if CompResultTy is null.
15766 if (CompResultTy.isNull()) {
15767 if (ConvertHalfVec)
15768 return convertHalfVecBinOp(S&: *this, LHS, RHS, Opc, ResultTy, VK, OK, IsCompAssign: false,
15769 OpLoc, FPFeatures: CurFPFeatureOverrides());
15770 return BinaryOperator::Create(C: Context, lhs: LHS.get(), rhs: RHS.get(), opc: Opc, ResTy: ResultTy,
15771 VK, OK, opLoc: OpLoc, FPFeatures: CurFPFeatureOverrides());
15772 }
15773
15774 // Handle compound assignments.
15775 if (getLangOpts().CPlusPlus && LHS.get()->getObjectKind() !=
15776 OK_ObjCProperty) {
15777 VK = VK_LValue;
15778 OK = LHS.get()->getObjectKind();
15779 }
15780
15781 // The LHS is not converted to the result type for fixed-point compound
15782 // assignment as the common type is computed on demand. Reset the CompLHSTy
15783 // to the LHS type we would have gotten after unary conversions.
15784 if (CompResultTy->isFixedPointType())
15785 CompLHSTy = UsualUnaryConversions(E: LHS.get()).get()->getType();
15786
15787 if (ConvertHalfVec)
15788 return convertHalfVecBinOp(S&: *this, LHS, RHS, Opc, ResultTy, VK, OK, IsCompAssign: true,
15789 OpLoc, FPFeatures: CurFPFeatureOverrides());
15790
15791 return CompoundAssignOperator::Create(
15792 C: Context, lhs: LHS.get(), rhs: RHS.get(), opc: Opc, ResTy: ResultTy, VK, OK, opLoc: OpLoc,
15793 FPFeatures: CurFPFeatureOverrides(), CompLHSType: CompLHSTy, CompResultType: CompResultTy);
15794}
15795
15796/// DiagnoseBitwisePrecedence - Emit a warning when bitwise and comparison
15797/// operators are mixed in a way that suggests that the programmer forgot that
15798/// comparison operators have higher precedence. The most typical example of
15799/// such code is "flags & 0x0020 != 0", which is equivalent to "flags & 1".
15800static void DiagnoseBitwisePrecedence(Sema &Self, BinaryOperatorKind Opc,
15801 SourceLocation OpLoc, Expr *LHSExpr,
15802 Expr *RHSExpr) {
15803 BinaryOperator *LHSBO = dyn_cast<BinaryOperator>(Val: LHSExpr);
15804 BinaryOperator *RHSBO = dyn_cast<BinaryOperator>(Val: RHSExpr);
15805
15806 // Check that one of the sides is a comparison operator and the other isn't.
15807 bool isLeftComp = LHSBO && LHSBO->isComparisonOp();
15808 bool isRightComp = RHSBO && RHSBO->isComparisonOp();
15809 if (isLeftComp == isRightComp)
15810 return;
15811
15812 // Bitwise operations are sometimes used as eager logical ops.
15813 // Don't diagnose this.
15814 bool isLeftBitwise = LHSBO && LHSBO->isBitwiseOp();
15815 bool isRightBitwise = RHSBO && RHSBO->isBitwiseOp();
15816 if (isLeftBitwise || isRightBitwise)
15817 return;
15818
15819 SourceRange DiagRange = isLeftComp
15820 ? SourceRange(LHSExpr->getBeginLoc(), OpLoc)
15821 : SourceRange(OpLoc, RHSExpr->getEndLoc());
15822 StringRef OpStr = isLeftComp ? LHSBO->getOpcodeStr() : RHSBO->getOpcodeStr();
15823 SourceRange ParensRange =
15824 isLeftComp
15825 ? SourceRange(LHSBO->getRHS()->getBeginLoc(), RHSExpr->getEndLoc())
15826 : SourceRange(LHSExpr->getBeginLoc(), RHSBO->getLHS()->getEndLoc());
15827
15828 Self.Diag(Loc: OpLoc, DiagID: diag::warn_precedence_bitwise_rel)
15829 << DiagRange << BinaryOperator::getOpcodeStr(Op: Opc) << OpStr;
15830 SuggestParentheses(Self, Loc: OpLoc,
15831 Note: Self.PDiag(DiagID: diag::note_precedence_silence) << OpStr,
15832 ParenRange: (isLeftComp ? LHSExpr : RHSExpr)->getSourceRange());
15833 SuggestParentheses(Self, Loc: OpLoc,
15834 Note: Self.PDiag(DiagID: diag::note_precedence_bitwise_first)
15835 << BinaryOperator::getOpcodeStr(Op: Opc),
15836 ParenRange: ParensRange);
15837}
15838
15839/// It accepts a '&&' expr that is inside a '||' one.
15840/// Emit a diagnostic together with a fixit hint that wraps the '&&' expression
15841/// in parentheses.
15842static void
15843EmitDiagnosticForLogicalAndInLogicalOr(Sema &Self, SourceLocation OpLoc,
15844 BinaryOperator *Bop) {
15845 assert(Bop->getOpcode() == BO_LAnd);
15846 Self.Diag(Loc: Bop->getOperatorLoc(), DiagID: diag::warn_logical_and_in_logical_or)
15847 << Bop->getSourceRange() << OpLoc;
15848 SuggestParentheses(Self, Loc: Bop->getOperatorLoc(),
15849 Note: Self.PDiag(DiagID: diag::note_precedence_silence)
15850 << Bop->getOpcodeStr(),
15851 ParenRange: Bop->getSourceRange());
15852}
15853
15854/// Look for '&&' in the left hand of a '||' expr.
15855static void DiagnoseLogicalAndInLogicalOrLHS(Sema &S, SourceLocation OpLoc,
15856 Expr *LHSExpr, Expr *RHSExpr) {
15857 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(Val: LHSExpr)) {
15858 if (Bop->getOpcode() == BO_LAnd) {
15859 // If it's "string_literal && a || b" don't warn since the precedence
15860 // doesn't matter.
15861 if (!isa<StringLiteral>(Val: Bop->getLHS()->IgnoreParenImpCasts()))
15862 return EmitDiagnosticForLogicalAndInLogicalOr(Self&: S, OpLoc, Bop);
15863 } else if (Bop->getOpcode() == BO_LOr) {
15864 if (BinaryOperator *RBop = dyn_cast<BinaryOperator>(Val: Bop->getRHS())) {
15865 // If it's "a || b && string_literal || c" we didn't warn earlier for
15866 // "a || b && string_literal", but warn now.
15867 if (RBop->getOpcode() == BO_LAnd &&
15868 isa<StringLiteral>(Val: RBop->getRHS()->IgnoreParenImpCasts()))
15869 return EmitDiagnosticForLogicalAndInLogicalOr(Self&: S, OpLoc, Bop: RBop);
15870 }
15871 }
15872 }
15873}
15874
15875/// Look for '&&' in the right hand of a '||' expr.
15876static void DiagnoseLogicalAndInLogicalOrRHS(Sema &S, SourceLocation OpLoc,
15877 Expr *LHSExpr, Expr *RHSExpr) {
15878 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(Val: RHSExpr)) {
15879 if (Bop->getOpcode() == BO_LAnd) {
15880 // If it's "a || b && string_literal" don't warn since the precedence
15881 // doesn't matter.
15882 if (!isa<StringLiteral>(Val: Bop->getRHS()->IgnoreParenImpCasts()))
15883 return EmitDiagnosticForLogicalAndInLogicalOr(Self&: S, OpLoc, Bop);
15884 }
15885 }
15886}
15887
15888/// Look for bitwise op in the left or right hand of a bitwise op with
15889/// lower precedence and emit a diagnostic together with a fixit hint that wraps
15890/// the '&' expression in parentheses.
15891static void DiagnoseBitwiseOpInBitwiseOp(Sema &S, BinaryOperatorKind Opc,
15892 SourceLocation OpLoc, Expr *SubExpr) {
15893 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(Val: SubExpr)) {
15894 if (Bop->isBitwiseOp() && Bop->getOpcode() < Opc) {
15895 S.Diag(Loc: Bop->getOperatorLoc(), DiagID: diag::warn_bitwise_op_in_bitwise_op)
15896 << Bop->getOpcodeStr() << BinaryOperator::getOpcodeStr(Op: Opc)
15897 << Bop->getSourceRange() << OpLoc;
15898 SuggestParentheses(Self&: S, Loc: Bop->getOperatorLoc(),
15899 Note: S.PDiag(DiagID: diag::note_precedence_silence)
15900 << Bop->getOpcodeStr(),
15901 ParenRange: Bop->getSourceRange());
15902 }
15903 }
15904}
15905
15906static void DiagnoseAdditionInShift(Sema &S, SourceLocation OpLoc,
15907 Expr *SubExpr, StringRef Shift) {
15908 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(Val: SubExpr)) {
15909 if (Bop->getOpcode() == BO_Add || Bop->getOpcode() == BO_Sub) {
15910 StringRef Op = Bop->getOpcodeStr();
15911 S.Diag(Loc: Bop->getOperatorLoc(), DiagID: diag::warn_addition_in_bitshift)
15912 << Bop->getSourceRange() << OpLoc << Shift << Op;
15913 SuggestParentheses(Self&: S, Loc: Bop->getOperatorLoc(),
15914 Note: S.PDiag(DiagID: diag::note_precedence_silence) << Op,
15915 ParenRange: Bop->getSourceRange());
15916 }
15917 }
15918}
15919
15920static void DiagnoseShiftCompare(Sema &S, SourceLocation OpLoc,
15921 Expr *LHSExpr, Expr *RHSExpr) {
15922 CXXOperatorCallExpr *OCE = dyn_cast<CXXOperatorCallExpr>(Val: LHSExpr);
15923 if (!OCE)
15924 return;
15925
15926 FunctionDecl *FD = OCE->getDirectCallee();
15927 if (!FD || !FD->isOverloadedOperator())
15928 return;
15929
15930 OverloadedOperatorKind Kind = FD->getOverloadedOperator();
15931 if (Kind != OO_LessLess && Kind != OO_GreaterGreater)
15932 return;
15933
15934 S.Diag(Loc: OpLoc, DiagID: diag::warn_overloaded_shift_in_comparison)
15935 << LHSExpr->getSourceRange() << RHSExpr->getSourceRange()
15936 << (Kind == OO_LessLess);
15937 SuggestParentheses(Self&: S, Loc: OCE->getOperatorLoc(),
15938 Note: S.PDiag(DiagID: diag::note_precedence_silence)
15939 << (Kind == OO_LessLess ? "<<" : ">>"),
15940 ParenRange: OCE->getSourceRange());
15941 SuggestParentheses(
15942 Self&: S, Loc: OpLoc, Note: S.PDiag(DiagID: diag::note_evaluate_comparison_first),
15943 ParenRange: SourceRange(OCE->getArg(Arg: 1)->getBeginLoc(), RHSExpr->getEndLoc()));
15944}
15945
15946/// DiagnoseBinOpPrecedence - Emit warnings for expressions with tricky
15947/// precedence.
15948static void DiagnoseBinOpPrecedence(Sema &Self, BinaryOperatorKind Opc,
15949 SourceLocation OpLoc, Expr *LHSExpr,
15950 Expr *RHSExpr){
15951 // Diagnose "arg1 'bitwise' arg2 'eq' arg3".
15952 if (BinaryOperator::isBitwiseOp(Opc))
15953 DiagnoseBitwisePrecedence(Self, Opc, OpLoc, LHSExpr, RHSExpr);
15954
15955 // Diagnose "arg1 & arg2 | arg3"
15956 if ((Opc == BO_Or || Opc == BO_Xor) &&
15957 !OpLoc.isMacroID()/* Don't warn in macros. */) {
15958 DiagnoseBitwiseOpInBitwiseOp(S&: Self, Opc, OpLoc, SubExpr: LHSExpr);
15959 DiagnoseBitwiseOpInBitwiseOp(S&: Self, Opc, OpLoc, SubExpr: RHSExpr);
15960 }
15961
15962 // Warn about arg1 || arg2 && arg3, as GCC 4.3+ does.
15963 // We don't warn for 'assert(a || b && "bad")' since this is safe.
15964 if (Opc == BO_LOr && !OpLoc.isMacroID()/* Don't warn in macros. */) {
15965 DiagnoseLogicalAndInLogicalOrLHS(S&: Self, OpLoc, LHSExpr, RHSExpr);
15966 DiagnoseLogicalAndInLogicalOrRHS(S&: Self, OpLoc, LHSExpr, RHSExpr);
15967 }
15968
15969 if ((Opc == BO_Shl && LHSExpr->getType()->isIntegralType(Ctx: Self.getASTContext()))
15970 || Opc == BO_Shr) {
15971 StringRef Shift = BinaryOperator::getOpcodeStr(Op: Opc);
15972 DiagnoseAdditionInShift(S&: Self, OpLoc, SubExpr: LHSExpr, Shift);
15973 DiagnoseAdditionInShift(S&: Self, OpLoc, SubExpr: RHSExpr, Shift);
15974 }
15975
15976 // Warn on overloaded shift operators and comparisons, such as:
15977 // cout << 5 == 4;
15978 if (BinaryOperator::isComparisonOp(Opc))
15979 DiagnoseShiftCompare(S&: Self, OpLoc, LHSExpr, RHSExpr);
15980}
15981
15982ExprResult Sema::ActOnBinOp(Scope *S, SourceLocation TokLoc,
15983 tok::TokenKind Kind,
15984 Expr *LHSExpr, Expr *RHSExpr) {
15985 BinaryOperatorKind Opc = ConvertTokenKindToBinaryOpcode(Kind);
15986 assert(LHSExpr && "ActOnBinOp(): missing left expression");
15987 assert(RHSExpr && "ActOnBinOp(): missing right expression");
15988
15989 // Emit warnings for tricky precedence issues, e.g. "bitfield & 0x4 == 0"
15990 DiagnoseBinOpPrecedence(Self&: *this, Opc, OpLoc: TokLoc, LHSExpr, RHSExpr);
15991
15992 BuiltinCountedByRefKind K = BinaryOperator::isAssignmentOp(Opc)
15993 ? BuiltinCountedByRefKind::Assignment
15994 : BuiltinCountedByRefKind::BinaryExpr;
15995
15996 CheckInvalidBuiltinCountedByRef(E: LHSExpr, K);
15997 CheckInvalidBuiltinCountedByRef(E: RHSExpr, K);
15998
15999 return BuildBinOp(S, OpLoc: TokLoc, Opc, LHSExpr, RHSExpr);
16000}
16001
16002void Sema::LookupBinOp(Scope *S, SourceLocation OpLoc, BinaryOperatorKind Opc,
16003 UnresolvedSetImpl &Functions) {
16004 OverloadedOperatorKind OverOp = BinaryOperator::getOverloadedOperator(Opc);
16005 if (OverOp != OO_None && OverOp != OO_Equal)
16006 LookupOverloadedOperatorName(Op: OverOp, S, Functions);
16007
16008 // In C++20 onwards, we may have a second operator to look up.
16009 if (getLangOpts().CPlusPlus20) {
16010 if (OverloadedOperatorKind ExtraOp = getRewrittenOverloadedOperator(Kind: OverOp))
16011 LookupOverloadedOperatorName(Op: ExtraOp, S, Functions);
16012 }
16013}
16014
16015/// Build an overloaded binary operator expression in the given scope.
16016static ExprResult BuildOverloadedBinOp(Sema &S, Scope *Sc, SourceLocation OpLoc,
16017 BinaryOperatorKind Opc,
16018 Expr *LHS, Expr *RHS) {
16019 switch (Opc) {
16020 case BO_Assign:
16021 // In the non-overloaded case, we warn about self-assignment (x = x) for
16022 // both simple assignment and certain compound assignments where algebra
16023 // tells us the operation yields a constant result. When the operator is
16024 // overloaded, we can't do the latter because we don't want to assume that
16025 // those algebraic identities still apply; for example, a path-building
16026 // library might use operator/= to append paths. But it's still reasonable
16027 // to assume that simple assignment is just moving/copying values around
16028 // and so self-assignment is likely a bug.
16029 DiagnoseSelfAssignment(S, LHSExpr: LHS, RHSExpr: RHS, OpLoc, IsBuiltin: false);
16030 [[fallthrough]];
16031 case BO_DivAssign:
16032 case BO_RemAssign:
16033 case BO_SubAssign:
16034 case BO_AndAssign:
16035 case BO_OrAssign:
16036 case BO_XorAssign:
16037 CheckIdentityFieldAssignment(LHSExpr: LHS, RHSExpr: RHS, Loc: OpLoc, Sema&: S);
16038 break;
16039 default:
16040 break;
16041 }
16042
16043 // Find all of the overloaded operators visible from this point.
16044 UnresolvedSet<16> Functions;
16045 S.LookupBinOp(S: Sc, OpLoc, Opc, Functions);
16046
16047 // Build the (potentially-overloaded, potentially-dependent)
16048 // binary operation.
16049 return S.CreateOverloadedBinOp(OpLoc, Opc, Fns: Functions, LHS, RHS);
16050}
16051
16052ExprResult Sema::BuildBinOp(Scope *S, SourceLocation OpLoc,
16053 BinaryOperatorKind Opc, Expr *LHSExpr,
16054 Expr *RHSExpr, bool ForFoldExpression) {
16055 if (!LHSExpr || !RHSExpr)
16056 return ExprError();
16057
16058 // We want to end up calling one of SemaPseudoObject::checkAssignment
16059 // (if the LHS is a pseudo-object), BuildOverloadedBinOp (if
16060 // both expressions are overloadable or either is type-dependent),
16061 // or CreateBuiltinBinOp (in any other case). We also want to get
16062 // any placeholder types out of the way.
16063
16064 // Handle pseudo-objects in the LHS.
16065 if (const BuiltinType *pty = LHSExpr->getType()->getAsPlaceholderType()) {
16066 // Assignments with a pseudo-object l-value need special analysis.
16067 if (pty->getKind() == BuiltinType::PseudoObject &&
16068 BinaryOperator::isAssignmentOp(Opc))
16069 return PseudoObject().checkAssignment(S, OpLoc, Opcode: Opc, LHS: LHSExpr, RHS: RHSExpr);
16070
16071 // Don't resolve overloads if the other type is overloadable.
16072 if (getLangOpts().CPlusPlus && pty->getKind() == BuiltinType::Overload) {
16073 // We can't actually test that if we still have a placeholder,
16074 // though. Fortunately, none of the exceptions we see in that
16075 // code below are valid when the LHS is an overload set. Note
16076 // that an overload set can be dependently-typed, but it never
16077 // instantiates to having an overloadable type.
16078 ExprResult resolvedRHS = CheckPlaceholderExpr(E: RHSExpr);
16079 if (resolvedRHS.isInvalid()) return ExprError();
16080 RHSExpr = resolvedRHS.get();
16081
16082 if (RHSExpr->isTypeDependent() ||
16083 RHSExpr->getType()->isOverloadableType())
16084 return BuildOverloadedBinOp(S&: *this, Sc: S, OpLoc, Opc, LHS: LHSExpr, RHS: RHSExpr);
16085 }
16086
16087 // If we're instantiating "a.x < b" or "A::x < b" and 'x' names a function
16088 // template, diagnose the missing 'template' keyword instead of diagnosing
16089 // an invalid use of a bound member function.
16090 //
16091 // Note that "A::x < b" might be valid if 'b' has an overloadable type due
16092 // to C++1z [over.over]/1.4, but we already checked for that case above.
16093 if (Opc == BO_LT && inTemplateInstantiation() &&
16094 (pty->getKind() == BuiltinType::BoundMember ||
16095 pty->getKind() == BuiltinType::Overload)) {
16096 auto *OE = dyn_cast<OverloadExpr>(Val: LHSExpr);
16097 if (OE && !OE->hasTemplateKeyword() && !OE->hasExplicitTemplateArgs() &&
16098 llvm::any_of(Range: OE->decls(), P: [](NamedDecl *ND) {
16099 return isa<FunctionTemplateDecl>(Val: ND);
16100 })) {
16101 Diag(Loc: OE->getQualifier() ? OE->getQualifierLoc().getBeginLoc()
16102 : OE->getNameLoc(),
16103 DiagID: diag::err_template_kw_missing)
16104 << OE->getName().getAsIdentifierInfo();
16105 return ExprError();
16106 }
16107 }
16108
16109 ExprResult LHS = CheckPlaceholderExpr(E: LHSExpr);
16110 if (LHS.isInvalid()) return ExprError();
16111 LHSExpr = LHS.get();
16112 }
16113
16114 // Handle pseudo-objects in the RHS.
16115 if (const BuiltinType *pty = RHSExpr->getType()->getAsPlaceholderType()) {
16116 // An overload in the RHS can potentially be resolved by the type
16117 // being assigned to.
16118 if (Opc == BO_Assign && pty->getKind() == BuiltinType::Overload) {
16119 if (getLangOpts().CPlusPlus &&
16120 (LHSExpr->isTypeDependent() || RHSExpr->isTypeDependent() ||
16121 LHSExpr->getType()->isOverloadableType()))
16122 return BuildOverloadedBinOp(S&: *this, Sc: S, OpLoc, Opc, LHS: LHSExpr, RHS: RHSExpr);
16123
16124 return CreateBuiltinBinOp(OpLoc, Opc, LHSExpr, RHSExpr,
16125 ForFoldExpression);
16126 }
16127
16128 // Don't resolve overloads if the other type is overloadable.
16129 if (getLangOpts().CPlusPlus && pty->getKind() == BuiltinType::Overload &&
16130 LHSExpr->getType()->isOverloadableType())
16131 return BuildOverloadedBinOp(S&: *this, Sc: S, OpLoc, Opc, LHS: LHSExpr, RHS: RHSExpr);
16132
16133 ExprResult resolvedRHS = CheckPlaceholderExpr(E: RHSExpr);
16134 if (!resolvedRHS.isUsable()) return ExprError();
16135 RHSExpr = resolvedRHS.get();
16136 }
16137
16138 if (getLangOpts().HLSL && (LHSExpr->getType()->isHLSLResourceRecord() ||
16139 LHSExpr->getType()->isHLSLResourceRecordArray())) {
16140 if (!HLSL().CheckResourceBinOp(Opc, LHSExpr, RHSExpr, Loc: OpLoc))
16141 return ExprError();
16142 }
16143
16144 if (getLangOpts().CPlusPlus) {
16145 bool CanOverloadBinOp =
16146 !getLangOpts().HLSL ||
16147 HLSL().canHaveOverloadedBinOp(Ty: LHSExpr->getType(), Opc) ||
16148 HLSL().canHaveOverloadedBinOp(Ty: RHSExpr->getType(), Opc);
16149 bool TypeDependent =
16150 LHSExpr->isTypeDependent() || RHSExpr->isTypeDependent();
16151 bool Overloadable = LHSExpr->getType()->isOverloadableType() ||
16152 RHSExpr->getType()->isOverloadableType();
16153 if (CanOverloadBinOp && (TypeDependent || Overloadable))
16154 return BuildOverloadedBinOp(S&: *this, Sc: S, OpLoc, Opc, LHS: LHSExpr, RHS: RHSExpr);
16155 }
16156
16157 if (getLangOpts().RecoveryAST &&
16158 (LHSExpr->isTypeDependent() || RHSExpr->isTypeDependent())) {
16159 assert(!getLangOpts().CPlusPlus);
16160 assert((LHSExpr->containsErrors() || RHSExpr->containsErrors()) &&
16161 "Should only occur in error-recovery path.");
16162 if (BinaryOperator::isCompoundAssignmentOp(Opc))
16163 // C [6.15.16] p3:
16164 // An assignment expression has the value of the left operand after the
16165 // assignment, but is not an lvalue.
16166 return CompoundAssignOperator::Create(
16167 C: Context, lhs: LHSExpr, rhs: RHSExpr, opc: Opc,
16168 ResTy: LHSExpr->getType().getUnqualifiedType(), VK: VK_PRValue, OK: OK_Ordinary,
16169 opLoc: OpLoc, FPFeatures: CurFPFeatureOverrides());
16170 QualType ResultType;
16171 switch (Opc) {
16172 case BO_Assign:
16173 ResultType = LHSExpr->getType().getUnqualifiedType();
16174 break;
16175 case BO_LT:
16176 case BO_GT:
16177 case BO_LE:
16178 case BO_GE:
16179 case BO_EQ:
16180 case BO_NE:
16181 case BO_LAnd:
16182 case BO_LOr:
16183 // These operators have a fixed result type regardless of operands.
16184 ResultType = Context.IntTy;
16185 break;
16186 case BO_Comma:
16187 ResultType = RHSExpr->getType();
16188 break;
16189 default:
16190 ResultType = Context.DependentTy;
16191 break;
16192 }
16193 return BinaryOperator::Create(C: Context, lhs: LHSExpr, rhs: RHSExpr, opc: Opc, ResTy: ResultType,
16194 VK: VK_PRValue, OK: OK_Ordinary, opLoc: OpLoc,
16195 FPFeatures: CurFPFeatureOverrides());
16196 }
16197
16198 // Build a built-in binary operation.
16199 return CreateBuiltinBinOp(OpLoc, Opc, LHSExpr, RHSExpr, ForFoldExpression);
16200}
16201
16202static bool isOverflowingIntegerType(ASTContext &Ctx, QualType T) {
16203 if (T.isNull() || T->isDependentType())
16204 return false;
16205
16206 if (!Ctx.isPromotableIntegerType(T))
16207 return true;
16208
16209 return Ctx.getIntWidth(T) >= Ctx.getIntWidth(T: Ctx.IntTy);
16210}
16211
16212ExprResult Sema::CreateBuiltinUnaryOp(SourceLocation OpLoc,
16213 UnaryOperatorKind Opc, Expr *InputExpr,
16214 bool IsAfterAmp) {
16215 ExprResult Input = InputExpr;
16216 ExprValueKind VK = VK_PRValue;
16217 ExprObjectKind OK = OK_Ordinary;
16218 QualType resultType;
16219 bool CanOverflow = false;
16220
16221 bool ConvertHalfVec = false;
16222 if (getLangOpts().OpenCL) {
16223 QualType Ty = InputExpr->getType();
16224 // The only legal unary operation for atomics is '&'.
16225 if ((Opc != UO_AddrOf && Ty->isAtomicType()) ||
16226 // OpenCL special types - image, sampler, pipe, and blocks are to be used
16227 // only with a builtin functions and therefore should be disallowed here.
16228 (Ty->isImageType() || Ty->isSamplerT() || Ty->isPipeType()
16229 || Ty->isBlockPointerType())) {
16230 return ExprError(Diag(Loc: OpLoc, DiagID: diag::err_typecheck_unary_expr)
16231 << InputExpr->getType()
16232 << Input.get()->getSourceRange());
16233 }
16234 }
16235
16236 if (getLangOpts().HLSL && OpLoc.isValid()) {
16237 if (Opc == UO_AddrOf)
16238 return ExprError(Diag(Loc: OpLoc, DiagID: diag::err_hlsl_operator_unsupported) << 0);
16239 if (Opc == UO_Deref)
16240 return ExprError(Diag(Loc: OpLoc, DiagID: diag::err_hlsl_operator_unsupported) << 1);
16241 }
16242
16243 if (InputExpr->isTypeDependent() &&
16244 InputExpr->getType()->isSpecificBuiltinType(K: BuiltinType::Dependent)) {
16245 resultType = Context.DependentTy;
16246 } else {
16247 switch (Opc) {
16248 case UO_PreInc:
16249 case UO_PreDec:
16250 case UO_PostInc:
16251 case UO_PostDec:
16252 resultType =
16253 CheckIncrementDecrementOperand(S&: *this, Op: Input.get(), VK, OK, OpLoc,
16254 IsInc: Opc == UO_PreInc || Opc == UO_PostInc,
16255 IsPrefix: Opc == UO_PreInc || Opc == UO_PreDec);
16256 CanOverflow = isOverflowingIntegerType(Ctx&: Context, T: resultType);
16257 break;
16258 case UO_AddrOf:
16259 resultType = CheckAddressOfOperand(OrigOp&: Input, OpLoc);
16260 CheckAddressOfNoDeref(E: InputExpr);
16261 RecordModifiableNonNullParam(S&: *this, Exp: InputExpr);
16262 break;
16263 case UO_Deref: {
16264 Input = DefaultFunctionArrayLvalueConversion(E: Input.get());
16265 if (Input.isInvalid())
16266 return ExprError();
16267 resultType =
16268 CheckIndirectionOperand(S&: *this, Op: Input.get(), VK, OpLoc, IsAfterAmp);
16269 break;
16270 }
16271 case UO_Plus:
16272 case UO_Minus:
16273 CanOverflow = Opc == UO_Minus &&
16274 isOverflowingIntegerType(Ctx&: Context, T: Input.get()->getType());
16275 Input = UsualUnaryConversions(E: Input.get());
16276 if (Input.isInvalid())
16277 return ExprError();
16278 // Unary plus and minus require promoting an operand of half vector to a
16279 // float vector and truncating the result back to a half vector. For now,
16280 // we do this only when HalfArgsAndReturns is set (that is, when the
16281 // target is arm or arm64).
16282 ConvertHalfVec = needsConversionOfHalfVec(OpRequiresConversion: true, Ctx&: Context, E0: Input.get());
16283
16284 // If the operand is a half vector, promote it to a float vector.
16285 if (ConvertHalfVec)
16286 Input = convertVector(E: Input.get(), ElementType: Context.FloatTy, S&: *this);
16287 resultType = Input.get()->getType();
16288 if (resultType->isArithmeticType()) // C99 6.5.3.3p1
16289 break;
16290 else if (resultType->isVectorType() &&
16291 // The z vector extensions don't allow + or - with bool vectors.
16292 (!Context.getLangOpts().ZVector ||
16293 resultType->castAs<VectorType>()->getVectorKind() !=
16294 VectorKind::AltiVecBool))
16295 break;
16296 else if (resultType->isSveVLSBuiltinType()) // SVE vectors allow + and -
16297 break;
16298 else if (getLangOpts().CPlusPlus && // C++ [expr.unary.op]p6
16299 Opc == UO_Plus && resultType->isPointerType())
16300 break;
16301
16302 return ExprError(Diag(Loc: OpLoc, DiagID: diag::err_typecheck_unary_expr)
16303 << resultType << Input.get()->getSourceRange());
16304
16305 case UO_Not: // bitwise complement
16306 Input = UsualUnaryConversions(E: Input.get());
16307 if (Input.isInvalid())
16308 return ExprError();
16309 resultType = Input.get()->getType();
16310 // C99 6.5.3.3p1. We allow complex int and float as a GCC extension.
16311 if (resultType->isComplexType() || resultType->isComplexIntegerType())
16312 // C99 does not support '~' for complex conjugation.
16313 Diag(Loc: OpLoc, DiagID: diag::ext_integer_complement_complex)
16314 << resultType << Input.get()->getSourceRange();
16315 else if (resultType->hasIntegerRepresentation())
16316 break;
16317 else if (resultType->isExtVectorType() && Context.getLangOpts().OpenCL) {
16318 // OpenCL v1.1 s6.3.f: The bitwise operator not (~) does not operate
16319 // on vector float types.
16320 QualType T = resultType->castAs<ExtVectorType>()->getElementType();
16321 if (!T->isIntegerType())
16322 return ExprError(Diag(Loc: OpLoc, DiagID: diag::err_typecheck_unary_expr)
16323 << resultType << Input.get()->getSourceRange());
16324 } else {
16325 return ExprError(Diag(Loc: OpLoc, DiagID: diag::err_typecheck_unary_expr)
16326 << resultType << Input.get()->getSourceRange());
16327 }
16328 break;
16329
16330 case UO_LNot: // logical negation
16331 // Unlike +/-/~, integer promotions aren't done here (C99 6.5.3.3p5).
16332 Input = DefaultFunctionArrayLvalueConversion(E: Input.get());
16333 if (Input.isInvalid())
16334 return ExprError();
16335 resultType = Input.get()->getType();
16336
16337 // Though we still have to promote half FP to float...
16338 if (resultType->isHalfType() && !Context.getLangOpts().NativeHalfType) {
16339 Input = ImpCastExprToType(E: Input.get(), Type: Context.FloatTy, CK: CK_FloatingCast)
16340 .get();
16341 resultType = Context.FloatTy;
16342 }
16343
16344 // WebAsembly tables can't be used in unary expressions.
16345 if (resultType->isPointerType() &&
16346 resultType->getPointeeType().isWebAssemblyReferenceType()) {
16347 return ExprError(Diag(Loc: OpLoc, DiagID: diag::err_typecheck_unary_expr)
16348 << resultType << Input.get()->getSourceRange());
16349 }
16350
16351 if (resultType->isScalarType() && !isScopedEnumerationType(T: resultType)) {
16352 // C99 6.5.3.3p1: ok, fallthrough;
16353 if (Context.getLangOpts().CPlusPlus) {
16354 // C++03 [expr.unary.op]p8, C++0x [expr.unary.op]p9:
16355 // operand contextually converted to bool.
16356 Input = ImpCastExprToType(E: Input.get(), Type: Context.BoolTy,
16357 CK: ScalarTypeToBooleanCastKind(ScalarTy: resultType));
16358 } else if (Context.getLangOpts().OpenCL &&
16359 Context.getLangOpts().OpenCLVersion < 120) {
16360 // OpenCL v1.1 6.3.h: The logical operator not (!) does not
16361 // operate on scalar float types.
16362 if (!resultType->isIntegerType() && !resultType->isPointerType())
16363 return ExprError(Diag(Loc: OpLoc, DiagID: diag::err_typecheck_unary_expr)
16364 << resultType << Input.get()->getSourceRange());
16365 }
16366 } else if (Context.getLangOpts().HLSL && resultType->isVectorType() &&
16367 !resultType->hasBooleanRepresentation()) {
16368 // HLSL unary logical 'not' behaves like C++, which states that the
16369 // operand is converted to bool and the result is bool, however HLSL
16370 // extends this property to vectors.
16371 const VectorType *VTy = resultType->castAs<VectorType>();
16372 resultType =
16373 Context.getExtVectorType(VectorType: Context.BoolTy, NumElts: VTy->getNumElements());
16374
16375 Input = ImpCastExprToType(
16376 E: Input.get(), Type: resultType,
16377 CK: ScalarTypeToBooleanCastKind(ScalarTy: VTy->getElementType()))
16378 .get();
16379 break;
16380 } else if (resultType->isExtVectorType()) {
16381 if (Context.getLangOpts().OpenCL &&
16382 Context.getLangOpts().getOpenCLCompatibleVersion() < 120) {
16383 // OpenCL v1.1 6.3.h: The logical operator not (!) does not
16384 // operate on vector float types.
16385 QualType T = resultType->castAs<ExtVectorType>()->getElementType();
16386 if (!T->isIntegerType())
16387 return ExprError(Diag(Loc: OpLoc, DiagID: diag::err_typecheck_unary_expr)
16388 << resultType << Input.get()->getSourceRange());
16389 }
16390 // Vector logical not returns the signed variant of the operand type.
16391 resultType = GetSignedVectorType(V: resultType);
16392 break;
16393 } else if (Context.getLangOpts().CPlusPlus &&
16394 resultType->isVectorType()) {
16395 const VectorType *VTy = resultType->castAs<VectorType>();
16396 if (VTy->getVectorKind() != VectorKind::Generic)
16397 return ExprError(Diag(Loc: OpLoc, DiagID: diag::err_typecheck_unary_expr)
16398 << resultType << Input.get()->getSourceRange());
16399
16400 // Vector logical not returns the signed variant of the operand type.
16401 resultType = GetSignedVectorType(V: resultType);
16402 break;
16403 } else if (resultType == Context.AMDGPUFeaturePredicateTy) {
16404 resultType = Context.getLogicalOperationType();
16405 Input = AMDGPU().ExpandAMDGPUPredicateBuiltIn(CE: InputExpr);
16406 break;
16407 } else {
16408 return ExprError(Diag(Loc: OpLoc, DiagID: diag::err_typecheck_unary_expr)
16409 << resultType << Input.get()->getSourceRange());
16410 }
16411
16412 // LNot always has type int. C99 6.5.3.3p5.
16413 // In C++, it's bool. C++ 5.3.1p8
16414 resultType = Context.getLogicalOperationType();
16415 break;
16416 case UO_Real:
16417 case UO_Imag:
16418 resultType = CheckRealImagOperand(S&: *this, V&: Input, Loc: OpLoc, IsReal: Opc == UO_Real);
16419 // _Real maps ordinary l-values into ordinary l-values. _Imag maps
16420 // ordinary complex l-values to ordinary l-values and all other values to
16421 // r-values.
16422 if (Input.isInvalid())
16423 return ExprError();
16424 if (Opc == UO_Real || Input.get()->getType()->isAnyComplexType()) {
16425 if (Input.get()->isGLValue() &&
16426 Input.get()->getObjectKind() == OK_Ordinary)
16427 VK = Input.get()->getValueKind();
16428 } else if (!getLangOpts().CPlusPlus) {
16429 // In C, a volatile scalar is read by __imag. In C++, it is not.
16430 Input = DefaultLvalueConversion(E: Input.get());
16431 }
16432 break;
16433 case UO_Extension:
16434 resultType = Input.get()->getType();
16435 VK = Input.get()->getValueKind();
16436 OK = Input.get()->getObjectKind();
16437 break;
16438 case UO_Coawait:
16439 // It's unnecessary to represent the pass-through operator co_await in the
16440 // AST; just return the input expression instead.
16441 assert(!Input.get()->getType()->isDependentType() &&
16442 "the co_await expression must be non-dependant before "
16443 "building operator co_await");
16444 return Input;
16445 }
16446 }
16447 if (resultType.isNull() || Input.isInvalid())
16448 return ExprError();
16449
16450 // Check for array bounds violations in the operand of the UnaryOperator,
16451 // except for the '*' and '&' operators that have to be handled specially
16452 // by CheckArrayAccess (as there are special cases like &array[arraysize]
16453 // that are explicitly defined as valid by the standard).
16454 if (Opc != UO_AddrOf && Opc != UO_Deref)
16455 CheckArrayAccess(E: Input.get());
16456
16457 auto *UO =
16458 UnaryOperator::Create(C: Context, input: Input.get(), opc: Opc, type: resultType, VK, OK,
16459 l: OpLoc, CanOverflow, FPFeatures: CurFPFeatureOverrides());
16460
16461 if (Opc == UO_Deref && UO->getType()->hasAttr(AK: attr::NoDeref) &&
16462 !isa<ArrayType>(Val: UO->getType().getDesugaredType(Context)) &&
16463 !isUnevaluatedContext())
16464 ExprEvalContexts.back().PossibleDerefs.insert(Ptr: UO);
16465
16466 // Convert the result back to a half vector.
16467 if (ConvertHalfVec)
16468 return convertVector(E: UO, ElementType: Context.HalfTy, S&: *this);
16469 return UO;
16470}
16471
16472bool Sema::isQualifiedMemberAccess(Expr *E) {
16473 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Val: E)) {
16474 if (!DRE->getQualifier())
16475 return false;
16476
16477 ValueDecl *VD = DRE->getDecl();
16478 if (!VD->isCXXClassMember())
16479 return false;
16480
16481 if (isa<FieldDecl>(Val: VD) || isa<IndirectFieldDecl>(Val: VD))
16482 return true;
16483 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Val: VD))
16484 return Method->isImplicitObjectMemberFunction();
16485
16486 return false;
16487 }
16488
16489 if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(Val: E)) {
16490 if (!ULE->getQualifier())
16491 return false;
16492
16493 for (NamedDecl *D : ULE->decls()) {
16494 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Val: D)) {
16495 if (Method->isImplicitObjectMemberFunction())
16496 return true;
16497 } else {
16498 // Overload set does not contain methods.
16499 break;
16500 }
16501 }
16502
16503 return false;
16504 }
16505
16506 return false;
16507}
16508
16509ExprResult Sema::BuildUnaryOp(Scope *S, SourceLocation OpLoc,
16510 UnaryOperatorKind Opc, Expr *Input,
16511 bool IsAfterAmp) {
16512 // First things first: handle placeholders so that the
16513 // overloaded-operator check considers the right type.
16514 if (const BuiltinType *pty = Input->getType()->getAsPlaceholderType()) {
16515 // Increment and decrement of pseudo-object references.
16516 if (pty->getKind() == BuiltinType::PseudoObject &&
16517 UnaryOperator::isIncrementDecrementOp(Op: Opc))
16518 return PseudoObject().checkIncDec(S, OpLoc, Opcode: Opc, Op: Input);
16519
16520 // extension is always a builtin operator.
16521 if (Opc == UO_Extension)
16522 return CreateBuiltinUnaryOp(OpLoc, Opc, InputExpr: Input);
16523
16524 // & gets special logic for several kinds of placeholder.
16525 // The builtin code knows what to do.
16526 if (Opc == UO_AddrOf &&
16527 (pty->getKind() == BuiltinType::Overload ||
16528 pty->getKind() == BuiltinType::UnknownAny ||
16529 pty->getKind() == BuiltinType::BoundMember))
16530 return CreateBuiltinUnaryOp(OpLoc, Opc, InputExpr: Input);
16531
16532 // Anything else needs to be handled now.
16533 ExprResult Result = CheckPlaceholderExpr(E: Input);
16534 if (Result.isInvalid()) return ExprError();
16535 Input = Result.get();
16536 }
16537
16538 if (getLangOpts().CPlusPlus && Input->getType()->isOverloadableType() &&
16539 UnaryOperator::getOverloadedOperator(Opc) != OO_None &&
16540 !(Opc == UO_AddrOf && isQualifiedMemberAccess(E: Input))) {
16541 // Find all of the overloaded operators visible from this point.
16542 UnresolvedSet<16> Functions;
16543 OverloadedOperatorKind OverOp = UnaryOperator::getOverloadedOperator(Opc);
16544 if (S && OverOp != OO_None)
16545 LookupOverloadedOperatorName(Op: OverOp, S, Functions);
16546
16547 return CreateOverloadedUnaryOp(OpLoc, Opc, Fns: Functions, input: Input);
16548 }
16549
16550 return CreateBuiltinUnaryOp(OpLoc, Opc, InputExpr: Input, IsAfterAmp);
16551}
16552
16553ExprResult Sema::ActOnUnaryOp(Scope *S, SourceLocation OpLoc, tok::TokenKind Op,
16554 Expr *Input, bool IsAfterAmp) {
16555 return BuildUnaryOp(S, OpLoc, Opc: ConvertTokenKindToUnaryOpcode(Kind: Op), Input,
16556 IsAfterAmp);
16557}
16558
16559ExprResult Sema::ActOnAddrLabel(SourceLocation OpLoc, SourceLocation LabLoc,
16560 LabelDecl *TheDecl) {
16561 TheDecl->markUsed(C&: Context);
16562 // Create the AST node. The address of a label always has type 'void*'.
16563 auto *Res = new (Context) AddrLabelExpr(
16564 OpLoc, LabLoc, TheDecl, Context.getPointerType(T: Context.VoidTy));
16565
16566 if (getCurFunction())
16567 getCurFunction()->AddrLabels.push_back(Elt: Res);
16568
16569 return Res;
16570}
16571
16572void Sema::ActOnStartStmtExpr() {
16573 PushExpressionEvaluationContext(NewContext: ExprEvalContexts.back().Context);
16574 // Make sure we diagnose jumping into a statement expression.
16575 setFunctionHasBranchProtectedScope();
16576}
16577
16578void Sema::ActOnStmtExprError() {
16579 // Note that function is also called by TreeTransform when leaving a
16580 // StmtExpr scope without rebuilding anything.
16581
16582 DiscardCleanupsInEvaluationContext();
16583 PopExpressionEvaluationContext();
16584}
16585
16586ExprResult Sema::ActOnStmtExpr(Scope *S, SourceLocation LPLoc, Stmt *SubStmt,
16587 SourceLocation RPLoc) {
16588 return BuildStmtExpr(LPLoc, SubStmt, RPLoc, TemplateDepth: getTemplateDepth(S));
16589}
16590
16591ExprResult Sema::BuildStmtExpr(SourceLocation LPLoc, Stmt *SubStmt,
16592 SourceLocation RPLoc, unsigned TemplateDepth) {
16593 assert(SubStmt && isa<CompoundStmt>(SubStmt) && "Invalid action invocation!");
16594 CompoundStmt *Compound = cast<CompoundStmt>(Val: SubStmt);
16595
16596 if (hasAnyUnrecoverableErrorsInThisFunction())
16597 DiscardCleanupsInEvaluationContext();
16598 assert(!Cleanup.exprNeedsCleanups() &&
16599 "cleanups within StmtExpr not correctly bound!");
16600 PopExpressionEvaluationContext();
16601
16602 // FIXME: there are a variety of strange constraints to enforce here, for
16603 // example, it is not possible to goto into a stmt expression apparently.
16604 // More semantic analysis is needed.
16605
16606 // If there are sub-stmts in the compound stmt, take the type of the last one
16607 // as the type of the stmtexpr.
16608 QualType Ty = Context.VoidTy;
16609 bool StmtExprMayBindToTemp = false;
16610 if (!Compound->body_empty()) {
16611 if (const auto *LastStmt = dyn_cast<ValueStmt>(Val: Compound->body_back())) {
16612 if (const Expr *Value = LastStmt->getExprStmt()) {
16613 StmtExprMayBindToTemp = true;
16614 Ty = Value->getType();
16615 }
16616 }
16617 }
16618
16619 // FIXME: Check that expression type is complete/non-abstract; statement
16620 // expressions are not lvalues.
16621 Expr *ResStmtExpr =
16622 new (Context) StmtExpr(Compound, Ty, LPLoc, RPLoc, TemplateDepth);
16623 if (StmtExprMayBindToTemp)
16624 return MaybeBindToTemporary(E: ResStmtExpr);
16625 return ResStmtExpr;
16626}
16627
16628ExprResult Sema::ActOnStmtExprResult(ExprResult ER) {
16629 if (ER.isInvalid())
16630 return ExprError();
16631
16632 // Do function/array conversion on the last expression, but not
16633 // lvalue-to-rvalue. However, initialize an unqualified type.
16634 ER = DefaultFunctionArrayConversion(E: ER.get());
16635 if (ER.isInvalid())
16636 return ExprError();
16637 Expr *E = ER.get();
16638
16639 if (E->isTypeDependent())
16640 return E;
16641
16642 // In ARC, if the final expression ends in a consume, splice
16643 // the consume out and bind it later. In the alternate case
16644 // (when dealing with a retainable type), the result
16645 // initialization will create a produce. In both cases the
16646 // result will be +1, and we'll need to balance that out with
16647 // a bind.
16648 auto *Cast = dyn_cast<ImplicitCastExpr>(Val: E);
16649 if (Cast && Cast->getCastKind() == CK_ARCConsumeObject)
16650 return Cast->getSubExpr();
16651
16652 // FIXME: Provide a better location for the initialization.
16653 return PerformCopyInitialization(
16654 Entity: InitializedEntity::InitializeStmtExprResult(
16655 ReturnLoc: E->getBeginLoc(), Type: E->getType().getAtomicUnqualifiedType()),
16656 EqualLoc: SourceLocation(), Init: E);
16657}
16658
16659ExprResult Sema::BuildBuiltinOffsetOf(SourceLocation BuiltinLoc,
16660 TypeSourceInfo *TInfo,
16661 const Designation &Desig,
16662 SourceLocation RParenLoc) {
16663 QualType ArgTy = TInfo->getType();
16664 bool Dependent = ArgTy->isDependentType();
16665 SourceRange TypeRange = TInfo->getTypeLoc().getLocalSourceRange();
16666
16667 // We must have at least one component that refers to the type, and the first
16668 // one is known to be a field designator. Verify that the ArgTy represents
16669 // a struct/union/class.
16670 if (!Dependent && !ArgTy->isRecordType())
16671 return ExprError(Diag(Loc: BuiltinLoc, DiagID: diag::err_offsetof_record_type)
16672 << ArgTy << TypeRange);
16673
16674 // Type must be complete per C99 7.17p3 because a declaring a variable
16675 // with an incomplete type would be ill-formed.
16676 if (!Dependent
16677 && RequireCompleteType(Loc: BuiltinLoc, T: ArgTy,
16678 DiagID: diag::err_offsetof_incomplete_type, Args: TypeRange))
16679 return ExprError();
16680
16681 bool DidWarnAboutNonPOD = false;
16682 QualType CurrentType = ArgTy;
16683 SmallVector<OffsetOfNode, 4> Comps;
16684 SmallVector<Expr *, 4> Exprs;
16685 for (unsigned I = 0, N = Desig.getNumDesignators(); I != N; ++I) {
16686 const Designator &D = Desig.getDesignator(Idx: I);
16687 assert(!D.isArrayRangeDesignator());
16688 if (D.isArrayDesignator()) {
16689 // Offset of an array sub-field. TODO: Should we allow vector elements?
16690 if (!CurrentType->isDependentType()) {
16691 const ArrayType *AT = Context.getAsArrayType(T: CurrentType);
16692 if(!AT)
16693 return ExprError(Diag(Loc: D.getEndLoc(), DiagID: diag::err_offsetof_array_type)
16694 << CurrentType);
16695 CurrentType = AT->getElementType();
16696 } else
16697 CurrentType = Context.DependentTy;
16698
16699 ExprResult IdxRval = DefaultLvalueConversion(E: D.getArrayIndex());
16700 if (IdxRval.isInvalid())
16701 return ExprError();
16702 Expr *Idx = IdxRval.get();
16703
16704 // The expression must be an integral expression.
16705 // FIXME: An integral constant expression?
16706 if (!Idx->isTypeDependent() && !Idx->isValueDependent() &&
16707 !Idx->getType()->isIntegerType())
16708 return ExprError(
16709 Diag(Loc: Idx->getBeginLoc(), DiagID: diag::err_typecheck_subscript_not_integer)
16710 << Idx->getSourceRange());
16711
16712 // Record this array index.
16713 Comps.push_back(
16714 Elt: OffsetOfNode(D.getBeginLoc(), Exprs.size(), D.getEndLoc()));
16715 Exprs.push_back(Elt: Idx);
16716 continue;
16717 }
16718
16719 assert(D.isFieldDesignator());
16720 const IdentifierInfo *Name = D.getFieldDecl();
16721
16722 // Offset of a field.
16723 if (CurrentType->isDependentType()) {
16724 // We have the offset of a field, but we can't look into the dependent
16725 // type. Just record the identifier of the field.
16726 Comps.push_back(Elt: OffsetOfNode(D.getBeginLoc(), Name, D.getEndLoc()));
16727 CurrentType = Context.DependentTy;
16728 continue;
16729 }
16730
16731 // We need to have a complete type to look into.
16732 if (RequireCompleteType(Loc: D.getBeginLoc(), T: CurrentType,
16733 DiagID: diag::err_offsetof_incomplete_type))
16734 return ExprError();
16735
16736 // Look for the designated field.
16737 auto *RD = CurrentType->getAsRecordDecl();
16738 if (!RD)
16739 return ExprError(Diag(Loc: D.getEndLoc(), DiagID: diag::err_offsetof_record_type)
16740 << CurrentType);
16741
16742 // C++ [lib.support.types]p5:
16743 // The macro offsetof accepts a restricted set of type arguments in this
16744 // International Standard. type shall be a POD structure or a POD union
16745 // (clause 9).
16746 // C++11 [support.types]p4:
16747 // If type is not a standard-layout class (Clause 9), the results are
16748 // undefined.
16749 if (CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(Val: RD)) {
16750 bool IsSafe = LangOpts.CPlusPlus11? CRD->isStandardLayout() : CRD->isPOD();
16751 unsigned DiagID =
16752 LangOpts.CPlusPlus11? diag::ext_offsetof_non_standardlayout_type
16753 : diag::ext_offsetof_non_pod_type;
16754
16755 if (!IsSafe && !DidWarnAboutNonPOD && !isUnevaluatedContext()) {
16756 Diag(Loc: BuiltinLoc, DiagID)
16757 << SourceRange(Desig.getDesignator(Idx: 0).getBeginLoc(), D.getEndLoc())
16758 << CurrentType;
16759 DidWarnAboutNonPOD = true;
16760 }
16761 }
16762
16763 // Look for the field.
16764 LookupResult R(*this, Name, D.getBeginLoc(), LookupMemberName);
16765 LookupQualifiedName(R, LookupCtx: RD);
16766 FieldDecl *MemberDecl = R.getAsSingle<FieldDecl>();
16767 IndirectFieldDecl *IndirectMemberDecl = nullptr;
16768 if (!MemberDecl) {
16769 if ((IndirectMemberDecl = R.getAsSingle<IndirectFieldDecl>()))
16770 MemberDecl = IndirectMemberDecl->getAnonField();
16771 }
16772
16773 if (!MemberDecl) {
16774 // Lookup could be ambiguous when looking up a placeholder variable
16775 // __builtin_offsetof(S, _).
16776 // In that case we would already have emitted a diagnostic
16777 if (!R.isAmbiguous())
16778 Diag(Loc: BuiltinLoc, DiagID: diag::err_no_member)
16779 << Name << RD << SourceRange(D.getBeginLoc(), D.getEndLoc());
16780 return ExprError();
16781 }
16782
16783 // C99 7.17p3:
16784 // (If the specified member is a bit-field, the behavior is undefined.)
16785 //
16786 // We diagnose this as an error.
16787 if (MemberDecl->isBitField()) {
16788 Diag(Loc: D.getEndLoc(), DiagID: diag::err_offsetof_bitfield)
16789 << MemberDecl->getDeclName() << SourceRange(BuiltinLoc, RParenLoc);
16790 Diag(Loc: MemberDecl->getLocation(), DiagID: diag::note_bitfield_decl);
16791 return ExprError();
16792 }
16793
16794 RecordDecl *Parent = MemberDecl->getParent();
16795 if (IndirectMemberDecl)
16796 Parent = cast<RecordDecl>(Val: IndirectMemberDecl->getDeclContext());
16797
16798 // If the member was found in a base class, introduce OffsetOfNodes for
16799 // the base class indirections.
16800 CXXBasePaths Paths;
16801 if (IsDerivedFrom(Loc: D.getBeginLoc(), Derived: CurrentType,
16802 Base: Context.getCanonicalTagType(TD: Parent), Paths)) {
16803 if (Paths.getDetectedVirtual()) {
16804 Diag(Loc: D.getEndLoc(), DiagID: diag::err_offsetof_field_of_virtual_base)
16805 << MemberDecl->getDeclName() << SourceRange(BuiltinLoc, RParenLoc);
16806 return ExprError();
16807 }
16808
16809 CXXBasePath &Path = Paths.front();
16810 for (const CXXBasePathElement &B : Path)
16811 Comps.push_back(Elt: OffsetOfNode(B.Base));
16812 }
16813
16814 if (IndirectMemberDecl) {
16815 for (auto *FI : IndirectMemberDecl->chain()) {
16816 assert(isa<FieldDecl>(FI));
16817 Comps.push_back(
16818 Elt: OffsetOfNode(D.getBeginLoc(), cast<FieldDecl>(Val: FI), D.getEndLoc()));
16819 }
16820 } else
16821 Comps.push_back(Elt: OffsetOfNode(D.getBeginLoc(), MemberDecl, D.getEndLoc()));
16822
16823 CurrentType = MemberDecl->getType().getNonReferenceType();
16824 }
16825
16826 return OffsetOfExpr::Create(C: Context, type: Context.getSizeType(), OperatorLoc: BuiltinLoc, tsi: TInfo,
16827 comps: Comps, exprs: Exprs, RParenLoc);
16828}
16829
16830ExprResult Sema::ActOnBuiltinOffsetOf(Scope *S, SourceLocation BuiltinLoc,
16831 SourceLocation TypeLoc,
16832 ParsedType ParsedArgTy,
16833 const Designation &Desig,
16834 SourceLocation RParenLoc) {
16835
16836 TypeSourceInfo *ArgTInfo;
16837 QualType ArgTy = GetTypeFromParser(Ty: ParsedArgTy, TInfo: &ArgTInfo);
16838 if (ArgTy.isNull())
16839 return ExprError();
16840
16841 if (!ArgTInfo)
16842 ArgTInfo = Context.getTrivialTypeSourceInfo(T: ArgTy, Loc: TypeLoc);
16843
16844 return BuildBuiltinOffsetOf(BuiltinLoc, TInfo: ArgTInfo, Desig, RParenLoc);
16845}
16846
16847ExprResult Sema::ActOnChooseExpr(SourceLocation BuiltinLoc,
16848 Expr *CondExpr,
16849 Expr *LHSExpr, Expr *RHSExpr,
16850 SourceLocation RPLoc) {
16851 assert((CondExpr && LHSExpr && RHSExpr) && "Missing type argument(s)");
16852
16853 ExprValueKind VK = VK_PRValue;
16854 ExprObjectKind OK = OK_Ordinary;
16855 QualType resType;
16856 bool CondIsTrue = false;
16857 if (CondExpr->isTypeDependent() || CondExpr->isValueDependent()) {
16858 resType = Context.DependentTy;
16859 } else {
16860 // The conditional expression is required to be a constant expression.
16861 llvm::APSInt condEval(32);
16862 ExprResult CondICE = VerifyIntegerConstantExpression(
16863 E: CondExpr, Result: &condEval, DiagID: diag::err_typecheck_choose_expr_requires_constant);
16864 if (CondICE.isInvalid())
16865 return ExprError();
16866 CondExpr = CondICE.get();
16867 CondIsTrue = condEval.getZExtValue();
16868
16869 // If the condition is > zero, then the AST type is the same as the LHSExpr.
16870 Expr *ActiveExpr = CondIsTrue ? LHSExpr : RHSExpr;
16871
16872 resType = ActiveExpr->getType();
16873 VK = ActiveExpr->getValueKind();
16874 OK = ActiveExpr->getObjectKind();
16875 }
16876
16877 return new (Context) ChooseExpr(BuiltinLoc, CondExpr, LHSExpr, RHSExpr,
16878 resType, VK, OK, RPLoc, CondIsTrue);
16879}
16880
16881//===----------------------------------------------------------------------===//
16882// Clang Extensions.
16883//===----------------------------------------------------------------------===//
16884
16885void Sema::ActOnBlockStart(SourceLocation CaretLoc, Scope *CurScope) {
16886 BlockDecl *Block = BlockDecl::Create(C&: Context, DC: CurContext, L: CaretLoc);
16887
16888 if (LangOpts.CPlusPlus) {
16889 MangleNumberingContext *MCtx;
16890 Decl *ManglingContextDecl;
16891 std::tie(args&: MCtx, args&: ManglingContextDecl) =
16892 getCurrentMangleNumberContext(DC: Block->getDeclContext());
16893 if (MCtx) {
16894 unsigned ManglingNumber = MCtx->getManglingNumber(BD: Block);
16895 Block->setBlockMangling(Number: ManglingNumber, Ctx: ManglingContextDecl);
16896 }
16897 }
16898
16899 PushBlockScope(BlockScope: CurScope, Block);
16900 CurContext->addDecl(D: Block);
16901 if (CurScope)
16902 PushDeclContext(S: CurScope, DC: Block);
16903 else
16904 CurContext = Block;
16905
16906 getCurBlock()->HasImplicitReturnType = true;
16907
16908 // Enter a new evaluation context to insulate the block from any
16909 // cleanups from the enclosing full-expression.
16910 PushExpressionEvaluationContext(
16911 NewContext: ExpressionEvaluationContext::PotentiallyEvaluated);
16912}
16913
16914void Sema::ActOnBlockArguments(SourceLocation CaretLoc, Declarator &ParamInfo,
16915 Scope *CurScope) {
16916 assert(ParamInfo.getIdentifier() == nullptr &&
16917 "block-id should have no identifier!");
16918 assert(ParamInfo.getContext() == DeclaratorContext::BlockLiteral);
16919 BlockScopeInfo *CurBlock = getCurBlock();
16920
16921 TypeSourceInfo *Sig = GetTypeForDeclarator(D&: ParamInfo);
16922 QualType T = Sig->getType();
16923 DiagnoseUnexpandedParameterPack(Loc: CaretLoc, T: Sig, UPPC: UPPC_Block);
16924
16925 // GetTypeForDeclarator always produces a function type for a block
16926 // literal signature. Furthermore, it is always a FunctionProtoType
16927 // unless the function was written with a typedef.
16928 assert(T->isFunctionType() &&
16929 "GetTypeForDeclarator made a non-function block signature");
16930
16931 // Look for an explicit signature in that function type.
16932 FunctionProtoTypeLoc ExplicitSignature;
16933
16934 if ((ExplicitSignature = Sig->getTypeLoc()
16935 .getAsAdjusted<FunctionProtoTypeLoc>())) {
16936
16937 // Check whether that explicit signature was synthesized by
16938 // GetTypeForDeclarator. If so, don't save that as part of the
16939 // written signature.
16940 if (ExplicitSignature.getLocalRangeBegin() ==
16941 ExplicitSignature.getLocalRangeEnd()) {
16942 // This would be much cheaper if we stored TypeLocs instead of
16943 // TypeSourceInfos.
16944 TypeLoc Result = ExplicitSignature.getReturnLoc();
16945 unsigned Size = Result.getFullDataSize();
16946 Sig = Context.CreateTypeSourceInfo(T: Result.getType(), Size);
16947 Sig->getTypeLoc().initializeFullCopy(Other: Result, Size);
16948
16949 ExplicitSignature = FunctionProtoTypeLoc();
16950 }
16951 }
16952
16953 CurBlock->TheDecl->setSignatureAsWritten(Sig);
16954 CurBlock->FunctionType = T;
16955
16956 const auto *Fn = T->castAs<FunctionType>();
16957 QualType RetTy = Fn->getReturnType();
16958 bool isVariadic =
16959 (isa<FunctionProtoType>(Val: Fn) && cast<FunctionProtoType>(Val: Fn)->isVariadic());
16960
16961 CurBlock->TheDecl->setIsVariadic(isVariadic);
16962
16963 // Context.DependentTy is used as a placeholder for a missing block
16964 // return type. TODO: what should we do with declarators like:
16965 // ^ * { ... }
16966 // If the answer is "apply template argument deduction"....
16967 if (RetTy != Context.DependentTy) {
16968 CurBlock->ReturnType = RetTy;
16969 CurBlock->TheDecl->setBlockMissingReturnType(false);
16970 CurBlock->HasImplicitReturnType = false;
16971 }
16972
16973 // Push block parameters from the declarator if we had them.
16974 SmallVector<ParmVarDecl*, 8> Params;
16975 if (ExplicitSignature) {
16976 for (unsigned I = 0, E = ExplicitSignature.getNumParams(); I != E; ++I) {
16977 ParmVarDecl *Param = ExplicitSignature.getParam(i: I);
16978 if (Param->getIdentifier() == nullptr && !Param->isImplicit() &&
16979 !Param->isInvalidDecl() && !getLangOpts().CPlusPlus) {
16980 // Diagnose this as an extension in C17 and earlier.
16981 if (!getLangOpts().C23)
16982 Diag(Loc: Param->getLocation(), DiagID: diag::ext_parameter_name_omitted_c23);
16983 }
16984 Params.push_back(Elt: Param);
16985 }
16986
16987 // Fake up parameter variables if we have a typedef, like
16988 // ^ fntype { ... }
16989 } else if (const FunctionProtoType *Fn = T->getAs<FunctionProtoType>()) {
16990 for (const auto &I : Fn->param_types()) {
16991 ParmVarDecl *Param = BuildParmVarDeclForTypedef(
16992 DC: CurBlock->TheDecl, Loc: ParamInfo.getBeginLoc(), T: I);
16993 Params.push_back(Elt: Param);
16994 }
16995 }
16996
16997 // Set the parameters on the block decl.
16998 if (!Params.empty()) {
16999 CurBlock->TheDecl->setParams(Params);
17000 CheckParmsForFunctionDef(Parameters: CurBlock->TheDecl->parameters(),
17001 /*CheckParameterNames=*/false);
17002 }
17003
17004 // Finally we can process decl attributes.
17005 ProcessDeclAttributes(S: CurScope, D: CurBlock->TheDecl, PD: ParamInfo);
17006
17007 // Put the parameter variables in scope.
17008 for (auto *AI : CurBlock->TheDecl->parameters()) {
17009 AI->setOwningFunction(CurBlock->TheDecl);
17010
17011 // If this has an identifier, add it to the scope stack.
17012 if (AI->getIdentifier()) {
17013 CheckShadow(S: CurBlock->TheScope, D: AI);
17014
17015 PushOnScopeChains(D: AI, S: CurBlock->TheScope);
17016 }
17017
17018 if (AI->isInvalidDecl())
17019 CurBlock->TheDecl->setInvalidDecl();
17020 }
17021}
17022
17023void Sema::ActOnBlockError(SourceLocation CaretLoc, Scope *CurScope) {
17024 // Leave the expression-evaluation context.
17025 DiscardCleanupsInEvaluationContext();
17026 PopExpressionEvaluationContext();
17027
17028 // Pop off CurBlock, handle nested blocks.
17029 PopDeclContext();
17030 PopFunctionScopeInfo();
17031}
17032
17033ExprResult Sema::ActOnBlockStmtExpr(SourceLocation CaretLoc,
17034 Stmt *Body, Scope *CurScope) {
17035 // If blocks are disabled, emit an error.
17036 if (!LangOpts.Blocks)
17037 Diag(Loc: CaretLoc, DiagID: diag::err_blocks_disable) << LangOpts.OpenCL;
17038
17039 // Leave the expression-evaluation context.
17040 if (hasAnyUnrecoverableErrorsInThisFunction())
17041 DiscardCleanupsInEvaluationContext();
17042 assert(!Cleanup.exprNeedsCleanups() &&
17043 "cleanups within block not correctly bound!");
17044 PopExpressionEvaluationContext();
17045
17046 BlockScopeInfo *BSI = cast<BlockScopeInfo>(Val: FunctionScopes.back());
17047 BlockDecl *BD = BSI->TheDecl;
17048
17049 maybeAddDeclWithEffects(D: BD);
17050
17051 if (BSI->HasImplicitReturnType)
17052 deduceClosureReturnType(CSI&: *BSI);
17053
17054 QualType RetTy = Context.VoidTy;
17055 if (!BSI->ReturnType.isNull())
17056 RetTy = BSI->ReturnType;
17057
17058 bool NoReturn = BD->hasAttr<NoReturnAttr>();
17059 QualType BlockTy;
17060
17061 // If the user wrote a function type in some form, try to use that.
17062 if (!BSI->FunctionType.isNull()) {
17063 const FunctionType *FTy = BSI->FunctionType->castAs<FunctionType>();
17064
17065 FunctionType::ExtInfo Ext = FTy->getExtInfo();
17066 if (NoReturn && !Ext.getNoReturn()) Ext = Ext.withNoReturn(noReturn: true);
17067
17068 // Turn protoless block types into nullary block types.
17069 if (isa<FunctionNoProtoType>(Val: FTy)) {
17070 FunctionProtoType::ExtProtoInfo EPI;
17071 EPI.ExtInfo = Ext;
17072 BlockTy = Context.getFunctionType(ResultTy: RetTy, Args: {}, EPI);
17073
17074 // Otherwise, if we don't need to change anything about the function type,
17075 // preserve its sugar structure.
17076 } else if (FTy->getReturnType() == RetTy &&
17077 (!NoReturn || FTy->getNoReturnAttr())) {
17078 BlockTy = BSI->FunctionType;
17079
17080 // Otherwise, make the minimal modifications to the function type.
17081 } else {
17082 const FunctionProtoType *FPT = cast<FunctionProtoType>(Val: FTy);
17083 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
17084 EPI.TypeQuals = Qualifiers();
17085 EPI.ExtInfo = Ext;
17086 BlockTy = Context.getFunctionType(ResultTy: RetTy, Args: FPT->getParamTypes(), EPI);
17087 }
17088
17089 // If we don't have a function type, just build one from nothing.
17090 } else {
17091 FunctionProtoType::ExtProtoInfo EPI;
17092 EPI.ExtInfo = FunctionType::ExtInfo().withNoReturn(noReturn: NoReturn);
17093 BlockTy = Context.getFunctionType(ResultTy: RetTy, Args: {}, EPI);
17094 }
17095
17096 DiagnoseUnusedParameters(Parameters: BD->parameters());
17097 BlockTy = Context.getBlockPointerType(T: BlockTy);
17098
17099 // If needed, diagnose invalid gotos and switches in the block.
17100 if (getCurFunction()->NeedsScopeChecking() &&
17101 !PP.isCodeCompletionEnabled())
17102 DiagnoseInvalidJumps(Body: cast<CompoundStmt>(Val: Body));
17103
17104 BD->setBody(cast<CompoundStmt>(Val: Body));
17105
17106 if (Body && getCurFunction()->HasPotentialAvailabilityViolations)
17107 DiagnoseUnguardedAvailabilityViolations(FD: BD);
17108
17109 // Try to apply the named return value optimization. We have to check again
17110 // if we can do this, though, because blocks keep return statements around
17111 // to deduce an implicit return type.
17112 if (getLangOpts().CPlusPlus && RetTy->isRecordType() &&
17113 !BD->isDependentContext())
17114 computeNRVO(Body, Scope: BSI);
17115
17116 if (RetTy.hasNonTrivialToPrimitiveDestructCUnion() ||
17117 RetTy.hasNonTrivialToPrimitiveCopyCUnion())
17118 checkNonTrivialCUnion(QT: RetTy, Loc: BD->getCaretLocation(),
17119 UseContext: NonTrivialCUnionContext::FunctionReturn,
17120 NonTrivialKind: NTCUK_Destruct | NTCUK_Copy);
17121
17122 PopDeclContext();
17123
17124 // Set the captured variables on the block.
17125 SmallVector<BlockDecl::Capture, 4> Captures;
17126 for (Capture &Cap : BSI->Captures) {
17127 if (Cap.isInvalid() || Cap.isThisCapture())
17128 continue;
17129 // Cap.getVariable() is always a VarDecl because
17130 // blocks cannot capture structured bindings or other ValueDecl kinds.
17131 auto *Var = cast<VarDecl>(Val: Cap.getVariable());
17132 Expr *CopyExpr = nullptr;
17133 if (getLangOpts().CPlusPlus && Cap.isCopyCapture()) {
17134 if (auto *Record = Cap.getCaptureType()->getAsCXXRecordDecl()) {
17135 // The capture logic needs the destructor, so make sure we mark it.
17136 // Usually this is unnecessary because most local variables have
17137 // their destructors marked at declaration time, but parameters are
17138 // an exception because it's technically only the call site that
17139 // actually requires the destructor.
17140 if (isa<ParmVarDecl>(Val: Var))
17141 FinalizeVarWithDestructor(VD: Var, DeclInit: Record);
17142
17143 // Enter a separate potentially-evaluated context while building block
17144 // initializers to isolate their cleanups from those of the block
17145 // itself.
17146 // FIXME: Is this appropriate even when the block itself occurs in an
17147 // unevaluated operand?
17148 EnterExpressionEvaluationContext EvalContext(
17149 *this, ExpressionEvaluationContext::PotentiallyEvaluated);
17150
17151 SourceLocation Loc = Cap.getLocation();
17152
17153 ExprResult Result = BuildDeclarationNameExpr(
17154 SS: CXXScopeSpec(), NameInfo: DeclarationNameInfo(Var->getDeclName(), Loc), D: Var);
17155
17156 // According to the blocks spec, the capture of a variable from
17157 // the stack requires a const copy constructor. This is not true
17158 // of the copy/move done to move a __block variable to the heap.
17159 if (!Result.isInvalid() &&
17160 !Result.get()->getType().isConstQualified()) {
17161 Result = ImpCastExprToType(E: Result.get(),
17162 Type: Result.get()->getType().withConst(),
17163 CK: CK_NoOp, VK: VK_LValue);
17164 }
17165
17166 if (!Result.isInvalid()) {
17167 Result = PerformCopyInitialization(
17168 Entity: InitializedEntity::InitializeBlock(BlockVarLoc: Var->getLocation(),
17169 Type: Cap.getCaptureType()),
17170 EqualLoc: Loc, Init: Result.get());
17171 }
17172
17173 // Build a full-expression copy expression if initialization
17174 // succeeded and used a non-trivial constructor. Recover from
17175 // errors by pretending that the copy isn't necessary.
17176 if (!Result.isInvalid() &&
17177 !cast<CXXConstructExpr>(Val: Result.get())->getConstructor()
17178 ->isTrivial()) {
17179 Result = MaybeCreateExprWithCleanups(SubExpr: Result);
17180 CopyExpr = Result.get();
17181 }
17182 }
17183 }
17184
17185 BlockDecl::Capture NewCap(Var, Cap.isBlockCapture(), Cap.isNested(),
17186 CopyExpr);
17187 Captures.push_back(Elt: NewCap);
17188 }
17189 BD->setCaptures(Context, Captures, CapturesCXXThis: BSI->CXXThisCaptureIndex != 0);
17190
17191 // Pop the block scope now but keep it alive to the end of this function.
17192 AnalysisBasedWarnings::Policy WP =
17193 AnalysisWarnings.getPolicyInEffectAt(Loc: Body->getEndLoc());
17194 PoppedFunctionScopePtr ScopeRAII = PopFunctionScopeInfo(WP: &WP, D: BD, BlockType: BlockTy);
17195
17196 BlockExpr *Result = new (Context)
17197 BlockExpr(BD, BlockTy, BSI->ContainsUnexpandedParameterPack);
17198
17199 // If the block isn't obviously global, i.e. it captures anything at
17200 // all, then we need to do a few things in the surrounding context:
17201 if (Result->getBlockDecl()->hasCaptures()) {
17202 // First, this expression has a new cleanup object.
17203 ExprCleanupObjects.push_back(Elt: Result->getBlockDecl());
17204 Cleanup.setExprNeedsCleanups(true);
17205
17206 // It also gets a branch-protected scope if any of the captured
17207 // variables needs destruction.
17208 for (const auto &CI : Result->getBlockDecl()->captures()) {
17209 const VarDecl *var = CI.getVariable();
17210 if (var->getType().isDestructedType() != QualType::DK_none) {
17211 setFunctionHasBranchProtectedScope();
17212 break;
17213 }
17214 }
17215 }
17216
17217 if (getCurFunction())
17218 getCurFunction()->addBlock(BD);
17219
17220 // This can happen if the block's return type is deduced, but
17221 // the return expression is invalid.
17222 if (BD->isInvalidDecl())
17223 return CreateRecoveryExpr(Begin: Result->getBeginLoc(), End: Result->getEndLoc(),
17224 SubExprs: {Result}, T: Result->getType());
17225 return Result;
17226}
17227
17228ExprResult Sema::ActOnVAArg(SourceLocation BuiltinLoc, Expr *E, ParsedType Ty,
17229 SourceLocation RPLoc) {
17230 TypeSourceInfo *TInfo;
17231 GetTypeFromParser(Ty, TInfo: &TInfo);
17232 return BuildVAArgExpr(BuiltinLoc, E, TInfo, RPLoc);
17233}
17234
17235ExprResult Sema::BuildVAArgExpr(SourceLocation BuiltinLoc,
17236 Expr *E, TypeSourceInfo *TInfo,
17237 SourceLocation RPLoc) {
17238 Expr *OrigExpr = E;
17239 bool IsMS = false;
17240
17241 // CUDA device global function does not support varargs.
17242 if (getLangOpts().CUDA && getLangOpts().CUDAIsDevice) {
17243 if (const FunctionDecl *F = dyn_cast<FunctionDecl>(Val: CurContext)) {
17244 CUDAFunctionTarget T = CUDA().IdentifyTarget(D: F);
17245 if (T == CUDAFunctionTarget::Global)
17246 return ExprError(Diag(Loc: E->getBeginLoc(), DiagID: diag::err_va_arg_in_device));
17247 }
17248 }
17249
17250 // NVPTX does not support va_arg expression.
17251 if (getLangOpts().OpenMP && getLangOpts().OpenMPIsTargetDevice &&
17252 Context.getTargetInfo().getTriple().isNVPTX())
17253 targetDiag(Loc: E->getBeginLoc(), DiagID: diag::err_va_arg_in_device);
17254
17255 // It might be a __builtin_ms_va_list. (But don't ever mark a va_arg()
17256 // as Microsoft ABI on an actual Microsoft platform, where
17257 // __builtin_ms_va_list and __builtin_va_list are the same.)
17258 if (!E->isTypeDependent() && Context.getTargetInfo().hasBuiltinMSVaList() &&
17259 Context.getTargetInfo().getBuiltinVaListKind() != TargetInfo::CharPtrBuiltinVaList) {
17260 QualType MSVaListType = Context.getBuiltinMSVaListType();
17261 if (Context.hasSameType(T1: MSVaListType, T2: E->getType())) {
17262 if (CheckForModifiableLvalue(E, Loc: BuiltinLoc, S&: *this))
17263 return ExprError();
17264 IsMS = true;
17265 }
17266 }
17267
17268 // Get the va_list type
17269 QualType VaListType = Context.getBuiltinVaListType();
17270 if (!IsMS) {
17271 if (VaListType->isArrayType()) {
17272 // Deal with implicit array decay; for example, on x86-64,
17273 // va_list is an array, but it's supposed to decay to
17274 // a pointer for va_arg.
17275 VaListType = Context.getArrayDecayedType(T: VaListType);
17276 // Make sure the input expression also decays appropriately.
17277 ExprResult Result = UsualUnaryConversions(E);
17278 if (Result.isInvalid())
17279 return ExprError();
17280 E = Result.get();
17281 } else if (VaListType->isRecordType() && getLangOpts().CPlusPlus) {
17282 // If va_list is a record type and we are compiling in C++ mode,
17283 // check the argument using reference binding.
17284 InitializedEntity Entity = InitializedEntity::InitializeParameter(
17285 Context, Type: Context.getLValueReferenceType(T: VaListType), Consumed: false);
17286 ExprResult Init = PerformCopyInitialization(Entity, EqualLoc: SourceLocation(), Init: E);
17287 if (Init.isInvalid())
17288 return ExprError();
17289 E = Init.getAs<Expr>();
17290 } else {
17291 // Otherwise, the va_list argument must be an l-value because
17292 // it is modified by va_arg.
17293 if (!E->isTypeDependent() &&
17294 CheckForModifiableLvalue(E, Loc: BuiltinLoc, S&: *this))
17295 return ExprError();
17296 }
17297 }
17298
17299 if (!IsMS && !E->isTypeDependent() &&
17300 !Context.hasSameType(T1: VaListType, T2: E->getType()))
17301 return ExprError(
17302 Diag(Loc: E->getBeginLoc(),
17303 DiagID: diag::err_first_argument_to_va_arg_not_of_type_va_list)
17304 << OrigExpr->getType() << E->getSourceRange());
17305
17306 if (!TInfo->getType()->isDependentType()) {
17307 if (RequireCompleteType(Loc: TInfo->getTypeLoc().getBeginLoc(), T: TInfo->getType(),
17308 DiagID: diag::err_second_parameter_to_va_arg_incomplete,
17309 Args: TInfo->getTypeLoc()))
17310 return ExprError();
17311
17312 if (RequireNonAbstractType(Loc: TInfo->getTypeLoc().getBeginLoc(),
17313 T: TInfo->getType(),
17314 DiagID: diag::err_second_parameter_to_va_arg_abstract,
17315 Args: TInfo->getTypeLoc()))
17316 return ExprError();
17317
17318 if (!TInfo->getType().isPODType(Context)) {
17319 Diag(Loc: TInfo->getTypeLoc().getBeginLoc(),
17320 DiagID: TInfo->getType()->isObjCLifetimeType()
17321 ? diag::warn_second_parameter_to_va_arg_ownership_qualified
17322 : diag::warn_second_parameter_to_va_arg_not_pod)
17323 << TInfo->getType()
17324 << TInfo->getTypeLoc().getSourceRange();
17325 }
17326
17327 if (TInfo->getType()->isArrayType()) {
17328 DiagRuntimeBehavior(Loc: TInfo->getTypeLoc().getBeginLoc(), Statement: E,
17329 PD: PDiag(DiagID: diag::warn_second_parameter_to_va_arg_array)
17330 << TInfo->getType()
17331 << TInfo->getTypeLoc().getSourceRange());
17332 }
17333
17334 // Check for va_arg where arguments of the given type will be promoted
17335 // (i.e. this va_arg is guaranteed to have undefined behavior).
17336 QualType PromoteType;
17337 if (Context.isPromotableIntegerType(T: TInfo->getType())) {
17338 PromoteType = Context.getPromotedIntegerType(PromotableType: TInfo->getType());
17339 // [cstdarg.syn]p1 defers the C++ behavior to what the C standard says,
17340 // and C23 7.16.1.1p2 says, in part:
17341 // If type is not compatible with the type of the actual next argument
17342 // (as promoted according to the default argument promotions), the
17343 // behavior is undefined, except for the following cases:
17344 // - both types are pointers to qualified or unqualified versions of
17345 // compatible types;
17346 // - one type is compatible with a signed integer type, the other
17347 // type is compatible with the corresponding unsigned integer type,
17348 // and the value is representable in both types;
17349 // - one type is pointer to qualified or unqualified void and the
17350 // other is a pointer to a qualified or unqualified character type;
17351 // - or, the type of the next argument is nullptr_t and type is a
17352 // pointer type that has the same representation and alignment
17353 // requirements as a pointer to a character type.
17354 // Given that type compatibility is the primary requirement (ignoring
17355 // qualifications), you would think we could call typesAreCompatible()
17356 // directly to test this. However, in C++, that checks for *same type*,
17357 // which causes false positives when passing an enumeration type to
17358 // va_arg. Instead, get the underlying type of the enumeration and pass
17359 // that.
17360 QualType UnderlyingType = TInfo->getType();
17361 if (const auto *ED = UnderlyingType->getAsEnumDecl())
17362 UnderlyingType = ED->getIntegerType();
17363 if (Context.typesAreCompatible(T1: PromoteType, T2: UnderlyingType,
17364 /*CompareUnqualified*/ true))
17365 PromoteType = QualType();
17366
17367 // If the types are still not compatible, we need to test whether the
17368 // promoted type and the underlying type are the same except for
17369 // signedness. Ask the AST for the correctly corresponding type and see
17370 // if that's compatible.
17371 if (!PromoteType.isNull() && !UnderlyingType->isBooleanType() &&
17372 PromoteType->isUnsignedIntegerType() !=
17373 UnderlyingType->isUnsignedIntegerType()) {
17374 UnderlyingType =
17375 UnderlyingType->isUnsignedIntegerType()
17376 ? Context.getCorrespondingSignedType(T: UnderlyingType)
17377 : Context.getCorrespondingUnsignedType(T: UnderlyingType);
17378 if (Context.typesAreCompatible(T1: PromoteType, T2: UnderlyingType,
17379 /*CompareUnqualified*/ true))
17380 PromoteType = QualType();
17381 }
17382 }
17383 if (TInfo->getType()->isSpecificBuiltinType(K: BuiltinType::Float))
17384 PromoteType = Context.DoubleTy;
17385 if (!PromoteType.isNull())
17386 DiagRuntimeBehavior(Loc: TInfo->getTypeLoc().getBeginLoc(), Statement: E,
17387 PD: PDiag(DiagID: diag::warn_second_parameter_to_va_arg_never_compatible)
17388 << TInfo->getType()
17389 << PromoteType
17390 << TInfo->getTypeLoc().getSourceRange());
17391 }
17392
17393 QualType T = TInfo->getType().getNonLValueExprType(Context);
17394 return new (Context) VAArgExpr(BuiltinLoc, E, TInfo, RPLoc, T, IsMS);
17395}
17396
17397ExprResult Sema::ActOnGNUNullExpr(SourceLocation TokenLoc) {
17398 // The type of __null will be int or long, depending on the size of
17399 // pointers on the target.
17400 QualType Ty;
17401 unsigned pw = Context.getTargetInfo().getPointerWidth(AddrSpace: LangAS::Default);
17402 if (pw == Context.getTargetInfo().getIntWidth())
17403 Ty = Context.IntTy;
17404 else if (pw == Context.getTargetInfo().getLongWidth())
17405 Ty = Context.LongTy;
17406 else if (pw == Context.getTargetInfo().getLongLongWidth())
17407 Ty = Context.LongLongTy;
17408 else {
17409 llvm_unreachable("I don't know size of pointer!");
17410 }
17411
17412 return new (Context) GNUNullExpr(Ty, TokenLoc);
17413}
17414
17415static CXXRecordDecl *LookupStdSourceLocationImpl(Sema &S, SourceLocation Loc) {
17416 CXXRecordDecl *ImplDecl = nullptr;
17417
17418 // Fetch the std::source_location::__impl decl.
17419 if (NamespaceDecl *Std = S.getStdNamespace()) {
17420 LookupResult ResultSL(S, &S.PP.getIdentifierTable().get(Name: "source_location"),
17421 Loc, Sema::LookupOrdinaryName);
17422 if (S.LookupQualifiedName(R&: ResultSL, LookupCtx: Std)) {
17423 if (auto *SLDecl = ResultSL.getAsSingle<RecordDecl>()) {
17424 LookupResult ResultImpl(S, &S.PP.getIdentifierTable().get(Name: "__impl"),
17425 Loc, Sema::LookupOrdinaryName);
17426 if ((SLDecl->isCompleteDefinition() || SLDecl->isBeingDefined()) &&
17427 S.LookupQualifiedName(R&: ResultImpl, LookupCtx: SLDecl)) {
17428 ImplDecl = ResultImpl.getAsSingle<CXXRecordDecl>();
17429 }
17430 }
17431 }
17432 }
17433
17434 if (!ImplDecl || !ImplDecl->isCompleteDefinition()) {
17435 S.Diag(Loc, DiagID: diag::err_std_source_location_impl_not_found);
17436 return nullptr;
17437 }
17438
17439 // Verify that __impl is a trivial struct type, with no base classes, and with
17440 // only the four expected fields.
17441 if (ImplDecl->isUnion() || !ImplDecl->isStandardLayout() ||
17442 ImplDecl->getNumBases() != 0) {
17443 S.Diag(Loc, DiagID: diag::err_std_source_location_impl_malformed);
17444 return nullptr;
17445 }
17446
17447 unsigned Count = 0;
17448 for (FieldDecl *F : ImplDecl->fields()) {
17449 StringRef Name = F->getName();
17450
17451 if (Name == "_M_file_name") {
17452 if (F->getType() !=
17453 S.Context.getPointerType(T: S.Context.CharTy.withConst()))
17454 break;
17455 Count++;
17456 } else if (Name == "_M_function_name") {
17457 if (F->getType() !=
17458 S.Context.getPointerType(T: S.Context.CharTy.withConst()))
17459 break;
17460 Count++;
17461 } else if (Name == "_M_line") {
17462 if (!F->getType()->isIntegerType())
17463 break;
17464 Count++;
17465 } else if (Name == "_M_column") {
17466 if (!F->getType()->isIntegerType())
17467 break;
17468 Count++;
17469 } else {
17470 Count = 100; // invalid
17471 break;
17472 }
17473 }
17474 if (Count != 4) {
17475 S.Diag(Loc, DiagID: diag::err_std_source_location_impl_malformed);
17476 return nullptr;
17477 }
17478
17479 return ImplDecl;
17480}
17481
17482ExprResult Sema::ActOnSourceLocExpr(SourceLocIdentKind Kind,
17483 SourceLocation BuiltinLoc,
17484 SourceLocation RPLoc) {
17485 QualType ResultTy;
17486 switch (Kind) {
17487 case SourceLocIdentKind::File:
17488 case SourceLocIdentKind::FileName:
17489 case SourceLocIdentKind::Function:
17490 case SourceLocIdentKind::FuncSig: {
17491 QualType ArrTy = Context.getStringLiteralArrayType(EltTy: Context.CharTy, Length: 0);
17492 ResultTy =
17493 Context.getPointerType(T: ArrTy->getAsArrayTypeUnsafe()->getElementType());
17494 break;
17495 }
17496 case SourceLocIdentKind::Line:
17497 case SourceLocIdentKind::Column:
17498 ResultTy = Context.UnsignedIntTy;
17499 break;
17500 case SourceLocIdentKind::SourceLocStruct:
17501 if (!StdSourceLocationImplDecl) {
17502 StdSourceLocationImplDecl =
17503 LookupStdSourceLocationImpl(S&: *this, Loc: BuiltinLoc);
17504 if (!StdSourceLocationImplDecl)
17505 return ExprError();
17506 }
17507 ResultTy = Context.getPointerType(
17508 T: Context.getCanonicalTagType(TD: StdSourceLocationImplDecl).withConst());
17509 break;
17510 }
17511
17512 return BuildSourceLocExpr(Kind, ResultTy, BuiltinLoc, RPLoc, ParentContext: CurContext);
17513}
17514
17515ExprResult Sema::BuildSourceLocExpr(SourceLocIdentKind Kind, QualType ResultTy,
17516 SourceLocation BuiltinLoc,
17517 SourceLocation RPLoc,
17518 DeclContext *ParentContext) {
17519 return new (Context)
17520 SourceLocExpr(Context, Kind, ResultTy, BuiltinLoc, RPLoc, ParentContext);
17521}
17522
17523ExprResult Sema::ActOnEmbedExpr(SourceLocation EmbedKeywordLoc,
17524 StringLiteral *BinaryData, StringRef FileName) {
17525 EmbedDataStorage *Data = new (Context) EmbedDataStorage;
17526 Data->BinaryData = BinaryData;
17527 Data->FileName = FileName;
17528 return new (Context)
17529 EmbedExpr(Context, EmbedKeywordLoc, Data, /*NumOfElements=*/0,
17530 Data->getDataElementCount());
17531}
17532
17533static bool maybeDiagnoseAssignmentToFunction(Sema &S, QualType DstType,
17534 const Expr *SrcExpr) {
17535 if (!DstType->isFunctionPointerType() ||
17536 !SrcExpr->getType()->isFunctionType())
17537 return false;
17538
17539 auto *DRE = dyn_cast<DeclRefExpr>(Val: SrcExpr->IgnoreParenImpCasts());
17540 if (!DRE)
17541 return false;
17542
17543 auto *FD = dyn_cast<FunctionDecl>(Val: DRE->getDecl());
17544 if (!FD)
17545 return false;
17546
17547 return !S.checkAddressOfFunctionIsAvailable(Function: FD,
17548 /*Complain=*/true,
17549 Loc: SrcExpr->getBeginLoc());
17550}
17551
17552bool Sema::DiagnoseAssignmentResult(AssignConvertType ConvTy,
17553 SourceLocation Loc,
17554 QualType DstType, QualType SrcType,
17555 Expr *SrcExpr, AssignmentAction Action,
17556 bool *Complained) {
17557 if (Complained)
17558 *Complained = false;
17559
17560 // Decode the result (notice that AST's are still created for extensions).
17561 bool CheckInferredResultType = false;
17562 bool isInvalid = false;
17563 unsigned DiagKind = 0;
17564 ConversionFixItGenerator ConvHints;
17565 bool MayHaveConvFixit = false;
17566 bool MayHaveFunctionDiff = false;
17567 const ObjCInterfaceDecl *IFace = nullptr;
17568 const ObjCProtocolDecl *PDecl = nullptr;
17569
17570 switch (ConvTy) {
17571 case AssignConvertType::Compatible:
17572 DiagnoseAssignmentEnum(DstType, SrcType, SrcExpr);
17573 return false;
17574 case AssignConvertType::CompatibleVoidPtrToNonVoidPtr:
17575 // Still a valid conversion, but we may want to diagnose for C++
17576 // compatibility reasons.
17577 DiagKind = diag::warn_compatible_implicit_pointer_conv;
17578 break;
17579 case AssignConvertType::PointerToInt:
17580 if (getLangOpts().CPlusPlus) {
17581 DiagKind = diag::err_typecheck_convert_pointer_int;
17582 isInvalid = true;
17583 } else {
17584 DiagKind = diag::ext_typecheck_convert_pointer_int;
17585 }
17586 ConvHints.tryToFixConversion(FromExpr: SrcExpr, FromQTy: SrcType, ToQTy: DstType, S&: *this);
17587 MayHaveConvFixit = true;
17588 break;
17589 case AssignConvertType::IntToPointer:
17590 if (getLangOpts().CPlusPlus) {
17591 DiagKind = diag::err_typecheck_convert_int_pointer;
17592 isInvalid = true;
17593 } else {
17594 DiagKind = diag::ext_typecheck_convert_int_pointer;
17595 }
17596 ConvHints.tryToFixConversion(FromExpr: SrcExpr, FromQTy: SrcType, ToQTy: DstType, S&: *this);
17597 MayHaveConvFixit = true;
17598 break;
17599 case AssignConvertType::IncompatibleFunctionPointerStrict:
17600 DiagKind =
17601 diag::warn_typecheck_convert_incompatible_function_pointer_strict;
17602 ConvHints.tryToFixConversion(FromExpr: SrcExpr, FromQTy: SrcType, ToQTy: DstType, S&: *this);
17603 MayHaveConvFixit = true;
17604 break;
17605 case AssignConvertType::IncompatibleFunctionPointer:
17606 if (getLangOpts().CPlusPlus) {
17607 DiagKind = diag::err_typecheck_convert_incompatible_function_pointer;
17608 isInvalid = true;
17609 } else {
17610 DiagKind = diag::ext_typecheck_convert_incompatible_function_pointer;
17611 }
17612 ConvHints.tryToFixConversion(FromExpr: SrcExpr, FromQTy: SrcType, ToQTy: DstType, S&: *this);
17613 MayHaveConvFixit = true;
17614 break;
17615 case AssignConvertType::IncompatiblePointer:
17616 if (Action == AssignmentAction::Passing_CFAudited) {
17617 DiagKind = diag::err_arc_typecheck_convert_incompatible_pointer;
17618 } else if (getLangOpts().CPlusPlus) {
17619 DiagKind = diag::err_typecheck_convert_incompatible_pointer;
17620 isInvalid = true;
17621 } else {
17622 DiagKind = diag::ext_typecheck_convert_incompatible_pointer;
17623 }
17624 CheckInferredResultType = DstType->isObjCObjectPointerType() &&
17625 SrcType->isObjCObjectPointerType();
17626 if (CheckInferredResultType) {
17627 SrcType = SrcType.getUnqualifiedType();
17628 DstType = DstType.getUnqualifiedType();
17629 } else {
17630 ConvHints.tryToFixConversion(FromExpr: SrcExpr, FromQTy: SrcType, ToQTy: DstType, S&: *this);
17631 }
17632 MayHaveConvFixit = true;
17633 break;
17634 case AssignConvertType::IncompatiblePointerSign:
17635 if (getLangOpts().CPlusPlus) {
17636 DiagKind = diag::err_typecheck_convert_incompatible_pointer_sign;
17637 isInvalid = true;
17638 } else {
17639 DiagKind = diag::ext_typecheck_convert_incompatible_pointer_sign;
17640 }
17641 break;
17642 case AssignConvertType::FunctionVoidPointer:
17643 if (getLangOpts().CPlusPlus) {
17644 DiagKind = diag::err_typecheck_convert_pointer_void_func;
17645 isInvalid = true;
17646 } else {
17647 DiagKind = diag::ext_typecheck_convert_pointer_void_func;
17648 }
17649 break;
17650 case AssignConvertType::IncompatiblePointerDiscardsQualifiers: {
17651 // Perform decay if necessary.
17652 if (SrcType->canDecayToPointerType())
17653 SrcType = Context.getDecayedType(T: SrcType);
17654
17655 isInvalid = true;
17656
17657 Qualifiers lhq = SrcType->getPointeeType().getQualifiers();
17658 Qualifiers rhq = DstType->getPointeeType().getQualifiers();
17659 if (lhq.getAddressSpace() != rhq.getAddressSpace()) {
17660 DiagKind = diag::err_typecheck_incompatible_address_space;
17661 break;
17662 } else if (lhq.getObjCLifetime() != rhq.getObjCLifetime()) {
17663 DiagKind = diag::err_typecheck_incompatible_ownership;
17664 break;
17665 } else if (!lhq.getPointerAuth().isEquivalent(Other: rhq.getPointerAuth())) {
17666 DiagKind = diag::err_typecheck_incompatible_ptrauth;
17667 break;
17668 }
17669
17670 llvm_unreachable("unknown error case for discarding qualifiers!");
17671 // fallthrough
17672 }
17673 case AssignConvertType::IncompatiblePointerDiscardsOverflowBehavior:
17674 if (SrcType->isArrayType())
17675 SrcType = Context.getArrayDecayedType(T: SrcType);
17676
17677 DiagKind = diag::ext_typecheck_convert_discards_overflow_behavior;
17678 break;
17679 case AssignConvertType::CompatiblePointerDiscardsQualifiers:
17680 // If the qualifiers lost were because we were applying the
17681 // (deprecated) C++ conversion from a string literal to a char*
17682 // (or wchar_t*), then there was no error (C++ 4.2p2). FIXME:
17683 // Ideally, this check would be performed in
17684 // checkPointerTypesForAssignment. However, that would require a
17685 // bit of refactoring (so that the second argument is an
17686 // expression, rather than a type), which should be done as part
17687 // of a larger effort to fix checkPointerTypesForAssignment for
17688 // C++ semantics.
17689 if (getLangOpts().CPlusPlus &&
17690 IsStringLiteralToNonConstPointerConversion(From: SrcExpr, ToType: DstType))
17691 return false;
17692 if (getLangOpts().CPlusPlus) {
17693 DiagKind = diag::err_typecheck_convert_discards_qualifiers;
17694 isInvalid = true;
17695 } else {
17696 DiagKind = diag::ext_typecheck_convert_discards_qualifiers;
17697 }
17698
17699 break;
17700 case AssignConvertType::IncompatibleNestedPointerQualifiers:
17701 if (getLangOpts().CPlusPlus) {
17702 isInvalid = true;
17703 DiagKind = diag::err_nested_pointer_qualifier_mismatch;
17704 } else {
17705 DiagKind = diag::ext_nested_pointer_qualifier_mismatch;
17706 }
17707 break;
17708 case AssignConvertType::IncompatibleNestedPointerAddressSpaceMismatch:
17709 DiagKind = diag::err_typecheck_incompatible_nested_address_space;
17710 isInvalid = true;
17711 break;
17712 case AssignConvertType::IntToBlockPointer:
17713 DiagKind = diag::err_int_to_block_pointer;
17714 isInvalid = true;
17715 break;
17716 case AssignConvertType::IncompatibleBlockPointer:
17717 DiagKind = diag::err_typecheck_convert_incompatible_block_pointer;
17718 isInvalid = true;
17719 break;
17720 case AssignConvertType::IncompatibleObjCQualifiedId: {
17721 if (SrcType->isObjCQualifiedIdType()) {
17722 const ObjCObjectPointerType *srcOPT =
17723 SrcType->castAs<ObjCObjectPointerType>();
17724 for (auto *srcProto : srcOPT->quals()) {
17725 PDecl = srcProto;
17726 break;
17727 }
17728 if (const ObjCInterfaceType *IFaceT =
17729 DstType->castAs<ObjCObjectPointerType>()->getInterfaceType())
17730 IFace = IFaceT->getDecl();
17731 }
17732 else if (DstType->isObjCQualifiedIdType()) {
17733 const ObjCObjectPointerType *dstOPT =
17734 DstType->castAs<ObjCObjectPointerType>();
17735 for (auto *dstProto : dstOPT->quals()) {
17736 PDecl = dstProto;
17737 break;
17738 }
17739 if (const ObjCInterfaceType *IFaceT =
17740 SrcType->castAs<ObjCObjectPointerType>()->getInterfaceType())
17741 IFace = IFaceT->getDecl();
17742 }
17743 if (getLangOpts().CPlusPlus) {
17744 DiagKind = diag::err_incompatible_qualified_id;
17745 isInvalid = true;
17746 } else {
17747 DiagKind = diag::warn_incompatible_qualified_id;
17748 }
17749 break;
17750 }
17751 case AssignConvertType::IncompatibleVectors:
17752 if (getLangOpts().CPlusPlus) {
17753 DiagKind = diag::err_incompatible_vectors;
17754 isInvalid = true;
17755 } else {
17756 DiagKind = diag::warn_incompatible_vectors;
17757 }
17758 break;
17759 case AssignConvertType::IncompatibleObjCWeakRef:
17760 DiagKind = diag::err_arc_weak_unavailable_assign;
17761 isInvalid = true;
17762 break;
17763 case AssignConvertType::CompatibleOBTDiscards:
17764 return false;
17765 case AssignConvertType::IncompatibleOBTKinds: {
17766 assert(!SrcType->isFunctionType() &&
17767 "Unexpected function type found in IncompatibleOBTKinds assignment");
17768 if (SrcType->canDecayToPointerType())
17769 SrcType = Context.getDecayedType(T: SrcType);
17770
17771 auto getOBTKindName = [](QualType Ty) -> StringRef {
17772 if (Ty->isPointerType())
17773 Ty = Ty->getPointeeType();
17774 if (const auto *OBT = Ty->getAs<OverflowBehaviorType>()) {
17775 return OBT->getBehaviorKind() ==
17776 OverflowBehaviorType::OverflowBehaviorKind::Trap
17777 ? "__ob_trap"
17778 : "__ob_wrap";
17779 }
17780 llvm_unreachable("OBT kind unhandled");
17781 };
17782
17783 Diag(Loc, DiagID: diag::err_incompatible_obt_kinds_assignment)
17784 << DstType << SrcType << getOBTKindName(DstType)
17785 << getOBTKindName(SrcType);
17786 isInvalid = true;
17787 return true;
17788 }
17789 case AssignConvertType::Incompatible:
17790 if (maybeDiagnoseAssignmentToFunction(S&: *this, DstType, SrcExpr)) {
17791 if (Complained)
17792 *Complained = true;
17793 return true;
17794 }
17795
17796 DiagKind = diag::err_typecheck_convert_incompatible;
17797 ConvHints.tryToFixConversion(FromExpr: SrcExpr, FromQTy: SrcType, ToQTy: DstType, S&: *this);
17798 MayHaveConvFixit = true;
17799 isInvalid = true;
17800 MayHaveFunctionDiff = true;
17801 break;
17802 }
17803
17804 QualType FirstType, SecondType;
17805 switch (Action) {
17806 case AssignmentAction::Assigning:
17807 case AssignmentAction::Initializing:
17808 // The destination type comes first.
17809 FirstType = DstType;
17810 SecondType = SrcType;
17811 break;
17812
17813 case AssignmentAction::Returning:
17814 case AssignmentAction::Passing:
17815 case AssignmentAction::Passing_CFAudited:
17816 case AssignmentAction::Converting:
17817 case AssignmentAction::Sending:
17818 case AssignmentAction::Casting:
17819 // The source type comes first.
17820 FirstType = SrcType;
17821 SecondType = DstType;
17822 break;
17823 }
17824
17825 PartialDiagnostic FDiag = PDiag(DiagID: DiagKind);
17826 AssignmentAction ActionForDiag = Action;
17827 if (Action == AssignmentAction::Passing_CFAudited)
17828 ActionForDiag = AssignmentAction::Passing;
17829
17830 FDiag << FirstType << SecondType << ActionForDiag
17831 << SrcExpr->getSourceRange();
17832
17833 if (DiagKind == diag::ext_typecheck_convert_incompatible_pointer_sign ||
17834 DiagKind == diag::err_typecheck_convert_incompatible_pointer_sign) {
17835 auto isPlainChar = [](const clang::Type *Type) {
17836 return Type->isSpecificBuiltinType(K: BuiltinType::Char_S) ||
17837 Type->isSpecificBuiltinType(K: BuiltinType::Char_U);
17838 };
17839 FDiag << (isPlainChar(FirstType->getPointeeOrArrayElementType()) ||
17840 isPlainChar(SecondType->getPointeeOrArrayElementType()));
17841 }
17842
17843 // If we can fix the conversion, suggest the FixIts.
17844 if (!ConvHints.isNull()) {
17845 for (FixItHint &H : ConvHints.Hints)
17846 FDiag << H;
17847 }
17848
17849 if (MayHaveConvFixit) { FDiag << (unsigned) (ConvHints.Kind); }
17850
17851 if (MayHaveFunctionDiff)
17852 HandleFunctionTypeMismatch(PDiag&: FDiag, FromType: SecondType, ToType: FirstType);
17853
17854 Diag(Loc, PD: FDiag);
17855 if ((DiagKind == diag::warn_incompatible_qualified_id ||
17856 DiagKind == diag::err_incompatible_qualified_id) &&
17857 PDecl && IFace && !IFace->hasDefinition())
17858 Diag(Loc: IFace->getLocation(), DiagID: diag::note_incomplete_class_and_qualified_id)
17859 << IFace << PDecl;
17860
17861 if (SecondType == Context.OverloadTy)
17862 NoteAllOverloadCandidates(E: OverloadExpr::find(E: SrcExpr).Expression,
17863 DestType: FirstType, /*TakingAddress=*/true);
17864
17865 if (CheckInferredResultType)
17866 ObjC().EmitRelatedResultTypeNote(E: SrcExpr);
17867
17868 if (Action == AssignmentAction::Returning &&
17869 ConvTy == AssignConvertType::IncompatiblePointer)
17870 ObjC().EmitRelatedResultTypeNoteForReturn(destType: DstType);
17871
17872 if (Complained)
17873 *Complained = true;
17874 return isInvalid;
17875}
17876
17877ExprResult Sema::VerifyIntegerConstantExpression(Expr *E,
17878 llvm::APSInt *Result,
17879 AllowFoldKind CanFold) {
17880 class SimpleICEDiagnoser : public VerifyICEDiagnoser {
17881 public:
17882 SemaDiagnosticBuilder diagnoseNotICEType(Sema &S, SourceLocation Loc,
17883 QualType T) override {
17884 return S.Diag(Loc, DiagID: diag::err_ice_not_integral)
17885 << T << S.LangOpts.CPlusPlus;
17886 }
17887 SemaDiagnosticBuilder diagnoseNotICE(Sema &S, SourceLocation Loc) override {
17888 return S.Diag(Loc, DiagID: diag::err_expr_not_ice) << S.LangOpts.CPlusPlus;
17889 }
17890 } Diagnoser;
17891
17892 return VerifyIntegerConstantExpression(E, Result, Diagnoser, CanFold);
17893}
17894
17895ExprResult Sema::VerifyIntegerConstantExpression(Expr *E,
17896 llvm::APSInt *Result,
17897 unsigned DiagID,
17898 AllowFoldKind CanFold) {
17899 class IDDiagnoser : public VerifyICEDiagnoser {
17900 unsigned DiagID;
17901
17902 public:
17903 IDDiagnoser(unsigned DiagID)
17904 : VerifyICEDiagnoser(DiagID == 0), DiagID(DiagID) { }
17905
17906 SemaDiagnosticBuilder diagnoseNotICE(Sema &S, SourceLocation Loc) override {
17907 return S.Diag(Loc, DiagID);
17908 }
17909 } Diagnoser(DiagID);
17910
17911 return VerifyIntegerConstantExpression(E, Result, Diagnoser, CanFold);
17912}
17913
17914Sema::SemaDiagnosticBuilder
17915Sema::VerifyICEDiagnoser::diagnoseNotICEType(Sema &S, SourceLocation Loc,
17916 QualType T) {
17917 return diagnoseNotICE(S, Loc);
17918}
17919
17920Sema::SemaDiagnosticBuilder
17921Sema::VerifyICEDiagnoser::diagnoseFold(Sema &S, SourceLocation Loc) {
17922 return S.Diag(Loc, DiagID: diag::ext_expr_not_ice) << S.LangOpts.CPlusPlus;
17923}
17924
17925ExprResult
17926Sema::VerifyIntegerConstantExpression(Expr *E, llvm::APSInt *Result,
17927 VerifyICEDiagnoser &Diagnoser,
17928 AllowFoldKind CanFold) {
17929 SourceLocation DiagLoc = E->getBeginLoc();
17930
17931 if (getLangOpts().CPlusPlus11) {
17932 // C++11 [expr.const]p5:
17933 // If an expression of literal class type is used in a context where an
17934 // integral constant expression is required, then that class type shall
17935 // have a single non-explicit conversion function to an integral or
17936 // unscoped enumeration type
17937 ExprResult Converted;
17938 class CXX11ConvertDiagnoser : public ICEConvertDiagnoser {
17939 VerifyICEDiagnoser &BaseDiagnoser;
17940 public:
17941 CXX11ConvertDiagnoser(VerifyICEDiagnoser &BaseDiagnoser)
17942 : ICEConvertDiagnoser(/*AllowScopedEnumerations*/ false,
17943 BaseDiagnoser.Suppress, true),
17944 BaseDiagnoser(BaseDiagnoser) {}
17945
17946 SemaDiagnosticBuilder diagnoseNotInt(Sema &S, SourceLocation Loc,
17947 QualType T) override {
17948 return BaseDiagnoser.diagnoseNotICEType(S, Loc, T);
17949 }
17950
17951 SemaDiagnosticBuilder diagnoseIncomplete(
17952 Sema &S, SourceLocation Loc, QualType T) override {
17953 return S.Diag(Loc, DiagID: diag::err_ice_incomplete_type) << T;
17954 }
17955
17956 SemaDiagnosticBuilder diagnoseExplicitConv(
17957 Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) override {
17958 return S.Diag(Loc, DiagID: diag::err_ice_explicit_conversion) << T << ConvTy;
17959 }
17960
17961 SemaDiagnosticBuilder noteExplicitConv(
17962 Sema &S, CXXConversionDecl *Conv, QualType ConvTy) override {
17963 return S.Diag(Loc: Conv->getLocation(), DiagID: diag::note_ice_conversion_here)
17964 << ConvTy->isEnumeralType() << ConvTy;
17965 }
17966
17967 SemaDiagnosticBuilder diagnoseAmbiguous(
17968 Sema &S, SourceLocation Loc, QualType T) override {
17969 return S.Diag(Loc, DiagID: diag::err_ice_ambiguous_conversion) << T;
17970 }
17971
17972 SemaDiagnosticBuilder noteAmbiguous(
17973 Sema &S, CXXConversionDecl *Conv, QualType ConvTy) override {
17974 return S.Diag(Loc: Conv->getLocation(), DiagID: diag::note_ice_conversion_here)
17975 << ConvTy->isEnumeralType() << ConvTy;
17976 }
17977
17978 SemaDiagnosticBuilder diagnoseConversion(
17979 Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) override {
17980 llvm_unreachable("conversion functions are permitted");
17981 }
17982 } ConvertDiagnoser(Diagnoser);
17983
17984 Converted = PerformContextualImplicitConversion(Loc: DiagLoc, FromE: E,
17985 Converter&: ConvertDiagnoser);
17986 if (Converted.isInvalid())
17987 return Converted;
17988 E = Converted.get();
17989 // The 'explicit' case causes us to get a RecoveryExpr. Give up here so we
17990 // don't try to evaluate it later. We also don't want to return the
17991 // RecoveryExpr here, as it results in this call succeeding, thus callers of
17992 // this function will attempt to use 'Value'.
17993 if (isa<RecoveryExpr>(Val: E))
17994 return ExprError();
17995 if (!E->getType()->isIntegralOrUnscopedEnumerationType())
17996 return ExprError();
17997 } else if (!E->getType()->isIntegralOrUnscopedEnumerationType()) {
17998 // An ICE must be of integral or unscoped enumeration type.
17999 if (!Diagnoser.Suppress)
18000 Diagnoser.diagnoseNotICEType(S&: *this, Loc: DiagLoc, T: E->getType())
18001 << E->getSourceRange();
18002 return ExprError();
18003 }
18004
18005 ExprResult RValueExpr = DefaultLvalueConversion(E);
18006 if (RValueExpr.isInvalid())
18007 return ExprError();
18008
18009 E = RValueExpr.get();
18010
18011 // Circumvent ICE checking in C++11 to avoid evaluating the expression twice
18012 // in the non-ICE case.
18013 if (!getLangOpts().CPlusPlus11 && E->isIntegerConstantExpr(Ctx: Context)) {
18014 SmallVector<PartialDiagnosticAt, 8> Notes;
18015 if (Result)
18016 *Result = E->EvaluateKnownConstIntCheckOverflow(Ctx: Context, Diag: &Notes);
18017 if (!isa<ConstantExpr>(Val: E))
18018 E = Result ? ConstantExpr::Create(Context, E, Result: APValue(*Result))
18019 : ConstantExpr::Create(Context, E);
18020
18021 if (Notes.empty())
18022 return E;
18023
18024 // If our only note is the usual "invalid subexpression" note, just point
18025 // the caret at its location rather than producing an essentially
18026 // redundant note.
18027 if (Notes.size() == 1 && Notes[0].second.getDiagID() ==
18028 diag::note_invalid_subexpr_in_const_expr) {
18029 DiagLoc = Notes[0].first;
18030 Notes.clear();
18031 }
18032
18033 if (getLangOpts().CPlusPlus) {
18034 if (!Diagnoser.Suppress) {
18035 Diagnoser.diagnoseNotICE(S&: *this, Loc: DiagLoc) << E->getSourceRange();
18036 for (const PartialDiagnosticAt &Note : Notes)
18037 Diag(Loc: Note.first, PD: Note.second);
18038 }
18039 return ExprError();
18040 }
18041
18042 Diagnoser.diagnoseFold(S&: *this, Loc: DiagLoc) << E->getSourceRange();
18043 for (const PartialDiagnosticAt &Note : Notes)
18044 Diag(Loc: Note.first, PD: Note.second);
18045
18046 return E;
18047 }
18048
18049 Expr::EvalResult EvalResult;
18050 SmallVector<PartialDiagnosticAt, 8> Notes;
18051 EvalResult.Diag = &Notes;
18052
18053 // Try to evaluate the expression, and produce diagnostics explaining why it's
18054 // not a constant expression as a side-effect.
18055 bool Folded =
18056 E->EvaluateAsRValue(Result&: EvalResult, Ctx: Context, /*isConstantContext*/ InConstantContext: true) &&
18057 EvalResult.Val.isInt() && !EvalResult.HasSideEffects &&
18058 (!getLangOpts().CPlusPlus || !EvalResult.HasUndefinedBehavior);
18059
18060 if (!isa<ConstantExpr>(Val: E))
18061 E = ConstantExpr::Create(Context, E, Result: EvalResult.Val);
18062
18063 // In C++11, we can rely on diagnostics being produced for any expression
18064 // which is not a constant expression. If no diagnostics were produced, then
18065 // this is a constant expression.
18066 if (Folded && getLangOpts().CPlusPlus11 && Notes.empty()) {
18067 if (Result)
18068 *Result = EvalResult.Val.getInt();
18069 return E;
18070 }
18071
18072 // If our only note is the usual "invalid subexpression" note, just point
18073 // the caret at its location rather than producing an essentially
18074 // redundant note.
18075 if (Notes.size() == 1 && Notes[0].second.getDiagID() ==
18076 diag::note_invalid_subexpr_in_const_expr) {
18077 DiagLoc = Notes[0].first;
18078 Notes.clear();
18079 }
18080
18081 if (!Folded || CanFold == AllowFoldKind::No) {
18082 if (!Diagnoser.Suppress) {
18083 Diagnoser.diagnoseNotICE(S&: *this, Loc: DiagLoc) << E->getSourceRange();
18084 for (const PartialDiagnosticAt &Note : Notes)
18085 Diag(Loc: Note.first, PD: Note.second);
18086 }
18087
18088 return ExprError();
18089 }
18090
18091 Diagnoser.diagnoseFold(S&: *this, Loc: DiagLoc) << E->getSourceRange();
18092 for (const PartialDiagnosticAt &Note : Notes)
18093 Diag(Loc: Note.first, PD: Note.second);
18094
18095 if (Result)
18096 *Result = EvalResult.Val.getInt();
18097 return E;
18098}
18099
18100namespace {
18101 // Handle the case where we conclude a expression which we speculatively
18102 // considered to be unevaluated is actually evaluated.
18103 class TransformToPE : public TreeTransform<TransformToPE> {
18104 typedef TreeTransform<TransformToPE> BaseTransform;
18105
18106 public:
18107 TransformToPE(Sema &SemaRef) : BaseTransform(SemaRef) { }
18108
18109 // Make sure we redo semantic analysis
18110 bool AlwaysRebuild() { return true; }
18111 bool ReplacingOriginal() { return true; }
18112
18113 // We need to special-case DeclRefExprs referring to FieldDecls which
18114 // are not part of a member pointer formation; normal TreeTransforming
18115 // doesn't catch this case because of the way we represent them in the AST.
18116 // FIXME: This is a bit ugly; is it really the best way to handle this
18117 // case?
18118 //
18119 // Error on DeclRefExprs referring to FieldDecls.
18120 ExprResult TransformDeclRefExpr(DeclRefExpr *E) {
18121 if (isa<FieldDecl>(Val: E->getDecl()) &&
18122 !SemaRef.isUnevaluatedContext())
18123 return SemaRef.Diag(Loc: E->getLocation(),
18124 DiagID: diag::err_invalid_non_static_member_use)
18125 << E->getDecl() << E->getSourceRange();
18126
18127 return BaseTransform::TransformDeclRefExpr(E);
18128 }
18129
18130 // Exception: filter out member pointer formation
18131 ExprResult TransformUnaryOperator(UnaryOperator *E) {
18132 if (E->getOpcode() == UO_AddrOf && E->getType()->isMemberPointerType())
18133 return E;
18134
18135 return BaseTransform::TransformUnaryOperator(E);
18136 }
18137
18138 // The body of a lambda-expression is in a separate expression evaluation
18139 // context so never needs to be transformed.
18140 // FIXME: Ideally we wouldn't transform the closure type either, and would
18141 // just recreate the capture expressions and lambda expression.
18142 StmtResult TransformLambdaBody(LambdaExpr *E, Stmt *Body) {
18143 return SkipLambdaBody(E, S: Body);
18144 }
18145 };
18146}
18147
18148ExprResult Sema::TransformToPotentiallyEvaluated(Expr *E) {
18149 assert(isUnevaluatedContext() &&
18150 "Should only transform unevaluated expressions");
18151 ExprEvalContexts.back().Context =
18152 ExprEvalContexts[ExprEvalContexts.size()-2].Context;
18153 if (isUnevaluatedContext())
18154 return E;
18155 return TransformToPE(*this).TransformExpr(E);
18156}
18157
18158TypeSourceInfo *Sema::TransformToPotentiallyEvaluated(TypeSourceInfo *TInfo) {
18159 assert(isUnevaluatedContext() &&
18160 "Should only transform unevaluated expressions");
18161 ExprEvalContexts.back().Context = parentEvaluationContext().Context;
18162 if (isUnevaluatedContext())
18163 return TInfo;
18164 return TransformToPE(*this).TransformType(TSI: TInfo);
18165}
18166
18167void
18168Sema::PushExpressionEvaluationContext(
18169 ExpressionEvaluationContext NewContext, Decl *LambdaContextDecl,
18170 ExpressionEvaluationContextRecord::ExpressionKind ExprContext) {
18171 ExprEvalContexts.emplace_back(Args&: NewContext, Args: ExprCleanupObjects.size(), Args&: Cleanup,
18172 Args&: LambdaContextDecl, Args&: ExprContext);
18173
18174 // Discarded statements and immediate contexts nested in other
18175 // discarded statements or immediate context are themselves
18176 // a discarded statement or an immediate context, respectively.
18177 ExprEvalContexts.back().InDiscardedStatement =
18178 parentEvaluationContext().isDiscardedStatementContext();
18179
18180 // C++23 [expr.const]/p15
18181 // An expression or conversion is in an immediate function context if [...]
18182 // it is a subexpression of a manifestly constant-evaluated expression or
18183 // conversion.
18184 const auto &Prev = parentEvaluationContext();
18185 ExprEvalContexts.back().InImmediateFunctionContext =
18186 Prev.isImmediateFunctionContext() || Prev.isConstantEvaluated();
18187
18188 ExprEvalContexts.back().InImmediateEscalatingFunctionContext =
18189 Prev.InImmediateEscalatingFunctionContext;
18190
18191 Cleanup.reset();
18192 if (!MaybeODRUseExprs.empty())
18193 std::swap(LHS&: MaybeODRUseExprs, RHS&: ExprEvalContexts.back().SavedMaybeODRUseExprs);
18194}
18195
18196void
18197Sema::PushExpressionEvaluationContext(
18198 ExpressionEvaluationContext NewContext, ReuseLambdaContextDecl_t,
18199 ExpressionEvaluationContextRecord::ExpressionKind ExprContext) {
18200 Decl *ClosureContextDecl = ExprEvalContexts.back().ManglingContextDecl;
18201 PushExpressionEvaluationContext(NewContext, LambdaContextDecl: ClosureContextDecl, ExprContext);
18202}
18203
18204void Sema::PushExpressionEvaluationContextForFunction(
18205 ExpressionEvaluationContext NewContext, FunctionDecl *FD) {
18206 // [expr.const]/p14.1
18207 // An expression or conversion is in an immediate function context if it is
18208 // potentially evaluated and either: its innermost enclosing non-block scope
18209 // is a function parameter scope of an immediate function.
18210 PushExpressionEvaluationContext(
18211 NewContext: FD && FD->isConsteval()
18212 ? ExpressionEvaluationContext::ImmediateFunctionContext
18213 : NewContext);
18214 const Sema::ExpressionEvaluationContextRecord &Parent =
18215 parentEvaluationContext();
18216 Sema::ExpressionEvaluationContextRecord &Current = currentEvaluationContext();
18217
18218 Current.InDiscardedStatement = false;
18219
18220 if (FD) {
18221
18222 // Each ExpressionEvaluationContextRecord also keeps track of whether the
18223 // context is nested in an immediate function context, so smaller contexts
18224 // that appear inside immediate functions (like variable initializers) are
18225 // considered to be inside an immediate function context even though by
18226 // themselves they are not immediate function contexts. But when a new
18227 // function is entered, we need to reset this tracking, since the entered
18228 // function might be not an immediate function.
18229
18230 Current.InImmediateEscalatingFunctionContext =
18231 getLangOpts().CPlusPlus20 && FD->isImmediateEscalating();
18232
18233 if (isLambdaMethod(DC: FD))
18234 Current.InImmediateFunctionContext =
18235 FD->isConsteval() ||
18236 (isLambdaMethod(DC: FD) && (Parent.isConstantEvaluated() ||
18237 Parent.isImmediateFunctionContext()));
18238 else
18239 Current.InImmediateFunctionContext = FD->isConsteval();
18240 }
18241}
18242
18243ExprResult Sema::ActOnCXXReflectExpr(SourceLocation CaretCaretLoc,
18244 TypeSourceInfo *TSI) {
18245 return BuildCXXReflectExpr(OperatorLoc: CaretCaretLoc, TSI);
18246}
18247
18248ExprResult Sema::BuildCXXReflectExpr(SourceLocation CaretCaretLoc,
18249 TypeSourceInfo *TSI) {
18250 return CXXReflectExpr::Create(C&: Context, OperatorLoc: CaretCaretLoc, TL: TSI);
18251}
18252
18253namespace {
18254
18255const DeclRefExpr *CheckPossibleDeref(Sema &S, const Expr *PossibleDeref) {
18256 PossibleDeref = PossibleDeref->IgnoreParenImpCasts();
18257 if (const auto *E = dyn_cast<UnaryOperator>(Val: PossibleDeref)) {
18258 if (E->getOpcode() == UO_Deref)
18259 return CheckPossibleDeref(S, PossibleDeref: E->getSubExpr());
18260 } else if (const auto *E = dyn_cast<ArraySubscriptExpr>(Val: PossibleDeref)) {
18261 return CheckPossibleDeref(S, PossibleDeref: E->getBase());
18262 } else if (const auto *E = dyn_cast<MemberExpr>(Val: PossibleDeref)) {
18263 return CheckPossibleDeref(S, PossibleDeref: E->getBase());
18264 } else if (const auto E = dyn_cast<DeclRefExpr>(Val: PossibleDeref)) {
18265 QualType Inner;
18266 QualType Ty = E->getType();
18267 if (const auto *Ptr = Ty->getAs<PointerType>())
18268 Inner = Ptr->getPointeeType();
18269 else if (const auto *Arr = S.Context.getAsArrayType(T: Ty))
18270 Inner = Arr->getElementType();
18271 else
18272 return nullptr;
18273
18274 if (Inner->hasAttr(AK: attr::NoDeref))
18275 return E;
18276 }
18277 return nullptr;
18278}
18279
18280} // namespace
18281
18282void Sema::WarnOnPendingNoDerefs(ExpressionEvaluationContextRecord &Rec) {
18283 for (const Expr *E : Rec.PossibleDerefs) {
18284 const DeclRefExpr *DeclRef = CheckPossibleDeref(S&: *this, PossibleDeref: E);
18285 if (DeclRef) {
18286 const ValueDecl *Decl = DeclRef->getDecl();
18287 Diag(Loc: E->getExprLoc(), DiagID: diag::warn_dereference_of_noderef_type)
18288 << Decl->getName() << E->getSourceRange();
18289 Diag(Loc: Decl->getLocation(), DiagID: diag::note_previous_decl) << Decl->getName();
18290 } else {
18291 Diag(Loc: E->getExprLoc(), DiagID: diag::warn_dereference_of_noderef_type_no_decl)
18292 << E->getSourceRange();
18293 }
18294 }
18295 Rec.PossibleDerefs.clear();
18296}
18297
18298void Sema::CheckUnusedVolatileAssignment(Expr *E) {
18299 if (!E->getType().isVolatileQualified() || !getLangOpts().CPlusPlus20)
18300 return;
18301
18302 // Note: ignoring parens here is not justified by the standard rules, but
18303 // ignoring parentheses seems like a more reasonable approach, and this only
18304 // drives a deprecation warning so doesn't affect conformance.
18305 if (auto *BO = dyn_cast<BinaryOperator>(Val: E->IgnoreParenImpCasts())) {
18306 if (BO->getOpcode() == BO_Assign) {
18307 auto &LHSs = ExprEvalContexts.back().VolatileAssignmentLHSs;
18308 llvm::erase(C&: LHSs, V: BO->getLHS());
18309 }
18310 }
18311}
18312
18313void Sema::MarkExpressionAsImmediateEscalating(Expr *E) {
18314 assert(getLangOpts().CPlusPlus20 &&
18315 ExprEvalContexts.back().InImmediateEscalatingFunctionContext &&
18316 "Cannot mark an immediate escalating expression outside of an "
18317 "immediate escalating context");
18318 if (auto *Call = dyn_cast<CallExpr>(Val: E->IgnoreImplicit());
18319 Call && Call->getCallee()) {
18320 if (auto *DeclRef =
18321 dyn_cast<DeclRefExpr>(Val: Call->getCallee()->IgnoreImplicit()))
18322 DeclRef->setIsImmediateEscalating(true);
18323 } else if (auto *Ctr = dyn_cast<CXXConstructExpr>(Val: E->IgnoreImplicit())) {
18324 Ctr->setIsImmediateEscalating(true);
18325 } else if (auto *DeclRef = dyn_cast<DeclRefExpr>(Val: E->IgnoreImplicit())) {
18326 DeclRef->setIsImmediateEscalating(true);
18327 } else {
18328 assert(false && "expected an immediately escalating expression");
18329 }
18330 if (FunctionScopeInfo *FI = getCurFunction())
18331 FI->FoundImmediateEscalatingExpression = true;
18332}
18333
18334ExprResult Sema::CheckForImmediateInvocation(ExprResult E, FunctionDecl *Decl) {
18335 if (isUnevaluatedContext() || !E.isUsable() || !Decl ||
18336 !Decl->isImmediateFunction() || isAlwaysConstantEvaluatedContext() ||
18337 isCheckingDefaultArgumentOrInitializer() ||
18338 RebuildingImmediateInvocation || isImmediateFunctionContext())
18339 return E;
18340
18341 /// Opportunistically remove the callee from ReferencesToConsteval if we can.
18342 /// It's OK if this fails; we'll also remove this in
18343 /// HandleImmediateInvocations, but catching it here allows us to avoid
18344 /// walking the AST looking for it in simple cases.
18345 if (auto *Call = dyn_cast<CallExpr>(Val: E.get()->IgnoreImplicit()))
18346 if (auto *DeclRef =
18347 dyn_cast<DeclRefExpr>(Val: Call->getCallee()->IgnoreImplicit()))
18348 ExprEvalContexts.back().ReferenceToConsteval.erase(Ptr: DeclRef);
18349
18350 // C++23 [expr.const]/p16
18351 // An expression or conversion is immediate-escalating if it is not initially
18352 // in an immediate function context and it is [...] an immediate invocation
18353 // that is not a constant expression and is not a subexpression of an
18354 // immediate invocation.
18355 APValue Cached;
18356 auto CheckConstantExpressionAndKeepResult = [&]() {
18357 Expr::EvalResult Eval;
18358 bool Res = E.get()->EvaluateAsConstantExpr(
18359 Result&: Eval, Ctx: getASTContext(), Kind: ConstantExprKind::ImmediateInvocation);
18360 if (Res && !Eval.DiagEmitted) {
18361 Cached = std::move(Eval.Val);
18362 return true;
18363 }
18364 return false;
18365 };
18366
18367 if (!E.get()->isValueDependent() &&
18368 ExprEvalContexts.back().InImmediateEscalatingFunctionContext &&
18369 !CheckConstantExpressionAndKeepResult()) {
18370 MarkExpressionAsImmediateEscalating(E: E.get());
18371 return E;
18372 }
18373
18374 if (Cleanup.exprNeedsCleanups()) {
18375 // Since an immediate invocation is a full expression itself - it requires
18376 // an additional ExprWithCleanups node, but it can participate to a bigger
18377 // full expression which actually requires cleanups to be run after so
18378 // create ExprWithCleanups without using MaybeCreateExprWithCleanups as it
18379 // may discard cleanups for outer expression too early.
18380
18381 // Note that ExprWithCleanups created here must always have empty cleanup
18382 // objects:
18383 // - compound literals do not create cleanup objects in C++ and immediate
18384 // invocations are C++-only.
18385 // - blocks are not allowed inside constant expressions and compiler will
18386 // issue an error if they appear there.
18387 //
18388 // Hence, in correct code any cleanup objects created inside current
18389 // evaluation context must be outside the immediate invocation.
18390 E = ExprWithCleanups::Create(C: getASTContext(), subexpr: E.get(),
18391 CleanupsHaveSideEffects: Cleanup.cleanupsHaveSideEffects(), objects: {});
18392 }
18393
18394 ConstantExpr *Res = ConstantExpr::Create(
18395 Context: getASTContext(), E: E.get(),
18396 Storage: ConstantExpr::getStorageKind(T: Decl->getReturnType().getTypePtr(),
18397 Context: getASTContext()),
18398 /*IsImmediateInvocation*/ true);
18399 if (Cached.hasValue())
18400 Res->MoveIntoResult(Value&: Cached, Context: getASTContext());
18401 /// Value-dependent constant expressions should not be immediately
18402 /// evaluated until they are instantiated.
18403 if (!Res->isValueDependent())
18404 ExprEvalContexts.back().ImmediateInvocationCandidates.emplace_back(Args&: Res, Args: 0);
18405 return Res;
18406}
18407
18408static void EvaluateAndDiagnoseImmediateInvocation(
18409 Sema &SemaRef, Sema::ImmediateInvocationCandidate Candidate) {
18410 llvm::SmallVector<PartialDiagnosticAt, 8> Notes;
18411 Expr::EvalResult Eval;
18412 Eval.Diag = &Notes;
18413 ConstantExpr *CE = Candidate.getPointer();
18414 bool Result = CE->EvaluateAsConstantExpr(
18415 Result&: Eval, Ctx: SemaRef.getASTContext(), Kind: ConstantExprKind::ImmediateInvocation);
18416 if (!Result || !Notes.empty()) {
18417 SemaRef.FailedImmediateInvocations.insert(Ptr: CE);
18418 Expr *InnerExpr = CE->getSubExpr()->IgnoreImplicit();
18419 if (auto *FunctionalCast = dyn_cast<CXXFunctionalCastExpr>(Val: InnerExpr))
18420 InnerExpr = FunctionalCast->getSubExpr()->IgnoreImplicit();
18421 FunctionDecl *FD = nullptr;
18422 if (auto *Call = dyn_cast<CallExpr>(Val: InnerExpr))
18423 FD = cast<FunctionDecl>(Val: Call->getCalleeDecl());
18424 else if (auto *Call = dyn_cast<CXXConstructExpr>(Val: InnerExpr))
18425 FD = Call->getConstructor();
18426 else if (auto *Cast = dyn_cast<CastExpr>(Val: InnerExpr))
18427 FD = dyn_cast_or_null<FunctionDecl>(Val: Cast->getConversionFunction());
18428
18429 assert(FD && FD->isImmediateFunction() &&
18430 "could not find an immediate function in this expression");
18431 if (FD->isInvalidDecl())
18432 return;
18433 SemaRef.Diag(Loc: CE->getBeginLoc(), DiagID: diag::err_invalid_consteval_call)
18434 << FD << FD->isConsteval();
18435 if (auto Context =
18436 SemaRef.InnermostDeclarationWithDelayedImmediateInvocations()) {
18437 SemaRef.Diag(Loc: Context->Loc, DiagID: diag::note_invalid_consteval_initializer)
18438 << Context->Decl;
18439 SemaRef.Diag(Loc: Context->Decl->getBeginLoc(), DiagID: diag::note_declared_at);
18440 }
18441 if (!FD->isConsteval())
18442 SemaRef.DiagnoseImmediateEscalatingReason(FD);
18443 for (auto &Note : Notes)
18444 SemaRef.Diag(Loc: Note.first, PD: Note.second);
18445 return;
18446 }
18447 CE->MoveIntoResult(Value&: Eval.Val, Context: SemaRef.getASTContext());
18448}
18449
18450static void RemoveNestedImmediateInvocation(
18451 Sema &SemaRef, Sema::ExpressionEvaluationContextRecord &Rec,
18452 SmallVector<Sema::ImmediateInvocationCandidate, 4>::reverse_iterator It) {
18453 struct ComplexRemove : TreeTransform<ComplexRemove> {
18454 using Base = TreeTransform<ComplexRemove>;
18455 llvm::SmallPtrSetImpl<DeclRefExpr *> &DRSet;
18456 SmallVector<Sema::ImmediateInvocationCandidate, 4> &IISet;
18457 SmallVector<Sema::ImmediateInvocationCandidate, 4>::reverse_iterator
18458 CurrentII;
18459 ComplexRemove(Sema &SemaRef, llvm::SmallPtrSetImpl<DeclRefExpr *> &DR,
18460 SmallVector<Sema::ImmediateInvocationCandidate, 4> &II,
18461 SmallVector<Sema::ImmediateInvocationCandidate,
18462 4>::reverse_iterator Current)
18463 : Base(SemaRef), DRSet(DR), IISet(II), CurrentII(Current) {}
18464 void RemoveImmediateInvocation(ConstantExpr* E) {
18465 auto It = std::find_if(first: CurrentII, last: IISet.rend(),
18466 pred: [E](Sema::ImmediateInvocationCandidate Elem) {
18467 return Elem.getPointer() == E;
18468 });
18469 // It is possible that some subexpression of the current immediate
18470 // invocation was handled from another expression evaluation context. Do
18471 // not handle the current immediate invocation if some of its
18472 // subexpressions failed before.
18473 if (It == IISet.rend()) {
18474 if (SemaRef.FailedImmediateInvocations.contains(Ptr: E))
18475 CurrentII->setInt(1);
18476 } else {
18477 It->setInt(1); // Mark as deleted
18478 }
18479 }
18480 ExprResult TransformConstantExpr(ConstantExpr *E) {
18481 if (!E->isImmediateInvocation())
18482 return Base::TransformConstantExpr(E);
18483 RemoveImmediateInvocation(E);
18484 return Base::TransformExpr(E: E->getSubExpr());
18485 }
18486 /// Base::TransfromCXXOperatorCallExpr doesn't traverse the callee so
18487 /// we need to remove its DeclRefExpr from the DRSet.
18488 ExprResult TransformCXXOperatorCallExpr(CXXOperatorCallExpr *E) {
18489 DRSet.erase(Ptr: cast<DeclRefExpr>(Val: E->getCallee()->IgnoreImplicit()));
18490 return Base::TransformCXXOperatorCallExpr(E);
18491 }
18492 /// Base::TransformUserDefinedLiteral doesn't preserve the
18493 /// UserDefinedLiteral node.
18494 ExprResult TransformUserDefinedLiteral(UserDefinedLiteral *E) { return E; }
18495 /// Base::TransformInitializer skips ConstantExpr so we need to visit them
18496 /// here.
18497 ExprResult TransformInitializer(Expr *Init, bool NotCopyInit) {
18498 if (!Init)
18499 return Init;
18500
18501 // We cannot use IgnoreImpCasts because we need to preserve
18502 // full expressions.
18503 while (true) {
18504 if (auto *ICE = dyn_cast<ImplicitCastExpr>(Val: Init))
18505 Init = ICE->getSubExpr();
18506 else if (auto *ICE = dyn_cast<MaterializeTemporaryExpr>(Val: Init))
18507 Init = ICE->getSubExpr();
18508 else
18509 break;
18510 }
18511 /// ConstantExprs are the first layer of implicit node to be removed so if
18512 /// Init isn't a ConstantExpr, no ConstantExpr will be skipped.
18513 if (auto *CE = dyn_cast<ConstantExpr>(Val: Init);
18514 CE && CE->isImmediateInvocation())
18515 RemoveImmediateInvocation(E: CE);
18516 return Base::TransformInitializer(Init, NotCopyInit);
18517 }
18518 ExprResult TransformDeclRefExpr(DeclRefExpr *E) {
18519 DRSet.erase(Ptr: E);
18520 return E;
18521 }
18522 ExprResult TransformLambdaExpr(LambdaExpr *E) {
18523 // Do not rebuild lambdas to avoid creating a new type.
18524 // Lambdas have already been processed inside their eval contexts.
18525 return E;
18526 }
18527
18528 // We do not have enough information to transform opaque expressions and
18529 // assume they do not contain immediate subexpressions.
18530 ExprResult TransformOpaqueValueExpr(OpaqueValueExpr *E) { return E; }
18531
18532 bool AlwaysRebuild() { return false; }
18533 bool ReplacingOriginal() { return true; }
18534 bool AllowSkippingCXXConstructExpr() {
18535 bool Res = AllowSkippingFirstCXXConstructExpr;
18536 AllowSkippingFirstCXXConstructExpr = true;
18537 return Res;
18538 }
18539 bool AllowSkippingFirstCXXConstructExpr = true;
18540 } Transformer(SemaRef, Rec.ReferenceToConsteval,
18541 Rec.ImmediateInvocationCandidates, It);
18542
18543 /// CXXConstructExpr with a single argument are getting skipped by
18544 /// TreeTransform in some situtation because they could be implicit. This
18545 /// can only occur for the top-level CXXConstructExpr because it is used
18546 /// nowhere in the expression being transformed therefore will not be rebuilt.
18547 /// Setting AllowSkippingFirstCXXConstructExpr to false will prevent from
18548 /// skipping the first CXXConstructExpr.
18549 if (isa<CXXConstructExpr>(Val: It->getPointer()->IgnoreImplicit()))
18550 Transformer.AllowSkippingFirstCXXConstructExpr = false;
18551
18552 ExprResult Res = Transformer.TransformExpr(E: It->getPointer()->getSubExpr());
18553 // The result may not be usable in case of previous compilation errors.
18554 // In this case evaluation of the expression may result in crash so just
18555 // don't do anything further with the result.
18556 if (Res.isUsable()) {
18557 Res = SemaRef.MaybeCreateExprWithCleanups(SubExpr: Res);
18558 It->getPointer()->setSubExpr(Res.get());
18559 }
18560}
18561
18562static void
18563HandleImmediateInvocations(Sema &SemaRef,
18564 Sema::ExpressionEvaluationContextRecord &Rec) {
18565 if ((Rec.ImmediateInvocationCandidates.size() == 0 &&
18566 Rec.ReferenceToConsteval.size() == 0) ||
18567 Rec.isImmediateFunctionContext() || SemaRef.RebuildingImmediateInvocation)
18568 return;
18569
18570 // An expression or conversion is 'manifestly constant-evaluated' if it is:
18571 // [...]
18572 // - the initializer of a variable that is usable in constant expressions or
18573 // has constant initialization.
18574 if (SemaRef.getLangOpts().CPlusPlus23 &&
18575 Rec.ExprContext ==
18576 Sema::ExpressionEvaluationContextRecord::EK_VariableInit) {
18577 auto *VD = dyn_cast<VarDecl>(Val: Rec.ManglingContextDecl);
18578 if (VD && (VD->isUsableInConstantExpressions(C: SemaRef.Context) ||
18579 VD->hasConstantInitialization())) {
18580 // An expression or conversion is in an 'immediate function context' if it
18581 // is potentially evaluated and either:
18582 // [...]
18583 // - it is a subexpression of a manifestly constant-evaluated expression
18584 // or conversion.
18585 return;
18586 }
18587 }
18588
18589 /// When we have more than 1 ImmediateInvocationCandidates or previously
18590 /// failed immediate invocations, we need to check for nested
18591 /// ImmediateInvocationCandidates in order to avoid duplicate diagnostics.
18592 /// Otherwise we only need to remove ReferenceToConsteval in the immediate
18593 /// invocation.
18594 if (Rec.ImmediateInvocationCandidates.size() > 1 ||
18595 !SemaRef.FailedImmediateInvocations.empty()) {
18596
18597 /// Prevent sema calls during the tree transform from adding pointers that
18598 /// are already in the sets.
18599 llvm::SaveAndRestore DisableIITracking(
18600 SemaRef.RebuildingImmediateInvocation, true);
18601
18602 /// Prevent diagnostic during tree transfrom as they are duplicates
18603 Sema::TentativeAnalysisScope DisableDiag(SemaRef);
18604
18605 for (auto It = Rec.ImmediateInvocationCandidates.rbegin();
18606 It != Rec.ImmediateInvocationCandidates.rend(); It++)
18607 if (!It->getInt())
18608 RemoveNestedImmediateInvocation(SemaRef, Rec, It);
18609 } else if (Rec.ImmediateInvocationCandidates.size() == 1 &&
18610 Rec.ReferenceToConsteval.size()) {
18611 struct SimpleRemove : DynamicRecursiveASTVisitor {
18612 llvm::SmallPtrSetImpl<DeclRefExpr *> &DRSet;
18613 SimpleRemove(llvm::SmallPtrSetImpl<DeclRefExpr *> &S) : DRSet(S) {}
18614 bool VisitDeclRefExpr(DeclRefExpr *E) override {
18615 DRSet.erase(Ptr: E);
18616 return DRSet.size();
18617 }
18618 } Visitor(Rec.ReferenceToConsteval);
18619 Visitor.TraverseStmt(
18620 S: Rec.ImmediateInvocationCandidates.front().getPointer()->getSubExpr());
18621 }
18622 for (auto CE : Rec.ImmediateInvocationCandidates)
18623 if (!CE.getInt())
18624 EvaluateAndDiagnoseImmediateInvocation(SemaRef, Candidate: CE);
18625 for (auto *DR : Rec.ReferenceToConsteval) {
18626 // If the expression is immediate escalating, it is not an error;
18627 // The outer context itself becomes immediate and further errors,
18628 // if any, will be handled by DiagnoseImmediateEscalatingReason.
18629 if (DR->isImmediateEscalating())
18630 continue;
18631 auto *FD = cast<FunctionDecl>(Val: DR->getDecl());
18632 const NamedDecl *ND = FD;
18633 if (const auto *MD = dyn_cast<CXXMethodDecl>(Val: ND);
18634 MD && (MD->isLambdaStaticInvoker() || isLambdaCallOperator(MD)))
18635 ND = MD->getParent();
18636
18637 // C++23 [expr.const]/p16
18638 // An expression or conversion is immediate-escalating if it is not
18639 // initially in an immediate function context and it is [...] a
18640 // potentially-evaluated id-expression that denotes an immediate function
18641 // that is not a subexpression of an immediate invocation.
18642 bool ImmediateEscalating = false;
18643 bool IsPotentiallyEvaluated =
18644 Rec.Context ==
18645 Sema::ExpressionEvaluationContext::PotentiallyEvaluated ||
18646 Rec.Context ==
18647 Sema::ExpressionEvaluationContext::PotentiallyEvaluatedIfUsed;
18648 if (SemaRef.inTemplateInstantiation() && IsPotentiallyEvaluated)
18649 ImmediateEscalating = Rec.InImmediateEscalatingFunctionContext;
18650
18651 if (!Rec.InImmediateEscalatingFunctionContext ||
18652 (SemaRef.inTemplateInstantiation() && !ImmediateEscalating)) {
18653 SemaRef.Diag(Loc: DR->getBeginLoc(), DiagID: diag::err_invalid_consteval_take_address)
18654 << ND << isa<CXXRecordDecl>(Val: ND) << FD->isConsteval();
18655 if (!FD->getBuiltinID())
18656 SemaRef.Diag(Loc: ND->getLocation(), DiagID: diag::note_declared_at);
18657 if (auto Context =
18658 SemaRef.InnermostDeclarationWithDelayedImmediateInvocations()) {
18659 SemaRef.Diag(Loc: Context->Loc, DiagID: diag::note_invalid_consteval_initializer)
18660 << Context->Decl;
18661 SemaRef.Diag(Loc: Context->Decl->getBeginLoc(), DiagID: diag::note_declared_at);
18662 }
18663 if (FD->isImmediateEscalating() && !FD->isConsteval())
18664 SemaRef.DiagnoseImmediateEscalatingReason(FD);
18665
18666 } else {
18667 SemaRef.MarkExpressionAsImmediateEscalating(E: DR);
18668 }
18669 }
18670}
18671
18672void Sema::PopExpressionEvaluationContext() {
18673 ExpressionEvaluationContextRecord& Rec = ExprEvalContexts.back();
18674 if (!Rec.Lambdas.empty()) {
18675 using ExpressionKind = ExpressionEvaluationContextRecord::ExpressionKind;
18676 if (!getLangOpts().CPlusPlus20 &&
18677 (Rec.ExprContext == ExpressionKind::EK_TemplateArgument ||
18678 Rec.isUnevaluated() ||
18679 (Rec.isConstantEvaluated() && !getLangOpts().CPlusPlus17))) {
18680 unsigned D;
18681 if (Rec.isUnevaluated()) {
18682 // C++11 [expr.prim.lambda]p2:
18683 // A lambda-expression shall not appear in an unevaluated operand
18684 // (Clause 5).
18685 D = diag::err_lambda_unevaluated_operand;
18686 } else if (Rec.isConstantEvaluated() && !getLangOpts().CPlusPlus17) {
18687 // C++1y [expr.const]p2:
18688 // A conditional-expression e is a core constant expression unless the
18689 // evaluation of e, following the rules of the abstract machine, would
18690 // evaluate [...] a lambda-expression.
18691 D = diag::err_lambda_in_constant_expression;
18692 } else if (Rec.ExprContext == ExpressionKind::EK_TemplateArgument) {
18693 // C++17 [expr.prim.lamda]p2:
18694 // A lambda-expression shall not appear [...] in a template-argument.
18695 D = diag::err_lambda_in_invalid_context;
18696 } else
18697 llvm_unreachable("Couldn't infer lambda error message.");
18698
18699 for (const auto *L : Rec.Lambdas)
18700 Diag(Loc: L->getBeginLoc(), DiagID: D);
18701 }
18702 }
18703
18704 // Append the collected materialized temporaries into previous context before
18705 // exit if the previous also is a lifetime extending context.
18706 if (getLangOpts().CPlusPlus23 && Rec.InLifetimeExtendingContext &&
18707 parentEvaluationContext().InLifetimeExtendingContext &&
18708 !Rec.ForRangeLifetimeExtendTemps.empty()) {
18709 parentEvaluationContext().ForRangeLifetimeExtendTemps.append(
18710 RHS: Rec.ForRangeLifetimeExtendTemps);
18711 }
18712
18713 WarnOnPendingNoDerefs(Rec);
18714 HandleImmediateInvocations(SemaRef&: *this, Rec);
18715
18716 // Warn on any volatile-qualified simple-assignments that are not discarded-
18717 // value expressions nor unevaluated operands (those cases get removed from
18718 // this list by CheckUnusedVolatileAssignment).
18719 for (auto *BO : Rec.VolatileAssignmentLHSs)
18720 Diag(Loc: BO->getBeginLoc(), DiagID: diag::warn_deprecated_simple_assign_volatile)
18721 << BO->getType();
18722
18723 // When are coming out of an unevaluated context, clear out any
18724 // temporaries that we may have created as part of the evaluation of
18725 // the expression in that context: they aren't relevant because they
18726 // will never be constructed.
18727 if (Rec.isUnevaluated() || Rec.isConstantEvaluated()) {
18728 ExprCleanupObjects.erase(CS: ExprCleanupObjects.begin() + Rec.NumCleanupObjects,
18729 CE: ExprCleanupObjects.end());
18730 Cleanup = Rec.ParentCleanup;
18731 CleanupVarDeclMarking();
18732 std::swap(LHS&: MaybeODRUseExprs, RHS&: Rec.SavedMaybeODRUseExprs);
18733 // Otherwise, merge the contexts together.
18734 } else {
18735 Cleanup.mergeFrom(Rhs: Rec.ParentCleanup);
18736 MaybeODRUseExprs.insert_range(R&: Rec.SavedMaybeODRUseExprs);
18737 }
18738
18739 DiagnoseMisalignedMembers();
18740
18741 // Pop the current expression evaluation context off the stack.
18742 ExprEvalContexts.pop_back();
18743}
18744
18745void Sema::DiscardCleanupsInEvaluationContext() {
18746 ExprCleanupObjects.erase(
18747 CS: ExprCleanupObjects.begin() + ExprEvalContexts.back().NumCleanupObjects,
18748 CE: ExprCleanupObjects.end());
18749 Cleanup.reset();
18750 MaybeODRUseExprs.clear();
18751}
18752
18753ExprResult Sema::HandleExprEvaluationContextForTypeof(Expr *E) {
18754 ExprResult Result = CheckPlaceholderExpr(E);
18755 if (Result.isInvalid())
18756 return ExprError();
18757 E = Result.get();
18758 if (!E->getType()->isVariablyModifiedType())
18759 return E;
18760 return TransformToPotentiallyEvaluated(E);
18761}
18762
18763/// Are we in a context that is potentially constant evaluated per C++20
18764/// [expr.const]p12?
18765static bool isPotentiallyConstantEvaluatedContext(Sema &SemaRef) {
18766 /// C++2a [expr.const]p12:
18767 // An expression or conversion is potentially constant evaluated if it is
18768 switch (SemaRef.ExprEvalContexts.back().Context) {
18769 case Sema::ExpressionEvaluationContext::ConstantEvaluated:
18770 case Sema::ExpressionEvaluationContext::ImmediateFunctionContext:
18771
18772 // -- a manifestly constant-evaluated expression,
18773 case Sema::ExpressionEvaluationContext::PotentiallyEvaluated:
18774 case Sema::ExpressionEvaluationContext::PotentiallyEvaluatedIfUsed:
18775 case Sema::ExpressionEvaluationContext::DiscardedStatement:
18776 // -- a potentially-evaluated expression,
18777 case Sema::ExpressionEvaluationContext::UnevaluatedList:
18778 // -- an immediate subexpression of a braced-init-list,
18779
18780 // -- [FIXME] an expression of the form & cast-expression that occurs
18781 // within a templated entity
18782 // -- a subexpression of one of the above that is not a subexpression of
18783 // a nested unevaluated operand.
18784 return true;
18785
18786 case Sema::ExpressionEvaluationContext::Unevaluated:
18787 case Sema::ExpressionEvaluationContext::UnevaluatedAbstract:
18788 // Expressions in this context are never evaluated.
18789 return false;
18790 }
18791 llvm_unreachable("Invalid context");
18792}
18793
18794/// Return true if this function has a calling convention that requires mangling
18795/// in the size of the parameter pack.
18796static bool funcHasParameterSizeMangling(Sema &S, FunctionDecl *FD) {
18797 // These manglings are only applicable for targets whcih use Microsoft
18798 // mangling scheme for C.
18799 if (!S.Context.getTargetInfo().shouldUseMicrosoftCCforMangling())
18800 return false;
18801
18802 // If this is C++ and this isn't an extern "C" function, parameters do not
18803 // need to be complete. In this case, C++ mangling will apply, which doesn't
18804 // use the size of the parameters.
18805 if (S.getLangOpts().CPlusPlus && !FD->isExternC())
18806 return false;
18807
18808 // Stdcall, fastcall, and vectorcall need this special treatment.
18809 CallingConv CC = FD->getType()->castAs<FunctionType>()->getCallConv();
18810 switch (CC) {
18811 case CC_X86StdCall:
18812 case CC_X86FastCall:
18813 case CC_X86VectorCall:
18814 return true;
18815 default:
18816 break;
18817 }
18818 return false;
18819}
18820
18821/// Require that all of the parameter types of function be complete. Normally,
18822/// parameter types are only required to be complete when a function is called
18823/// or defined, but to mangle functions with certain calling conventions, the
18824/// mangler needs to know the size of the parameter list. In this situation,
18825/// MSVC doesn't emit an error or instantiate templates. Instead, MSVC mangles
18826/// the function as _foo@0, i.e. zero bytes of parameters, which will usually
18827/// result in a linker error. Clang doesn't implement this behavior, and instead
18828/// attempts to error at compile time.
18829static void CheckCompleteParameterTypesForMangler(Sema &S, FunctionDecl *FD,
18830 SourceLocation Loc) {
18831 class ParamIncompleteTypeDiagnoser : public Sema::TypeDiagnoser {
18832 FunctionDecl *FD;
18833 ParmVarDecl *Param;
18834
18835 public:
18836 ParamIncompleteTypeDiagnoser(FunctionDecl *FD, ParmVarDecl *Param)
18837 : FD(FD), Param(Param) {}
18838
18839 void diagnose(Sema &S, SourceLocation Loc, QualType T) override {
18840 CallingConv CC = FD->getType()->castAs<FunctionType>()->getCallConv();
18841 StringRef CCName;
18842 switch (CC) {
18843 case CC_X86StdCall:
18844 CCName = "stdcall";
18845 break;
18846 case CC_X86FastCall:
18847 CCName = "fastcall";
18848 break;
18849 case CC_X86VectorCall:
18850 CCName = "vectorcall";
18851 break;
18852 default:
18853 llvm_unreachable("CC does not need mangling");
18854 }
18855
18856 S.Diag(Loc, DiagID: diag::err_cconv_incomplete_param_type)
18857 << Param->getDeclName() << FD->getDeclName() << CCName;
18858 }
18859 };
18860
18861 for (ParmVarDecl *Param : FD->parameters()) {
18862 ParamIncompleteTypeDiagnoser Diagnoser(FD, Param);
18863 S.RequireCompleteType(Loc, T: Param->getType(), Diagnoser);
18864 }
18865}
18866
18867namespace {
18868enum class OdrUseContext {
18869 /// Declarations in this context are not odr-used.
18870 None,
18871 /// Declarations in this context are formally odr-used, but this is a
18872 /// dependent context.
18873 Dependent,
18874 /// Declarations in this context are odr-used but not actually used (yet).
18875 FormallyOdrUsed,
18876 /// Declarations in this context are used.
18877 Used
18878};
18879}
18880
18881/// Are we within a context in which references to resolved functions or to
18882/// variables result in odr-use?
18883static OdrUseContext isOdrUseContext(Sema &SemaRef) {
18884 const Sema::ExpressionEvaluationContextRecord &Context =
18885 SemaRef.currentEvaluationContext();
18886
18887 if (Context.isUnevaluated())
18888 return OdrUseContext::None;
18889
18890 if (SemaRef.CurContext->isDependentContext())
18891 return OdrUseContext::Dependent;
18892
18893 if (Context.isDiscardedStatementContext())
18894 return OdrUseContext::FormallyOdrUsed;
18895
18896 else if (Context.Context ==
18897 Sema::ExpressionEvaluationContext::PotentiallyEvaluatedIfUsed)
18898 return OdrUseContext::FormallyOdrUsed;
18899
18900 return OdrUseContext::Used;
18901}
18902
18903static bool isImplicitlyDefinableConstexprFunction(FunctionDecl *Func) {
18904 if (!Func->isConstexpr())
18905 return false;
18906
18907 if (Func->isImplicitlyInstantiable() || !Func->isUserProvided())
18908 return true;
18909
18910 // Lambda conversion operators are never user provided.
18911 if (CXXConversionDecl *Conv = dyn_cast<CXXConversionDecl>(Val: Func))
18912 return isLambdaConversionOperator(C: Conv);
18913
18914 auto *CCD = dyn_cast<CXXConstructorDecl>(Val: Func);
18915 return CCD && CCD->getInheritedConstructor();
18916}
18917
18918void Sema::MarkFunctionReferenced(SourceLocation Loc, FunctionDecl *Func,
18919 bool MightBeOdrUse) {
18920 assert(Func && "No function?");
18921
18922 Func->setReferenced();
18923
18924 // Recursive functions aren't really used until they're used from some other
18925 // context.
18926 bool IsRecursiveCall = CurContext == Func;
18927
18928 // C++11 [basic.def.odr]p3:
18929 // A function whose name appears as a potentially-evaluated expression is
18930 // odr-used if it is the unique lookup result or the selected member of a
18931 // set of overloaded functions [...].
18932 //
18933 // We (incorrectly) mark overload resolution as an unevaluated context, so we
18934 // can just check that here.
18935 OdrUseContext OdrUse =
18936 MightBeOdrUse ? isOdrUseContext(SemaRef&: *this) : OdrUseContext::None;
18937 if (IsRecursiveCall && OdrUse == OdrUseContext::Used)
18938 OdrUse = OdrUseContext::FormallyOdrUsed;
18939
18940 // Trivial default constructors and destructors are never actually used.
18941 // FIXME: What about other special members?
18942 if (Func->isTrivial() && !Func->hasAttr<DLLExportAttr>() &&
18943 OdrUse == OdrUseContext::Used) {
18944 if (auto *Constructor = dyn_cast<CXXConstructorDecl>(Val: Func))
18945 if (Constructor->isDefaultConstructor())
18946 OdrUse = OdrUseContext::FormallyOdrUsed;
18947 if (isa<CXXDestructorDecl>(Val: Func))
18948 OdrUse = OdrUseContext::FormallyOdrUsed;
18949 }
18950
18951 // C++20 [expr.const]p12:
18952 // A function [...] is needed for constant evaluation if it is [...] a
18953 // constexpr function that is named by an expression that is potentially
18954 // constant evaluated
18955 bool NeededForConstantEvaluation =
18956 isPotentiallyConstantEvaluatedContext(SemaRef&: *this) &&
18957 isImplicitlyDefinableConstexprFunction(Func);
18958
18959 // Determine whether we require a function definition to exist, per
18960 // C++11 [temp.inst]p3:
18961 // Unless a function template specialization has been explicitly
18962 // instantiated or explicitly specialized, the function template
18963 // specialization is implicitly instantiated when the specialization is
18964 // referenced in a context that requires a function definition to exist.
18965 // C++20 [temp.inst]p7:
18966 // The existence of a definition of a [...] function is considered to
18967 // affect the semantics of the program if the [...] function is needed for
18968 // constant evaluation by an expression
18969 // C++20 [basic.def.odr]p10:
18970 // Every program shall contain exactly one definition of every non-inline
18971 // function or variable that is odr-used in that program outside of a
18972 // discarded statement
18973 // C++20 [special]p1:
18974 // The implementation will implicitly define [defaulted special members]
18975 // if they are odr-used or needed for constant evaluation.
18976 //
18977 // Note that we skip the implicit instantiation of templates that are only
18978 // used in unused default arguments or by recursive calls to themselves.
18979 // This is formally non-conforming, but seems reasonable in practice.
18980 bool NeedDefinition =
18981 !IsRecursiveCall &&
18982 (OdrUse == OdrUseContext::Used ||
18983 (NeededForConstantEvaluation && !Func->isPureVirtual()));
18984
18985 // C++14 [temp.expl.spec]p6:
18986 // If a template [...] is explicitly specialized then that specialization
18987 // shall be declared before the first use of that specialization that would
18988 // cause an implicit instantiation to take place, in every translation unit
18989 // in which such a use occurs
18990 if (NeedDefinition &&
18991 (Func->getTemplateSpecializationKind() != TSK_Undeclared ||
18992 Func->getMemberSpecializationInfo()))
18993 checkSpecializationReachability(Loc, Spec: Func);
18994
18995 if (getLangOpts().CUDA)
18996 CUDA().CheckCall(Loc, Callee: Func);
18997
18998 // If we need a definition, try to create one.
18999 if (NeedDefinition && !Func->getBody()) {
19000 runWithSufficientStackSpace(Loc, Fn: [&] {
19001 if (CXXConstructorDecl *Constructor =
19002 dyn_cast<CXXConstructorDecl>(Val: Func)) {
19003 Constructor = cast<CXXConstructorDecl>(Val: Constructor->getFirstDecl());
19004 if (Constructor->isDefaulted() && !Constructor->isDeleted()) {
19005 if (Constructor->isDefaultConstructor()) {
19006 if (Constructor->isTrivial() &&
19007 !Constructor->hasAttr<DLLExportAttr>())
19008 return;
19009 DefineImplicitDefaultConstructor(CurrentLocation: Loc, Constructor);
19010 } else if (Constructor->isCopyConstructor()) {
19011 DefineImplicitCopyConstructor(CurrentLocation: Loc, Constructor);
19012 } else if (Constructor->isMoveConstructor()) {
19013 DefineImplicitMoveConstructor(CurrentLocation: Loc, Constructor);
19014 }
19015 } else if (Constructor->getInheritedConstructor()) {
19016 DefineInheritingConstructor(UseLoc: Loc, Constructor);
19017 }
19018 } else if (CXXDestructorDecl *Destructor =
19019 dyn_cast<CXXDestructorDecl>(Val: Func)) {
19020 Destructor = cast<CXXDestructorDecl>(Val: Destructor->getFirstDecl());
19021 if (Destructor->isDefaulted() && !Destructor->isDeleted()) {
19022 if (Destructor->isTrivial() && !Destructor->hasAttr<DLLExportAttr>())
19023 return;
19024 DefineImplicitDestructor(CurrentLocation: Loc, Destructor);
19025 }
19026 if (Destructor->isVirtual() && getLangOpts().AppleKext)
19027 MarkVTableUsed(Loc, Class: Destructor->getParent());
19028 } else if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(Val: Func)) {
19029 if (MethodDecl->isOverloadedOperator() &&
19030 MethodDecl->getOverloadedOperator() == OO_Equal) {
19031 MethodDecl = cast<CXXMethodDecl>(Val: MethodDecl->getFirstDecl());
19032 if (MethodDecl->isDefaulted() && !MethodDecl->isDeleted()) {
19033 if (MethodDecl->isCopyAssignmentOperator())
19034 DefineImplicitCopyAssignment(CurrentLocation: Loc, MethodDecl);
19035 else if (MethodDecl->isMoveAssignmentOperator())
19036 DefineImplicitMoveAssignment(CurrentLocation: Loc, MethodDecl);
19037 }
19038 } else if (isa<CXXConversionDecl>(Val: MethodDecl) &&
19039 MethodDecl->getParent()->isLambda()) {
19040 CXXConversionDecl *Conversion =
19041 cast<CXXConversionDecl>(Val: MethodDecl->getFirstDecl());
19042 if (Conversion->isLambdaToBlockPointerConversion())
19043 DefineImplicitLambdaToBlockPointerConversion(CurrentLoc: Loc, Conv: Conversion);
19044 else
19045 DefineImplicitLambdaToFunctionPointerConversion(CurrentLoc: Loc, Conv: Conversion);
19046 } else if (MethodDecl->isVirtual() && getLangOpts().AppleKext)
19047 MarkVTableUsed(Loc, Class: MethodDecl->getParent());
19048 }
19049
19050 if (Func->isDefaulted() && !Func->isDeleted()) {
19051 DefaultedComparisonKind DCK = getDefaultedComparisonKind(FD: Func);
19052 if (DCK != DefaultedComparisonKind::None)
19053 DefineDefaultedComparison(Loc, FD: Func, DCK);
19054 }
19055
19056 // Implicit instantiation of function templates and member functions of
19057 // class templates.
19058 if (Func->isImplicitlyInstantiable()) {
19059 TemplateSpecializationKind TSK =
19060 Func->getTemplateSpecializationKindForInstantiation();
19061 SourceLocation PointOfInstantiation = Func->getPointOfInstantiation();
19062 bool FirstInstantiation = PointOfInstantiation.isInvalid();
19063 if (FirstInstantiation) {
19064 PointOfInstantiation = Loc;
19065 if (auto *MSI = Func->getMemberSpecializationInfo())
19066 MSI->setPointOfInstantiation(Loc);
19067 // FIXME: Notify listener.
19068 else
19069 Func->setTemplateSpecializationKind(TSK, PointOfInstantiation);
19070 } else if (TSK != TSK_ImplicitInstantiation) {
19071 // Use the point of use as the point of instantiation, instead of the
19072 // point of explicit instantiation (which we track as the actual point
19073 // of instantiation). This gives better backtraces in diagnostics.
19074 PointOfInstantiation = Loc;
19075 }
19076
19077 if (FirstInstantiation || TSK != TSK_ImplicitInstantiation ||
19078 Func->isConstexpr()) {
19079 if (isa<CXXRecordDecl>(Val: Func->getDeclContext()) &&
19080 cast<CXXRecordDecl>(Val: Func->getDeclContext())->isLocalClass() &&
19081 CodeSynthesisContexts.size())
19082 PendingLocalImplicitInstantiations.push_back(
19083 x: std::make_pair(x&: Func, y&: PointOfInstantiation));
19084 else if (Func->isConstexpr())
19085 // Do not defer instantiations of constexpr functions, to avoid the
19086 // expression evaluator needing to call back into Sema if it sees a
19087 // call to such a function.
19088 InstantiateFunctionDefinition(PointOfInstantiation, Function: Func);
19089 else {
19090 Func->setInstantiationIsPending(true);
19091 PendingInstantiations.push_back(
19092 x: std::make_pair(x&: Func, y&: PointOfInstantiation));
19093 if (llvm::isTimeTraceVerbose()) {
19094 llvm::timeTraceAddInstantEvent(Name: "DeferInstantiation", Detail: [&] {
19095 std::string Name;
19096 llvm::raw_string_ostream OS(Name);
19097 Func->getNameForDiagnostic(OS, Policy: getPrintingPolicy(),
19098 /*Qualified=*/true);
19099 return Name;
19100 });
19101 }
19102 // Notify the consumer that a function was implicitly instantiated.
19103 Consumer.HandleCXXImplicitFunctionInstantiation(D: Func);
19104 }
19105 }
19106 } else {
19107 // Walk redefinitions, as some of them may be instantiable.
19108 for (auto *i : Func->redecls()) {
19109 if (!i->isUsed(CheckUsedAttr: false) && i->isImplicitlyInstantiable())
19110 MarkFunctionReferenced(Loc, Func: i, MightBeOdrUse);
19111 }
19112 }
19113 });
19114 }
19115
19116 // If a constructor was defined in the context of a default parameter
19117 // or of another default member initializer (ie a PotentiallyEvaluatedIfUsed
19118 // context), its initializers may not be referenced yet.
19119 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Val: Func)) {
19120 EnterExpressionEvaluationContext EvalContext(
19121 *this,
19122 Constructor->isImmediateFunction()
19123 ? ExpressionEvaluationContext::ImmediateFunctionContext
19124 : ExpressionEvaluationContext::PotentiallyEvaluated,
19125 Constructor);
19126 for (CXXCtorInitializer *Init : Constructor->inits()) {
19127 if (Init->isInClassMemberInitializer())
19128 runWithSufficientStackSpace(Loc: Init->getSourceLocation(), Fn: [&]() {
19129 MarkDeclarationsReferencedInExpr(E: Init->getInit());
19130 });
19131 }
19132 }
19133
19134 // C++14 [except.spec]p17:
19135 // An exception-specification is considered to be needed when:
19136 // - the function is odr-used or, if it appears in an unevaluated operand,
19137 // would be odr-used if the expression were potentially-evaluated;
19138 //
19139 // Note, we do this even if MightBeOdrUse is false. That indicates that the
19140 // function is a pure virtual function we're calling, and in that case the
19141 // function was selected by overload resolution and we need to resolve its
19142 // exception specification for a different reason.
19143 const FunctionProtoType *FPT = Func->getType()->getAs<FunctionProtoType>();
19144 if (FPT && isUnresolvedExceptionSpec(ESpecType: FPT->getExceptionSpecType()))
19145 ResolveExceptionSpec(Loc, FPT);
19146
19147 // A callee could be called by a host function then by a device function.
19148 // If we only try recording once, we will miss recording the use on device
19149 // side. Therefore keep trying until it is recorded.
19150 if (LangOpts.OffloadImplicitHostDeviceTemplates && LangOpts.CUDAIsDevice &&
19151 !getASTContext().CUDAImplicitHostDeviceFunUsedByDevice.count(V: Func))
19152 CUDA().RecordImplicitHostDeviceFuncUsedByDevice(FD: Func);
19153
19154 // If this is the first "real" use, act on that.
19155 if (OdrUse == OdrUseContext::Used && !Func->isUsed(/*CheckUsedAttr=*/false)) {
19156 // Keep track of used but undefined functions.
19157 if (!Func->isDefined() && !Func->isInAnotherModuleUnit()) {
19158 if (mightHaveNonExternalLinkage(FD: Func))
19159 UndefinedButUsed.insert(KV: std::make_pair(x: Func->getCanonicalDecl(), y&: Loc));
19160 else if (Func->getMostRecentDecl()->isInlined() &&
19161 !LangOpts.GNUInline &&
19162 !Func->getMostRecentDecl()->hasAttr<GNUInlineAttr>())
19163 UndefinedButUsed.insert(KV: std::make_pair(x: Func->getCanonicalDecl(), y&: Loc));
19164 else if (isExternalWithNoLinkageType(VD: Func))
19165 UndefinedButUsed.insert(KV: std::make_pair(x: Func->getCanonicalDecl(), y&: Loc));
19166 }
19167
19168 // Some x86 Windows calling conventions mangle the size of the parameter
19169 // pack into the name. Computing the size of the parameters requires the
19170 // parameter types to be complete. Check that now.
19171 if (funcHasParameterSizeMangling(S&: *this, FD: Func))
19172 CheckCompleteParameterTypesForMangler(S&: *this, FD: Func, Loc);
19173
19174 // In the MS C++ ABI, the compiler emits destructor variants where they are
19175 // used. If the destructor is used here but defined elsewhere, mark the
19176 // virtual base destructors referenced. If those virtual base destructors
19177 // are inline, this will ensure they are defined when emitting the complete
19178 // destructor variant. This checking may be redundant if the destructor is
19179 // provided later in this TU.
19180 if (Context.getTargetInfo().getCXXABI().isMicrosoft()) {
19181 if (auto *Dtor = dyn_cast<CXXDestructorDecl>(Val: Func)) {
19182 CXXRecordDecl *Parent = Dtor->getParent();
19183 if (Parent->getNumVBases() > 0 && !Dtor->getBody())
19184 CheckCompleteDestructorVariant(CurrentLocation: Loc, Dtor);
19185 }
19186 }
19187
19188 Func->markUsed(C&: Context);
19189 }
19190}
19191
19192/// Directly mark a variable odr-used. Given a choice, prefer to use
19193/// MarkVariableReferenced since it does additional checks and then
19194/// calls MarkVarDeclODRUsed.
19195/// If the variable must be captured:
19196/// - if FunctionScopeIndexToStopAt is null, capture it in the CurContext
19197/// - else capture it in the DeclContext that maps to the
19198/// *FunctionScopeIndexToStopAt on the FunctionScopeInfo stack.
19199static void
19200MarkVarDeclODRUsed(ValueDecl *V, SourceLocation Loc, Sema &SemaRef,
19201 const unsigned *const FunctionScopeIndexToStopAt = nullptr) {
19202 // Keep track of used but undefined variables.
19203 // FIXME: We shouldn't suppress this warning for static data members.
19204 VarDecl *Var = V->getPotentiallyDecomposedVarDecl();
19205 assert(Var && "expected a capturable variable");
19206
19207 if (Var->hasDefinition(SemaRef.Context) == VarDecl::DeclarationOnly &&
19208 (!Var->isExternallyVisible() || Var->isInline() ||
19209 SemaRef.isExternalWithNoLinkageType(VD: Var)) &&
19210 !(Var->isStaticDataMember() && Var->hasInit())) {
19211 SourceLocation &old = SemaRef.UndefinedButUsed[Var->getCanonicalDecl()];
19212 if (old.isInvalid())
19213 old = Loc;
19214 }
19215 QualType CaptureType, DeclRefType;
19216 if (SemaRef.LangOpts.OpenMP)
19217 SemaRef.OpenMP().tryCaptureOpenMPLambdas(V);
19218 SemaRef.tryCaptureVariable(Var: V, Loc, Kind: TryCaptureKind::Implicit,
19219 /*EllipsisLoc*/ SourceLocation(),
19220 /*BuildAndDiagnose*/ true, CaptureType,
19221 DeclRefType, FunctionScopeIndexToStopAt);
19222
19223 if (SemaRef.LangOpts.CUDA && Var->hasGlobalStorage()) {
19224 auto *FD = dyn_cast_or_null<FunctionDecl>(Val: SemaRef.CurContext);
19225 auto VarTarget = SemaRef.CUDA().IdentifyTarget(D: Var);
19226 auto UserTarget = SemaRef.CUDA().IdentifyTarget(D: FD);
19227 if (VarTarget == SemaCUDA::CVT_Host &&
19228 (UserTarget == CUDAFunctionTarget::Device ||
19229 UserTarget == CUDAFunctionTarget::HostDevice ||
19230 UserTarget == CUDAFunctionTarget::Global)) {
19231 // Diagnose ODR-use of host global variables in device functions.
19232 // Reference of device global variables in host functions is allowed
19233 // through shadow variables therefore it is not diagnosed.
19234 if (SemaRef.LangOpts.CUDAIsDevice && !SemaRef.LangOpts.HIPStdPar) {
19235 SemaRef.targetDiag(Loc, DiagID: diag::err_ref_bad_target)
19236 << /*host*/ 2 << /*variable*/ 1 << Var << UserTarget;
19237 SemaRef.targetDiag(Loc: Var->getLocation(),
19238 DiagID: Var->getType().isConstQualified()
19239 ? diag::note_cuda_const_var_unpromoted
19240 : diag::note_cuda_host_var);
19241 }
19242 } else if ((VarTarget == SemaCUDA::CVT_Device ||
19243 // Also capture __device__ const variables, which are classified
19244 // as CVT_Both due to an implicit CUDAConstantAttr. We check for
19245 // an explicit CUDADeviceAttr to distinguish them from plain
19246 // const variables (no __device__), which also get CVT_Both but
19247 // only have an implicit CUDADeviceAttr.
19248 (VarTarget == SemaCUDA::CVT_Both &&
19249 Var->hasAttr<CUDADeviceAttr>() &&
19250 !Var->getAttr<CUDADeviceAttr>()->isImplicit())) &&
19251 !Var->hasAttr<CUDASharedAttr>() &&
19252 (UserTarget == CUDAFunctionTarget::Host ||
19253 UserTarget == CUDAFunctionTarget::HostDevice)) {
19254 // Record a CUDA/HIP device side variable if it is ODR-used
19255 // by host code. This is done conservatively, when the variable is
19256 // referenced in any of the following contexts:
19257 // - a non-function context
19258 // - a host function
19259 // - a host device function
19260 // This makes the ODR-use of the device side variable by host code to
19261 // be visible in the device compilation for the compiler to be able to
19262 // emit template variables instantiated by host code only and to
19263 // externalize the static device side variable ODR-used by host code.
19264 if (!Var->hasExternalStorage())
19265 SemaRef.getASTContext().CUDADeviceVarODRUsedByHost.insert(X: Var);
19266 else if (SemaRef.LangOpts.GPURelocatableDeviceCode &&
19267 (!FD || (!FD->getDescribedFunctionTemplate() &&
19268 SemaRef.getASTContext().GetGVALinkageForFunction(FD) ==
19269 GVA_StrongExternal)))
19270 SemaRef.getASTContext().CUDAExternalDeviceDeclODRUsedByHost.insert(X: Var);
19271 }
19272 }
19273
19274 V->markUsed(C&: SemaRef.Context);
19275}
19276
19277void Sema::MarkCaptureUsedInEnclosingContext(ValueDecl *Capture,
19278 SourceLocation Loc,
19279 unsigned CapturingScopeIndex) {
19280 MarkVarDeclODRUsed(V: Capture, Loc, SemaRef&: *this, FunctionScopeIndexToStopAt: &CapturingScopeIndex);
19281}
19282
19283static void diagnoseUncapturableValueReferenceOrBinding(Sema &S,
19284 SourceLocation loc,
19285 ValueDecl *var) {
19286 DeclContext *VarDC = var->getDeclContext();
19287
19288 // If the parameter still belongs to the translation unit, then
19289 // we're actually just using one parameter in the declaration of
19290 // the next.
19291 if (isa<ParmVarDecl>(Val: var) &&
19292 isa<TranslationUnitDecl>(Val: VarDC))
19293 return;
19294
19295 // For C code, don't diagnose about capture if we're not actually in code
19296 // right now; it's impossible to write a non-constant expression outside of
19297 // function context, so we'll get other (more useful) diagnostics later.
19298 //
19299 // For C++, things get a bit more nasty... it would be nice to suppress this
19300 // diagnostic for certain cases like using a local variable in an array bound
19301 // for a member of a local class, but the correct predicate is not obvious.
19302 if (!S.getLangOpts().CPlusPlus && !S.CurContext->isFunctionOrMethod())
19303 return;
19304
19305 unsigned ValueKind = isa<BindingDecl>(Val: var) ? 1 : 0;
19306 unsigned ContextKind = 3; // unknown
19307 if (isa<CXXMethodDecl>(Val: VarDC) &&
19308 cast<CXXRecordDecl>(Val: VarDC->getParent())->isLambda()) {
19309 ContextKind = 2;
19310 } else if (isa<FunctionDecl>(Val: VarDC)) {
19311 ContextKind = 0;
19312 } else if (isa<BlockDecl>(Val: VarDC)) {
19313 ContextKind = 1;
19314 }
19315
19316 S.Diag(Loc: loc, DiagID: diag::err_reference_to_local_in_enclosing_context)
19317 << var << ValueKind << ContextKind << VarDC;
19318 S.Diag(Loc: var->getLocation(), DiagID: diag::note_entity_declared_at)
19319 << var;
19320
19321 // FIXME: Add additional diagnostic info about class etc. which prevents
19322 // capture.
19323}
19324
19325static bool isVariableAlreadyCapturedInScopeInfo(CapturingScopeInfo *CSI,
19326 ValueDecl *Var,
19327 bool &SubCapturesAreNested,
19328 QualType &CaptureType,
19329 QualType &DeclRefType) {
19330 // Check whether we've already captured it.
19331 if (CSI->CaptureMap.count(Val: Var)) {
19332 // If we found a capture, any subcaptures are nested.
19333 SubCapturesAreNested = true;
19334
19335 // Retrieve the capture type for this variable.
19336 CaptureType = CSI->getCapture(Var).getCaptureType();
19337
19338 // Compute the type of an expression that refers to this variable.
19339 DeclRefType = CaptureType.getNonReferenceType();
19340
19341 // Similarly to mutable captures in lambda, all the OpenMP captures by copy
19342 // are mutable in the sense that user can change their value - they are
19343 // private instances of the captured declarations.
19344 const Capture &Cap = CSI->getCapture(Var);
19345 // C++ [expr.prim.lambda]p10:
19346 // The type of such a data member is [...] an lvalue reference to the
19347 // referenced function type if the entity is a reference to a function.
19348 // [...]
19349 if (Cap.isCopyCapture() && !DeclRefType->isFunctionType() &&
19350 !(isa<LambdaScopeInfo>(Val: CSI) &&
19351 !cast<LambdaScopeInfo>(Val: CSI)->lambdaCaptureShouldBeConst()) &&
19352 !(isa<CapturedRegionScopeInfo>(Val: CSI) &&
19353 cast<CapturedRegionScopeInfo>(Val: CSI)->CapRegionKind == CR_OpenMP))
19354 DeclRefType.addConst();
19355 return true;
19356 }
19357 return false;
19358}
19359
19360// Only block literals, captured statements, and lambda expressions can
19361// capture; other scopes don't work.
19362static DeclContext *getParentOfCapturingContextOrNull(DeclContext *DC,
19363 ValueDecl *Var,
19364 SourceLocation Loc,
19365 const bool Diagnose,
19366 Sema &S) {
19367 if (isa<BlockDecl>(Val: DC) || isa<CapturedDecl>(Val: DC) || isLambdaCallOperator(DC))
19368 return getLambdaAwareParentOfDeclContext(DC);
19369
19370 VarDecl *Underlying = Var->getPotentiallyDecomposedVarDecl();
19371 if (Underlying) {
19372 if (Underlying->hasLocalStorage() && Diagnose)
19373 diagnoseUncapturableValueReferenceOrBinding(S, loc: Loc, var: Var);
19374 }
19375 return nullptr;
19376}
19377
19378// Certain capturing entities (lambdas, blocks etc.) are not allowed to capture
19379// certain types of variables (unnamed, variably modified types etc.)
19380// so check for eligibility.
19381static bool isVariableCapturable(CapturingScopeInfo *CSI, ValueDecl *Var,
19382 SourceLocation Loc, const bool Diagnose,
19383 Sema &S) {
19384
19385 assert((isa<VarDecl, BindingDecl>(Var)) &&
19386 "Only variables and structured bindings can be captured");
19387
19388 bool IsBlock = isa<BlockScopeInfo>(Val: CSI);
19389 bool IsLambda = isa<LambdaScopeInfo>(Val: CSI);
19390
19391 // Lambdas are not allowed to capture unnamed variables
19392 // (e.g. anonymous unions).
19393 // FIXME: The C++11 rule don't actually state this explicitly, but I'm
19394 // assuming that's the intent.
19395 if (IsLambda && !Var->getDeclName()) {
19396 if (Diagnose) {
19397 S.Diag(Loc, DiagID: diag::err_lambda_capture_anonymous_var);
19398 S.Diag(Loc: Var->getLocation(), DiagID: diag::note_declared_at);
19399 }
19400 return false;
19401 }
19402
19403 // Prohibit variably-modified types in blocks; they're difficult to deal with.
19404 if (Var->getType()->isVariablyModifiedType() && IsBlock) {
19405 if (Diagnose) {
19406 S.Diag(Loc, DiagID: diag::err_ref_vm_type);
19407 S.Diag(Loc: Var->getLocation(), DiagID: diag::note_previous_decl) << Var;
19408 }
19409 return false;
19410 }
19411 // Prohibit structs with flexible array members too.
19412 // We cannot capture what is in the tail end of the struct.
19413 if (const auto *VTD = Var->getType()->getAsRecordDecl();
19414 VTD && VTD->hasFlexibleArrayMember()) {
19415 if (Diagnose) {
19416 if (IsBlock)
19417 S.Diag(Loc, DiagID: diag::err_ref_flexarray_type);
19418 else
19419 S.Diag(Loc, DiagID: diag::err_lambda_capture_flexarray_type) << Var;
19420 S.Diag(Loc: Var->getLocation(), DiagID: diag::note_previous_decl) << Var;
19421 }
19422 return false;
19423 }
19424 const bool HasBlocksAttr = Var->hasAttr<BlocksAttr>();
19425 // Lambdas and captured statements are not allowed to capture __block
19426 // variables; they don't support the expected semantics.
19427 if (HasBlocksAttr && (IsLambda || isa<CapturedRegionScopeInfo>(Val: CSI))) {
19428 if (Diagnose) {
19429 S.Diag(Loc, DiagID: diag::err_capture_block_variable) << Var << !IsLambda;
19430 S.Diag(Loc: Var->getLocation(), DiagID: diag::note_previous_decl) << Var;
19431 }
19432 return false;
19433 }
19434 // OpenCL v2.0 s6.12.5: Blocks cannot reference/capture other blocks
19435 if (S.getLangOpts().OpenCL && IsBlock &&
19436 Var->getType()->isBlockPointerType()) {
19437 if (Diagnose)
19438 S.Diag(Loc, DiagID: diag::err_opencl_block_ref_block);
19439 return false;
19440 }
19441
19442 if (isa<BindingDecl>(Val: Var)) {
19443 if (!IsLambda || !S.getLangOpts().CPlusPlus) {
19444 if (Diagnose)
19445 diagnoseUncapturableValueReferenceOrBinding(S, loc: Loc, var: Var);
19446 return false;
19447 } else if (Diagnose && S.getLangOpts().CPlusPlus) {
19448 S.Diag(Loc, DiagID: S.LangOpts.CPlusPlus20
19449 ? diag::warn_cxx17_compat_capture_binding
19450 : diag::ext_capture_binding)
19451 << Var;
19452 S.Diag(Loc: Var->getLocation(), DiagID: diag::note_entity_declared_at) << Var;
19453 }
19454 }
19455
19456 return true;
19457}
19458
19459// Returns true if the capture by block was successful.
19460static bool captureInBlock(BlockScopeInfo *BSI, ValueDecl *Var,
19461 SourceLocation Loc, const bool BuildAndDiagnose,
19462 QualType &CaptureType, QualType &DeclRefType,
19463 const bool Nested, Sema &S, bool Invalid) {
19464 bool ByRef = false;
19465
19466 // Blocks are not allowed to capture arrays, excepting OpenCL.
19467 // OpenCL v2.0 s1.12.5 (revision 40): arrays are captured by reference
19468 // (decayed to pointers).
19469 if (!Invalid && !S.getLangOpts().OpenCL && CaptureType->isArrayType()) {
19470 if (BuildAndDiagnose) {
19471 S.Diag(Loc, DiagID: diag::err_ref_array_type);
19472 S.Diag(Loc: Var->getLocation(), DiagID: diag::note_previous_decl) << Var;
19473 Invalid = true;
19474 } else {
19475 return false;
19476 }
19477 }
19478
19479 // Forbid the block-capture of autoreleasing variables.
19480 if (!Invalid &&
19481 CaptureType.getObjCLifetime() == Qualifiers::OCL_Autoreleasing) {
19482 if (BuildAndDiagnose) {
19483 S.Diag(Loc, DiagID: diag::err_arc_autoreleasing_capture)
19484 << /*block*/ 0;
19485 S.Diag(Loc: Var->getLocation(), DiagID: diag::note_previous_decl) << Var;
19486 Invalid = true;
19487 } else {
19488 return false;
19489 }
19490 }
19491
19492 // Warn about implicitly autoreleasing indirect parameters captured by blocks.
19493 if (const auto *PT = CaptureType->getAs<PointerType>()) {
19494 QualType PointeeTy = PT->getPointeeType();
19495
19496 if (!Invalid && PointeeTy->getAs<ObjCObjectPointerType>() &&
19497 PointeeTy.getObjCLifetime() == Qualifiers::OCL_Autoreleasing &&
19498 !S.Context.hasDirectOwnershipQualifier(Ty: PointeeTy)) {
19499 if (BuildAndDiagnose) {
19500 SourceLocation VarLoc = Var->getLocation();
19501 S.Diag(Loc, DiagID: diag::warn_block_capture_autoreleasing);
19502 S.Diag(Loc: VarLoc, DiagID: diag::note_declare_parameter_strong);
19503 }
19504 }
19505 }
19506
19507 const bool HasBlocksAttr = Var->hasAttr<BlocksAttr>();
19508 if (HasBlocksAttr || CaptureType->isReferenceType() ||
19509 (S.getLangOpts().OpenMP && S.OpenMP().isOpenMPCapturedDecl(D: Var))) {
19510 // Block capture by reference does not change the capture or
19511 // declaration reference types.
19512 ByRef = true;
19513 } else {
19514 // Block capture by copy introduces 'const'.
19515 CaptureType = CaptureType.getNonReferenceType().withConst();
19516 DeclRefType = CaptureType;
19517 }
19518
19519 // Actually capture the variable.
19520 if (BuildAndDiagnose)
19521 BSI->addCapture(Var, isBlock: HasBlocksAttr, isByref: ByRef, isNested: Nested, Loc, EllipsisLoc: SourceLocation(),
19522 CaptureType, Invalid);
19523
19524 return !Invalid;
19525}
19526
19527/// Capture the given variable in the captured region.
19528static bool captureInCapturedRegion(
19529 CapturedRegionScopeInfo *RSI, ValueDecl *Var, SourceLocation Loc,
19530 const bool BuildAndDiagnose, QualType &CaptureType, QualType &DeclRefType,
19531 const bool RefersToCapturedVariable, TryCaptureKind Kind, bool IsTopScope,
19532 Sema &S, bool Invalid) {
19533 // By default, capture variables by reference.
19534 bool ByRef = true;
19535 if (IsTopScope && Kind != TryCaptureKind::Implicit) {
19536 ByRef = (Kind == TryCaptureKind::ExplicitByRef);
19537 } else if (S.getLangOpts().OpenMP && RSI->CapRegionKind == CR_OpenMP) {
19538 // Using an LValue reference type is consistent with Lambdas (see below).
19539 if (S.OpenMP().isOpenMPCapturedDecl(D: Var)) {
19540 bool HasConst = DeclRefType.isConstQualified();
19541 DeclRefType = DeclRefType.getUnqualifiedType();
19542 // Don't lose diagnostics about assignments to const.
19543 if (HasConst)
19544 DeclRefType.addConst();
19545 }
19546 // Do not capture firstprivates in tasks.
19547 if (S.OpenMP().isOpenMPPrivateDecl(D: Var, Level: RSI->OpenMPLevel,
19548 CapLevel: RSI->OpenMPCaptureLevel) != OMPC_unknown)
19549 return true;
19550 ByRef = S.OpenMP().isOpenMPCapturedByRef(D: Var, Level: RSI->OpenMPLevel,
19551 OpenMPCaptureLevel: RSI->OpenMPCaptureLevel);
19552 }
19553
19554 if (ByRef)
19555 CaptureType = S.Context.getLValueReferenceType(T: DeclRefType);
19556 else
19557 CaptureType = DeclRefType;
19558
19559 // Actually capture the variable.
19560 if (BuildAndDiagnose)
19561 RSI->addCapture(Var, /*isBlock*/ false, isByref: ByRef, isNested: RefersToCapturedVariable,
19562 Loc, EllipsisLoc: SourceLocation(), CaptureType, Invalid);
19563
19564 return !Invalid;
19565}
19566
19567/// Capture the given variable in the lambda.
19568static bool captureInLambda(LambdaScopeInfo *LSI, ValueDecl *Var,
19569 SourceLocation Loc, const bool BuildAndDiagnose,
19570 QualType &CaptureType, QualType &DeclRefType,
19571 const bool RefersToCapturedVariable,
19572 const TryCaptureKind Kind,
19573 SourceLocation EllipsisLoc, const bool IsTopScope,
19574 Sema &S, bool Invalid) {
19575 // Determine whether we are capturing by reference or by value.
19576 bool ByRef = false;
19577 if (IsTopScope && Kind != TryCaptureKind::Implicit) {
19578 ByRef = (Kind == TryCaptureKind::ExplicitByRef);
19579 } else {
19580 ByRef = (LSI->ImpCaptureStyle == LambdaScopeInfo::ImpCap_LambdaByref);
19581 }
19582
19583 if (BuildAndDiagnose && S.Context.getTargetInfo().getTriple().isWasm() &&
19584 CaptureType.getNonReferenceType().isWebAssemblyReferenceType()) {
19585 S.Diag(Loc, DiagID: diag::err_wasm_ca_reference) << 0;
19586 Invalid = true;
19587 }
19588
19589 // Compute the type of the field that will capture this variable.
19590 if (ByRef) {
19591 // C++11 [expr.prim.lambda]p15:
19592 // An entity is captured by reference if it is implicitly or
19593 // explicitly captured but not captured by copy. It is
19594 // unspecified whether additional unnamed non-static data
19595 // members are declared in the closure type for entities
19596 // captured by reference.
19597 //
19598 // FIXME: It is not clear whether we want to build an lvalue reference
19599 // to the DeclRefType or to CaptureType.getNonReferenceType(). GCC appears
19600 // to do the former, while EDG does the latter. Core issue 1249 will
19601 // clarify, but for now we follow GCC because it's a more permissive and
19602 // easily defensible position.
19603 CaptureType = S.Context.getLValueReferenceType(T: DeclRefType);
19604 } else {
19605 // C++11 [expr.prim.lambda]p14:
19606 // For each entity captured by copy, an unnamed non-static
19607 // data member is declared in the closure type. The
19608 // declaration order of these members is unspecified. The type
19609 // of such a data member is the type of the corresponding
19610 // captured entity if the entity is not a reference to an
19611 // object, or the referenced type otherwise. [Note: If the
19612 // captured entity is a reference to a function, the
19613 // corresponding data member is also a reference to a
19614 // function. - end note ]
19615 if (const ReferenceType *RefType = CaptureType->getAs<ReferenceType>()){
19616 if (!RefType->getPointeeType()->isFunctionType())
19617 CaptureType = RefType->getPointeeType();
19618 }
19619
19620 // Forbid the lambda copy-capture of autoreleasing variables.
19621 if (!Invalid &&
19622 CaptureType.getObjCLifetime() == Qualifiers::OCL_Autoreleasing) {
19623 if (BuildAndDiagnose) {
19624 S.Diag(Loc, DiagID: diag::err_arc_autoreleasing_capture) << /*lambda*/ 1;
19625 S.Diag(Loc: Var->getLocation(), DiagID: diag::note_previous_decl)
19626 << Var->getDeclName();
19627 Invalid = true;
19628 } else {
19629 return false;
19630 }
19631 }
19632
19633 // Make sure that by-copy captures are of a complete and non-abstract type.
19634 if (!Invalid && BuildAndDiagnose) {
19635 if (!CaptureType->isDependentType() &&
19636 S.RequireCompleteSizedType(
19637 Loc, T: CaptureType,
19638 DiagID: diag::err_capture_of_incomplete_or_sizeless_type,
19639 Args: Var->getDeclName()))
19640 Invalid = true;
19641 else if (S.RequireNonAbstractType(Loc, T: CaptureType,
19642 DiagID: diag::err_capture_of_abstract_type))
19643 Invalid = true;
19644 }
19645 }
19646
19647 // Compute the type of a reference to this captured variable.
19648 if (ByRef)
19649 DeclRefType = CaptureType.getNonReferenceType();
19650 else {
19651 // C++ [expr.prim.lambda]p5:
19652 // The closure type for a lambda-expression has a public inline
19653 // function call operator [...]. This function call operator is
19654 // declared const (9.3.1) if and only if the lambda-expression's
19655 // parameter-declaration-clause is not followed by mutable.
19656 DeclRefType = CaptureType.getNonReferenceType();
19657 bool Const = LSI->lambdaCaptureShouldBeConst();
19658 // C++ [expr.prim.lambda]p10:
19659 // The type of such a data member is [...] an lvalue reference to the
19660 // referenced function type if the entity is a reference to a function.
19661 // [...]
19662 if (Const && !CaptureType->isReferenceType() &&
19663 !DeclRefType->isFunctionType())
19664 DeclRefType.addConst();
19665 }
19666
19667 // Add the capture.
19668 if (BuildAndDiagnose)
19669 LSI->addCapture(Var, /*isBlock=*/false, isByref: ByRef, isNested: RefersToCapturedVariable,
19670 Loc, EllipsisLoc, CaptureType, Invalid);
19671
19672 return !Invalid;
19673}
19674
19675static bool canCaptureVariableByCopy(ValueDecl *Var,
19676 const ASTContext &Context) {
19677 // Offer a Copy fix even if the type is dependent.
19678 if (Var->getType()->isDependentType())
19679 return true;
19680 QualType T = Var->getType().getNonReferenceType();
19681 if (T.isTriviallyCopyableType(Context))
19682 return true;
19683 if (CXXRecordDecl *RD = T->getAsCXXRecordDecl()) {
19684
19685 if (!(RD = RD->getDefinition()))
19686 return false;
19687 if (RD->hasSimpleCopyConstructor())
19688 return true;
19689 if (RD->hasUserDeclaredCopyConstructor())
19690 for (CXXConstructorDecl *Ctor : RD->ctors())
19691 if (Ctor->isCopyConstructor())
19692 return !Ctor->isDeleted();
19693 }
19694 return false;
19695}
19696
19697/// Create up to 4 fix-its for explicit reference and value capture of \p Var or
19698/// default capture. Fixes may be omitted if they aren't allowed by the
19699/// standard, for example we can't emit a default copy capture fix-it if we
19700/// already explicitly copy capture capture another variable.
19701static void buildLambdaCaptureFixit(Sema &Sema, LambdaScopeInfo *LSI,
19702 ValueDecl *Var) {
19703 assert(LSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_None);
19704 // Don't offer Capture by copy of default capture by copy fixes if Var is
19705 // known not to be copy constructible.
19706 bool ShouldOfferCopyFix = canCaptureVariableByCopy(Var, Context: Sema.getASTContext());
19707
19708 SmallString<32> FixBuffer;
19709 StringRef Separator = LSI->NumExplicitCaptures > 0 ? ", " : "";
19710 if (Var->getDeclName().isIdentifier() && !Var->getName().empty()) {
19711 SourceLocation VarInsertLoc = LSI->IntroducerRange.getEnd();
19712 if (ShouldOfferCopyFix) {
19713 // Offer fixes to insert an explicit capture for the variable.
19714 // [] -> [VarName]
19715 // [OtherCapture] -> [OtherCapture, VarName]
19716 FixBuffer.assign(Refs: {Separator, Var->getName()});
19717 Sema.Diag(Loc: VarInsertLoc, DiagID: diag::note_lambda_variable_capture_fixit)
19718 << Var << /*value*/ 0
19719 << FixItHint::CreateInsertion(InsertionLoc: VarInsertLoc, Code: FixBuffer);
19720 }
19721 // As above but capture by reference.
19722 FixBuffer.assign(Refs: {Separator, "&", Var->getName()});
19723 Sema.Diag(Loc: VarInsertLoc, DiagID: diag::note_lambda_variable_capture_fixit)
19724 << Var << /*reference*/ 1
19725 << FixItHint::CreateInsertion(InsertionLoc: VarInsertLoc, Code: FixBuffer);
19726 }
19727
19728 // Only try to offer default capture if there are no captures excluding this
19729 // and init captures.
19730 // [this]: OK.
19731 // [X = Y]: OK.
19732 // [&A, &B]: Don't offer.
19733 // [A, B]: Don't offer.
19734 if (llvm::any_of(Range&: LSI->Captures, P: [](Capture &C) {
19735 return !C.isThisCapture() && !C.isInitCapture();
19736 }))
19737 return;
19738
19739 // The default capture specifiers, '=' or '&', must appear first in the
19740 // capture body.
19741 SourceLocation DefaultInsertLoc =
19742 LSI->IntroducerRange.getBegin().getLocWithOffset(Offset: 1);
19743
19744 if (ShouldOfferCopyFix) {
19745 bool CanDefaultCopyCapture = true;
19746 // [=, *this] OK since c++17
19747 // [=, this] OK since c++20
19748 if (LSI->isCXXThisCaptured() && !Sema.getLangOpts().CPlusPlus20)
19749 CanDefaultCopyCapture = Sema.getLangOpts().CPlusPlus17
19750 ? LSI->getCXXThisCapture().isCopyCapture()
19751 : false;
19752 // We can't use default capture by copy if any captures already specified
19753 // capture by copy.
19754 if (CanDefaultCopyCapture && llvm::none_of(Range&: LSI->Captures, P: [](Capture &C) {
19755 return !C.isThisCapture() && !C.isInitCapture() && C.isCopyCapture();
19756 })) {
19757 FixBuffer.assign(Refs: {"=", Separator});
19758 Sema.Diag(Loc: DefaultInsertLoc, DiagID: diag::note_lambda_default_capture_fixit)
19759 << /*value*/ 0
19760 << FixItHint::CreateInsertion(InsertionLoc: DefaultInsertLoc, Code: FixBuffer);
19761 }
19762 }
19763
19764 // We can't use default capture by reference if any captures already specified
19765 // capture by reference.
19766 if (llvm::none_of(Range&: LSI->Captures, P: [](Capture &C) {
19767 return !C.isInitCapture() && C.isReferenceCapture() &&
19768 !C.isThisCapture();
19769 })) {
19770 FixBuffer.assign(Refs: {"&", Separator});
19771 Sema.Diag(Loc: DefaultInsertLoc, DiagID: diag::note_lambda_default_capture_fixit)
19772 << /*reference*/ 1
19773 << FixItHint::CreateInsertion(InsertionLoc: DefaultInsertLoc, Code: FixBuffer);
19774 }
19775}
19776
19777bool Sema::tryCaptureVariable(
19778 ValueDecl *Var, SourceLocation ExprLoc, TryCaptureKind Kind,
19779 SourceLocation EllipsisLoc, bool BuildAndDiagnose, QualType &CaptureType,
19780 QualType &DeclRefType, const unsigned *const FunctionScopeIndexToStopAt) {
19781 // An init-capture is notionally from the context surrounding its
19782 // declaration, but its parent DC is the lambda class.
19783 DeclContext *VarDC = Var->getDeclContext();
19784 DeclContext *DC = CurContext;
19785
19786 // Skip past RequiresExprBodys because they don't constitute function scopes.
19787 while (DC->isRequiresExprBody())
19788 DC = DC->getParent();
19789
19790 // tryCaptureVariable is called every time a DeclRef is formed,
19791 // it can therefore have non-negigible impact on performances.
19792 // For local variables and when there is no capturing scope,
19793 // we can bailout early.
19794 if (CapturingFunctionScopes == 0 && (!BuildAndDiagnose || VarDC == DC))
19795 return true;
19796
19797 // Exception: Function parameters are not tied to the function's DeclContext
19798 // until we enter the function definition. Capturing them anyway would result
19799 // in an out-of-bounds error while traversing DC and its parents.
19800 if (isa<ParmVarDecl>(Val: Var) && !VarDC->isFunctionOrMethod())
19801 return true;
19802
19803 const auto *VD = dyn_cast<VarDecl>(Val: Var);
19804 if (VD) {
19805 if (VD->isInitCapture())
19806 VarDC = VarDC->getParent();
19807 } else {
19808 VD = Var->getPotentiallyDecomposedVarDecl();
19809 }
19810 assert(VD && "Cannot capture a null variable");
19811
19812 const unsigned MaxFunctionScopesIndex = FunctionScopeIndexToStopAt
19813 ? *FunctionScopeIndexToStopAt : FunctionScopes.size() - 1;
19814 // We need to sync up the Declaration Context with the
19815 // FunctionScopeIndexToStopAt
19816 if (FunctionScopeIndexToStopAt) {
19817 assert(!FunctionScopes.empty() && "No function scopes to stop at?");
19818 unsigned FSIndex = FunctionScopes.size() - 1;
19819 // When we're parsing the lambda parameter list, the current DeclContext is
19820 // NOT the lambda but its parent. So move away the current LSI before
19821 // aligning DC and FunctionScopeIndexToStopAt.
19822 if (auto *LSI = dyn_cast<LambdaScopeInfo>(Val: FunctionScopes[FSIndex]);
19823 FSIndex && LSI && !LSI->AfterParameterList)
19824 --FSIndex;
19825 assert(MaxFunctionScopesIndex <= FSIndex &&
19826 "FunctionScopeIndexToStopAt should be no greater than FSIndex into "
19827 "FunctionScopes.");
19828 while (FSIndex != MaxFunctionScopesIndex) {
19829 DC = getLambdaAwareParentOfDeclContext(DC);
19830 --FSIndex;
19831 }
19832 }
19833
19834 // Capture global variables if it is required to use private copy of this
19835 // variable.
19836 bool IsGlobal = !VD->hasLocalStorage();
19837 if (IsGlobal && !(LangOpts.OpenMP &&
19838 OpenMP().isOpenMPCapturedDecl(D: Var, /*CheckScopeInfo=*/true,
19839 StopAt: MaxFunctionScopesIndex)))
19840 return true;
19841
19842 if (isa<VarDecl>(Val: Var))
19843 Var = cast<VarDecl>(Val: Var->getCanonicalDecl());
19844
19845 // Walk up the stack to determine whether we can capture the variable,
19846 // performing the "simple" checks that don't depend on type. We stop when
19847 // we've either hit the declared scope of the variable or find an existing
19848 // capture of that variable. We start from the innermost capturing-entity
19849 // (the DC) and ensure that all intervening capturing-entities
19850 // (blocks/lambdas etc.) between the innermost capturer and the variable`s
19851 // declcontext can either capture the variable or have already captured
19852 // the variable.
19853 CaptureType = Var->getType();
19854 DeclRefType = CaptureType.getNonReferenceType();
19855 bool Nested = false;
19856 bool Explicit = (Kind != TryCaptureKind::Implicit);
19857 unsigned FunctionScopesIndex = MaxFunctionScopesIndex;
19858 do {
19859
19860 LambdaScopeInfo *LSI = nullptr;
19861 if (!FunctionScopes.empty())
19862 LSI = dyn_cast_or_null<LambdaScopeInfo>(
19863 Val: FunctionScopes[FunctionScopesIndex]);
19864
19865 bool IsInScopeDeclarationContext =
19866 !LSI || LSI->AfterParameterList || CurContext == LSI->CallOperator;
19867
19868 if (LSI && !LSI->AfterParameterList) {
19869 // This allows capturing parameters from a default value which does not
19870 // seems correct
19871 if (isa<ParmVarDecl>(Val: Var) && !Var->getDeclContext()->isFunctionOrMethod())
19872 return true;
19873 }
19874 // If the variable is declared in the current context, there is no need to
19875 // capture it.
19876 if (IsInScopeDeclarationContext &&
19877 FunctionScopesIndex == MaxFunctionScopesIndex && VarDC == DC)
19878 return true;
19879
19880 // Only block literals, captured statements, and lambda expressions can
19881 // capture; other scopes don't work.
19882 DeclContext *ParentDC =
19883 !IsInScopeDeclarationContext
19884 ? DC->getParent()
19885 : getParentOfCapturingContextOrNull(DC, Var, Loc: ExprLoc,
19886 Diagnose: BuildAndDiagnose, S&: *this);
19887 // We need to check for the parent *first* because, if we *have*
19888 // private-captured a global variable, we need to recursively capture it in
19889 // intermediate blocks, lambdas, etc.
19890 if (!ParentDC) {
19891 if (IsGlobal) {
19892 FunctionScopesIndex = MaxFunctionScopesIndex - 1;
19893 break;
19894 }
19895 return true;
19896 }
19897
19898 FunctionScopeInfo *FSI = FunctionScopes[FunctionScopesIndex];
19899 CapturingScopeInfo *CSI = cast<CapturingScopeInfo>(Val: FSI);
19900
19901 // Check whether we've already captured it.
19902 if (isVariableAlreadyCapturedInScopeInfo(CSI, Var, SubCapturesAreNested&: Nested, CaptureType,
19903 DeclRefType)) {
19904 CSI->getCapture(Var).markUsed(IsODRUse: BuildAndDiagnose);
19905 break;
19906 }
19907
19908 // When evaluating some attributes (like enable_if) we might refer to a
19909 // function parameter appertaining to the same declaration as that
19910 // attribute.
19911 if (const auto *Parm = dyn_cast<ParmVarDecl>(Val: Var);
19912 Parm && Parm->getDeclContext() == DC)
19913 return true;
19914
19915 // If we are instantiating a generic lambda call operator body,
19916 // we do not want to capture new variables. What was captured
19917 // during either a lambdas transformation or initial parsing
19918 // should be used.
19919 if (isGenericLambdaCallOperatorSpecialization(DC)) {
19920 if (BuildAndDiagnose) {
19921 LambdaScopeInfo *LSI = cast<LambdaScopeInfo>(Val: CSI);
19922 if (LSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_None) {
19923 Diag(Loc: ExprLoc, DiagID: diag::err_lambda_impcap) << Var;
19924 Diag(Loc: Var->getLocation(), DiagID: diag::note_previous_decl) << Var;
19925 Diag(Loc: LSI->Lambda->getBeginLoc(), DiagID: diag::note_lambda_decl);
19926 buildLambdaCaptureFixit(Sema&: *this, LSI, Var);
19927 } else
19928 diagnoseUncapturableValueReferenceOrBinding(S&: *this, loc: ExprLoc, var: Var);
19929 }
19930 return true;
19931 }
19932
19933 // Try to capture variable-length arrays types.
19934 if (Var->getType()->isVariablyModifiedType()) {
19935 // We're going to walk down into the type and look for VLA
19936 // expressions.
19937 QualType QTy = Var->getType();
19938 if (ParmVarDecl *PVD = dyn_cast_or_null<ParmVarDecl>(Val: Var))
19939 QTy = PVD->getOriginalType();
19940 captureVariablyModifiedType(Context, T: QTy, CSI);
19941 }
19942
19943 if (getLangOpts().OpenMP) {
19944 if (auto *RSI = dyn_cast<CapturedRegionScopeInfo>(Val: CSI)) {
19945 // OpenMP private variables should not be captured in outer scope, so
19946 // just break here. Similarly, global variables that are captured in a
19947 // target region should not be captured outside the scope of the region.
19948 if (RSI->CapRegionKind == CR_OpenMP) {
19949 // FIXME: We should support capturing structured bindings in OpenMP.
19950 if (isa<BindingDecl>(Val: Var)) {
19951 if (BuildAndDiagnose) {
19952 Diag(Loc: ExprLoc, DiagID: diag::err_capture_binding_openmp) << Var;
19953 Diag(Loc: Var->getLocation(), DiagID: diag::note_entity_declared_at) << Var;
19954 }
19955 return true;
19956 }
19957 OpenMPClauseKind IsOpenMPPrivateDecl = OpenMP().isOpenMPPrivateDecl(
19958 D: Var, Level: RSI->OpenMPLevel, CapLevel: RSI->OpenMPCaptureLevel);
19959 // If the variable is private (i.e. not captured) and has variably
19960 // modified type, we still need to capture the type for correct
19961 // codegen in all regions, associated with the construct. Currently,
19962 // it is captured in the innermost captured region only.
19963 if (IsOpenMPPrivateDecl != OMPC_unknown &&
19964 Var->getType()->isVariablyModifiedType()) {
19965 QualType QTy = Var->getType();
19966 if (ParmVarDecl *PVD = dyn_cast_or_null<ParmVarDecl>(Val: Var))
19967 QTy = PVD->getOriginalType();
19968 for (int I = 1,
19969 E = OpenMP().getNumberOfConstructScopes(Level: RSI->OpenMPLevel);
19970 I < E; ++I) {
19971 auto *OuterRSI = cast<CapturedRegionScopeInfo>(
19972 Val: FunctionScopes[FunctionScopesIndex - I]);
19973 assert(RSI->OpenMPLevel == OuterRSI->OpenMPLevel &&
19974 "Wrong number of captured regions associated with the "
19975 "OpenMP construct.");
19976 captureVariablyModifiedType(Context, T: QTy, CSI: OuterRSI);
19977 }
19978 }
19979 bool IsTargetCap =
19980 IsOpenMPPrivateDecl != OMPC_private &&
19981 OpenMP().isOpenMPTargetCapturedDecl(D: Var, Level: RSI->OpenMPLevel,
19982 CaptureLevel: RSI->OpenMPCaptureLevel);
19983 // Do not capture global if it is not privatized in outer regions.
19984 bool IsGlobalCap =
19985 IsGlobal && OpenMP().isOpenMPGlobalCapturedDecl(
19986 D: Var, Level: RSI->OpenMPLevel, CaptureLevel: RSI->OpenMPCaptureLevel);
19987
19988 // When we detect target captures we are looking from inside the
19989 // target region, therefore we need to propagate the capture from the
19990 // enclosing region. Therefore, the capture is not initially nested.
19991 if (IsTargetCap)
19992 OpenMP().adjustOpenMPTargetScopeIndex(FunctionScopesIndex,
19993 Level: RSI->OpenMPLevel);
19994
19995 if (IsTargetCap || IsOpenMPPrivateDecl == OMPC_private ||
19996 (IsGlobal && !IsGlobalCap)) {
19997 Nested = !IsTargetCap;
19998 bool HasConst = DeclRefType.isConstQualified();
19999 DeclRefType = DeclRefType.getUnqualifiedType();
20000 // Don't lose diagnostics about assignments to const.
20001 if (HasConst)
20002 DeclRefType.addConst();
20003 CaptureType = Context.getLValueReferenceType(T: DeclRefType);
20004 break;
20005 }
20006 }
20007 }
20008 }
20009 if (CSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_None && !Explicit) {
20010 // No capture-default, and this is not an explicit capture
20011 // so cannot capture this variable.
20012 if (BuildAndDiagnose) {
20013 Diag(Loc: ExprLoc, DiagID: diag::err_lambda_impcap) << Var;
20014 Diag(Loc: Var->getLocation(), DiagID: diag::note_previous_decl) << Var;
20015 auto *LSI = cast<LambdaScopeInfo>(Val: CSI);
20016 if (LSI->Lambda) {
20017 Diag(Loc: LSI->Lambda->getBeginLoc(), DiagID: diag::note_lambda_decl);
20018 buildLambdaCaptureFixit(Sema&: *this, LSI, Var);
20019 }
20020 // FIXME: If we error out because an outer lambda can not implicitly
20021 // capture a variable that an inner lambda explicitly captures, we
20022 // should have the inner lambda do the explicit capture - because
20023 // it makes for cleaner diagnostics later. This would purely be done
20024 // so that the diagnostic does not misleadingly claim that a variable
20025 // can not be captured by a lambda implicitly even though it is captured
20026 // explicitly. Suggestion:
20027 // - create const bool VariableCaptureWasInitiallyExplicit = Explicit
20028 // at the function head
20029 // - cache the StartingDeclContext - this must be a lambda
20030 // - captureInLambda in the innermost lambda the variable.
20031 }
20032 return true;
20033 }
20034 Explicit = false;
20035 FunctionScopesIndex--;
20036 if (IsInScopeDeclarationContext)
20037 DC = ParentDC;
20038 } while (!VarDC->Equals(DC));
20039
20040 // Walk back down the scope stack, (e.g. from outer lambda to inner lambda)
20041 // computing the type of the capture at each step, checking type-specific
20042 // requirements, and adding captures if requested.
20043 // If the variable had already been captured previously, we start capturing
20044 // at the lambda nested within that one.
20045 bool Invalid = false;
20046 for (unsigned I = ++FunctionScopesIndex, N = MaxFunctionScopesIndex + 1; I != N;
20047 ++I) {
20048 CapturingScopeInfo *CSI = cast<CapturingScopeInfo>(Val: FunctionScopes[I]);
20049
20050 // Certain capturing entities (lambdas, blocks etc.) are not allowed to capture
20051 // certain types of variables (unnamed, variably modified types etc.)
20052 // so check for eligibility.
20053 if (!Invalid)
20054 Invalid =
20055 !isVariableCapturable(CSI, Var, Loc: ExprLoc, Diagnose: BuildAndDiagnose, S&: *this);
20056
20057 // After encountering an error, if we're actually supposed to capture, keep
20058 // capturing in nested contexts to suppress any follow-on diagnostics.
20059 if (Invalid && !BuildAndDiagnose)
20060 return true;
20061
20062 if (BlockScopeInfo *BSI = dyn_cast<BlockScopeInfo>(Val: CSI)) {
20063 Invalid = !captureInBlock(BSI, Var, Loc: ExprLoc, BuildAndDiagnose, CaptureType,
20064 DeclRefType, Nested, S&: *this, Invalid);
20065 Nested = true;
20066 } else if (CapturedRegionScopeInfo *RSI = dyn_cast<CapturedRegionScopeInfo>(Val: CSI)) {
20067 Invalid = !captureInCapturedRegion(
20068 RSI, Var, Loc: ExprLoc, BuildAndDiagnose, CaptureType, DeclRefType, RefersToCapturedVariable: Nested,
20069 Kind, /*IsTopScope*/ I == N - 1, S&: *this, Invalid);
20070 Nested = true;
20071 } else {
20072 LambdaScopeInfo *LSI = cast<LambdaScopeInfo>(Val: CSI);
20073 Invalid =
20074 !captureInLambda(LSI, Var, Loc: ExprLoc, BuildAndDiagnose, CaptureType,
20075 DeclRefType, RefersToCapturedVariable: Nested, Kind, EllipsisLoc,
20076 /*IsTopScope*/ I == N - 1, S&: *this, Invalid);
20077 Nested = true;
20078 }
20079
20080 if (Invalid && !BuildAndDiagnose)
20081 return true;
20082 }
20083 return Invalid;
20084}
20085
20086bool Sema::tryCaptureVariable(ValueDecl *Var, SourceLocation Loc,
20087 TryCaptureKind Kind, SourceLocation EllipsisLoc) {
20088 QualType CaptureType;
20089 QualType DeclRefType;
20090 return tryCaptureVariable(Var, ExprLoc: Loc, Kind, EllipsisLoc,
20091 /*BuildAndDiagnose=*/true, CaptureType,
20092 DeclRefType, FunctionScopeIndexToStopAt: nullptr);
20093}
20094
20095bool Sema::NeedToCaptureVariable(ValueDecl *Var, SourceLocation Loc) {
20096 QualType CaptureType;
20097 QualType DeclRefType;
20098 return !tryCaptureVariable(
20099 Var, ExprLoc: Loc, Kind: TryCaptureKind::Implicit, EllipsisLoc: SourceLocation(),
20100 /*BuildAndDiagnose=*/false, CaptureType, DeclRefType, FunctionScopeIndexToStopAt: nullptr);
20101}
20102
20103QualType Sema::getCapturedDeclRefType(ValueDecl *Var, SourceLocation Loc) {
20104 assert(Var && "Null value cannot be captured");
20105
20106 QualType CaptureType;
20107 QualType DeclRefType;
20108
20109 // Determine whether we can capture this variable.
20110 if (tryCaptureVariable(Var, ExprLoc: Loc, Kind: TryCaptureKind::Implicit, EllipsisLoc: SourceLocation(),
20111 /*BuildAndDiagnose=*/false, CaptureType, DeclRefType,
20112 FunctionScopeIndexToStopAt: nullptr))
20113 return QualType();
20114
20115 return DeclRefType;
20116}
20117
20118namespace {
20119// Helper to copy the template arguments from a DeclRefExpr or MemberExpr.
20120// The produced TemplateArgumentListInfo* points to data stored within this
20121// object, so should only be used in contexts where the pointer will not be
20122// used after the CopiedTemplateArgs object is destroyed.
20123class CopiedTemplateArgs {
20124 bool HasArgs;
20125 TemplateArgumentListInfo TemplateArgStorage;
20126public:
20127 template<typename RefExpr>
20128 CopiedTemplateArgs(RefExpr *E) : HasArgs(E->hasExplicitTemplateArgs()) {
20129 if (HasArgs)
20130 E->copyTemplateArgumentsInto(TemplateArgStorage);
20131 }
20132 operator TemplateArgumentListInfo*()
20133#ifdef __has_cpp_attribute
20134#if __has_cpp_attribute(clang::lifetimebound)
20135 [[clang::lifetimebound]]
20136#endif
20137#endif
20138 {
20139 return HasArgs ? &TemplateArgStorage : nullptr;
20140 }
20141};
20142}
20143
20144/// Walk the set of potential results of an expression and mark them all as
20145/// non-odr-uses if they satisfy the side-conditions of the NonOdrUseReason.
20146///
20147/// \return A new expression if we found any potential results, ExprEmpty() if
20148/// not, and ExprError() if we diagnosed an error.
20149static ExprResult rebuildPotentialResultsAsNonOdrUsed(Sema &S, Expr *E,
20150 NonOdrUseReason NOUR) {
20151 // Per C++11 [basic.def.odr], a variable is odr-used "unless it is
20152 // an object that satisfies the requirements for appearing in a
20153 // constant expression (5.19) and the lvalue-to-rvalue conversion (4.1)
20154 // is immediately applied." This function handles the lvalue-to-rvalue
20155 // conversion part.
20156 //
20157 // If we encounter a node that claims to be an odr-use but shouldn't be, we
20158 // transform it into the relevant kind of non-odr-use node and rebuild the
20159 // tree of nodes leading to it.
20160 //
20161 // This is a mini-TreeTransform that only transforms a restricted subset of
20162 // nodes (and only certain operands of them).
20163
20164 // Rebuild a subexpression.
20165 auto Rebuild = [&](Expr *Sub) {
20166 return rebuildPotentialResultsAsNonOdrUsed(S, E: Sub, NOUR);
20167 };
20168
20169 // Check whether a potential result satisfies the requirements of NOUR.
20170 auto IsPotentialResultOdrUsed = [&](NamedDecl *D) {
20171 // Any entity other than a VarDecl is always odr-used whenever it's named
20172 // in a potentially-evaluated expression.
20173 auto *VD = dyn_cast<VarDecl>(Val: D);
20174 if (!VD)
20175 return true;
20176
20177 // C++2a [basic.def.odr]p4:
20178 // A variable x whose name appears as a potentially-evalauted expression
20179 // e is odr-used by e unless
20180 // -- x is a reference that is usable in constant expressions, or
20181 // -- x is a variable of non-reference type that is usable in constant
20182 // expressions and has no mutable subobjects, and e is an element of
20183 // the set of potential results of an expression of
20184 // non-volatile-qualified non-class type to which the lvalue-to-rvalue
20185 // conversion is applied, or
20186 // -- x is a variable of non-reference type, and e is an element of the
20187 // set of potential results of a discarded-value expression to which
20188 // the lvalue-to-rvalue conversion is not applied
20189 //
20190 // We check the first bullet and the "potentially-evaluated" condition in
20191 // BuildDeclRefExpr. We check the type requirements in the second bullet
20192 // in CheckLValueToRValueConversionOperand below.
20193 switch (NOUR) {
20194 case NOUR_None:
20195 case NOUR_Unevaluated:
20196 llvm_unreachable("unexpected non-odr-use-reason");
20197
20198 case NOUR_Constant:
20199 // Constant references were handled when they were built.
20200 if (VD->getType()->isReferenceType())
20201 return true;
20202 if (auto *RD = VD->getType()->getAsCXXRecordDecl())
20203 if (RD->hasDefinition() && RD->hasMutableFields())
20204 return true;
20205 if (!VD->isUsableInConstantExpressions(C: S.Context))
20206 return true;
20207 break;
20208
20209 case NOUR_Discarded:
20210 if (VD->getType()->isReferenceType())
20211 return true;
20212 break;
20213 }
20214 return false;
20215 };
20216
20217 // Check whether this expression may be odr-used in CUDA/HIP.
20218 auto MaybeCUDAODRUsed = [&]() -> bool {
20219 if (!S.LangOpts.CUDA)
20220 return false;
20221 LambdaScopeInfo *LSI = S.getCurLambda();
20222 if (!LSI)
20223 return false;
20224 auto *DRE = dyn_cast<DeclRefExpr>(Val: E);
20225 if (!DRE)
20226 return false;
20227 auto *VD = dyn_cast<VarDecl>(Val: DRE->getDecl());
20228 if (!VD)
20229 return false;
20230 return LSI->CUDAPotentialODRUsedVars.count(Ptr: VD);
20231 };
20232
20233 // Mark that this expression does not constitute an odr-use.
20234 auto MarkNotOdrUsed = [&] {
20235 if (!MaybeCUDAODRUsed()) {
20236 S.MaybeODRUseExprs.remove(X: E);
20237 if (LambdaScopeInfo *LSI = S.getCurLambda())
20238 LSI->markVariableExprAsNonODRUsed(CapturingVarExpr: E);
20239 }
20240 };
20241
20242 // C++2a [basic.def.odr]p2:
20243 // The set of potential results of an expression e is defined as follows:
20244 switch (E->getStmtClass()) {
20245 // -- If e is an id-expression, ...
20246 case Expr::DeclRefExprClass: {
20247 auto *DRE = cast<DeclRefExpr>(Val: E);
20248 if (DRE->isNonOdrUse() || IsPotentialResultOdrUsed(DRE->getDecl()))
20249 break;
20250
20251 // Rebuild as a non-odr-use DeclRefExpr.
20252 MarkNotOdrUsed();
20253 return DeclRefExpr::Create(
20254 Context: S.Context, QualifierLoc: DRE->getQualifierLoc(), TemplateKWLoc: DRE->getTemplateKeywordLoc(),
20255 D: DRE->getDecl(), RefersToEnclosingVariableOrCapture: DRE->refersToEnclosingVariableOrCapture(),
20256 NameInfo: DRE->getNameInfo(), T: DRE->getType(), VK: DRE->getValueKind(),
20257 FoundD: DRE->getFoundDecl(), TemplateArgs: CopiedTemplateArgs(DRE), NOUR);
20258 }
20259
20260 case Expr::FunctionParmPackExprClass: {
20261 auto *FPPE = cast<FunctionParmPackExpr>(Val: E);
20262 // If any of the declarations in the pack is odr-used, then the expression
20263 // as a whole constitutes an odr-use.
20264 for (ValueDecl *D : *FPPE)
20265 if (IsPotentialResultOdrUsed(D))
20266 return ExprEmpty();
20267
20268 // FIXME: Rebuild as a non-odr-use FunctionParmPackExpr? In practice,
20269 // nothing cares about whether we marked this as an odr-use, but it might
20270 // be useful for non-compiler tools.
20271 MarkNotOdrUsed();
20272 break;
20273 }
20274
20275 // -- If e is a subscripting operation with an array operand...
20276 case Expr::ArraySubscriptExprClass: {
20277 auto *ASE = cast<ArraySubscriptExpr>(Val: E);
20278 Expr *OldBase = ASE->getBase()->IgnoreImplicit();
20279 if (!OldBase->getType()->isArrayType())
20280 break;
20281 ExprResult Base = Rebuild(OldBase);
20282 if (!Base.isUsable())
20283 return Base;
20284 Expr *LHS = ASE->getBase() == ASE->getLHS() ? Base.get() : ASE->getLHS();
20285 Expr *RHS = ASE->getBase() == ASE->getRHS() ? Base.get() : ASE->getRHS();
20286 SourceLocation LBracketLoc = ASE->getBeginLoc(); // FIXME: Not stored.
20287 return S.ActOnArraySubscriptExpr(S: nullptr, base: LHS, lbLoc: LBracketLoc, ArgExprs: RHS,
20288 rbLoc: ASE->getRBracketLoc());
20289 }
20290
20291 case Expr::MemberExprClass: {
20292 auto *ME = cast<MemberExpr>(Val: E);
20293 // -- If e is a class member access expression [...] naming a non-static
20294 // data member...
20295 if (isa<FieldDecl>(Val: ME->getMemberDecl())) {
20296 ExprResult Base = Rebuild(ME->getBase());
20297 if (!Base.isUsable())
20298 return Base;
20299 return MemberExpr::Create(
20300 C: S.Context, Base: Base.get(), IsArrow: ME->isArrow(), OperatorLoc: ME->getOperatorLoc(),
20301 QualifierLoc: ME->getQualifierLoc(), TemplateKWLoc: ME->getTemplateKeywordLoc(),
20302 MemberDecl: ME->getMemberDecl(), FoundDecl: ME->getFoundDecl(), MemberNameInfo: ME->getMemberNameInfo(),
20303 TemplateArgs: CopiedTemplateArgs(ME), T: ME->getType(), VK: ME->getValueKind(),
20304 OK: ME->getObjectKind(), NOUR: ME->isNonOdrUse());
20305 }
20306
20307 if (ME->getMemberDecl()->isCXXInstanceMember())
20308 break;
20309
20310 // -- If e is a class member access expression naming a static data member,
20311 // ...
20312 if (ME->isNonOdrUse() || IsPotentialResultOdrUsed(ME->getMemberDecl()))
20313 break;
20314
20315 // Rebuild as a non-odr-use MemberExpr.
20316 MarkNotOdrUsed();
20317 return MemberExpr::Create(
20318 C: S.Context, Base: ME->getBase(), IsArrow: ME->isArrow(), OperatorLoc: ME->getOperatorLoc(),
20319 QualifierLoc: ME->getQualifierLoc(), TemplateKWLoc: ME->getTemplateKeywordLoc(), MemberDecl: ME->getMemberDecl(),
20320 FoundDecl: ME->getFoundDecl(), MemberNameInfo: ME->getMemberNameInfo(), TemplateArgs: CopiedTemplateArgs(ME),
20321 T: ME->getType(), VK: ME->getValueKind(), OK: ME->getObjectKind(), NOUR);
20322 }
20323
20324 case Expr::BinaryOperatorClass: {
20325 auto *BO = cast<BinaryOperator>(Val: E);
20326 Expr *LHS = BO->getLHS();
20327 Expr *RHS = BO->getRHS();
20328 // -- If e is a pointer-to-member expression of the form e1 .* e2 ...
20329 if (BO->getOpcode() == BO_PtrMemD) {
20330 ExprResult Sub = Rebuild(LHS);
20331 if (!Sub.isUsable())
20332 return Sub;
20333 BO->setLHS(Sub.get());
20334 // -- If e is a comma expression, ...
20335 } else if (BO->getOpcode() == BO_Comma) {
20336 ExprResult Sub = Rebuild(RHS);
20337 if (!Sub.isUsable())
20338 return Sub;
20339 BO->setRHS(Sub.get());
20340 } else {
20341 break;
20342 }
20343 return ExprResult(BO);
20344 }
20345
20346 // -- If e has the form (e1)...
20347 case Expr::ParenExprClass: {
20348 auto *PE = cast<ParenExpr>(Val: E);
20349 ExprResult Sub = Rebuild(PE->getSubExpr());
20350 if (!Sub.isUsable())
20351 return Sub;
20352 return S.ActOnParenExpr(L: PE->getLParen(), R: PE->getRParen(), E: Sub.get());
20353 }
20354
20355 // -- If e is a glvalue conditional expression, ...
20356 // We don't apply this to a binary conditional operator. FIXME: Should we?
20357 case Expr::ConditionalOperatorClass: {
20358 auto *CO = cast<ConditionalOperator>(Val: E);
20359 ExprResult LHS = Rebuild(CO->getLHS());
20360 if (LHS.isInvalid())
20361 return ExprError();
20362 ExprResult RHS = Rebuild(CO->getRHS());
20363 if (RHS.isInvalid())
20364 return ExprError();
20365 if (!LHS.isUsable() && !RHS.isUsable())
20366 return ExprEmpty();
20367 if (!LHS.isUsable())
20368 LHS = CO->getLHS();
20369 if (!RHS.isUsable())
20370 RHS = CO->getRHS();
20371 return S.ActOnConditionalOp(QuestionLoc: CO->getQuestionLoc(), ColonLoc: CO->getColonLoc(),
20372 CondExpr: CO->getCond(), LHSExpr: LHS.get(), RHSExpr: RHS.get());
20373 }
20374
20375 // [Clang extension]
20376 // -- If e has the form __extension__ e1...
20377 case Expr::UnaryOperatorClass: {
20378 auto *UO = cast<UnaryOperator>(Val: E);
20379 if (UO->getOpcode() != UO_Extension)
20380 break;
20381 ExprResult Sub = Rebuild(UO->getSubExpr());
20382 if (!Sub.isUsable())
20383 return Sub;
20384 return S.BuildUnaryOp(S: nullptr, OpLoc: UO->getOperatorLoc(), Opc: UO_Extension,
20385 Input: Sub.get());
20386 }
20387
20388 // [Clang extension]
20389 // -- If e has the form _Generic(...), the set of potential results is the
20390 // union of the sets of potential results of the associated expressions.
20391 case Expr::GenericSelectionExprClass: {
20392 auto *GSE = cast<GenericSelectionExpr>(Val: E);
20393
20394 SmallVector<Expr *, 4> AssocExprs;
20395 bool AnyChanged = false;
20396 for (Expr *OrigAssocExpr : GSE->getAssocExprs()) {
20397 ExprResult AssocExpr = Rebuild(OrigAssocExpr);
20398 if (AssocExpr.isInvalid())
20399 return ExprError();
20400 if (AssocExpr.isUsable()) {
20401 AssocExprs.push_back(Elt: AssocExpr.get());
20402 AnyChanged = true;
20403 } else {
20404 AssocExprs.push_back(Elt: OrigAssocExpr);
20405 }
20406 }
20407
20408 void *ExOrTy = nullptr;
20409 bool IsExpr = GSE->isExprPredicate();
20410 if (IsExpr)
20411 ExOrTy = GSE->getControllingExpr();
20412 else
20413 ExOrTy = GSE->getControllingType();
20414 return AnyChanged ? S.CreateGenericSelectionExpr(
20415 KeyLoc: GSE->getGenericLoc(), DefaultLoc: GSE->getDefaultLoc(),
20416 RParenLoc: GSE->getRParenLoc(), PredicateIsExpr: IsExpr, ControllingExprOrType: ExOrTy,
20417 Types: GSE->getAssocTypeSourceInfos(), Exprs: AssocExprs)
20418 : ExprEmpty();
20419 }
20420
20421 // [Clang extension]
20422 // -- If e has the form __builtin_choose_expr(...), the set of potential
20423 // results is the union of the sets of potential results of the
20424 // second and third subexpressions.
20425 case Expr::ChooseExprClass: {
20426 auto *CE = cast<ChooseExpr>(Val: E);
20427
20428 ExprResult LHS = Rebuild(CE->getLHS());
20429 if (LHS.isInvalid())
20430 return ExprError();
20431
20432 ExprResult RHS = Rebuild(CE->getLHS());
20433 if (RHS.isInvalid())
20434 return ExprError();
20435
20436 if (!LHS.get() && !RHS.get())
20437 return ExprEmpty();
20438 if (!LHS.isUsable())
20439 LHS = CE->getLHS();
20440 if (!RHS.isUsable())
20441 RHS = CE->getRHS();
20442
20443 return S.ActOnChooseExpr(BuiltinLoc: CE->getBuiltinLoc(), CondExpr: CE->getCond(), LHSExpr: LHS.get(),
20444 RHSExpr: RHS.get(), RPLoc: CE->getRParenLoc());
20445 }
20446
20447 // Step through non-syntactic nodes.
20448 case Expr::ConstantExprClass: {
20449 auto *CE = cast<ConstantExpr>(Val: E);
20450 ExprResult Sub = Rebuild(CE->getSubExpr());
20451 if (!Sub.isUsable())
20452 return Sub;
20453 return ConstantExpr::Create(Context: S.Context, E: Sub.get());
20454 }
20455
20456 // We could mostly rely on the recursive rebuilding to rebuild implicit
20457 // casts, but not at the top level, so rebuild them here.
20458 case Expr::ImplicitCastExprClass: {
20459 auto *ICE = cast<ImplicitCastExpr>(Val: E);
20460 // Only step through the narrow set of cast kinds we expect to encounter.
20461 // Anything else suggests we've left the region in which potential results
20462 // can be found.
20463 switch (ICE->getCastKind()) {
20464 case CK_NoOp:
20465 case CK_DerivedToBase:
20466 case CK_UncheckedDerivedToBase: {
20467 ExprResult Sub = Rebuild(ICE->getSubExpr());
20468 if (!Sub.isUsable())
20469 return Sub;
20470 CXXCastPath Path(ICE->path());
20471 return S.ImpCastExprToType(E: Sub.get(), Type: ICE->getType(), CK: ICE->getCastKind(),
20472 VK: ICE->getValueKind(), BasePath: &Path);
20473 }
20474
20475 default:
20476 break;
20477 }
20478 break;
20479 }
20480
20481 default:
20482 break;
20483 }
20484
20485 // Can't traverse through this node. Nothing to do.
20486 return ExprEmpty();
20487}
20488
20489ExprResult Sema::CheckLValueToRValueConversionOperand(Expr *E) {
20490 // Check whether the operand is or contains an object of non-trivial C union
20491 // type.
20492 if (E->getType().isVolatileQualified() &&
20493 (E->getType().hasNonTrivialToPrimitiveDestructCUnion() ||
20494 E->getType().hasNonTrivialToPrimitiveCopyCUnion()))
20495 checkNonTrivialCUnion(QT: E->getType(), Loc: E->getExprLoc(),
20496 UseContext: NonTrivialCUnionContext::LValueToRValueVolatile,
20497 NonTrivialKind: NTCUK_Destruct | NTCUK_Copy);
20498
20499 // C++2a [basic.def.odr]p4:
20500 // [...] an expression of non-volatile-qualified non-class type to which
20501 // the lvalue-to-rvalue conversion is applied [...]
20502 if (E->getType().isVolatileQualified() || E->getType()->isRecordType())
20503 return E;
20504
20505 ExprResult Result =
20506 rebuildPotentialResultsAsNonOdrUsed(S&: *this, E, NOUR: NOUR_Constant);
20507 if (Result.isInvalid())
20508 return ExprError();
20509 return Result.get() ? Result : E;
20510}
20511
20512ExprResult Sema::ActOnConstantExpression(ExprResult Res) {
20513 if (!Res.isUsable())
20514 return Res;
20515
20516 // If a constant-expression is a reference to a variable where we delay
20517 // deciding whether it is an odr-use, just assume we will apply the
20518 // lvalue-to-rvalue conversion. In the one case where this doesn't happen
20519 // (a non-type template argument), we have special handling anyway.
20520 return CheckLValueToRValueConversionOperand(E: Res.get());
20521}
20522
20523void Sema::CleanupVarDeclMarking() {
20524 // Iterate through a local copy in case MarkVarDeclODRUsed makes a recursive
20525 // call.
20526 MaybeODRUseExprSet LocalMaybeODRUseExprs;
20527 std::swap(LHS&: LocalMaybeODRUseExprs, RHS&: MaybeODRUseExprs);
20528
20529 for (Expr *E : LocalMaybeODRUseExprs) {
20530 if (auto *DRE = dyn_cast<DeclRefExpr>(Val: E)) {
20531 MarkVarDeclODRUsed(V: cast<VarDecl>(Val: DRE->getDecl()),
20532 Loc: DRE->getLocation(), SemaRef&: *this);
20533 } else if (auto *ME = dyn_cast<MemberExpr>(Val: E)) {
20534 MarkVarDeclODRUsed(V: cast<VarDecl>(Val: ME->getMemberDecl()), Loc: ME->getMemberLoc(),
20535 SemaRef&: *this);
20536 } else if (auto *FP = dyn_cast<FunctionParmPackExpr>(Val: E)) {
20537 for (ValueDecl *VD : *FP)
20538 MarkVarDeclODRUsed(V: VD, Loc: FP->getParameterPackLocation(), SemaRef&: *this);
20539 } else {
20540 llvm_unreachable("Unexpected expression");
20541 }
20542 }
20543
20544 assert(MaybeODRUseExprs.empty() &&
20545 "MarkVarDeclODRUsed failed to cleanup MaybeODRUseExprs?");
20546}
20547
20548static void DoMarkPotentialCapture(Sema &SemaRef, SourceLocation Loc,
20549 ValueDecl *Var, Expr *E) {
20550 VarDecl *VD = Var->getPotentiallyDecomposedVarDecl();
20551 if (!VD)
20552 return;
20553
20554 const bool RefersToEnclosingScope =
20555 (SemaRef.CurContext != VD->getDeclContext() &&
20556 VD->getDeclContext()->isFunctionOrMethod() && VD->hasLocalStorage());
20557 if (RefersToEnclosingScope) {
20558 LambdaScopeInfo *const LSI =
20559 SemaRef.getCurLambda(/*IgnoreNonLambdaCapturingScope=*/true);
20560 if (LSI && (!LSI->CallOperator ||
20561 !LSI->CallOperator->Encloses(DC: Var->getDeclContext()))) {
20562 // If a variable could potentially be odr-used, defer marking it so
20563 // until we finish analyzing the full expression for any
20564 // lvalue-to-rvalue
20565 // or discarded value conversions that would obviate odr-use.
20566 // Add it to the list of potential captures that will be analyzed
20567 // later (ActOnFinishFullExpr) for eventual capture and odr-use marking
20568 // unless the variable is a reference that was initialized by a constant
20569 // expression (this will never need to be captured or odr-used).
20570 //
20571 // FIXME: We can simplify this a lot after implementing P0588R1.
20572 assert(E && "Capture variable should be used in an expression.");
20573 if (!Var->getType()->isReferenceType() ||
20574 !VD->isUsableInConstantExpressions(C: SemaRef.Context))
20575 LSI->addPotentialCapture(VarExpr: E->IgnoreParens());
20576 }
20577 }
20578}
20579
20580static void DoMarkVarDeclReferenced(
20581 Sema &SemaRef, SourceLocation Loc, VarDecl *Var, Expr *E,
20582 llvm::DenseMap<const VarDecl *, int> &RefsMinusAssignments) {
20583 assert((!E || isa<DeclRefExpr>(E) || isa<MemberExpr>(E) ||
20584 isa<FunctionParmPackExpr>(E)) &&
20585 "Invalid Expr argument to DoMarkVarDeclReferenced");
20586 Var->setReferenced();
20587
20588 if (Var->isInvalidDecl())
20589 return;
20590
20591 auto *MSI = Var->getMemberSpecializationInfo();
20592 TemplateSpecializationKind TSK = MSI ? MSI->getTemplateSpecializationKind()
20593 : Var->getTemplateSpecializationKind();
20594
20595 OdrUseContext OdrUse = isOdrUseContext(SemaRef);
20596 bool UsableInConstantExpr =
20597 Var->mightBeUsableInConstantExpressions(C: SemaRef.Context);
20598
20599 // Only track variables with internal linkage or local scope.
20600 // Use canonical decl so in-class declarations and out-of-class definitions
20601 // of static data members in anonymous namespaces are tracked as a single
20602 // entry.
20603 const VarDecl *CanonVar = Var->getCanonicalDecl();
20604 if ((CanonVar->isLocalVarDeclOrParm() ||
20605 CanonVar->isInternalLinkageFileVar()) &&
20606 !CanonVar->hasExternalStorage()) {
20607 RefsMinusAssignments.insert(KV: {CanonVar, 0}).first->getSecond()++;
20608 }
20609
20610 // C++20 [expr.const]p12:
20611 // A variable [...] is needed for constant evaluation if it is [...] a
20612 // variable whose name appears as a potentially constant evaluated
20613 // expression that is either a contexpr variable or is of non-volatile
20614 // const-qualified integral type or of reference type
20615 bool NeededForConstantEvaluation =
20616 isPotentiallyConstantEvaluatedContext(SemaRef) && UsableInConstantExpr;
20617
20618 bool NeedDefinition =
20619 OdrUse == OdrUseContext::Used || NeededForConstantEvaluation ||
20620 (TSK != clang::TSK_Undeclared && !UsableInConstantExpr &&
20621 Var->getType()->isUndeducedType());
20622
20623 assert(!isa<VarTemplatePartialSpecializationDecl>(Var) &&
20624 "Can't instantiate a partial template specialization.");
20625
20626 // If this might be a member specialization of a static data member, check
20627 // the specialization is visible. We already did the checks for variable
20628 // template specializations when we created them.
20629 if (NeedDefinition && TSK != TSK_Undeclared &&
20630 !isa<VarTemplateSpecializationDecl>(Val: Var))
20631 SemaRef.checkSpecializationVisibility(Loc, Spec: Var);
20632
20633 // Perform implicit instantiation of static data members, static data member
20634 // templates of class templates, and variable template specializations. Delay
20635 // instantiations of variable templates, except for those that could be used
20636 // in a constant expression.
20637 if (NeedDefinition && isTemplateInstantiation(Kind: TSK)) {
20638 // Per C++17 [temp.explicit]p10, we may instantiate despite an explicit
20639 // instantiation declaration if a variable is usable in a constant
20640 // expression (among other cases).
20641 bool TryInstantiating =
20642 TSK == TSK_ImplicitInstantiation ||
20643 (TSK == TSK_ExplicitInstantiationDeclaration && UsableInConstantExpr);
20644
20645 if (TryInstantiating) {
20646 SourceLocation PointOfInstantiation =
20647 MSI ? MSI->getPointOfInstantiation() : Var->getPointOfInstantiation();
20648 bool FirstInstantiation = PointOfInstantiation.isInvalid();
20649 if (FirstInstantiation) {
20650 PointOfInstantiation = Loc;
20651 if (MSI)
20652 MSI->setPointOfInstantiation(PointOfInstantiation);
20653 // FIXME: Notify listener.
20654 else
20655 Var->setTemplateSpecializationKind(TSK, PointOfInstantiation);
20656 }
20657
20658 if (UsableInConstantExpr || Var->getType()->isUndeducedType()) {
20659 // Do not defer instantiations of variables that could be used in a
20660 // constant expression.
20661 // The type deduction also needs a complete initializer.
20662 SemaRef.runWithSufficientStackSpace(Loc: PointOfInstantiation, Fn: [&] {
20663 SemaRef.InstantiateVariableDefinition(PointOfInstantiation, Var);
20664 });
20665
20666 // The size of an incomplete array type can be updated by
20667 // instantiating the initializer. The DeclRefExpr's type should be
20668 // updated accordingly too, or users of it would be confused!
20669 if (E)
20670 SemaRef.getCompletedType(E);
20671
20672 // Re-set the member to trigger a recomputation of the dependence bits
20673 // for the expression.
20674 if (auto *DRE = dyn_cast_or_null<DeclRefExpr>(Val: E))
20675 DRE->setDecl(DRE->getDecl());
20676 else if (auto *ME = dyn_cast_or_null<MemberExpr>(Val: E))
20677 ME->setMemberDecl(ME->getMemberDecl());
20678 } else if (FirstInstantiation) {
20679 SemaRef.PendingInstantiations
20680 .push_back(x: std::make_pair(x&: Var, y&: PointOfInstantiation));
20681 } else {
20682 bool Inserted = false;
20683 for (auto &I : SemaRef.SavedPendingInstantiations) {
20684 auto Iter = llvm::find_if(
20685 Range&: I, P: [Var](const Sema::PendingImplicitInstantiation &P) {
20686 return P.first == Var;
20687 });
20688 if (Iter != I.end()) {
20689 SemaRef.PendingInstantiations.push_back(x: *Iter);
20690 I.erase(position: Iter);
20691 Inserted = true;
20692 break;
20693 }
20694 }
20695
20696 // FIXME: For a specialization of a variable template, we don't
20697 // distinguish between "declaration and type implicitly instantiated"
20698 // and "implicit instantiation of definition requested", so we have
20699 // no direct way to avoid enqueueing the pending instantiation
20700 // multiple times.
20701 if (isa<VarTemplateSpecializationDecl>(Val: Var) && !Inserted)
20702 SemaRef.PendingInstantiations
20703 .push_back(x: std::make_pair(x&: Var, y&: PointOfInstantiation));
20704 }
20705 }
20706 }
20707
20708 // C++2a [basic.def.odr]p4:
20709 // A variable x whose name appears as a potentially-evaluated expression e
20710 // is odr-used by e unless
20711 // -- x is a reference that is usable in constant expressions
20712 // -- x is a variable of non-reference type that is usable in constant
20713 // expressions and has no mutable subobjects [FIXME], and e is an
20714 // element of the set of potential results of an expression of
20715 // non-volatile-qualified non-class type to which the lvalue-to-rvalue
20716 // conversion is applied
20717 // -- x is a variable of non-reference type, and e is an element of the set
20718 // of potential results of a discarded-value expression to which the
20719 // lvalue-to-rvalue conversion is not applied [FIXME]
20720 //
20721 // We check the first part of the second bullet here, and
20722 // Sema::CheckLValueToRValueConversionOperand deals with the second part.
20723 // FIXME: To get the third bullet right, we need to delay this even for
20724 // variables that are not usable in constant expressions.
20725
20726 // If we already know this isn't an odr-use, there's nothing more to do.
20727 if (DeclRefExpr *DRE = dyn_cast_or_null<DeclRefExpr>(Val: E))
20728 if (DRE->isNonOdrUse())
20729 return;
20730 if (MemberExpr *ME = dyn_cast_or_null<MemberExpr>(Val: E))
20731 if (ME->isNonOdrUse())
20732 return;
20733
20734 switch (OdrUse) {
20735 case OdrUseContext::None:
20736 // In some cases, a variable may not have been marked unevaluated, if it
20737 // appears in a defaukt initializer.
20738 assert((!E || isa<FunctionParmPackExpr>(E) ||
20739 SemaRef.isUnevaluatedContext()) &&
20740 "missing non-odr-use marking for unevaluated decl ref");
20741 break;
20742
20743 case OdrUseContext::FormallyOdrUsed:
20744 // FIXME: Ignoring formal odr-uses results in incorrect lambda capture
20745 // behavior.
20746 break;
20747
20748 case OdrUseContext::Used:
20749 // If we might later find that this expression isn't actually an odr-use,
20750 // delay the marking.
20751 if (E && Var->isUsableInConstantExpressions(C: SemaRef.Context))
20752 SemaRef.MaybeODRUseExprs.insert(X: E);
20753 else
20754 MarkVarDeclODRUsed(V: Var, Loc, SemaRef);
20755 break;
20756
20757 case OdrUseContext::Dependent:
20758 // If this is a dependent context, we don't need to mark variables as
20759 // odr-used, but we may still need to track them for lambda capture.
20760 // FIXME: Do we also need to do this inside dependent typeid expressions
20761 // (which are modeled as unevaluated at this point)?
20762 DoMarkPotentialCapture(SemaRef, Loc, Var, E);
20763 break;
20764 }
20765}
20766
20767static void DoMarkBindingDeclReferenced(Sema &SemaRef, SourceLocation Loc,
20768 BindingDecl *BD, Expr *E) {
20769 BD->setReferenced();
20770
20771 if (BD->isInvalidDecl())
20772 return;
20773
20774 OdrUseContext OdrUse = isOdrUseContext(SemaRef);
20775 if (OdrUse == OdrUseContext::Used) {
20776 QualType CaptureType, DeclRefType;
20777 SemaRef.tryCaptureVariable(Var: BD, ExprLoc: Loc, Kind: TryCaptureKind::Implicit,
20778 /*EllipsisLoc*/ SourceLocation(),
20779 /*BuildAndDiagnose*/ true, CaptureType,
20780 DeclRefType,
20781 /*FunctionScopeIndexToStopAt*/ nullptr);
20782 } else if (OdrUse == OdrUseContext::Dependent) {
20783 DoMarkPotentialCapture(SemaRef, Loc, Var: BD, E);
20784 }
20785}
20786
20787void Sema::MarkVariableReferenced(SourceLocation Loc, VarDecl *Var) {
20788 DoMarkVarDeclReferenced(SemaRef&: *this, Loc, Var, E: nullptr, RefsMinusAssignments);
20789}
20790
20791// C++ [temp.dep.expr]p3:
20792// An id-expression is type-dependent if it contains:
20793// - an identifier associated by name lookup with an entity captured by copy
20794// in a lambda-expression that has an explicit object parameter whose type
20795// is dependent ([dcl.fct]),
20796static void FixDependencyOfIdExpressionsInLambdaWithDependentObjectParameter(
20797 Sema &SemaRef, ValueDecl *D, Expr *E) {
20798 auto *ID = dyn_cast<DeclRefExpr>(Val: E);
20799 if (!ID || ID->isTypeDependent() || !ID->refersToEnclosingVariableOrCapture())
20800 return;
20801
20802 // If any enclosing lambda with a dependent explicit object parameter either
20803 // explicitly captures the variable by value, or has a capture default of '='
20804 // and does not capture the variable by reference, then the type of the DRE
20805 // is dependent on the type of that lambda's explicit object parameter.
20806 auto IsDependent = [&]() {
20807 for (auto *Scope : llvm::reverse(C&: SemaRef.FunctionScopes)) {
20808 auto *LSI = dyn_cast<sema::LambdaScopeInfo>(Val: Scope);
20809 if (!LSI)
20810 continue;
20811
20812 if (LSI->Lambda && !LSI->Lambda->Encloses(DC: SemaRef.CurContext) &&
20813 LSI->AfterParameterList)
20814 return false;
20815
20816 const auto *MD = LSI->CallOperator;
20817 if (MD->getType().isNull())
20818 continue;
20819
20820 const auto *Ty = MD->getType()->getAs<FunctionProtoType>();
20821 if (!Ty || !MD->isExplicitObjectMemberFunction() ||
20822 !Ty->getParamType(i: 0)->isDependentType())
20823 continue;
20824
20825 if (auto *C = LSI->CaptureMap.count(Val: D) ? &LSI->getCapture(Var: D) : nullptr) {
20826 if (C->isCopyCapture())
20827 return true;
20828 continue;
20829 }
20830
20831 if (LSI->ImpCaptureStyle == LambdaScopeInfo::ImpCap_LambdaByval)
20832 return true;
20833 }
20834 return false;
20835 }();
20836
20837 ID->setCapturedByCopyInLambdaWithExplicitObjectParameter(
20838 Set: IsDependent, Context: SemaRef.getASTContext());
20839}
20840
20841static void
20842MarkExprReferenced(Sema &SemaRef, SourceLocation Loc, Decl *D, Expr *E,
20843 bool MightBeOdrUse,
20844 llvm::DenseMap<const VarDecl *, int> &RefsMinusAssignments) {
20845 if (SemaRef.OpenMP().isInOpenMPDeclareTargetContext())
20846 SemaRef.OpenMP().checkDeclIsAllowedInOpenMPTarget(E, D);
20847
20848 if (SemaRef.getLangOpts().OpenACC)
20849 SemaRef.OpenACC().CheckDeclReference(Loc, E, D);
20850
20851 if (VarDecl *Var = dyn_cast<VarDecl>(Val: D)) {
20852 DoMarkVarDeclReferenced(SemaRef, Loc, Var, E, RefsMinusAssignments);
20853 if (SemaRef.getLangOpts().CPlusPlus)
20854 FixDependencyOfIdExpressionsInLambdaWithDependentObjectParameter(SemaRef,
20855 D: Var, E);
20856 return;
20857 }
20858
20859 if (BindingDecl *Decl = dyn_cast<BindingDecl>(Val: D)) {
20860 DoMarkBindingDeclReferenced(SemaRef, Loc, BD: Decl, E);
20861 if (SemaRef.getLangOpts().CPlusPlus)
20862 FixDependencyOfIdExpressionsInLambdaWithDependentObjectParameter(SemaRef,
20863 D: Decl, E);
20864 return;
20865 }
20866 SemaRef.MarkAnyDeclReferenced(Loc, D, MightBeOdrUse);
20867
20868 // If this is a call to a method via a cast, also mark the method in the
20869 // derived class used in case codegen can devirtualize the call.
20870 const MemberExpr *ME = dyn_cast<MemberExpr>(Val: E);
20871 if (!ME)
20872 return;
20873 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Val: ME->getMemberDecl());
20874 if (!MD)
20875 return;
20876 // Only attempt to devirtualize if this is truly a virtual call.
20877 bool IsVirtualCall = MD->isVirtual() &&
20878 ME->performsVirtualDispatch(LO: SemaRef.getLangOpts());
20879 if (!IsVirtualCall)
20880 return;
20881
20882 // If it's possible to devirtualize the call, mark the called function
20883 // referenced.
20884 CXXMethodDecl *DM = MD->getDevirtualizedMethod(
20885 Base: ME->getBase(), IsAppleKext: SemaRef.getLangOpts().AppleKext);
20886 if (DM)
20887 SemaRef.MarkAnyDeclReferenced(Loc, D: DM, MightBeOdrUse);
20888}
20889
20890void Sema::MarkDeclRefReferenced(DeclRefExpr *E, const Expr *Base) {
20891 // [basic.def.odr] (CWG 1614)
20892 // A function is named by an expression or conversion [...]
20893 // unless it is a pure virtual function and either the expression is not an
20894 // id-expression naming the function with an explicitly qualified name or
20895 // the expression forms a pointer to member
20896 bool OdrUse = true;
20897 if (const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Val: E->getDecl()))
20898 if (Method->isVirtual() &&
20899 !Method->getDevirtualizedMethod(Base, IsAppleKext: getLangOpts().AppleKext))
20900 OdrUse = false;
20901
20902 if (auto *FD = dyn_cast<FunctionDecl>(Val: E->getDecl())) {
20903 if (!isUnevaluatedContext() && !isConstantEvaluatedContext() &&
20904 !isImmediateFunctionContext() &&
20905 !isCheckingDefaultArgumentOrInitializer() &&
20906 FD->isImmediateFunction() && !RebuildingImmediateInvocation &&
20907 !FD->isDependentContext())
20908 ExprEvalContexts.back().ReferenceToConsteval.insert(Ptr: E);
20909 }
20910 MarkExprReferenced(SemaRef&: *this, Loc: E->getLocation(), D: E->getDecl(), E, MightBeOdrUse: OdrUse,
20911 RefsMinusAssignments);
20912}
20913
20914void Sema::MarkMemberReferenced(MemberExpr *E) {
20915 // C++11 [basic.def.odr]p2:
20916 // A non-overloaded function whose name appears as a potentially-evaluated
20917 // expression or a member of a set of candidate functions, if selected by
20918 // overload resolution when referred to from a potentially-evaluated
20919 // expression, is odr-used, unless it is a pure virtual function and its
20920 // name is not explicitly qualified.
20921 bool MightBeOdrUse = true;
20922 if (E->performsVirtualDispatch(LO: getLangOpts())) {
20923 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Val: E->getMemberDecl()))
20924 if (Method->isPureVirtual())
20925 MightBeOdrUse = false;
20926 }
20927 SourceLocation Loc =
20928 E->getMemberLoc().isValid() ? E->getMemberLoc() : E->getBeginLoc();
20929 MarkExprReferenced(SemaRef&: *this, Loc, D: E->getMemberDecl(), E, MightBeOdrUse,
20930 RefsMinusAssignments);
20931}
20932
20933void Sema::MarkFunctionParmPackReferenced(FunctionParmPackExpr *E) {
20934 for (ValueDecl *VD : *E)
20935 MarkExprReferenced(SemaRef&: *this, Loc: E->getParameterPackLocation(), D: VD, E, MightBeOdrUse: true,
20936 RefsMinusAssignments);
20937}
20938
20939/// Perform marking for a reference to an arbitrary declaration. It
20940/// marks the declaration referenced, and performs odr-use checking for
20941/// functions and variables. This method should not be used when building a
20942/// normal expression which refers to a variable.
20943void Sema::MarkAnyDeclReferenced(SourceLocation Loc, Decl *D,
20944 bool MightBeOdrUse) {
20945 if (MightBeOdrUse) {
20946 if (auto *VD = dyn_cast<VarDecl>(Val: D)) {
20947 MarkVariableReferenced(Loc, Var: VD);
20948 return;
20949 }
20950 }
20951 if (auto *FD = dyn_cast<FunctionDecl>(Val: D)) {
20952 MarkFunctionReferenced(Loc, Func: FD, MightBeOdrUse);
20953 return;
20954 }
20955 D->setReferenced();
20956}
20957
20958namespace {
20959 // Mark all of the declarations used by a type as referenced.
20960 // FIXME: Not fully implemented yet! We need to have a better understanding
20961 // of when we're entering a context we should not recurse into.
20962 // FIXME: This is and EvaluatedExprMarker are more-or-less equivalent to
20963 // TreeTransforms rebuilding the type in a new context. Rather than
20964 // duplicating the TreeTransform logic, we should consider reusing it here.
20965 // Currently that causes problems when rebuilding LambdaExprs.
20966class MarkReferencedDecls : public DynamicRecursiveASTVisitor {
20967 Sema &S;
20968 SourceLocation Loc;
20969
20970public:
20971 MarkReferencedDecls(Sema &S, SourceLocation Loc) : S(S), Loc(Loc) {}
20972
20973 bool TraverseTemplateArgument(const TemplateArgument &Arg) override;
20974};
20975}
20976
20977bool MarkReferencedDecls::TraverseTemplateArgument(
20978 const TemplateArgument &Arg) {
20979 {
20980 // A non-type template argument is a constant-evaluated context.
20981 EnterExpressionEvaluationContext Evaluated(
20982 S, Sema::ExpressionEvaluationContext::ConstantEvaluated);
20983 if (Arg.getKind() == TemplateArgument::Declaration) {
20984 if (Decl *D = Arg.getAsDecl())
20985 S.MarkAnyDeclReferenced(Loc, D, MightBeOdrUse: true);
20986 } else if (Arg.getKind() == TemplateArgument::Expression) {
20987 S.MarkDeclarationsReferencedInExpr(E: Arg.getAsExpr(), SkipLocalVariables: false);
20988 }
20989 }
20990
20991 return DynamicRecursiveASTVisitor::TraverseTemplateArgument(Arg);
20992}
20993
20994void Sema::MarkDeclarationsReferencedInType(SourceLocation Loc, QualType T) {
20995 MarkReferencedDecls Marker(*this, Loc);
20996 Marker.TraverseType(T);
20997}
20998
20999namespace {
21000/// Helper class that marks all of the declarations referenced by
21001/// potentially-evaluated subexpressions as "referenced".
21002class EvaluatedExprMarker : public UsedDeclVisitor<EvaluatedExprMarker> {
21003public:
21004 typedef UsedDeclVisitor<EvaluatedExprMarker> Inherited;
21005 bool SkipLocalVariables;
21006 ArrayRef<const Expr *> StopAt;
21007
21008 EvaluatedExprMarker(Sema &S, bool SkipLocalVariables,
21009 ArrayRef<const Expr *> StopAt)
21010 : Inherited(S), SkipLocalVariables(SkipLocalVariables), StopAt(StopAt) {}
21011
21012 void visitUsedDecl(SourceLocation Loc, Decl *D) {
21013 S.MarkFunctionReferenced(Loc, Func: cast<FunctionDecl>(Val: D));
21014 }
21015
21016 void Visit(Expr *E) {
21017 if (llvm::is_contained(Range&: StopAt, Element: E))
21018 return;
21019 Inherited::Visit(S: E);
21020 }
21021
21022 void VisitConstantExpr(ConstantExpr *E) {
21023 // Don't mark declarations within a ConstantExpression, as this expression
21024 // will be evaluated and folded to a value.
21025 }
21026
21027 void VisitDeclRefExpr(DeclRefExpr *E) {
21028 // If we were asked not to visit local variables, don't.
21029 if (SkipLocalVariables) {
21030 if (VarDecl *VD = dyn_cast<VarDecl>(Val: E->getDecl()))
21031 if (VD->hasLocalStorage())
21032 return;
21033 }
21034
21035 // FIXME: This can trigger the instantiation of the initializer of a
21036 // variable, which can cause the expression to become value-dependent
21037 // or error-dependent. Do we need to propagate the new dependence bits?
21038 S.MarkDeclRefReferenced(E);
21039 }
21040
21041 void VisitMemberExpr(MemberExpr *E) {
21042 S.MarkMemberReferenced(E);
21043 Visit(E: E->getBase());
21044 }
21045};
21046} // namespace
21047
21048void Sema::MarkDeclarationsReferencedInExpr(Expr *E,
21049 bool SkipLocalVariables,
21050 ArrayRef<const Expr*> StopAt) {
21051 EvaluatedExprMarker(*this, SkipLocalVariables, StopAt).Visit(E);
21052}
21053
21054/// Emit a diagnostic when statements are reachable.
21055bool Sema::DiagIfReachable(SourceLocation Loc, ArrayRef<const Stmt *> Stmts,
21056 const PartialDiagnostic &PD) {
21057 VarDecl *Decl = ExprEvalContexts.back().DeclForInitializer;
21058 // The initializer of a constexpr variable or of the first declaration of a
21059 // static data member is not syntactically a constant evaluated constant,
21060 // but nonetheless is always required to be a constant expression, so we
21061 // can skip diagnosing.
21062 if (Decl &&
21063 (Decl->isConstexpr() || (Decl->isStaticDataMember() &&
21064 Decl->isFirstDecl() && !Decl->isInline())))
21065 return false;
21066
21067 if (Stmts.empty()) {
21068 Diag(Loc, PD);
21069 return true;
21070 }
21071
21072 if (getCurFunction()) {
21073 FunctionScopes.back()->PossiblyUnreachableDiags.push_back(
21074 Elt: sema::PossiblyUnreachableDiag(PD, Loc, Stmts));
21075 return true;
21076 }
21077
21078 // For non-constexpr file-scope variables with reachability context (non-empty
21079 // Stmts), build a CFG for the initializer and check whether the context in
21080 // question is reachable.
21081 if (Decl && Decl->isFileVarDecl()) {
21082 AnalysisWarnings.registerVarDeclWarning(
21083 VD: Decl, PUD: sema::PossiblyUnreachableDiag(PD, Loc, Stmts));
21084 return true;
21085 }
21086
21087 Diag(Loc, PD);
21088 return true;
21089}
21090
21091/// Emit a diagnostic that describes an effect on the run-time behavior
21092/// of the program being compiled.
21093///
21094/// This routine emits the given diagnostic when the code currently being
21095/// type-checked is "potentially evaluated", meaning that there is a
21096/// possibility that the code will actually be executable. Code in sizeof()
21097/// expressions, code used only during overload resolution, etc., are not
21098/// potentially evaluated. This routine will suppress such diagnostics or,
21099/// in the absolutely nutty case of potentially potentially evaluated
21100/// expressions (C++ typeid), queue the diagnostic to potentially emit it
21101/// later.
21102///
21103/// This routine should be used for all diagnostics that describe the run-time
21104/// behavior of a program, such as passing a non-POD value through an ellipsis.
21105/// Failure to do so will likely result in spurious diagnostics or failures
21106/// during overload resolution or within sizeof/alignof/typeof/typeid.
21107bool Sema::DiagRuntimeBehavior(SourceLocation Loc, ArrayRef<const Stmt*> Stmts,
21108 const PartialDiagnostic &PD) {
21109
21110 if (ExprEvalContexts.back().isDiscardedStatementContext())
21111 return false;
21112
21113 switch (ExprEvalContexts.back().Context) {
21114 case ExpressionEvaluationContext::Unevaluated:
21115 case ExpressionEvaluationContext::UnevaluatedList:
21116 case ExpressionEvaluationContext::UnevaluatedAbstract:
21117 case ExpressionEvaluationContext::DiscardedStatement:
21118 // The argument will never be evaluated, so don't complain.
21119 break;
21120
21121 case ExpressionEvaluationContext::ConstantEvaluated:
21122 case ExpressionEvaluationContext::ImmediateFunctionContext:
21123 // Relevant diagnostics should be produced by constant evaluation.
21124 break;
21125
21126 case ExpressionEvaluationContext::PotentiallyEvaluated:
21127 case ExpressionEvaluationContext::PotentiallyEvaluatedIfUsed:
21128 return DiagIfReachable(Loc, Stmts, PD);
21129 }
21130
21131 return false;
21132}
21133
21134bool Sema::DiagRuntimeBehavior(SourceLocation Loc, const Stmt *Statement,
21135 const PartialDiagnostic &PD) {
21136 return DiagRuntimeBehavior(
21137 Loc, Stmts: Statement ? llvm::ArrayRef(Statement) : llvm::ArrayRef<Stmt *>(),
21138 PD);
21139}
21140
21141bool Sema::CheckCallReturnType(QualType ReturnType, SourceLocation Loc,
21142 CallExpr *CE, FunctionDecl *FD) {
21143 if (ReturnType->isVoidType() || !ReturnType->isIncompleteType())
21144 return false;
21145
21146 // If we're inside a decltype's expression, don't check for a valid return
21147 // type or construct temporaries until we know whether this is the last call.
21148 if (ExprEvalContexts.back().ExprContext ==
21149 ExpressionEvaluationContextRecord::EK_Decltype) {
21150 ExprEvalContexts.back().DelayedDecltypeCalls.push_back(Elt: CE);
21151 return false;
21152 }
21153
21154 class CallReturnIncompleteDiagnoser : public TypeDiagnoser {
21155 FunctionDecl *FD;
21156 CallExpr *CE;
21157
21158 public:
21159 CallReturnIncompleteDiagnoser(FunctionDecl *FD, CallExpr *CE)
21160 : FD(FD), CE(CE) { }
21161
21162 void diagnose(Sema &S, SourceLocation Loc, QualType T) override {
21163 if (!FD) {
21164 S.Diag(Loc, DiagID: diag::err_call_incomplete_return)
21165 << T << CE->getSourceRange();
21166 return;
21167 }
21168
21169 S.Diag(Loc, DiagID: diag::err_call_function_incomplete_return)
21170 << CE->getSourceRange() << FD << T;
21171 S.Diag(Loc: FD->getLocation(), DiagID: diag::note_entity_declared_at)
21172 << FD->getDeclName();
21173 }
21174 } Diagnoser(FD, CE);
21175
21176 if (RequireCompleteType(Loc, T: ReturnType, Diagnoser))
21177 return true;
21178
21179 return false;
21180}
21181
21182// Diagnose the s/=/==/ and s/\|=/!=/ typos. Note that adding parentheses
21183// will prevent this condition from triggering, which is what we want.
21184void Sema::DiagnoseAssignmentAsCondition(Expr *E) {
21185 SourceLocation Loc;
21186
21187 unsigned diagnostic = diag::warn_condition_is_assignment;
21188 bool IsOrAssign = false;
21189
21190 if (BinaryOperator *Op = dyn_cast<BinaryOperator>(Val: E)) {
21191 if (Op->getOpcode() != BO_Assign && Op->getOpcode() != BO_OrAssign)
21192 return;
21193
21194 IsOrAssign = Op->getOpcode() == BO_OrAssign;
21195
21196 // Greylist some idioms by putting them into a warning subcategory.
21197 if (ObjCMessageExpr *ME
21198 = dyn_cast<ObjCMessageExpr>(Val: Op->getRHS()->IgnoreParenCasts())) {
21199 Selector Sel = ME->getSelector();
21200
21201 // self = [<foo> init...]
21202 if (ObjC().isSelfExpr(RExpr: Op->getLHS()) && ME->getMethodFamily() == OMF_init)
21203 diagnostic = diag::warn_condition_is_idiomatic_assignment;
21204
21205 // <foo> = [<bar> nextObject]
21206 else if (Sel.isUnarySelector() && Sel.getNameForSlot(argIndex: 0) == "nextObject")
21207 diagnostic = diag::warn_condition_is_idiomatic_assignment;
21208 }
21209
21210 Loc = Op->getOperatorLoc();
21211 } else if (CXXOperatorCallExpr *Op = dyn_cast<CXXOperatorCallExpr>(Val: E)) {
21212 if (Op->getOperator() != OO_Equal && Op->getOperator() != OO_PipeEqual)
21213 return;
21214
21215 IsOrAssign = Op->getOperator() == OO_PipeEqual;
21216 Loc = Op->getOperatorLoc();
21217 } else if (PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(Val: E))
21218 return DiagnoseAssignmentAsCondition(E: POE->getSyntacticForm());
21219 else {
21220 // Not an assignment.
21221 return;
21222 }
21223
21224 Diag(Loc, DiagID: diagnostic) << E->getSourceRange();
21225
21226 SourceLocation Open = E->getBeginLoc();
21227 SourceLocation Close = getLocForEndOfToken(Loc: E->getSourceRange().getEnd());
21228 Diag(Loc, DiagID: diag::note_condition_assign_silence)
21229 << FixItHint::CreateInsertion(InsertionLoc: Open, Code: "(")
21230 << FixItHint::CreateInsertion(InsertionLoc: Close, Code: ")");
21231
21232 if (IsOrAssign)
21233 Diag(Loc, DiagID: diag::note_condition_or_assign_to_comparison)
21234 << FixItHint::CreateReplacement(RemoveRange: Loc, Code: "!=");
21235 else
21236 Diag(Loc, DiagID: diag::note_condition_assign_to_comparison)
21237 << FixItHint::CreateReplacement(RemoveRange: Loc, Code: "==");
21238}
21239
21240void Sema::DiagnoseEqualityWithExtraParens(ParenExpr *ParenE) {
21241 // Don't warn if the parens came from a macro.
21242 SourceLocation parenLoc = ParenE->getBeginLoc();
21243 if (parenLoc.isInvalid() || parenLoc.isMacroID())
21244 return;
21245 // Don't warn for dependent expressions.
21246 if (ParenE->isTypeDependent())
21247 return;
21248
21249 Expr *E = ParenE->IgnoreParens();
21250 if (ParenE->isProducedByFoldExpansion() && ParenE->getSubExpr() == E)
21251 return;
21252
21253 if (BinaryOperator *opE = dyn_cast<BinaryOperator>(Val: E))
21254 if (opE->getOpcode() == BO_EQ &&
21255 opE->getLHS()->IgnoreParenImpCasts()->isModifiableLvalue(Ctx&: Context)
21256 == Expr::MLV_Valid) {
21257 SourceLocation Loc = opE->getOperatorLoc();
21258
21259 Diag(Loc, DiagID: diag::warn_equality_with_extra_parens) << E->getSourceRange();
21260 SourceRange ParenERange = ParenE->getSourceRange();
21261 Diag(Loc, DiagID: diag::note_equality_comparison_silence)
21262 << FixItHint::CreateRemoval(RemoveRange: ParenERange.getBegin())
21263 << FixItHint::CreateRemoval(RemoveRange: ParenERange.getEnd());
21264 Diag(Loc, DiagID: diag::note_equality_comparison_to_assign)
21265 << FixItHint::CreateReplacement(RemoveRange: Loc, Code: "=");
21266 }
21267}
21268
21269ExprResult Sema::CheckBooleanCondition(SourceLocation Loc, Expr *E,
21270 bool IsConstexpr) {
21271 DiagnoseAssignmentAsCondition(E);
21272 if (ParenExpr *parenE = dyn_cast<ParenExpr>(Val: E))
21273 DiagnoseEqualityWithExtraParens(ParenE: parenE);
21274
21275 ExprResult result = CheckPlaceholderExpr(E);
21276 if (result.isInvalid()) return ExprError();
21277 E = result.get();
21278
21279 if (!E->isTypeDependent()) {
21280 if (E->getType() == Context.AMDGPUFeaturePredicateTy)
21281 return AMDGPU().ExpandAMDGPUPredicateBuiltIn(CE: E);
21282
21283 if (getLangOpts().CPlusPlus)
21284 return CheckCXXBooleanCondition(CondExpr: E, IsConstexpr); // C++ 6.4p4
21285
21286 ExprResult ERes = DefaultFunctionArrayLvalueConversion(E);
21287 if (ERes.isInvalid())
21288 return ExprError();
21289 E = ERes.get();
21290
21291 QualType T = E->getType();
21292 if (!T->isScalarType()) { // C99 6.8.4.1p1
21293 Diag(Loc, DiagID: diag::err_typecheck_statement_requires_scalar)
21294 << T << E->getSourceRange();
21295 return ExprError();
21296 }
21297 CheckBoolLikeConversion(E, CC: Loc);
21298 }
21299
21300 return E;
21301}
21302
21303Sema::ConditionResult Sema::ActOnCondition(Scope *S, SourceLocation Loc,
21304 Expr *SubExpr, ConditionKind CK,
21305 bool MissingOK) {
21306 // MissingOK indicates whether having no condition expression is valid
21307 // (for loop) or invalid (e.g. while loop).
21308 if (!SubExpr)
21309 return MissingOK ? ConditionResult() : ConditionError();
21310
21311 ExprResult Cond;
21312 switch (CK) {
21313 case ConditionKind::Boolean:
21314 Cond = CheckBooleanCondition(Loc, E: SubExpr);
21315 break;
21316
21317 case ConditionKind::ConstexprIf:
21318 // Note: this might produce a FullExpr
21319 Cond = CheckBooleanCondition(Loc, E: SubExpr, IsConstexpr: true);
21320 break;
21321
21322 case ConditionKind::Switch:
21323 Cond = CheckSwitchCondition(SwitchLoc: Loc, Cond: SubExpr);
21324 break;
21325 }
21326 if (Cond.isInvalid()) {
21327 Cond = CreateRecoveryExpr(Begin: SubExpr->getBeginLoc(), End: SubExpr->getEndLoc(),
21328 SubExprs: {SubExpr}, T: PreferredConditionType(K: CK));
21329 if (!Cond.get())
21330 return ConditionError();
21331 } else if (Cond.isUsable() && !isa<FullExpr>(Val: Cond.get()))
21332 Cond = ActOnFinishFullExpr(Expr: Cond.get(), CC: Loc, /*DiscardedValue*/ false);
21333
21334 if (!Cond.isUsable())
21335 return ConditionError();
21336
21337 return ConditionResult(*this, nullptr, Cond,
21338 CK == ConditionKind::ConstexprIf);
21339}
21340
21341namespace {
21342 /// A visitor for rebuilding a call to an __unknown_any expression
21343 /// to have an appropriate type.
21344 struct RebuildUnknownAnyFunction
21345 : StmtVisitor<RebuildUnknownAnyFunction, ExprResult> {
21346
21347 Sema &S;
21348
21349 RebuildUnknownAnyFunction(Sema &S) : S(S) {}
21350
21351 ExprResult VisitStmt(Stmt *S) {
21352 llvm_unreachable("unexpected statement!");
21353 }
21354
21355 ExprResult VisitExpr(Expr *E) {
21356 S.Diag(Loc: E->getExprLoc(), DiagID: diag::err_unsupported_unknown_any_call)
21357 << E->getSourceRange();
21358 return ExprError();
21359 }
21360
21361 /// Rebuild an expression which simply semantically wraps another
21362 /// expression which it shares the type and value kind of.
21363 template <class T> ExprResult rebuildSugarExpr(T *E) {
21364 ExprResult SubResult = Visit(S: E->getSubExpr());
21365 if (SubResult.isInvalid()) return ExprError();
21366
21367 Expr *SubExpr = SubResult.get();
21368 E->setSubExpr(SubExpr);
21369 E->setType(SubExpr->getType());
21370 E->setValueKind(SubExpr->getValueKind());
21371 assert(E->getObjectKind() == OK_Ordinary);
21372 return E;
21373 }
21374
21375 ExprResult VisitParenExpr(ParenExpr *E) {
21376 return rebuildSugarExpr(E);
21377 }
21378
21379 ExprResult VisitUnaryExtension(UnaryOperator *E) {
21380 return rebuildSugarExpr(E);
21381 }
21382
21383 ExprResult VisitUnaryAddrOf(UnaryOperator *E) {
21384 ExprResult SubResult = Visit(S: E->getSubExpr());
21385 if (SubResult.isInvalid()) return ExprError();
21386
21387 Expr *SubExpr = SubResult.get();
21388 E->setSubExpr(SubExpr);
21389 E->setType(S.Context.getPointerType(T: SubExpr->getType()));
21390 assert(E->isPRValue());
21391 assert(E->getObjectKind() == OK_Ordinary);
21392 return E;
21393 }
21394
21395 ExprResult resolveDecl(Expr *E, ValueDecl *VD) {
21396 if (!isa<FunctionDecl>(Val: VD)) return VisitExpr(E);
21397
21398 E->setType(VD->getType());
21399
21400 assert(E->isPRValue());
21401 if (S.getLangOpts().CPlusPlus &&
21402 !(isa<CXXMethodDecl>(Val: VD) &&
21403 cast<CXXMethodDecl>(Val: VD)->isInstance()))
21404 E->setValueKind(VK_LValue);
21405
21406 return E;
21407 }
21408
21409 ExprResult VisitMemberExpr(MemberExpr *E) {
21410 return resolveDecl(E, VD: E->getMemberDecl());
21411 }
21412
21413 ExprResult VisitDeclRefExpr(DeclRefExpr *E) {
21414 return resolveDecl(E, VD: E->getDecl());
21415 }
21416 };
21417}
21418
21419/// Given a function expression of unknown-any type, try to rebuild it
21420/// to have a function type.
21421static ExprResult rebuildUnknownAnyFunction(Sema &S, Expr *FunctionExpr) {
21422 ExprResult Result = RebuildUnknownAnyFunction(S).Visit(S: FunctionExpr);
21423 if (Result.isInvalid()) return ExprError();
21424 return S.DefaultFunctionArrayConversion(E: Result.get());
21425}
21426
21427namespace {
21428 /// A visitor for rebuilding an expression of type __unknown_anytype
21429 /// into one which resolves the type directly on the referring
21430 /// expression. Strict preservation of the original source
21431 /// structure is not a goal.
21432 struct RebuildUnknownAnyExpr
21433 : StmtVisitor<RebuildUnknownAnyExpr, ExprResult> {
21434
21435 Sema &S;
21436
21437 /// The current destination type.
21438 QualType DestType;
21439
21440 RebuildUnknownAnyExpr(Sema &S, QualType CastType)
21441 : S(S), DestType(CastType) {}
21442
21443 ExprResult VisitStmt(Stmt *S) {
21444 llvm_unreachable("unexpected statement!");
21445 }
21446
21447 ExprResult VisitExpr(Expr *E) {
21448 S.Diag(Loc: E->getExprLoc(), DiagID: diag::err_unsupported_unknown_any_expr)
21449 << E->getSourceRange();
21450 return ExprError();
21451 }
21452
21453 ExprResult VisitCallExpr(CallExpr *E);
21454 ExprResult VisitObjCMessageExpr(ObjCMessageExpr *E);
21455
21456 /// Rebuild an expression which simply semantically wraps another
21457 /// expression which it shares the type and value kind of.
21458 template <class T> ExprResult rebuildSugarExpr(T *E) {
21459 ExprResult SubResult = Visit(S: E->getSubExpr());
21460 if (SubResult.isInvalid()) return ExprError();
21461 Expr *SubExpr = SubResult.get();
21462 E->setSubExpr(SubExpr);
21463 E->setType(SubExpr->getType());
21464 E->setValueKind(SubExpr->getValueKind());
21465 assert(E->getObjectKind() == OK_Ordinary);
21466 return E;
21467 }
21468
21469 ExprResult VisitParenExpr(ParenExpr *E) {
21470 return rebuildSugarExpr(E);
21471 }
21472
21473 ExprResult VisitUnaryExtension(UnaryOperator *E) {
21474 return rebuildSugarExpr(E);
21475 }
21476
21477 ExprResult VisitUnaryAddrOf(UnaryOperator *E) {
21478 const PointerType *Ptr = DestType->getAs<PointerType>();
21479 if (!Ptr) {
21480 S.Diag(Loc: E->getOperatorLoc(), DiagID: diag::err_unknown_any_addrof)
21481 << E->getSourceRange();
21482 return ExprError();
21483 }
21484
21485 if (isa<CallExpr>(Val: E->getSubExpr())) {
21486 S.Diag(Loc: E->getOperatorLoc(), DiagID: diag::err_unknown_any_addrof_call)
21487 << E->getSourceRange();
21488 return ExprError();
21489 }
21490
21491 assert(E->isPRValue());
21492 assert(E->getObjectKind() == OK_Ordinary);
21493 E->setType(DestType);
21494
21495 // Build the sub-expression as if it were an object of the pointee type.
21496 DestType = Ptr->getPointeeType();
21497 ExprResult SubResult = Visit(S: E->getSubExpr());
21498 if (SubResult.isInvalid()) return ExprError();
21499 E->setSubExpr(SubResult.get());
21500 return E;
21501 }
21502
21503 ExprResult VisitImplicitCastExpr(ImplicitCastExpr *E);
21504
21505 ExprResult resolveDecl(Expr *E, ValueDecl *VD);
21506
21507 ExprResult VisitMemberExpr(MemberExpr *E) {
21508 return resolveDecl(E, VD: E->getMemberDecl());
21509 }
21510
21511 ExprResult VisitDeclRefExpr(DeclRefExpr *E) {
21512 return resolveDecl(E, VD: E->getDecl());
21513 }
21514 };
21515}
21516
21517/// Rebuilds a call expression which yielded __unknown_anytype.
21518ExprResult RebuildUnknownAnyExpr::VisitCallExpr(CallExpr *E) {
21519 Expr *CalleeExpr = E->getCallee();
21520
21521 enum FnKind {
21522 FK_MemberFunction,
21523 FK_FunctionPointer,
21524 FK_BlockPointer
21525 };
21526
21527 FnKind Kind;
21528 QualType CalleeType = CalleeExpr->getType();
21529 if (CalleeType == S.Context.BoundMemberTy) {
21530 assert(isa<CXXMemberCallExpr>(E) || isa<CXXOperatorCallExpr>(E));
21531 Kind = FK_MemberFunction;
21532 CalleeType = Expr::findBoundMemberType(expr: CalleeExpr);
21533 } else if (const PointerType *Ptr = CalleeType->getAs<PointerType>()) {
21534 CalleeType = Ptr->getPointeeType();
21535 Kind = FK_FunctionPointer;
21536 } else {
21537 CalleeType = CalleeType->castAs<BlockPointerType>()->getPointeeType();
21538 Kind = FK_BlockPointer;
21539 }
21540 const FunctionType *FnType = CalleeType->castAs<FunctionType>();
21541
21542 // Verify that this is a legal result type of a function.
21543 if ((DestType->isArrayType() && !S.getLangOpts().allowArrayReturnTypes()) ||
21544 DestType->isFunctionType()) {
21545 unsigned diagID = diag::err_func_returning_array_function;
21546 if (Kind == FK_BlockPointer)
21547 diagID = diag::err_block_returning_array_function;
21548
21549 S.Diag(Loc: E->getExprLoc(), DiagID: diagID)
21550 << DestType->isFunctionType() << DestType;
21551 return ExprError();
21552 }
21553
21554 // Otherwise, go ahead and set DestType as the call's result.
21555 E->setType(DestType.getNonLValueExprType(Context: S.Context));
21556 E->setValueKind(Expr::getValueKindForType(T: DestType));
21557 assert(E->getObjectKind() == OK_Ordinary);
21558
21559 // Rebuild the function type, replacing the result type with DestType.
21560 const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(Val: FnType);
21561 if (Proto) {
21562 // __unknown_anytype(...) is a special case used by the debugger when
21563 // it has no idea what a function's signature is.
21564 //
21565 // We want to build this call essentially under the K&R
21566 // unprototyped rules, but making a FunctionNoProtoType in C++
21567 // would foul up all sorts of assumptions. However, we cannot
21568 // simply pass all arguments as variadic arguments, nor can we
21569 // portably just call the function under a non-variadic type; see
21570 // the comment on IR-gen's TargetInfo::isNoProtoCallVariadic.
21571 // However, it turns out that in practice it is generally safe to
21572 // call a function declared as "A foo(B,C,D);" under the prototype
21573 // "A foo(B,C,D,...);". The only known exception is with the
21574 // Windows ABI, where any variadic function is implicitly cdecl
21575 // regardless of its normal CC. Therefore we change the parameter
21576 // types to match the types of the arguments.
21577 //
21578 // This is a hack, but it is far superior to moving the
21579 // corresponding target-specific code from IR-gen to Sema/AST.
21580
21581 ArrayRef<QualType> ParamTypes = Proto->getParamTypes();
21582 SmallVector<QualType, 8> ArgTypes;
21583 if (ParamTypes.empty() && Proto->isVariadic()) { // the special case
21584 ArgTypes.reserve(N: E->getNumArgs());
21585 for (unsigned i = 0, e = E->getNumArgs(); i != e; ++i) {
21586 ArgTypes.push_back(Elt: S.Context.getReferenceQualifiedType(e: E->getArg(Arg: i)));
21587 }
21588 ParamTypes = ArgTypes;
21589 }
21590 DestType = S.Context.getFunctionType(ResultTy: DestType, Args: ParamTypes,
21591 EPI: Proto->getExtProtoInfo());
21592 } else {
21593 DestType = S.Context.getFunctionNoProtoType(ResultTy: DestType,
21594 Info: FnType->getExtInfo());
21595 }
21596
21597 // Rebuild the appropriate pointer-to-function type.
21598 switch (Kind) {
21599 case FK_MemberFunction:
21600 // Nothing to do.
21601 break;
21602
21603 case FK_FunctionPointer:
21604 DestType = S.Context.getPointerType(T: DestType);
21605 break;
21606
21607 case FK_BlockPointer:
21608 DestType = S.Context.getBlockPointerType(T: DestType);
21609 break;
21610 }
21611
21612 // Finally, we can recurse.
21613 ExprResult CalleeResult = Visit(S: CalleeExpr);
21614 if (!CalleeResult.isUsable()) return ExprError();
21615 E->setCallee(CalleeResult.get());
21616
21617 // Bind a temporary if necessary.
21618 return S.MaybeBindToTemporary(E);
21619}
21620
21621ExprResult RebuildUnknownAnyExpr::VisitObjCMessageExpr(ObjCMessageExpr *E) {
21622 // Verify that this is a legal result type of a call.
21623 if (DestType->isArrayType() || DestType->isFunctionType()) {
21624 S.Diag(Loc: E->getExprLoc(), DiagID: diag::err_func_returning_array_function)
21625 << DestType->isFunctionType() << DestType;
21626 return ExprError();
21627 }
21628
21629 // Rewrite the method result type if available.
21630 if (ObjCMethodDecl *Method = E->getMethodDecl()) {
21631 assert(Method->getReturnType() == S.Context.UnknownAnyTy);
21632 Method->setReturnType(DestType);
21633 }
21634
21635 // Change the type of the message.
21636 E->setType(DestType.getNonReferenceType());
21637 E->setValueKind(Expr::getValueKindForType(T: DestType));
21638
21639 return S.MaybeBindToTemporary(E);
21640}
21641
21642ExprResult RebuildUnknownAnyExpr::VisitImplicitCastExpr(ImplicitCastExpr *E) {
21643 // The only case we should ever see here is a function-to-pointer decay.
21644 if (E->getCastKind() == CK_FunctionToPointerDecay) {
21645 assert(E->isPRValue());
21646 assert(E->getObjectKind() == OK_Ordinary);
21647
21648 E->setType(DestType);
21649
21650 // Rebuild the sub-expression as the pointee (function) type.
21651 DestType = DestType->castAs<PointerType>()->getPointeeType();
21652
21653 ExprResult Result = Visit(S: E->getSubExpr());
21654 if (!Result.isUsable()) return ExprError();
21655
21656 E->setSubExpr(Result.get());
21657 return E;
21658 } else if (E->getCastKind() == CK_LValueToRValue) {
21659 assert(E->isPRValue());
21660 assert(E->getObjectKind() == OK_Ordinary);
21661
21662 assert(isa<BlockPointerType>(E->getType()));
21663
21664 E->setType(DestType);
21665
21666 // The sub-expression has to be a lvalue reference, so rebuild it as such.
21667 DestType = S.Context.getLValueReferenceType(T: DestType);
21668
21669 ExprResult Result = Visit(S: E->getSubExpr());
21670 if (!Result.isUsable()) return ExprError();
21671
21672 E->setSubExpr(Result.get());
21673 return E;
21674 } else {
21675 llvm_unreachable("Unhandled cast type!");
21676 }
21677}
21678
21679ExprResult RebuildUnknownAnyExpr::resolveDecl(Expr *E, ValueDecl *VD) {
21680 ExprValueKind ValueKind = VK_LValue;
21681 QualType Type = DestType;
21682
21683 // We know how to make this work for certain kinds of decls:
21684
21685 // - functions
21686 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Val: VD)) {
21687 if (const PointerType *Ptr = Type->getAs<PointerType>()) {
21688 DestType = Ptr->getPointeeType();
21689 ExprResult Result = resolveDecl(E, VD);
21690 if (Result.isInvalid()) return ExprError();
21691 return S.ImpCastExprToType(E: Result.get(), Type, CK: CK_FunctionToPointerDecay,
21692 VK: VK_PRValue);
21693 }
21694
21695 if (!Type->isFunctionType()) {
21696 S.Diag(Loc: E->getExprLoc(), DiagID: diag::err_unknown_any_function)
21697 << VD << E->getSourceRange();
21698 return ExprError();
21699 }
21700 if (const FunctionProtoType *FT = Type->getAs<FunctionProtoType>()) {
21701 // We must match the FunctionDecl's type to the hack introduced in
21702 // RebuildUnknownAnyExpr::VisitCallExpr to vararg functions of unknown
21703 // type. See the lengthy commentary in that routine.
21704 QualType FDT = FD->getType();
21705 const FunctionType *FnType = FDT->castAs<FunctionType>();
21706 const FunctionProtoType *Proto = dyn_cast_or_null<FunctionProtoType>(Val: FnType);
21707 DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Val: E);
21708 if (DRE && Proto && Proto->getParamTypes().empty() && Proto->isVariadic()) {
21709 SourceLocation Loc = FD->getLocation();
21710 FunctionDecl *NewFD = FunctionDecl::Create(
21711 C&: S.Context, DC: FD->getDeclContext(), StartLoc: Loc, NLoc: Loc,
21712 N: FD->getNameInfo().getName(), T: DestType, TInfo: FD->getTypeSourceInfo(),
21713 SC: SC_None, UsesFPIntrin: S.getCurFPFeatures().isFPConstrained(),
21714 isInlineSpecified: false /*isInlineSpecified*/, hasWrittenPrototype: FD->hasPrototype(),
21715 /*ConstexprKind*/ ConstexprSpecKind::Unspecified);
21716
21717 if (FD->getQualifier())
21718 NewFD->setQualifierInfo(FD->getQualifierLoc());
21719
21720 SmallVector<ParmVarDecl*, 16> Params;
21721 for (const auto &AI : FT->param_types()) {
21722 ParmVarDecl *Param =
21723 S.BuildParmVarDeclForTypedef(DC: FD, Loc, T: AI);
21724 Param->setScopeInfo(scopeDepth: 0, parameterIndex: Params.size());
21725 Params.push_back(Elt: Param);
21726 }
21727 NewFD->setParams(Params);
21728 DRE->setDecl(NewFD);
21729 VD = DRE->getDecl();
21730 }
21731 }
21732
21733 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Val: FD))
21734 if (MD->isInstance()) {
21735 ValueKind = VK_PRValue;
21736 Type = S.Context.BoundMemberTy;
21737 }
21738
21739 // Function references aren't l-values in C.
21740 if (!S.getLangOpts().CPlusPlus)
21741 ValueKind = VK_PRValue;
21742
21743 // - variables
21744 } else if (isa<VarDecl>(Val: VD)) {
21745 if (const ReferenceType *RefTy = Type->getAs<ReferenceType>()) {
21746 Type = RefTy->getPointeeType();
21747 } else if (Type->isFunctionType()) {
21748 S.Diag(Loc: E->getExprLoc(), DiagID: diag::err_unknown_any_var_function_type)
21749 << VD << E->getSourceRange();
21750 return ExprError();
21751 }
21752
21753 // - nothing else
21754 } else {
21755 S.Diag(Loc: E->getExprLoc(), DiagID: diag::err_unsupported_unknown_any_decl)
21756 << VD << E->getSourceRange();
21757 return ExprError();
21758 }
21759
21760 // Modifying the declaration like this is friendly to IR-gen but
21761 // also really dangerous.
21762 VD->setType(DestType);
21763 E->setType(Type);
21764 E->setValueKind(ValueKind);
21765 return E;
21766}
21767
21768ExprResult Sema::checkUnknownAnyCast(SourceRange TypeRange, QualType CastType,
21769 Expr *CastExpr, CastKind &CastKind,
21770 ExprValueKind &VK, CXXCastPath &Path) {
21771 // The type we're casting to must be either void or complete.
21772 if (!CastType->isVoidType() &&
21773 RequireCompleteType(Loc: TypeRange.getBegin(), T: CastType,
21774 DiagID: diag::err_typecheck_cast_to_incomplete))
21775 return ExprError();
21776
21777 // Rewrite the casted expression from scratch.
21778 ExprResult result = RebuildUnknownAnyExpr(*this, CastType).Visit(S: CastExpr);
21779 if (!result.isUsable()) return ExprError();
21780
21781 CastExpr = result.get();
21782 VK = CastExpr->getValueKind();
21783 CastKind = CK_NoOp;
21784
21785 return CastExpr;
21786}
21787
21788ExprResult Sema::forceUnknownAnyToType(Expr *E, QualType ToType) {
21789 return RebuildUnknownAnyExpr(*this, ToType).Visit(S: E);
21790}
21791
21792ExprResult Sema::checkUnknownAnyArg(SourceLocation callLoc,
21793 Expr *arg, QualType &paramType) {
21794 // If the syntactic form of the argument is not an explicit cast of
21795 // any sort, just do default argument promotion.
21796 ExplicitCastExpr *castArg = dyn_cast<ExplicitCastExpr>(Val: arg->IgnoreParens());
21797 if (!castArg) {
21798 ExprResult result = DefaultArgumentPromotion(E: arg);
21799 if (result.isInvalid()) return ExprError();
21800 paramType = result.get()->getType();
21801 return result;
21802 }
21803
21804 // Otherwise, use the type that was written in the explicit cast.
21805 assert(!arg->hasPlaceholderType());
21806 paramType = castArg->getTypeAsWritten();
21807
21808 // Copy-initialize a parameter of that type.
21809 InitializedEntity entity =
21810 InitializedEntity::InitializeParameter(Context, Type: paramType,
21811 /*consumed*/ Consumed: false);
21812 return PerformCopyInitialization(Entity: entity, EqualLoc: callLoc, Init: arg);
21813}
21814
21815static ExprResult diagnoseUnknownAnyExpr(Sema &S, Expr *E) {
21816 Expr *orig = E;
21817 unsigned diagID = diag::err_uncasted_use_of_unknown_any;
21818 while (true) {
21819 E = E->IgnoreParenImpCasts();
21820 if (CallExpr *call = dyn_cast<CallExpr>(Val: E)) {
21821 E = call->getCallee();
21822 diagID = diag::err_uncasted_call_of_unknown_any;
21823 } else {
21824 break;
21825 }
21826 }
21827
21828 SourceLocation loc;
21829 NamedDecl *d;
21830 if (DeclRefExpr *ref = dyn_cast<DeclRefExpr>(Val: E)) {
21831 loc = ref->getLocation();
21832 d = ref->getDecl();
21833 } else if (MemberExpr *mem = dyn_cast<MemberExpr>(Val: E)) {
21834 loc = mem->getMemberLoc();
21835 d = mem->getMemberDecl();
21836 } else if (ObjCMessageExpr *msg = dyn_cast<ObjCMessageExpr>(Val: E)) {
21837 diagID = diag::err_uncasted_call_of_unknown_any;
21838 loc = msg->getSelectorStartLoc();
21839 d = msg->getMethodDecl();
21840 if (!d) {
21841 S.Diag(Loc: loc, DiagID: diag::err_uncasted_send_to_unknown_any_method)
21842 << static_cast<unsigned>(msg->isClassMessage()) << msg->getSelector()
21843 << orig->getSourceRange();
21844 return ExprError();
21845 }
21846 } else {
21847 S.Diag(Loc: E->getExprLoc(), DiagID: diag::err_unsupported_unknown_any_expr)
21848 << E->getSourceRange();
21849 return ExprError();
21850 }
21851
21852 S.Diag(Loc: loc, DiagID: diagID) << d << orig->getSourceRange();
21853
21854 // Never recoverable.
21855 return ExprError();
21856}
21857
21858ExprResult Sema::CheckPlaceholderExpr(Expr *E) {
21859 const BuiltinType *placeholderType = E->getType()->getAsPlaceholderType();
21860 if (!placeholderType) return E;
21861
21862 switch (placeholderType->getKind()) {
21863 case BuiltinType::UnresolvedTemplate: {
21864 auto *ULE = cast<UnresolvedLookupExpr>(Val: E->IgnoreParens());
21865 const DeclarationNameInfo &NameInfo = ULE->getNameInfo();
21866 // There's only one FoundDecl for UnresolvedTemplate type. See
21867 // BuildTemplateIdExpr.
21868 NamedDecl *Temp = *ULE->decls_begin();
21869 const bool IsTypeAliasTemplateDecl = isa<TypeAliasTemplateDecl>(Val: Temp);
21870
21871 NestedNameSpecifier NNS = ULE->getQualifierLoc().getNestedNameSpecifier();
21872 // FIXME: AssumedTemplate is not very appropriate for error recovery here,
21873 // as it models only the unqualified-id case, where this case can clearly be
21874 // qualified. Thus we can't just qualify an assumed template.
21875 TemplateName TN;
21876 if (auto *TD = dyn_cast<TemplateDecl>(Val: Temp))
21877 TN = Context.getQualifiedTemplateName(Qualifier: NNS, TemplateKeyword: ULE->hasTemplateKeyword(),
21878 Template: TemplateName(TD));
21879 else
21880 TN = Context.getAssumedTemplateName(Name: NameInfo.getName());
21881
21882 Diag(Loc: NameInfo.getLoc(), DiagID: diag::err_template_kw_refers_to_type_template)
21883 << TN << ULE->getSourceRange() << IsTypeAliasTemplateDecl;
21884 Diag(Loc: Temp->getLocation(), DiagID: diag::note_referenced_type_template)
21885 << IsTypeAliasTemplateDecl;
21886
21887 TemplateArgumentListInfo TAL(ULE->getLAngleLoc(), ULE->getRAngleLoc());
21888 bool HasAnyDependentTA = false;
21889 for (const TemplateArgumentLoc &Arg : ULE->template_arguments()) {
21890 HasAnyDependentTA |= Arg.getArgument().isDependent();
21891 TAL.addArgument(Loc: Arg);
21892 }
21893
21894 QualType TST;
21895 {
21896 SFINAETrap Trap(*this);
21897 TST = CheckTemplateIdType(
21898 Keyword: ElaboratedTypeKeyword::None, Template: TN, TemplateLoc: NameInfo.getBeginLoc(), TemplateArgs&: TAL,
21899 /*Scope=*/nullptr, /*ForNestedNameSpecifier=*/false);
21900 }
21901 if (TST.isNull())
21902 TST = Context.getTemplateSpecializationType(
21903 Keyword: ElaboratedTypeKeyword::None, T: TN, SpecifiedArgs: ULE->template_arguments(),
21904 /*CanonicalArgs=*/{},
21905 Canon: HasAnyDependentTA ? Context.DependentTy : Context.IntTy);
21906 return CreateRecoveryExpr(Begin: NameInfo.getBeginLoc(), End: NameInfo.getEndLoc(), SubExprs: {},
21907 T: TST);
21908 }
21909
21910 // Overloaded expressions.
21911 case BuiltinType::Overload: {
21912 // Try to resolve a single function template specialization.
21913 // This is obligatory.
21914 ExprResult Result = E;
21915 if (ResolveAndFixSingleFunctionTemplateSpecialization(SrcExpr&: Result, DoFunctionPointerConversion: false))
21916 return Result;
21917
21918 // No guarantees that ResolveAndFixSingleFunctionTemplateSpecialization
21919 // leaves Result unchanged on failure.
21920 Result = E;
21921 if (resolveAndFixAddressOfSingleOverloadCandidate(SrcExpr&: Result))
21922 return Result;
21923
21924 // If that failed, try to recover with a call.
21925 tryToRecoverWithCall(E&: Result, PD: PDiag(DiagID: diag::err_ovl_unresolvable),
21926 /*complain*/ ForceComplain: true);
21927 return Result;
21928 }
21929
21930 // Bound member functions.
21931 case BuiltinType::BoundMember: {
21932 ExprResult result = E;
21933 const Expr *BME = E->IgnoreParens();
21934 PartialDiagnostic PD = PDiag(DiagID: diag::err_bound_member_function);
21935 // Try to give a nicer diagnostic if it is a bound member that we recognize.
21936 if (isa<CXXPseudoDestructorExpr>(Val: BME)) {
21937 PD = PDiag(DiagID: diag::err_dtor_expr_without_call) << /*pseudo-destructor*/ 1;
21938 } else if (const auto *ME = dyn_cast<MemberExpr>(Val: BME)) {
21939 if (ME->getMemberNameInfo().getName().getNameKind() ==
21940 DeclarationName::CXXDestructorName)
21941 PD = PDiag(DiagID: diag::err_dtor_expr_without_call) << /*destructor*/ 0;
21942 }
21943 tryToRecoverWithCall(E&: result, PD,
21944 /*complain*/ ForceComplain: true);
21945 return result;
21946 }
21947
21948 // ARC unbridged casts.
21949 case BuiltinType::ARCUnbridgedCast: {
21950 Expr *realCast = ObjC().stripARCUnbridgedCast(e: E);
21951 ObjC().diagnoseARCUnbridgedCast(e: realCast);
21952 return realCast;
21953 }
21954
21955 // Expressions of unknown type.
21956 case BuiltinType::UnknownAny:
21957 return diagnoseUnknownAnyExpr(S&: *this, E);
21958
21959 // Pseudo-objects.
21960 case BuiltinType::PseudoObject:
21961 return PseudoObject().checkRValue(E);
21962
21963 case BuiltinType::BuiltinFn: {
21964 // Accept __noop without parens by implicitly converting it to a call expr.
21965 auto *DRE = dyn_cast<DeclRefExpr>(Val: E->IgnoreParenImpCasts());
21966 if (DRE) {
21967 auto *FD = cast<FunctionDecl>(Val: DRE->getDecl());
21968 unsigned BuiltinID = FD->getBuiltinID();
21969 if (BuiltinID == Builtin::BI__noop) {
21970 E = ImpCastExprToType(E, Type: Context.getPointerType(T: FD->getType()),
21971 CK: CK_BuiltinFnToFnPtr)
21972 .get();
21973 return CallExpr::Create(Ctx: Context, Fn: E, /*Args=*/{}, Ty: Context.IntTy,
21974 VK: VK_PRValue, RParenLoc: SourceLocation(),
21975 FPFeatures: FPOptionsOverride());
21976 }
21977
21978 if (Context.BuiltinInfo.isInStdNamespace(ID: BuiltinID)) {
21979 // Any use of these other than a direct call is ill-formed as of C++20,
21980 // because they are not addressable functions. In earlier language
21981 // modes, warn and force an instantiation of the real body.
21982 Diag(Loc: E->getBeginLoc(),
21983 DiagID: getLangOpts().CPlusPlus20
21984 ? diag::err_use_of_unaddressable_function
21985 : diag::warn_cxx20_compat_use_of_unaddressable_function);
21986 if (FD->isImplicitlyInstantiable()) {
21987 // Require a definition here because a normal attempt at
21988 // instantiation for a builtin will be ignored, and we won't try
21989 // again later. We assume that the definition of the template
21990 // precedes this use.
21991 InstantiateFunctionDefinition(PointOfInstantiation: E->getBeginLoc(), Function: FD,
21992 /*Recursive=*/false,
21993 /*DefinitionRequired=*/true,
21994 /*AtEndOfTU=*/false);
21995 }
21996 // Produce a properly-typed reference to the function.
21997 CXXScopeSpec SS;
21998 SS.Adopt(Other: DRE->getQualifierLoc());
21999 TemplateArgumentListInfo TemplateArgs;
22000 DRE->copyTemplateArgumentsInto(List&: TemplateArgs);
22001 return BuildDeclRefExpr(
22002 D: FD, Ty: FD->getType(), VK: VK_LValue, NameInfo: DRE->getNameInfo(),
22003 SS: DRE->hasQualifier() ? &SS : nullptr, FoundD: DRE->getFoundDecl(),
22004 TemplateKWLoc: DRE->getTemplateKeywordLoc(),
22005 TemplateArgs: DRE->hasExplicitTemplateArgs() ? &TemplateArgs : nullptr);
22006 }
22007 }
22008
22009 Diag(Loc: E->getBeginLoc(), DiagID: diag::err_builtin_fn_use);
22010 return ExprError();
22011 }
22012
22013 case BuiltinType::IncompleteMatrixIdx: {
22014 auto *MS = cast<MatrixSubscriptExpr>(Val: E->IgnoreParens());
22015 // At this point, we know there was no second [] to complete the operator.
22016 // In HLSL, treat "m[row]" as selecting a row lane of column sized vector.
22017 if (getLangOpts().HLSL) {
22018 return CreateBuiltinMatrixSingleSubscriptExpr(
22019 Base: MS->getBase(), RowIdx: MS->getRowIdx(), RBLoc: E->getExprLoc());
22020 }
22021 Diag(Loc: MS->getRowIdx()->getBeginLoc(), DiagID: diag::err_matrix_incomplete_index);
22022 return ExprError();
22023 }
22024
22025 // Expressions of unknown type.
22026 case BuiltinType::ArraySection:
22027 // If we've already diagnosed something on the array section type, we
22028 // shouldn't need to do any further diagnostic here.
22029 if (!E->containsErrors())
22030 Diag(Loc: E->getBeginLoc(), DiagID: diag::err_array_section_use)
22031 << cast<ArraySectionExpr>(Val: E->IgnoreParens())->isOMPArraySection();
22032 return ExprError();
22033
22034 // Expressions of unknown type.
22035 case BuiltinType::OMPArrayShaping:
22036 return ExprError(Diag(Loc: E->getBeginLoc(), DiagID: diag::err_omp_array_shaping_use));
22037
22038 case BuiltinType::OMPIterator:
22039 return ExprError(Diag(Loc: E->getBeginLoc(), DiagID: diag::err_omp_iterator_use));
22040
22041 // Everything else should be impossible.
22042#define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
22043 case BuiltinType::Id:
22044#include "clang/Basic/OpenCLImageTypes.def"
22045#define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \
22046 case BuiltinType::Id:
22047#include "clang/Basic/OpenCLExtensionTypes.def"
22048#define SVE_TYPE(Name, Id, SingletonId) \
22049 case BuiltinType::Id:
22050#include "clang/Basic/AArch64ACLETypes.def"
22051#define PPC_VECTOR_TYPE(Name, Id, Size) \
22052 case BuiltinType::Id:
22053#include "clang/Basic/PPCTypes.def"
22054#define RVV_TYPE(Name, Id, SingletonId) case BuiltinType::Id:
22055#include "clang/Basic/RISCVVTypes.def"
22056#define WASM_TYPE(Name, Id, SingletonId) case BuiltinType::Id:
22057#include "clang/Basic/WebAssemblyReferenceTypes.def"
22058#define AMDGPU_TYPE(Name, Id, SingletonId, Width, Align) case BuiltinType::Id:
22059#include "clang/Basic/AMDGPUTypes.def"
22060#define HLSL_INTANGIBLE_TYPE(Name, Id, SingletonId) case BuiltinType::Id:
22061#include "clang/Basic/HLSLIntangibleTypes.def"
22062#define BUILTIN_TYPE(Id, SingletonId) case BuiltinType::Id:
22063#define PLACEHOLDER_TYPE(Id, SingletonId)
22064#include "clang/AST/BuiltinTypes.def"
22065 break;
22066 }
22067
22068 llvm_unreachable("invalid placeholder type!");
22069}
22070
22071bool Sema::CheckCaseExpression(Expr *E) {
22072 if (E->isTypeDependent())
22073 return true;
22074 if (E->isValueDependent() || E->isIntegerConstantExpr(Ctx: Context))
22075 return E->getType()->isIntegralOrEnumerationType();
22076 return false;
22077}
22078
22079ExprResult Sema::CreateRecoveryExpr(SourceLocation Begin, SourceLocation End,
22080 ArrayRef<Expr *> SubExprs, QualType T) {
22081 if (!Context.getLangOpts().RecoveryAST)
22082 return ExprError();
22083
22084 if (isSFINAEContext())
22085 return ExprError();
22086
22087 if (T.isNull() || T->isUndeducedType() ||
22088 !Context.getLangOpts().RecoveryASTType)
22089 // We don't know the concrete type, fallback to dependent type.
22090 T = Context.DependentTy;
22091
22092 return RecoveryExpr::Create(Ctx&: Context, T, BeginLoc: Begin, EndLoc: End, SubExprs);
22093}
22094