Bug Summary

File:build/source/clang/lib/Sema/SemaExpr.cpp
Warning:line 7339, column 12
Called C++ object pointer is null

Annotated Source Code

Press '?' to see keyboard shortcuts

clang -cc1 -cc1 -triple x86_64-pc-linux-gnu -analyze -disable-free -clear-ast-before-backend -disable-llvm-verifier -discard-value-names -main-file-name SemaExpr.cpp -analyzer-checker=core -analyzer-checker=apiModeling -analyzer-checker=unix -analyzer-checker=deadcode -analyzer-checker=cplusplus -analyzer-checker=security.insecureAPI.UncheckedReturn -analyzer-checker=security.insecureAPI.getpw -analyzer-checker=security.insecureAPI.gets -analyzer-checker=security.insecureAPI.mktemp -analyzer-checker=security.insecureAPI.mkstemp -analyzer-checker=security.insecureAPI.vfork -analyzer-checker=nullability.NullPassedToNonnull -analyzer-checker=nullability.NullReturnedFromNonnull -analyzer-output plist -w -setup-static-analyzer -analyzer-config-compatibility-mode=true -mrelocation-model pic -pic-level 2 -mframe-pointer=none -relaxed-aliasing -fmath-errno -ffp-contract=on -fno-rounding-math -mconstructor-aliases -funwind-tables=2 -target-cpu x86-64 -tune-cpu generic -debugger-tuning=gdb -ffunction-sections -fdata-sections -fcoverage-compilation-dir=/build/source/build-llvm -resource-dir /usr/lib/llvm-17/lib/clang/17 -I tools/clang/lib/Sema -I /build/source/clang/lib/Sema -I /build/source/clang/include -I tools/clang/include -I include -I /build/source/llvm/include -D _DEBUG -D _GLIBCXX_ASSERTIONS -D _GNU_SOURCE -D _LIBCPP_ENABLE_ASSERTIONS -D __STDC_CONSTANT_MACROS -D __STDC_FORMAT_MACROS -D __STDC_LIMIT_MACROS -D _FORTIFY_SOURCE=2 -D NDEBUG -U NDEBUG -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/10/../../../../include/c++/10 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/10/../../../../include/x86_64-linux-gnu/c++/10 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/10/../../../../include/c++/10/backward -internal-isystem /usr/lib/llvm-17/lib/clang/17/include -internal-isystem /usr/local/include -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/10/../../../../x86_64-linux-gnu/include -internal-externc-isystem /usr/include/x86_64-linux-gnu -internal-externc-isystem /include -internal-externc-isystem /usr/include -fmacro-prefix-map=/build/source/build-llvm=build-llvm -fmacro-prefix-map=/build/source/= -fcoverage-prefix-map=/build/source/build-llvm=build-llvm -fcoverage-prefix-map=/build/source/= -O3 -Wno-unused-command-line-argument -Wno-unused-parameter -Wwrite-strings -Wno-missing-field-initializers -Wno-long-long -Wno-maybe-uninitialized -Wno-class-memaccess -Wno-redundant-move -Wno-pessimizing-move -Wno-noexcept-type -Wno-comment -Wno-misleading-indentation -std=c++17 -fdeprecated-macro -fdebug-compilation-dir=/build/source/build-llvm -fdebug-prefix-map=/build/source/build-llvm=build-llvm -fdebug-prefix-map=/build/source/= -fdebug-prefix-map=/build/source/build-llvm=build-llvm -fdebug-prefix-map=/build/source/= -ferror-limit 19 -fvisibility-inlines-hidden -stack-protector 2 -fgnuc-version=4.2.1 -fcolor-diagnostics -vectorize-loops -vectorize-slp -analyzer-output=html -analyzer-config stable-report-filename=true -faddrsig -D__GCC_HAVE_DWARF2_CFI_ASM=1 -o /tmp/scan-build-2023-05-10-133810-16478-1 -x c++ /build/source/clang/lib/Sema/SemaExpr.cpp
1//===--- SemaExpr.cpp - Semantic Analysis for Expressions -----------------===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8//
9// This file implements semantic analysis for expressions.
10//
11//===----------------------------------------------------------------------===//
12
13#include "TreeTransform.h"
14#include "UsedDeclVisitor.h"
15#include "clang/AST/ASTConsumer.h"
16#include "clang/AST/ASTContext.h"
17#include "clang/AST/ASTLambda.h"
18#include "clang/AST/ASTMutationListener.h"
19#include "clang/AST/CXXInheritance.h"
20#include "clang/AST/DeclObjC.h"
21#include "clang/AST/DeclTemplate.h"
22#include "clang/AST/EvaluatedExprVisitor.h"
23#include "clang/AST/Expr.h"
24#include "clang/AST/ExprCXX.h"
25#include "clang/AST/ExprObjC.h"
26#include "clang/AST/ExprOpenMP.h"
27#include "clang/AST/OperationKinds.h"
28#include "clang/AST/ParentMapContext.h"
29#include "clang/AST/RecursiveASTVisitor.h"
30#include "clang/AST/Type.h"
31#include "clang/AST/TypeLoc.h"
32#include "clang/Basic/Builtins.h"
33#include "clang/Basic/DiagnosticSema.h"
34#include "clang/Basic/PartialDiagnostic.h"
35#include "clang/Basic/SourceManager.h"
36#include "clang/Basic/Specifiers.h"
37#include "clang/Basic/TargetInfo.h"
38#include "clang/Lex/LiteralSupport.h"
39#include "clang/Lex/Preprocessor.h"
40#include "clang/Sema/AnalysisBasedWarnings.h"
41#include "clang/Sema/DeclSpec.h"
42#include "clang/Sema/DelayedDiagnostic.h"
43#include "clang/Sema/Designator.h"
44#include "clang/Sema/EnterExpressionEvaluationContext.h"
45#include "clang/Sema/Initialization.h"
46#include "clang/Sema/Lookup.h"
47#include "clang/Sema/Overload.h"
48#include "clang/Sema/ParsedTemplate.h"
49#include "clang/Sema/Scope.h"
50#include "clang/Sema/ScopeInfo.h"
51#include "clang/Sema/SemaFixItUtils.h"
52#include "clang/Sema/SemaInternal.h"
53#include "clang/Sema/Template.h"
54#include "llvm/ADT/STLExtras.h"
55#include "llvm/ADT/StringExtras.h"
56#include "llvm/Support/Casting.h"
57#include "llvm/Support/ConvertUTF.h"
58#include "llvm/Support/SaveAndRestore.h"
59#include "llvm/Support/TypeSize.h"
60#include <optional>
61
62using namespace clang;
63using namespace sema;
64
65/// Determine whether the use of this declaration is valid, without
66/// emitting diagnostics.
67bool Sema::CanUseDecl(NamedDecl *D, bool TreatUnavailableAsInvalid) {
68 // See if this is an auto-typed variable whose initializer we are parsing.
69 if (ParsingInitForAutoVars.count(D))
70 return false;
71
72 // See if this is a deleted function.
73 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
74 if (FD->isDeleted())
75 return false;
76
77 // If the function has a deduced return type, and we can't deduce it,
78 // then we can't use it either.
79 if (getLangOpts().CPlusPlus14 && FD->getReturnType()->isUndeducedType() &&
80 DeduceReturnType(FD, SourceLocation(), /*Diagnose*/ false))
81 return false;
82
83 // See if this is an aligned allocation/deallocation function that is
84 // unavailable.
85 if (TreatUnavailableAsInvalid &&
86 isUnavailableAlignedAllocationFunction(*FD))
87 return false;
88 }
89
90 // See if this function is unavailable.
91 if (TreatUnavailableAsInvalid && D->getAvailability() == AR_Unavailable &&
92 cast<Decl>(CurContext)->getAvailability() != AR_Unavailable)
93 return false;
94
95 if (isa<UnresolvedUsingIfExistsDecl>(D))
96 return false;
97
98 return true;
99}
100
101static void DiagnoseUnusedOfDecl(Sema &S, NamedDecl *D, SourceLocation Loc) {
102 // Warn if this is used but marked unused.
103 if (const auto *A = D->getAttr<UnusedAttr>()) {
104 // [[maybe_unused]] should not diagnose uses, but __attribute__((unused))
105 // should diagnose them.
106 if (A->getSemanticSpelling() != UnusedAttr::CXX11_maybe_unused &&
107 A->getSemanticSpelling() != UnusedAttr::C2x_maybe_unused) {
108 const Decl *DC = cast_or_null<Decl>(S.getCurObjCLexicalContext());
109 if (DC && !DC->hasAttr<UnusedAttr>())
110 S.Diag(Loc, diag::warn_used_but_marked_unused) << D;
111 }
112 }
113}
114
115/// Emit a note explaining that this function is deleted.
116void Sema::NoteDeletedFunction(FunctionDecl *Decl) {
117 assert(Decl && Decl->isDeleted())(static_cast <bool> (Decl && Decl->isDeleted
()) ? void (0) : __assert_fail ("Decl && Decl->isDeleted()"
, "clang/lib/Sema/SemaExpr.cpp", 117, __extension__ __PRETTY_FUNCTION__
))
;
118
119 if (Decl->isDefaulted()) {
120 // If the method was explicitly defaulted, point at that declaration.
121 if (!Decl->isImplicit())
122 Diag(Decl->getLocation(), diag::note_implicitly_deleted);
123
124 // Try to diagnose why this special member function was implicitly
125 // deleted. This might fail, if that reason no longer applies.
126 DiagnoseDeletedDefaultedFunction(Decl);
127 return;
128 }
129
130 auto *Ctor = dyn_cast<CXXConstructorDecl>(Decl);
131 if (Ctor && Ctor->isInheritingConstructor())
132 return NoteDeletedInheritingConstructor(Ctor);
133
134 Diag(Decl->getLocation(), diag::note_availability_specified_here)
135 << Decl << 1;
136}
137
138/// Determine whether a FunctionDecl was ever declared with an
139/// explicit storage class.
140static bool hasAnyExplicitStorageClass(const FunctionDecl *D) {
141 for (auto *I : D->redecls()) {
142 if (I->getStorageClass() != SC_None)
143 return true;
144 }
145 return false;
146}
147
148/// Check whether we're in an extern inline function and referring to a
149/// variable or function with internal linkage (C11 6.7.4p3).
150///
151/// This is only a warning because we used to silently accept this code, but
152/// in many cases it will not behave correctly. This is not enabled in C++ mode
153/// because the restriction language is a bit weaker (C++11 [basic.def.odr]p6)
154/// and so while there may still be user mistakes, most of the time we can't
155/// prove that there are errors.
156static void diagnoseUseOfInternalDeclInInlineFunction(Sema &S,
157 const NamedDecl *D,
158 SourceLocation Loc) {
159 // This is disabled under C++; there are too many ways for this to fire in
160 // contexts where the warning is a false positive, or where it is technically
161 // correct but benign.
162 if (S.getLangOpts().CPlusPlus)
163 return;
164
165 // Check if this is an inlined function or method.
166 FunctionDecl *Current = S.getCurFunctionDecl();
167 if (!Current)
168 return;
169 if (!Current->isInlined())
170 return;
171 if (!Current->isExternallyVisible())
172 return;
173
174 // Check if the decl has internal linkage.
175 if (D->getFormalLinkage() != InternalLinkage)
176 return;
177
178 // Downgrade from ExtWarn to Extension if
179 // (1) the supposedly external inline function is in the main file,
180 // and probably won't be included anywhere else.
181 // (2) the thing we're referencing is a pure function.
182 // (3) the thing we're referencing is another inline function.
183 // This last can give us false negatives, but it's better than warning on
184 // wrappers for simple C library functions.
185 const FunctionDecl *UsedFn = dyn_cast<FunctionDecl>(D);
186 bool DowngradeWarning = S.getSourceManager().isInMainFile(Loc);
187 if (!DowngradeWarning && UsedFn)
188 DowngradeWarning = UsedFn->isInlined() || UsedFn->hasAttr<ConstAttr>();
189
190 S.Diag(Loc, DowngradeWarning ? diag::ext_internal_in_extern_inline_quiet
191 : diag::ext_internal_in_extern_inline)
192 << /*IsVar=*/!UsedFn << D;
193
194 S.MaybeSuggestAddingStaticToDecl(Current);
195
196 S.Diag(D->getCanonicalDecl()->getLocation(), diag::note_entity_declared_at)
197 << D;
198}
199
200void Sema::MaybeSuggestAddingStaticToDecl(const FunctionDecl *Cur) {
201 const FunctionDecl *First = Cur->getFirstDecl();
202
203 // Suggest "static" on the function, if possible.
204 if (!hasAnyExplicitStorageClass(First)) {
205 SourceLocation DeclBegin = First->getSourceRange().getBegin();
206 Diag(DeclBegin, diag::note_convert_inline_to_static)
207 << Cur << FixItHint::CreateInsertion(DeclBegin, "static ");
208 }
209}
210
211/// Determine whether the use of this declaration is valid, and
212/// emit any corresponding diagnostics.
213///
214/// This routine diagnoses various problems with referencing
215/// declarations that can occur when using a declaration. For example,
216/// it might warn if a deprecated or unavailable declaration is being
217/// used, or produce an error (and return true) if a C++0x deleted
218/// function is being used.
219///
220/// \returns true if there was an error (this declaration cannot be
221/// referenced), false otherwise.
222///
223bool Sema::DiagnoseUseOfDecl(NamedDecl *D, ArrayRef<SourceLocation> Locs,
224 const ObjCInterfaceDecl *UnknownObjCClass,
225 bool ObjCPropertyAccess,
226 bool AvoidPartialAvailabilityChecks,
227 ObjCInterfaceDecl *ClassReceiver,
228 bool SkipTrailingRequiresClause) {
229 SourceLocation Loc = Locs.front();
230 if (getLangOpts().CPlusPlus && isa<FunctionDecl>(D)) {
231 // If there were any diagnostics suppressed by template argument deduction,
232 // emit them now.
233 auto Pos = SuppressedDiagnostics.find(D->getCanonicalDecl());
234 if (Pos != SuppressedDiagnostics.end()) {
235 for (const PartialDiagnosticAt &Suppressed : Pos->second)
236 Diag(Suppressed.first, Suppressed.second);
237
238 // Clear out the list of suppressed diagnostics, so that we don't emit
239 // them again for this specialization. However, we don't obsolete this
240 // entry from the table, because we want to avoid ever emitting these
241 // diagnostics again.
242 Pos->second.clear();
243 }
244
245 // C++ [basic.start.main]p3:
246 // The function 'main' shall not be used within a program.
247 if (cast<FunctionDecl>(D)->isMain())
248 Diag(Loc, diag::ext_main_used);
249
250 diagnoseUnavailableAlignedAllocation(*cast<FunctionDecl>(D), Loc);
251 }
252
253 // See if this is an auto-typed variable whose initializer we are parsing.
254 if (ParsingInitForAutoVars.count(D)) {
255 if (isa<BindingDecl>(D)) {
256 Diag(Loc, diag::err_binding_cannot_appear_in_own_initializer)
257 << D->getDeclName();
258 } else {
259 Diag(Loc, diag::err_auto_variable_cannot_appear_in_own_initializer)
260 << D->getDeclName() << cast<VarDecl>(D)->getType();
261 }
262 return true;
263 }
264
265 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
266 // See if this is a deleted function.
267 if (FD->isDeleted()) {
268 auto *Ctor = dyn_cast<CXXConstructorDecl>(FD);
269 if (Ctor && Ctor->isInheritingConstructor())
270 Diag(Loc, diag::err_deleted_inherited_ctor_use)
271 << Ctor->getParent()
272 << Ctor->getInheritedConstructor().getConstructor()->getParent();
273 else
274 Diag(Loc, diag::err_deleted_function_use);
275 NoteDeletedFunction(FD);
276 return true;
277 }
278
279 // [expr.prim.id]p4
280 // A program that refers explicitly or implicitly to a function with a
281 // trailing requires-clause whose constraint-expression is not satisfied,
282 // other than to declare it, is ill-formed. [...]
283 //
284 // See if this is a function with constraints that need to be satisfied.
285 // Check this before deducing the return type, as it might instantiate the
286 // definition.
287 if (!SkipTrailingRequiresClause && FD->getTrailingRequiresClause()) {
288 ConstraintSatisfaction Satisfaction;
289 if (CheckFunctionConstraints(FD, Satisfaction, Loc,
290 /*ForOverloadResolution*/ true))
291 // A diagnostic will have already been generated (non-constant
292 // constraint expression, for example)
293 return true;
294 if (!Satisfaction.IsSatisfied) {
295 Diag(Loc,
296 diag::err_reference_to_function_with_unsatisfied_constraints)
297 << D;
298 DiagnoseUnsatisfiedConstraint(Satisfaction);
299 return true;
300 }
301 }
302
303 // If the function has a deduced return type, and we can't deduce it,
304 // then we can't use it either.
305 if (getLangOpts().CPlusPlus14 && FD->getReturnType()->isUndeducedType() &&
306 DeduceReturnType(FD, Loc))
307 return true;
308
309 if (getLangOpts().CUDA && !CheckCUDACall(Loc, FD))
310 return true;
311
312 }
313
314 if (auto *MD = dyn_cast<CXXMethodDecl>(D)) {
315 // Lambdas are only default-constructible or assignable in C++2a onwards.
316 if (MD->getParent()->isLambda() &&
317 ((isa<CXXConstructorDecl>(MD) &&
318 cast<CXXConstructorDecl>(MD)->isDefaultConstructor()) ||
319 MD->isCopyAssignmentOperator() || MD->isMoveAssignmentOperator())) {
320 Diag(Loc, diag::warn_cxx17_compat_lambda_def_ctor_assign)
321 << !isa<CXXConstructorDecl>(MD);
322 }
323 }
324
325 auto getReferencedObjCProp = [](const NamedDecl *D) ->
326 const ObjCPropertyDecl * {
327 if (const auto *MD = dyn_cast<ObjCMethodDecl>(D))
328 return MD->findPropertyDecl();
329 return nullptr;
330 };
331 if (const ObjCPropertyDecl *ObjCPDecl = getReferencedObjCProp(D)) {
332 if (diagnoseArgIndependentDiagnoseIfAttrs(ObjCPDecl, Loc))
333 return true;
334 } else if (diagnoseArgIndependentDiagnoseIfAttrs(D, Loc)) {
335 return true;
336 }
337
338 // [OpenMP 4.0], 2.15 declare reduction Directive, Restrictions
339 // Only the variables omp_in and omp_out are allowed in the combiner.
340 // Only the variables omp_priv and omp_orig are allowed in the
341 // initializer-clause.
342 auto *DRD = dyn_cast<OMPDeclareReductionDecl>(CurContext);
343 if (LangOpts.OpenMP && DRD && !CurContext->containsDecl(D) &&
344 isa<VarDecl>(D)) {
345 Diag(Loc, diag::err_omp_wrong_var_in_declare_reduction)
346 << getCurFunction()->HasOMPDeclareReductionCombiner;
347 Diag(D->getLocation(), diag::note_entity_declared_at) << D;
348 return true;
349 }
350
351 // [OpenMP 5.0], 2.19.7.3. declare mapper Directive, Restrictions
352 // List-items in map clauses on this construct may only refer to the declared
353 // variable var and entities that could be referenced by a procedure defined
354 // at the same location.
355 // [OpenMP 5.2] Also allow iterator declared variables.
356 if (LangOpts.OpenMP && isa<VarDecl>(D) &&
357 !isOpenMPDeclareMapperVarDeclAllowed(cast<VarDecl>(D))) {
358 Diag(Loc, diag::err_omp_declare_mapper_wrong_var)
359 << getOpenMPDeclareMapperVarName();
360 Diag(D->getLocation(), diag::note_entity_declared_at) << D;
361 return true;
362 }
363
364 if (const auto *EmptyD = dyn_cast<UnresolvedUsingIfExistsDecl>(D)) {
365 Diag(Loc, diag::err_use_of_empty_using_if_exists);
366 Diag(EmptyD->getLocation(), diag::note_empty_using_if_exists_here);
367 return true;
368 }
369
370 DiagnoseAvailabilityOfDecl(D, Locs, UnknownObjCClass, ObjCPropertyAccess,
371 AvoidPartialAvailabilityChecks, ClassReceiver);
372
373 DiagnoseUnusedOfDecl(*this, D, Loc);
374
375 diagnoseUseOfInternalDeclInInlineFunction(*this, D, Loc);
376
377 if (auto *VD = dyn_cast<ValueDecl>(D))
378 checkTypeSupport(VD->getType(), Loc, VD);
379
380 if (LangOpts.SYCLIsDevice || (LangOpts.OpenMP && LangOpts.OpenMPIsDevice)) {
381 if (!Context.getTargetInfo().isTLSSupported())
382 if (const auto *VD = dyn_cast<VarDecl>(D))
383 if (VD->getTLSKind() != VarDecl::TLS_None)
384 targetDiag(*Locs.begin(), diag::err_thread_unsupported);
385 }
386
387 if (isa<ParmVarDecl>(D) && isa<RequiresExprBodyDecl>(D->getDeclContext()) &&
388 !isUnevaluatedContext()) {
389 // C++ [expr.prim.req.nested] p3
390 // A local parameter shall only appear as an unevaluated operand
391 // (Clause 8) within the constraint-expression.
392 Diag(Loc, diag::err_requires_expr_parameter_referenced_in_evaluated_context)
393 << D;
394 Diag(D->getLocation(), diag::note_entity_declared_at) << D;
395 return true;
396 }
397
398 return false;
399}
400
401/// DiagnoseSentinelCalls - This routine checks whether a call or
402/// message-send is to a declaration with the sentinel attribute, and
403/// if so, it checks that the requirements of the sentinel are
404/// satisfied.
405void Sema::DiagnoseSentinelCalls(NamedDecl *D, SourceLocation Loc,
406 ArrayRef<Expr *> Args) {
407 const SentinelAttr *attr = D->getAttr<SentinelAttr>();
408 if (!attr)
409 return;
410
411 // The number of formal parameters of the declaration.
412 unsigned numFormalParams;
413
414 // The kind of declaration. This is also an index into a %select in
415 // the diagnostic.
416 enum CalleeType { CT_Function, CT_Method, CT_Block } calleeType;
417
418 if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) {
419 numFormalParams = MD->param_size();
420 calleeType = CT_Method;
421 } else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
422 numFormalParams = FD->param_size();
423 calleeType = CT_Function;
424 } else if (isa<VarDecl>(D)) {
425 QualType type = cast<ValueDecl>(D)->getType();
426 const FunctionType *fn = nullptr;
427 if (const PointerType *ptr = type->getAs<PointerType>()) {
428 fn = ptr->getPointeeType()->getAs<FunctionType>();
429 if (!fn) return;
430 calleeType = CT_Function;
431 } else if (const BlockPointerType *ptr = type->getAs<BlockPointerType>()) {
432 fn = ptr->getPointeeType()->castAs<FunctionType>();
433 calleeType = CT_Block;
434 } else {
435 return;
436 }
437
438 if (const FunctionProtoType *proto = dyn_cast<FunctionProtoType>(fn)) {
439 numFormalParams = proto->getNumParams();
440 } else {
441 numFormalParams = 0;
442 }
443 } else {
444 return;
445 }
446
447 // "nullPos" is the number of formal parameters at the end which
448 // effectively count as part of the variadic arguments. This is
449 // useful if you would prefer to not have *any* formal parameters,
450 // but the language forces you to have at least one.
451 unsigned nullPos = attr->getNullPos();
452 assert((nullPos == 0 || nullPos == 1) && "invalid null position on sentinel")(static_cast <bool> ((nullPos == 0 || nullPos == 1) &&
"invalid null position on sentinel") ? void (0) : __assert_fail
("(nullPos == 0 || nullPos == 1) && \"invalid null position on sentinel\""
, "clang/lib/Sema/SemaExpr.cpp", 452, __extension__ __PRETTY_FUNCTION__
))
;
453 numFormalParams = (nullPos > numFormalParams ? 0 : numFormalParams - nullPos);
454
455 // The number of arguments which should follow the sentinel.
456 unsigned numArgsAfterSentinel = attr->getSentinel();
457
458 // If there aren't enough arguments for all the formal parameters,
459 // the sentinel, and the args after the sentinel, complain.
460 if (Args.size() < numFormalParams + numArgsAfterSentinel + 1) {
461 Diag(Loc, diag::warn_not_enough_argument) << D->getDeclName();
462 Diag(D->getLocation(), diag::note_sentinel_here) << int(calleeType);
463 return;
464 }
465
466 // Otherwise, find the sentinel expression.
467 Expr *sentinelExpr = Args[Args.size() - numArgsAfterSentinel - 1];
468 if (!sentinelExpr) return;
469 if (sentinelExpr->isValueDependent()) return;
470 if (Context.isSentinelNullExpr(sentinelExpr)) return;
471
472 // Pick a reasonable string to insert. Optimistically use 'nil', 'nullptr',
473 // or 'NULL' if those are actually defined in the context. Only use
474 // 'nil' for ObjC methods, where it's much more likely that the
475 // variadic arguments form a list of object pointers.
476 SourceLocation MissingNilLoc = getLocForEndOfToken(sentinelExpr->getEndLoc());
477 std::string NullValue;
478 if (calleeType == CT_Method && PP.isMacroDefined("nil"))
479 NullValue = "nil";
480 else if (getLangOpts().CPlusPlus11)
481 NullValue = "nullptr";
482 else if (PP.isMacroDefined("NULL"))
483 NullValue = "NULL";
484 else
485 NullValue = "(void*) 0";
486
487 if (MissingNilLoc.isInvalid())
488 Diag(Loc, diag::warn_missing_sentinel) << int(calleeType);
489 else
490 Diag(MissingNilLoc, diag::warn_missing_sentinel)
491 << int(calleeType)
492 << FixItHint::CreateInsertion(MissingNilLoc, ", " + NullValue);
493 Diag(D->getLocation(), diag::note_sentinel_here) << int(calleeType);
494}
495
496SourceRange Sema::getExprRange(Expr *E) const {
497 return E ? E->getSourceRange() : SourceRange();
498}
499
500//===----------------------------------------------------------------------===//
501// Standard Promotions and Conversions
502//===----------------------------------------------------------------------===//
503
504/// DefaultFunctionArrayConversion (C99 6.3.2.1p3, C99 6.3.2.1p4).
505ExprResult Sema::DefaultFunctionArrayConversion(Expr *E, bool Diagnose) {
506 // Handle any placeholder expressions which made it here.
507 if (E->hasPlaceholderType()) {
508 ExprResult result = CheckPlaceholderExpr(E);
509 if (result.isInvalid()) return ExprError();
510 E = result.get();
511 }
512
513 QualType Ty = E->getType();
514 assert(!Ty.isNull() && "DefaultFunctionArrayConversion - missing type")(static_cast <bool> (!Ty.isNull() && "DefaultFunctionArrayConversion - missing type"
) ? void (0) : __assert_fail ("!Ty.isNull() && \"DefaultFunctionArrayConversion - missing type\""
, "clang/lib/Sema/SemaExpr.cpp", 514, __extension__ __PRETTY_FUNCTION__
))
;
515
516 if (Ty->isFunctionType()) {
517 if (auto *DRE = dyn_cast<DeclRefExpr>(E->IgnoreParenCasts()))
518 if (auto *FD = dyn_cast<FunctionDecl>(DRE->getDecl()))
519 if (!checkAddressOfFunctionIsAvailable(FD, Diagnose, E->getExprLoc()))
520 return ExprError();
521
522 E = ImpCastExprToType(E, Context.getPointerType(Ty),
523 CK_FunctionToPointerDecay).get();
524 } else if (Ty->isArrayType()) {
525 // In C90 mode, arrays only promote to pointers if the array expression is
526 // an lvalue. The relevant legalese is C90 6.2.2.1p3: "an lvalue that has
527 // type 'array of type' is converted to an expression that has type 'pointer
528 // to type'...". In C99 this was changed to: C99 6.3.2.1p3: "an expression
529 // that has type 'array of type' ...". The relevant change is "an lvalue"
530 // (C90) to "an expression" (C99).
531 //
532 // C++ 4.2p1:
533 // An lvalue or rvalue of type "array of N T" or "array of unknown bound of
534 // T" can be converted to an rvalue of type "pointer to T".
535 //
536 if (getLangOpts().C99 || getLangOpts().CPlusPlus || E->isLValue()) {
537 ExprResult Res = ImpCastExprToType(E, Context.getArrayDecayedType(Ty),
538 CK_ArrayToPointerDecay);
539 if (Res.isInvalid())
540 return ExprError();
541 E = Res.get();
542 }
543 }
544 return E;
545}
546
547static void CheckForNullPointerDereference(Sema &S, Expr *E) {
548 // Check to see if we are dereferencing a null pointer. If so,
549 // and if not volatile-qualified, this is undefined behavior that the
550 // optimizer will delete, so warn about it. People sometimes try to use this
551 // to get a deterministic trap and are surprised by clang's behavior. This
552 // only handles the pattern "*null", which is a very syntactic check.
553 const auto *UO = dyn_cast<UnaryOperator>(E->IgnoreParenCasts());
554 if (UO && UO->getOpcode() == UO_Deref &&
555 UO->getSubExpr()->getType()->isPointerType()) {
556 const LangAS AS =
557 UO->getSubExpr()->getType()->getPointeeType().getAddressSpace();
558 if ((!isTargetAddressSpace(AS) ||
559 (isTargetAddressSpace(AS) && toTargetAddressSpace(AS) == 0)) &&
560 UO->getSubExpr()->IgnoreParenCasts()->isNullPointerConstant(
561 S.Context, Expr::NPC_ValueDependentIsNotNull) &&
562 !UO->getType().isVolatileQualified()) {
563 S.DiagRuntimeBehavior(UO->getOperatorLoc(), UO,
564 S.PDiag(diag::warn_indirection_through_null)
565 << UO->getSubExpr()->getSourceRange());
566 S.DiagRuntimeBehavior(UO->getOperatorLoc(), UO,
567 S.PDiag(diag::note_indirection_through_null));
568 }
569 }
570}
571
572static void DiagnoseDirectIsaAccess(Sema &S, const ObjCIvarRefExpr *OIRE,
573 SourceLocation AssignLoc,
574 const Expr* RHS) {
575 const ObjCIvarDecl *IV = OIRE->getDecl();
576 if (!IV)
577 return;
578
579 DeclarationName MemberName = IV->getDeclName();
580 IdentifierInfo *Member = MemberName.getAsIdentifierInfo();
581 if (!Member || !Member->isStr("isa"))
582 return;
583
584 const Expr *Base = OIRE->getBase();
585 QualType BaseType = Base->getType();
586 if (OIRE->isArrow())
587 BaseType = BaseType->getPointeeType();
588 if (const ObjCObjectType *OTy = BaseType->getAs<ObjCObjectType>())
589 if (ObjCInterfaceDecl *IDecl = OTy->getInterface()) {
590 ObjCInterfaceDecl *ClassDeclared = nullptr;
591 ObjCIvarDecl *IV = IDecl->lookupInstanceVariable(Member, ClassDeclared);
592 if (!ClassDeclared->getSuperClass()
593 && (*ClassDeclared->ivar_begin()) == IV) {
594 if (RHS) {
595 NamedDecl *ObjectSetClass =
596 S.LookupSingleName(S.TUScope,
597 &S.Context.Idents.get("object_setClass"),
598 SourceLocation(), S.LookupOrdinaryName);
599 if (ObjectSetClass) {
600 SourceLocation RHSLocEnd = S.getLocForEndOfToken(RHS->getEndLoc());
601 S.Diag(OIRE->getExprLoc(), diag::warn_objc_isa_assign)
602 << FixItHint::CreateInsertion(OIRE->getBeginLoc(),
603 "object_setClass(")
604 << FixItHint::CreateReplacement(
605 SourceRange(OIRE->getOpLoc(), AssignLoc), ",")
606 << FixItHint::CreateInsertion(RHSLocEnd, ")");
607 }
608 else
609 S.Diag(OIRE->getLocation(), diag::warn_objc_isa_assign);
610 } else {
611 NamedDecl *ObjectGetClass =
612 S.LookupSingleName(S.TUScope,
613 &S.Context.Idents.get("object_getClass"),
614 SourceLocation(), S.LookupOrdinaryName);
615 if (ObjectGetClass)
616 S.Diag(OIRE->getExprLoc(), diag::warn_objc_isa_use)
617 << FixItHint::CreateInsertion(OIRE->getBeginLoc(),
618 "object_getClass(")
619 << FixItHint::CreateReplacement(
620 SourceRange(OIRE->getOpLoc(), OIRE->getEndLoc()), ")");
621 else
622 S.Diag(OIRE->getLocation(), diag::warn_objc_isa_use);
623 }
624 S.Diag(IV->getLocation(), diag::note_ivar_decl);
625 }
626 }
627}
628
629ExprResult Sema::DefaultLvalueConversion(Expr *E) {
630 // Handle any placeholder expressions which made it here.
631 if (E->hasPlaceholderType()) {
632 ExprResult result = CheckPlaceholderExpr(E);
633 if (result.isInvalid()) return ExprError();
634 E = result.get();
635 }
636
637 // C++ [conv.lval]p1:
638 // A glvalue of a non-function, non-array type T can be
639 // converted to a prvalue.
640 if (!E->isGLValue()) return E;
641
642 QualType T = E->getType();
643 assert(!T.isNull() && "r-value conversion on typeless expression?")(static_cast <bool> (!T.isNull() && "r-value conversion on typeless expression?"
) ? void (0) : __assert_fail ("!T.isNull() && \"r-value conversion on typeless expression?\""
, "clang/lib/Sema/SemaExpr.cpp", 643, __extension__ __PRETTY_FUNCTION__
))
;
644
645 // lvalue-to-rvalue conversion cannot be applied to function or array types.
646 if (T->isFunctionType() || T->isArrayType())
647 return E;
648
649 // We don't want to throw lvalue-to-rvalue casts on top of
650 // expressions of certain types in C++.
651 if (getLangOpts().CPlusPlus &&
652 (E->getType() == Context.OverloadTy ||
653 T->isDependentType() ||
654 T->isRecordType()))
655 return E;
656
657 // The C standard is actually really unclear on this point, and
658 // DR106 tells us what the result should be but not why. It's
659 // generally best to say that void types just doesn't undergo
660 // lvalue-to-rvalue at all. Note that expressions of unqualified
661 // 'void' type are never l-values, but qualified void can be.
662 if (T->isVoidType())
663 return E;
664
665 // OpenCL usually rejects direct accesses to values of 'half' type.
666 if (getLangOpts().OpenCL &&
667 !getOpenCLOptions().isAvailableOption("cl_khr_fp16", getLangOpts()) &&
668 T->isHalfType()) {
669 Diag(E->getExprLoc(), diag::err_opencl_half_load_store)
670 << 0 << T;
671 return ExprError();
672 }
673
674 CheckForNullPointerDereference(*this, E);
675 if (const ObjCIsaExpr *OISA = dyn_cast<ObjCIsaExpr>(E->IgnoreParenCasts())) {
676 NamedDecl *ObjectGetClass = LookupSingleName(TUScope,
677 &Context.Idents.get("object_getClass"),
678 SourceLocation(), LookupOrdinaryName);
679 if (ObjectGetClass)
680 Diag(E->getExprLoc(), diag::warn_objc_isa_use)
681 << FixItHint::CreateInsertion(OISA->getBeginLoc(), "object_getClass(")
682 << FixItHint::CreateReplacement(
683 SourceRange(OISA->getOpLoc(), OISA->getIsaMemberLoc()), ")");
684 else
685 Diag(E->getExprLoc(), diag::warn_objc_isa_use);
686 }
687 else if (const ObjCIvarRefExpr *OIRE =
688 dyn_cast<ObjCIvarRefExpr>(E->IgnoreParenCasts()))
689 DiagnoseDirectIsaAccess(*this, OIRE, SourceLocation(), /* Expr*/nullptr);
690
691 // C++ [conv.lval]p1:
692 // [...] If T is a non-class type, the type of the prvalue is the
693 // cv-unqualified version of T. Otherwise, the type of the
694 // rvalue is T.
695 //
696 // C99 6.3.2.1p2:
697 // If the lvalue has qualified type, the value has the unqualified
698 // version of the type of the lvalue; otherwise, the value has the
699 // type of the lvalue.
700 if (T.hasQualifiers())
701 T = T.getUnqualifiedType();
702
703 // Under the MS ABI, lock down the inheritance model now.
704 if (T->isMemberPointerType() &&
705 Context.getTargetInfo().getCXXABI().isMicrosoft())
706 (void)isCompleteType(E->getExprLoc(), T);
707
708 ExprResult Res = CheckLValueToRValueConversionOperand(E);
709 if (Res.isInvalid())
710 return Res;
711 E = Res.get();
712
713 // Loading a __weak object implicitly retains the value, so we need a cleanup to
714 // balance that.
715 if (E->getType().getObjCLifetime() == Qualifiers::OCL_Weak)
716 Cleanup.setExprNeedsCleanups(true);
717
718 if (E->getType().isDestructedType() == QualType::DK_nontrivial_c_struct)
719 Cleanup.setExprNeedsCleanups(true);
720
721 // C++ [conv.lval]p3:
722 // If T is cv std::nullptr_t, the result is a null pointer constant.
723 CastKind CK = T->isNullPtrType() ? CK_NullToPointer : CK_LValueToRValue;
724 Res = ImplicitCastExpr::Create(Context, T, CK, E, nullptr, VK_PRValue,
725 CurFPFeatureOverrides());
726
727 // C11 6.3.2.1p2:
728 // ... if the lvalue has atomic type, the value has the non-atomic version
729 // of the type of the lvalue ...
730 if (const AtomicType *Atomic = T->getAs<AtomicType>()) {
731 T = Atomic->getValueType().getUnqualifiedType();
732 Res = ImplicitCastExpr::Create(Context, T, CK_AtomicToNonAtomic, Res.get(),
733 nullptr, VK_PRValue, FPOptionsOverride());
734 }
735
736 return Res;
737}
738
739ExprResult Sema::DefaultFunctionArrayLvalueConversion(Expr *E, bool Diagnose) {
740 ExprResult Res = DefaultFunctionArrayConversion(E, Diagnose);
741 if (Res.isInvalid())
742 return ExprError();
743 Res = DefaultLvalueConversion(Res.get());
744 if (Res.isInvalid())
745 return ExprError();
746 return Res;
747}
748
749/// CallExprUnaryConversions - a special case of an unary conversion
750/// performed on a function designator of a call expression.
751ExprResult Sema::CallExprUnaryConversions(Expr *E) {
752 QualType Ty = E->getType();
753 ExprResult Res = E;
754 // Only do implicit cast for a function type, but not for a pointer
755 // to function type.
756 if (Ty->isFunctionType()) {
757 Res = ImpCastExprToType(E, Context.getPointerType(Ty),
758 CK_FunctionToPointerDecay);
759 if (Res.isInvalid())
760 return ExprError();
761 }
762 Res = DefaultLvalueConversion(Res.get());
763 if (Res.isInvalid())
764 return ExprError();
765 return Res.get();
766}
767
768/// UsualUnaryConversions - Performs various conversions that are common to most
769/// operators (C99 6.3). The conversions of array and function types are
770/// sometimes suppressed. For example, the array->pointer conversion doesn't
771/// apply if the array is an argument to the sizeof or address (&) operators.
772/// In these instances, this routine should *not* be called.
773ExprResult Sema::UsualUnaryConversions(Expr *E) {
774 // First, convert to an r-value.
775 ExprResult Res = DefaultFunctionArrayLvalueConversion(E);
776 if (Res.isInvalid())
777 return ExprError();
778 E = Res.get();
779
780 QualType Ty = E->getType();
781 assert(!Ty.isNull() && "UsualUnaryConversions - missing type")(static_cast <bool> (!Ty.isNull() && "UsualUnaryConversions - missing type"
) ? void (0) : __assert_fail ("!Ty.isNull() && \"UsualUnaryConversions - missing type\""
, "clang/lib/Sema/SemaExpr.cpp", 781, __extension__ __PRETTY_FUNCTION__
))
;
782
783 LangOptions::FPEvalMethodKind EvalMethod = CurFPFeatures.getFPEvalMethod();
784 if (EvalMethod != LangOptions::FEM_Source && Ty->isFloatingType() &&
785 (getLangOpts().getFPEvalMethod() !=
786 LangOptions::FPEvalMethodKind::FEM_UnsetOnCommandLine ||
787 PP.getLastFPEvalPragmaLocation().isValid())) {
788 switch (EvalMethod) {
789 default:
790 llvm_unreachable("Unrecognized float evaluation method")::llvm::llvm_unreachable_internal("Unrecognized float evaluation method"
, "clang/lib/Sema/SemaExpr.cpp", 790)
;
791 break;
792 case LangOptions::FEM_UnsetOnCommandLine:
793 llvm_unreachable("Float evaluation method should be set by now")::llvm::llvm_unreachable_internal("Float evaluation method should be set by now"
, "clang/lib/Sema/SemaExpr.cpp", 793)
;
794 break;
795 case LangOptions::FEM_Double:
796 if (Context.getFloatingTypeOrder(Context.DoubleTy, Ty) > 0)
797 // Widen the expression to double.
798 return Ty->isComplexType()
799 ? ImpCastExprToType(E,
800 Context.getComplexType(Context.DoubleTy),
801 CK_FloatingComplexCast)
802 : ImpCastExprToType(E, Context.DoubleTy, CK_FloatingCast);
803 break;
804 case LangOptions::FEM_Extended:
805 if (Context.getFloatingTypeOrder(Context.LongDoubleTy, Ty) > 0)
806 // Widen the expression to long double.
807 return Ty->isComplexType()
808 ? ImpCastExprToType(
809 E, Context.getComplexType(Context.LongDoubleTy),
810 CK_FloatingComplexCast)
811 : ImpCastExprToType(E, Context.LongDoubleTy,
812 CK_FloatingCast);
813 break;
814 }
815 }
816
817 // Half FP have to be promoted to float unless it is natively supported
818 if (Ty->isHalfType() && !getLangOpts().NativeHalfType)
819 return ImpCastExprToType(Res.get(), Context.FloatTy, CK_FloatingCast);
820
821 // Try to perform integral promotions if the object has a theoretically
822 // promotable type.
823 if (Ty->isIntegralOrUnscopedEnumerationType()) {
824 // C99 6.3.1.1p2:
825 //
826 // The following may be used in an expression wherever an int or
827 // unsigned int may be used:
828 // - an object or expression with an integer type whose integer
829 // conversion rank is less than or equal to the rank of int
830 // and unsigned int.
831 // - A bit-field of type _Bool, int, signed int, or unsigned int.
832 //
833 // If an int can represent all values of the original type, the
834 // value is converted to an int; otherwise, it is converted to an
835 // unsigned int. These are called the integer promotions. All
836 // other types are unchanged by the integer promotions.
837
838 QualType PTy = Context.isPromotableBitField(E);
839 if (!PTy.isNull()) {
840 E = ImpCastExprToType(E, PTy, CK_IntegralCast).get();
841 return E;
842 }
843 if (Context.isPromotableIntegerType(Ty)) {
844 QualType PT = Context.getPromotedIntegerType(Ty);
845 E = ImpCastExprToType(E, PT, CK_IntegralCast).get();
846 return E;
847 }
848 }
849 return E;
850}
851
852/// DefaultArgumentPromotion (C99 6.5.2.2p6). Used for function calls that
853/// do not have a prototype. Arguments that have type float or __fp16
854/// are promoted to double. All other argument types are converted by
855/// UsualUnaryConversions().
856ExprResult Sema::DefaultArgumentPromotion(Expr *E) {
857 QualType Ty = E->getType();
858 assert(!Ty.isNull() && "DefaultArgumentPromotion - missing type")(static_cast <bool> (!Ty.isNull() && "DefaultArgumentPromotion - missing type"
) ? void (0) : __assert_fail ("!Ty.isNull() && \"DefaultArgumentPromotion - missing type\""
, "clang/lib/Sema/SemaExpr.cpp", 858, __extension__ __PRETTY_FUNCTION__
))
;
859
860 ExprResult Res = UsualUnaryConversions(E);
861 if (Res.isInvalid())
862 return ExprError();
863 E = Res.get();
864
865 // If this is a 'float' or '__fp16' (CVR qualified or typedef)
866 // promote to double.
867 // Note that default argument promotion applies only to float (and
868 // half/fp16); it does not apply to _Float16.
869 const BuiltinType *BTy = Ty->getAs<BuiltinType>();
870 if (BTy && (BTy->getKind() == BuiltinType::Half ||
871 BTy->getKind() == BuiltinType::Float)) {
872 if (getLangOpts().OpenCL &&
873 !getOpenCLOptions().isAvailableOption("cl_khr_fp64", getLangOpts())) {
874 if (BTy->getKind() == BuiltinType::Half) {
875 E = ImpCastExprToType(E, Context.FloatTy, CK_FloatingCast).get();
876 }
877 } else {
878 E = ImpCastExprToType(E, Context.DoubleTy, CK_FloatingCast).get();
879 }
880 }
881 if (BTy &&
882 getLangOpts().getExtendIntArgs() ==
883 LangOptions::ExtendArgsKind::ExtendTo64 &&
884 Context.getTargetInfo().supportsExtendIntArgs() && Ty->isIntegerType() &&
885 Context.getTypeSizeInChars(BTy) <
886 Context.getTypeSizeInChars(Context.LongLongTy)) {
887 E = (Ty->isUnsignedIntegerType())
888 ? ImpCastExprToType(E, Context.UnsignedLongLongTy, CK_IntegralCast)
889 .get()
890 : ImpCastExprToType(E, Context.LongLongTy, CK_IntegralCast).get();
891 assert(8 == Context.getTypeSizeInChars(Context.LongLongTy).getQuantity() &&(static_cast <bool> (8 == Context.getTypeSizeInChars(Context
.LongLongTy).getQuantity() && "Unexpected typesize for LongLongTy"
) ? void (0) : __assert_fail ("8 == Context.getTypeSizeInChars(Context.LongLongTy).getQuantity() && \"Unexpected typesize for LongLongTy\""
, "clang/lib/Sema/SemaExpr.cpp", 892, __extension__ __PRETTY_FUNCTION__
))
892 "Unexpected typesize for LongLongTy")(static_cast <bool> (8 == Context.getTypeSizeInChars(Context
.LongLongTy).getQuantity() && "Unexpected typesize for LongLongTy"
) ? void (0) : __assert_fail ("8 == Context.getTypeSizeInChars(Context.LongLongTy).getQuantity() && \"Unexpected typesize for LongLongTy\""
, "clang/lib/Sema/SemaExpr.cpp", 892, __extension__ __PRETTY_FUNCTION__
))
;
893 }
894
895 // C++ performs lvalue-to-rvalue conversion as a default argument
896 // promotion, even on class types, but note:
897 // C++11 [conv.lval]p2:
898 // When an lvalue-to-rvalue conversion occurs in an unevaluated
899 // operand or a subexpression thereof the value contained in the
900 // referenced object is not accessed. Otherwise, if the glvalue
901 // has a class type, the conversion copy-initializes a temporary
902 // of type T from the glvalue and the result of the conversion
903 // is a prvalue for the temporary.
904 // FIXME: add some way to gate this entire thing for correctness in
905 // potentially potentially evaluated contexts.
906 if (getLangOpts().CPlusPlus && E->isGLValue() && !isUnevaluatedContext()) {
907 ExprResult Temp = PerformCopyInitialization(
908 InitializedEntity::InitializeTemporary(E->getType()),
909 E->getExprLoc(), E);
910 if (Temp.isInvalid())
911 return ExprError();
912 E = Temp.get();
913 }
914
915 return E;
916}
917
918/// Determine the degree of POD-ness for an expression.
919/// Incomplete types are considered POD, since this check can be performed
920/// when we're in an unevaluated context.
921Sema::VarArgKind Sema::isValidVarArgType(const QualType &Ty) {
922 if (Ty->isIncompleteType()) {
923 // C++11 [expr.call]p7:
924 // After these conversions, if the argument does not have arithmetic,
925 // enumeration, pointer, pointer to member, or class type, the program
926 // is ill-formed.
927 //
928 // Since we've already performed array-to-pointer and function-to-pointer
929 // decay, the only such type in C++ is cv void. This also handles
930 // initializer lists as variadic arguments.
931 if (Ty->isVoidType())
932 return VAK_Invalid;
933
934 if (Ty->isObjCObjectType())
935 return VAK_Invalid;
936 return VAK_Valid;
937 }
938
939 if (Ty.isDestructedType() == QualType::DK_nontrivial_c_struct)
940 return VAK_Invalid;
941
942 if (Context.getTargetInfo().getTriple().isWasm() &&
943 Ty->isWebAssemblyReferenceType()) {
944 return VAK_Invalid;
945 }
946
947 if (Ty.isCXX98PODType(Context))
948 return VAK_Valid;
949
950 // C++11 [expr.call]p7:
951 // Passing a potentially-evaluated argument of class type (Clause 9)
952 // having a non-trivial copy constructor, a non-trivial move constructor,
953 // or a non-trivial destructor, with no corresponding parameter,
954 // is conditionally-supported with implementation-defined semantics.
955 if (getLangOpts().CPlusPlus11 && !Ty->isDependentType())
956 if (CXXRecordDecl *Record = Ty->getAsCXXRecordDecl())
957 if (!Record->hasNonTrivialCopyConstructor() &&
958 !Record->hasNonTrivialMoveConstructor() &&
959 !Record->hasNonTrivialDestructor())
960 return VAK_ValidInCXX11;
961
962 if (getLangOpts().ObjCAutoRefCount && Ty->isObjCLifetimeType())
963 return VAK_Valid;
964
965 if (Ty->isObjCObjectType())
966 return VAK_Invalid;
967
968 if (getLangOpts().MSVCCompat)
969 return VAK_MSVCUndefined;
970
971 // FIXME: In C++11, these cases are conditionally-supported, meaning we're
972 // permitted to reject them. We should consider doing so.
973 return VAK_Undefined;
974}
975
976void Sema::checkVariadicArgument(const Expr *E, VariadicCallType CT) {
977 // Don't allow one to pass an Objective-C interface to a vararg.
978 const QualType &Ty = E->getType();
979 VarArgKind VAK = isValidVarArgType(Ty);
980
981 // Complain about passing non-POD types through varargs.
982 switch (VAK) {
983 case VAK_ValidInCXX11:
984 DiagRuntimeBehavior(
985 E->getBeginLoc(), nullptr,
986 PDiag(diag::warn_cxx98_compat_pass_non_pod_arg_to_vararg) << Ty << CT);
987 [[fallthrough]];
988 case VAK_Valid:
989 if (Ty->isRecordType()) {
990 // This is unlikely to be what the user intended. If the class has a
991 // 'c_str' member function, the user probably meant to call that.
992 DiagRuntimeBehavior(E->getBeginLoc(), nullptr,
993 PDiag(diag::warn_pass_class_arg_to_vararg)
994 << Ty << CT << hasCStrMethod(E) << ".c_str()");
995 }
996 break;
997
998 case VAK_Undefined:
999 case VAK_MSVCUndefined:
1000 DiagRuntimeBehavior(E->getBeginLoc(), nullptr,
1001 PDiag(diag::warn_cannot_pass_non_pod_arg_to_vararg)
1002 << getLangOpts().CPlusPlus11 << Ty << CT);
1003 break;
1004
1005 case VAK_Invalid:
1006 if (Ty.isDestructedType() == QualType::DK_nontrivial_c_struct)
1007 Diag(E->getBeginLoc(),
1008 diag::err_cannot_pass_non_trivial_c_struct_to_vararg)
1009 << Ty << CT;
1010 else if (Ty->isObjCObjectType())
1011 DiagRuntimeBehavior(E->getBeginLoc(), nullptr,
1012 PDiag(diag::err_cannot_pass_objc_interface_to_vararg)
1013 << Ty << CT);
1014 else
1015 Diag(E->getBeginLoc(), diag::err_cannot_pass_to_vararg)
1016 << isa<InitListExpr>(E) << Ty << CT;
1017 break;
1018 }
1019}
1020
1021/// DefaultVariadicArgumentPromotion - Like DefaultArgumentPromotion, but
1022/// will create a trap if the resulting type is not a POD type.
1023ExprResult Sema::DefaultVariadicArgumentPromotion(Expr *E, VariadicCallType CT,
1024 FunctionDecl *FDecl) {
1025 if (const BuiltinType *PlaceholderTy = E->getType()->getAsPlaceholderType()) {
1026 // Strip the unbridged-cast placeholder expression off, if applicable.
1027 if (PlaceholderTy->getKind() == BuiltinType::ARCUnbridgedCast &&
1028 (CT == VariadicMethod ||
1029 (FDecl && FDecl->hasAttr<CFAuditedTransferAttr>()))) {
1030 E = stripARCUnbridgedCast(E);
1031
1032 // Otherwise, do normal placeholder checking.
1033 } else {
1034 ExprResult ExprRes = CheckPlaceholderExpr(E);
1035 if (ExprRes.isInvalid())
1036 return ExprError();
1037 E = ExprRes.get();
1038 }
1039 }
1040
1041 ExprResult ExprRes = DefaultArgumentPromotion(E);
1042 if (ExprRes.isInvalid())
1043 return ExprError();
1044
1045 // Copy blocks to the heap.
1046 if (ExprRes.get()->getType()->isBlockPointerType())
1047 maybeExtendBlockObject(ExprRes);
1048
1049 E = ExprRes.get();
1050
1051 // Diagnostics regarding non-POD argument types are
1052 // emitted along with format string checking in Sema::CheckFunctionCall().
1053 if (isValidVarArgType(E->getType()) == VAK_Undefined) {
1054 // Turn this into a trap.
1055 CXXScopeSpec SS;
1056 SourceLocation TemplateKWLoc;
1057 UnqualifiedId Name;
1058 Name.setIdentifier(PP.getIdentifierInfo("__builtin_trap"),
1059 E->getBeginLoc());
1060 ExprResult TrapFn = ActOnIdExpression(TUScope, SS, TemplateKWLoc, Name,
1061 /*HasTrailingLParen=*/true,
1062 /*IsAddressOfOperand=*/false);
1063 if (TrapFn.isInvalid())
1064 return ExprError();
1065
1066 ExprResult Call = BuildCallExpr(TUScope, TrapFn.get(), E->getBeginLoc(),
1067 std::nullopt, E->getEndLoc());
1068 if (Call.isInvalid())
1069 return ExprError();
1070
1071 ExprResult Comma =
1072 ActOnBinOp(TUScope, E->getBeginLoc(), tok::comma, Call.get(), E);
1073 if (Comma.isInvalid())
1074 return ExprError();
1075 return Comma.get();
1076 }
1077
1078 if (!getLangOpts().CPlusPlus &&
1079 RequireCompleteType(E->getExprLoc(), E->getType(),
1080 diag::err_call_incomplete_argument))
1081 return ExprError();
1082
1083 return E;
1084}
1085
1086/// Converts an integer to complex float type. Helper function of
1087/// UsualArithmeticConversions()
1088///
1089/// \return false if the integer expression is an integer type and is
1090/// successfully converted to the complex type.
1091static bool handleIntegerToComplexFloatConversion(Sema &S, ExprResult &IntExpr,
1092 ExprResult &ComplexExpr,
1093 QualType IntTy,
1094 QualType ComplexTy,
1095 bool SkipCast) {
1096 if (IntTy->isComplexType() || IntTy->isRealFloatingType()) return true;
1097 if (SkipCast) return false;
1098 if (IntTy->isIntegerType()) {
1099 QualType fpTy = ComplexTy->castAs<ComplexType>()->getElementType();
1100 IntExpr = S.ImpCastExprToType(IntExpr.get(), fpTy, CK_IntegralToFloating);
1101 IntExpr = S.ImpCastExprToType(IntExpr.get(), ComplexTy,
1102 CK_FloatingRealToComplex);
1103 } else {
1104 assert(IntTy->isComplexIntegerType())(static_cast <bool> (IntTy->isComplexIntegerType()) ?
void (0) : __assert_fail ("IntTy->isComplexIntegerType()"
, "clang/lib/Sema/SemaExpr.cpp", 1104, __extension__ __PRETTY_FUNCTION__
))
;
1105 IntExpr = S.ImpCastExprToType(IntExpr.get(), ComplexTy,
1106 CK_IntegralComplexToFloatingComplex);
1107 }
1108 return false;
1109}
1110
1111// This handles complex/complex, complex/float, or float/complex.
1112// When both operands are complex, the shorter operand is converted to the
1113// type of the longer, and that is the type of the result. This corresponds
1114// to what is done when combining two real floating-point operands.
1115// The fun begins when size promotion occur across type domains.
1116// From H&S 6.3.4: When one operand is complex and the other is a real
1117// floating-point type, the less precise type is converted, within it's
1118// real or complex domain, to the precision of the other type. For example,
1119// when combining a "long double" with a "double _Complex", the
1120// "double _Complex" is promoted to "long double _Complex".
1121static QualType handleComplexFloatConversion(Sema &S, ExprResult &Shorter,
1122 QualType ShorterType,
1123 QualType LongerType,
1124 bool PromotePrecision) {
1125 bool LongerIsComplex = isa<ComplexType>(LongerType.getCanonicalType());
1126 QualType Result =
1127 LongerIsComplex ? LongerType : S.Context.getComplexType(LongerType);
1128
1129 if (PromotePrecision) {
1130 if (isa<ComplexType>(ShorterType.getCanonicalType())) {
1131 Shorter =
1132 S.ImpCastExprToType(Shorter.get(), Result, CK_FloatingComplexCast);
1133 } else {
1134 if (LongerIsComplex)
1135 LongerType = LongerType->castAs<ComplexType>()->getElementType();
1136 Shorter = S.ImpCastExprToType(Shorter.get(), LongerType, CK_FloatingCast);
1137 }
1138 }
1139 return Result;
1140}
1141
1142/// Handle arithmetic conversion with complex types. Helper function of
1143/// UsualArithmeticConversions()
1144static QualType handleComplexConversion(Sema &S, ExprResult &LHS,
1145 ExprResult &RHS, QualType LHSType,
1146 QualType RHSType, bool IsCompAssign) {
1147 // if we have an integer operand, the result is the complex type.
1148 if (!handleIntegerToComplexFloatConversion(S, RHS, LHS, RHSType, LHSType,
1149 /*SkipCast=*/false))
1150 return LHSType;
1151 if (!handleIntegerToComplexFloatConversion(S, LHS, RHS, LHSType, RHSType,
1152 /*SkipCast=*/IsCompAssign))
1153 return RHSType;
1154
1155 // Compute the rank of the two types, regardless of whether they are complex.
1156 int Order = S.Context.getFloatingTypeOrder(LHSType, RHSType);
1157 if (Order < 0)
1158 // Promote the precision of the LHS if not an assignment.
1159 return handleComplexFloatConversion(S, LHS, LHSType, RHSType,
1160 /*PromotePrecision=*/!IsCompAssign);
1161 // Promote the precision of the RHS unless it is already the same as the LHS.
1162 return handleComplexFloatConversion(S, RHS, RHSType, LHSType,
1163 /*PromotePrecision=*/Order > 0);
1164}
1165
1166/// Handle arithmetic conversion from integer to float. Helper function
1167/// of UsualArithmeticConversions()
1168static QualType handleIntToFloatConversion(Sema &S, ExprResult &FloatExpr,
1169 ExprResult &IntExpr,
1170 QualType FloatTy, QualType IntTy,
1171 bool ConvertFloat, bool ConvertInt) {
1172 if (IntTy->isIntegerType()) {
1173 if (ConvertInt)
1174 // Convert intExpr to the lhs floating point type.
1175 IntExpr = S.ImpCastExprToType(IntExpr.get(), FloatTy,
1176 CK_IntegralToFloating);
1177 return FloatTy;
1178 }
1179
1180 // Convert both sides to the appropriate complex float.
1181 assert(IntTy->isComplexIntegerType())(static_cast <bool> (IntTy->isComplexIntegerType()) ?
void (0) : __assert_fail ("IntTy->isComplexIntegerType()"
, "clang/lib/Sema/SemaExpr.cpp", 1181, __extension__ __PRETTY_FUNCTION__
))
;
1182 QualType result = S.Context.getComplexType(FloatTy);
1183
1184 // _Complex int -> _Complex float
1185 if (ConvertInt)
1186 IntExpr = S.ImpCastExprToType(IntExpr.get(), result,
1187 CK_IntegralComplexToFloatingComplex);
1188
1189 // float -> _Complex float
1190 if (ConvertFloat)
1191 FloatExpr = S.ImpCastExprToType(FloatExpr.get(), result,
1192 CK_FloatingRealToComplex);
1193
1194 return result;
1195}
1196
1197/// Handle arithmethic conversion with floating point types. Helper
1198/// function of UsualArithmeticConversions()
1199static QualType handleFloatConversion(Sema &S, ExprResult &LHS,
1200 ExprResult &RHS, QualType LHSType,
1201 QualType RHSType, bool IsCompAssign) {
1202 bool LHSFloat = LHSType->isRealFloatingType();
1203 bool RHSFloat = RHSType->isRealFloatingType();
1204
1205 // N1169 4.1.4: If one of the operands has a floating type and the other
1206 // operand has a fixed-point type, the fixed-point operand
1207 // is converted to the floating type [...]
1208 if (LHSType->isFixedPointType() || RHSType->isFixedPointType()) {
1209 if (LHSFloat)
1210 RHS = S.ImpCastExprToType(RHS.get(), LHSType, CK_FixedPointToFloating);
1211 else if (!IsCompAssign)
1212 LHS = S.ImpCastExprToType(LHS.get(), RHSType, CK_FixedPointToFloating);
1213 return LHSFloat ? LHSType : RHSType;
1214 }
1215
1216 // If we have two real floating types, convert the smaller operand
1217 // to the bigger result.
1218 if (LHSFloat && RHSFloat) {
1219 int order = S.Context.getFloatingTypeOrder(LHSType, RHSType);
1220 if (order > 0) {
1221 RHS = S.ImpCastExprToType(RHS.get(), LHSType, CK_FloatingCast);
1222 return LHSType;
1223 }
1224
1225 assert(order < 0 && "illegal float comparison")(static_cast <bool> (order < 0 && "illegal float comparison"
) ? void (0) : __assert_fail ("order < 0 && \"illegal float comparison\""
, "clang/lib/Sema/SemaExpr.cpp", 1225, __extension__ __PRETTY_FUNCTION__
))
;
1226 if (!IsCompAssign)
1227 LHS = S.ImpCastExprToType(LHS.get(), RHSType, CK_FloatingCast);
1228 return RHSType;
1229 }
1230
1231 if (LHSFloat) {
1232 // Half FP has to be promoted to float unless it is natively supported
1233 if (LHSType->isHalfType() && !S.getLangOpts().NativeHalfType)
1234 LHSType = S.Context.FloatTy;
1235
1236 return handleIntToFloatConversion(S, LHS, RHS, LHSType, RHSType,
1237 /*ConvertFloat=*/!IsCompAssign,
1238 /*ConvertInt=*/ true);
1239 }
1240 assert(RHSFloat)(static_cast <bool> (RHSFloat) ? void (0) : __assert_fail
("RHSFloat", "clang/lib/Sema/SemaExpr.cpp", 1240, __extension__
__PRETTY_FUNCTION__))
;
1241 return handleIntToFloatConversion(S, RHS, LHS, RHSType, LHSType,
1242 /*ConvertFloat=*/ true,
1243 /*ConvertInt=*/!IsCompAssign);
1244}
1245
1246/// Diagnose attempts to convert between __float128, __ibm128 and
1247/// long double if there is no support for such conversion.
1248/// Helper function of UsualArithmeticConversions().
1249static bool unsupportedTypeConversion(const Sema &S, QualType LHSType,
1250 QualType RHSType) {
1251 // No issue if either is not a floating point type.
1252 if (!LHSType->isFloatingType() || !RHSType->isFloatingType())
1253 return false;
1254
1255 // No issue if both have the same 128-bit float semantics.
1256 auto *LHSComplex = LHSType->getAs<ComplexType>();
1257 auto *RHSComplex = RHSType->getAs<ComplexType>();
1258
1259 QualType LHSElem = LHSComplex ? LHSComplex->getElementType() : LHSType;
1260 QualType RHSElem = RHSComplex ? RHSComplex->getElementType() : RHSType;
1261
1262 const llvm::fltSemantics &LHSSem = S.Context.getFloatTypeSemantics(LHSElem);
1263 const llvm::fltSemantics &RHSSem = S.Context.getFloatTypeSemantics(RHSElem);
1264
1265 if ((&LHSSem != &llvm::APFloat::PPCDoubleDouble() ||
1266 &RHSSem != &llvm::APFloat::IEEEquad()) &&
1267 (&LHSSem != &llvm::APFloat::IEEEquad() ||
1268 &RHSSem != &llvm::APFloat::PPCDoubleDouble()))
1269 return false;
1270
1271 return true;
1272}
1273
1274typedef ExprResult PerformCastFn(Sema &S, Expr *operand, QualType toType);
1275
1276namespace {
1277/// These helper callbacks are placed in an anonymous namespace to
1278/// permit their use as function template parameters.
1279ExprResult doIntegralCast(Sema &S, Expr *op, QualType toType) {
1280 return S.ImpCastExprToType(op, toType, CK_IntegralCast);
1281}
1282
1283ExprResult doComplexIntegralCast(Sema &S, Expr *op, QualType toType) {
1284 return S.ImpCastExprToType(op, S.Context.getComplexType(toType),
1285 CK_IntegralComplexCast);
1286}
1287}
1288
1289/// Handle integer arithmetic conversions. Helper function of
1290/// UsualArithmeticConversions()
1291template <PerformCastFn doLHSCast, PerformCastFn doRHSCast>
1292static QualType handleIntegerConversion(Sema &S, ExprResult &LHS,
1293 ExprResult &RHS, QualType LHSType,
1294 QualType RHSType, bool IsCompAssign) {
1295 // The rules for this case are in C99 6.3.1.8
1296 int order = S.Context.getIntegerTypeOrder(LHSType, RHSType);
1297 bool LHSSigned = LHSType->hasSignedIntegerRepresentation();
1298 bool RHSSigned = RHSType->hasSignedIntegerRepresentation();
1299 if (LHSSigned == RHSSigned) {
1300 // Same signedness; use the higher-ranked type
1301 if (order >= 0) {
1302 RHS = (*doRHSCast)(S, RHS.get(), LHSType);
1303 return LHSType;
1304 } else if (!IsCompAssign)
1305 LHS = (*doLHSCast)(S, LHS.get(), RHSType);
1306 return RHSType;
1307 } else if (order != (LHSSigned ? 1 : -1)) {
1308 // The unsigned type has greater than or equal rank to the
1309 // signed type, so use the unsigned type
1310 if (RHSSigned) {
1311 RHS = (*doRHSCast)(S, RHS.get(), LHSType);
1312 return LHSType;
1313 } else if (!IsCompAssign)
1314 LHS = (*doLHSCast)(S, LHS.get(), RHSType);
1315 return RHSType;
1316 } else if (S.Context.getIntWidth(LHSType) != S.Context.getIntWidth(RHSType)) {
1317 // The two types are different widths; if we are here, that
1318 // means the signed type is larger than the unsigned type, so
1319 // use the signed type.
1320 if (LHSSigned) {
1321 RHS = (*doRHSCast)(S, RHS.get(), LHSType);
1322 return LHSType;
1323 } else if (!IsCompAssign)
1324 LHS = (*doLHSCast)(S, LHS.get(), RHSType);
1325 return RHSType;
1326 } else {
1327 // The signed type is higher-ranked than the unsigned type,
1328 // but isn't actually any bigger (like unsigned int and long
1329 // on most 32-bit systems). Use the unsigned type corresponding
1330 // to the signed type.
1331 QualType result =
1332 S.Context.getCorrespondingUnsignedType(LHSSigned ? LHSType : RHSType);
1333 RHS = (*doRHSCast)(S, RHS.get(), result);
1334 if (!IsCompAssign)
1335 LHS = (*doLHSCast)(S, LHS.get(), result);
1336 return result;
1337 }
1338}
1339
1340/// Handle conversions with GCC complex int extension. Helper function
1341/// of UsualArithmeticConversions()
1342static QualType handleComplexIntConversion(Sema &S, ExprResult &LHS,
1343 ExprResult &RHS, QualType LHSType,
1344 QualType RHSType,
1345 bool IsCompAssign) {
1346 const ComplexType *LHSComplexInt = LHSType->getAsComplexIntegerType();
1347 const ComplexType *RHSComplexInt = RHSType->getAsComplexIntegerType();
1348
1349 if (LHSComplexInt && RHSComplexInt) {
1350 QualType LHSEltType = LHSComplexInt->getElementType();
1351 QualType RHSEltType = RHSComplexInt->getElementType();
1352 QualType ScalarType =
1353 handleIntegerConversion<doComplexIntegralCast, doComplexIntegralCast>
1354 (S, LHS, RHS, LHSEltType, RHSEltType, IsCompAssign);
1355
1356 return S.Context.getComplexType(ScalarType);
1357 }
1358
1359 if (LHSComplexInt) {
1360 QualType LHSEltType = LHSComplexInt->getElementType();
1361 QualType ScalarType =
1362 handleIntegerConversion<doComplexIntegralCast, doIntegralCast>
1363 (S, LHS, RHS, LHSEltType, RHSType, IsCompAssign);
1364 QualType ComplexType = S.Context.getComplexType(ScalarType);
1365 RHS = S.ImpCastExprToType(RHS.get(), ComplexType,
1366 CK_IntegralRealToComplex);
1367
1368 return ComplexType;
1369 }
1370
1371 assert(RHSComplexInt)(static_cast <bool> (RHSComplexInt) ? void (0) : __assert_fail
("RHSComplexInt", "clang/lib/Sema/SemaExpr.cpp", 1371, __extension__
__PRETTY_FUNCTION__))
;
1372
1373 QualType RHSEltType = RHSComplexInt->getElementType();
1374 QualType ScalarType =
1375 handleIntegerConversion<doIntegralCast, doComplexIntegralCast>
1376 (S, LHS, RHS, LHSType, RHSEltType, IsCompAssign);
1377 QualType ComplexType = S.Context.getComplexType(ScalarType);
1378
1379 if (!IsCompAssign)
1380 LHS = S.ImpCastExprToType(LHS.get(), ComplexType,
1381 CK_IntegralRealToComplex);
1382 return ComplexType;
1383}
1384
1385/// Return the rank of a given fixed point or integer type. The value itself
1386/// doesn't matter, but the values must be increasing with proper increasing
1387/// rank as described in N1169 4.1.1.
1388static unsigned GetFixedPointRank(QualType Ty) {
1389 const auto *BTy = Ty->getAs<BuiltinType>();
1390 assert(BTy && "Expected a builtin type.")(static_cast <bool> (BTy && "Expected a builtin type."
) ? void (0) : __assert_fail ("BTy && \"Expected a builtin type.\""
, "clang/lib/Sema/SemaExpr.cpp", 1390, __extension__ __PRETTY_FUNCTION__
))
;
1391
1392 switch (BTy->getKind()) {
1393 case BuiltinType::ShortFract:
1394 case BuiltinType::UShortFract:
1395 case BuiltinType::SatShortFract:
1396 case BuiltinType::SatUShortFract:
1397 return 1;
1398 case BuiltinType::Fract:
1399 case BuiltinType::UFract:
1400 case BuiltinType::SatFract:
1401 case BuiltinType::SatUFract:
1402 return 2;
1403 case BuiltinType::LongFract:
1404 case BuiltinType::ULongFract:
1405 case BuiltinType::SatLongFract:
1406 case BuiltinType::SatULongFract:
1407 return 3;
1408 case BuiltinType::ShortAccum:
1409 case BuiltinType::UShortAccum:
1410 case BuiltinType::SatShortAccum:
1411 case BuiltinType::SatUShortAccum:
1412 return 4;
1413 case BuiltinType::Accum:
1414 case BuiltinType::UAccum:
1415 case BuiltinType::SatAccum:
1416 case BuiltinType::SatUAccum:
1417 return 5;
1418 case BuiltinType::LongAccum:
1419 case BuiltinType::ULongAccum:
1420 case BuiltinType::SatLongAccum:
1421 case BuiltinType::SatULongAccum:
1422 return 6;
1423 default:
1424 if (BTy->isInteger())
1425 return 0;
1426 llvm_unreachable("Unexpected fixed point or integer type")::llvm::llvm_unreachable_internal("Unexpected fixed point or integer type"
, "clang/lib/Sema/SemaExpr.cpp", 1426)
;
1427 }
1428}
1429
1430/// handleFixedPointConversion - Fixed point operations between fixed
1431/// point types and integers or other fixed point types do not fall under
1432/// usual arithmetic conversion since these conversions could result in loss
1433/// of precsision (N1169 4.1.4). These operations should be calculated with
1434/// the full precision of their result type (N1169 4.1.6.2.1).
1435static QualType handleFixedPointConversion(Sema &S, QualType LHSTy,
1436 QualType RHSTy) {
1437 assert((LHSTy->isFixedPointType() || RHSTy->isFixedPointType()) &&(static_cast <bool> ((LHSTy->isFixedPointType() || RHSTy
->isFixedPointType()) && "Expected at least one of the operands to be a fixed point type"
) ? void (0) : __assert_fail ("(LHSTy->isFixedPointType() || RHSTy->isFixedPointType()) && \"Expected at least one of the operands to be a fixed point type\""
, "clang/lib/Sema/SemaExpr.cpp", 1438, __extension__ __PRETTY_FUNCTION__
))
1438 "Expected at least one of the operands to be a fixed point type")(static_cast <bool> ((LHSTy->isFixedPointType() || RHSTy
->isFixedPointType()) && "Expected at least one of the operands to be a fixed point type"
) ? void (0) : __assert_fail ("(LHSTy->isFixedPointType() || RHSTy->isFixedPointType()) && \"Expected at least one of the operands to be a fixed point type\""
, "clang/lib/Sema/SemaExpr.cpp", 1438, __extension__ __PRETTY_FUNCTION__
))
;
1439 assert((LHSTy->isFixedPointOrIntegerType() ||(static_cast <bool> ((LHSTy->isFixedPointOrIntegerType
() || RHSTy->isFixedPointOrIntegerType()) && "Special fixed point arithmetic operation conversions are only "
"applied to ints or other fixed point types") ? void (0) : __assert_fail
("(LHSTy->isFixedPointOrIntegerType() || RHSTy->isFixedPointOrIntegerType()) && \"Special fixed point arithmetic operation conversions are only \" \"applied to ints or other fixed point types\""
, "clang/lib/Sema/SemaExpr.cpp", 1442, __extension__ __PRETTY_FUNCTION__
))
1440 RHSTy->isFixedPointOrIntegerType()) &&(static_cast <bool> ((LHSTy->isFixedPointOrIntegerType
() || RHSTy->isFixedPointOrIntegerType()) && "Special fixed point arithmetic operation conversions are only "
"applied to ints or other fixed point types") ? void (0) : __assert_fail
("(LHSTy->isFixedPointOrIntegerType() || RHSTy->isFixedPointOrIntegerType()) && \"Special fixed point arithmetic operation conversions are only \" \"applied to ints or other fixed point types\""
, "clang/lib/Sema/SemaExpr.cpp", 1442, __extension__ __PRETTY_FUNCTION__
))
1441 "Special fixed point arithmetic operation conversions are only "(static_cast <bool> ((LHSTy->isFixedPointOrIntegerType
() || RHSTy->isFixedPointOrIntegerType()) && "Special fixed point arithmetic operation conversions are only "
"applied to ints or other fixed point types") ? void (0) : __assert_fail
("(LHSTy->isFixedPointOrIntegerType() || RHSTy->isFixedPointOrIntegerType()) && \"Special fixed point arithmetic operation conversions are only \" \"applied to ints or other fixed point types\""
, "clang/lib/Sema/SemaExpr.cpp", 1442, __extension__ __PRETTY_FUNCTION__
))
1442 "applied to ints or other fixed point types")(static_cast <bool> ((LHSTy->isFixedPointOrIntegerType
() || RHSTy->isFixedPointOrIntegerType()) && "Special fixed point arithmetic operation conversions are only "
"applied to ints or other fixed point types") ? void (0) : __assert_fail
("(LHSTy->isFixedPointOrIntegerType() || RHSTy->isFixedPointOrIntegerType()) && \"Special fixed point arithmetic operation conversions are only \" \"applied to ints or other fixed point types\""
, "clang/lib/Sema/SemaExpr.cpp", 1442, __extension__ __PRETTY_FUNCTION__
))
;
1443
1444 // If one operand has signed fixed-point type and the other operand has
1445 // unsigned fixed-point type, then the unsigned fixed-point operand is
1446 // converted to its corresponding signed fixed-point type and the resulting
1447 // type is the type of the converted operand.
1448 if (RHSTy->isSignedFixedPointType() && LHSTy->isUnsignedFixedPointType())
1449 LHSTy = S.Context.getCorrespondingSignedFixedPointType(LHSTy);
1450 else if (RHSTy->isUnsignedFixedPointType() && LHSTy->isSignedFixedPointType())
1451 RHSTy = S.Context.getCorrespondingSignedFixedPointType(RHSTy);
1452
1453 // The result type is the type with the highest rank, whereby a fixed-point
1454 // conversion rank is always greater than an integer conversion rank; if the
1455 // type of either of the operands is a saturating fixedpoint type, the result
1456 // type shall be the saturating fixed-point type corresponding to the type
1457 // with the highest rank; the resulting value is converted (taking into
1458 // account rounding and overflow) to the precision of the resulting type.
1459 // Same ranks between signed and unsigned types are resolved earlier, so both
1460 // types are either signed or both unsigned at this point.
1461 unsigned LHSTyRank = GetFixedPointRank(LHSTy);
1462 unsigned RHSTyRank = GetFixedPointRank(RHSTy);
1463
1464 QualType ResultTy = LHSTyRank > RHSTyRank ? LHSTy : RHSTy;
1465
1466 if (LHSTy->isSaturatedFixedPointType() || RHSTy->isSaturatedFixedPointType())
1467 ResultTy = S.Context.getCorrespondingSaturatedType(ResultTy);
1468
1469 return ResultTy;
1470}
1471
1472/// Check that the usual arithmetic conversions can be performed on this pair of
1473/// expressions that might be of enumeration type.
1474static void checkEnumArithmeticConversions(Sema &S, Expr *LHS, Expr *RHS,
1475 SourceLocation Loc,
1476 Sema::ArithConvKind ACK) {
1477 // C++2a [expr.arith.conv]p1:
1478 // If one operand is of enumeration type and the other operand is of a
1479 // different enumeration type or a floating-point type, this behavior is
1480 // deprecated ([depr.arith.conv.enum]).
1481 //
1482 // Warn on this in all language modes. Produce a deprecation warning in C++20.
1483 // Eventually we will presumably reject these cases (in C++23 onwards?).
1484 QualType L = LHS->getType(), R = RHS->getType();
1485 bool LEnum = L->isUnscopedEnumerationType(),
1486 REnum = R->isUnscopedEnumerationType();
1487 bool IsCompAssign = ACK == Sema::ACK_CompAssign;
1488 if ((!IsCompAssign && LEnum && R->isFloatingType()) ||
1489 (REnum && L->isFloatingType())) {
1490 S.Diag(Loc, S.getLangOpts().CPlusPlus20
1491 ? diag::warn_arith_conv_enum_float_cxx20
1492 : diag::warn_arith_conv_enum_float)
1493 << LHS->getSourceRange() << RHS->getSourceRange()
1494 << (int)ACK << LEnum << L << R;
1495 } else if (!IsCompAssign && LEnum && REnum &&
1496 !S.Context.hasSameUnqualifiedType(L, R)) {
1497 unsigned DiagID;
1498 if (!L->castAs<EnumType>()->getDecl()->hasNameForLinkage() ||
1499 !R->castAs<EnumType>()->getDecl()->hasNameForLinkage()) {
1500 // If either enumeration type is unnamed, it's less likely that the
1501 // user cares about this, but this situation is still deprecated in
1502 // C++2a. Use a different warning group.
1503 DiagID = S.getLangOpts().CPlusPlus20
1504 ? diag::warn_arith_conv_mixed_anon_enum_types_cxx20
1505 : diag::warn_arith_conv_mixed_anon_enum_types;
1506 } else if (ACK == Sema::ACK_Conditional) {
1507 // Conditional expressions are separated out because they have
1508 // historically had a different warning flag.
1509 DiagID = S.getLangOpts().CPlusPlus20
1510 ? diag::warn_conditional_mixed_enum_types_cxx20
1511 : diag::warn_conditional_mixed_enum_types;
1512 } else if (ACK == Sema::ACK_Comparison) {
1513 // Comparison expressions are separated out because they have
1514 // historically had a different warning flag.
1515 DiagID = S.getLangOpts().CPlusPlus20
1516 ? diag::warn_comparison_mixed_enum_types_cxx20
1517 : diag::warn_comparison_mixed_enum_types;
1518 } else {
1519 DiagID = S.getLangOpts().CPlusPlus20
1520 ? diag::warn_arith_conv_mixed_enum_types_cxx20
1521 : diag::warn_arith_conv_mixed_enum_types;
1522 }
1523 S.Diag(Loc, DiagID) << LHS->getSourceRange() << RHS->getSourceRange()
1524 << (int)ACK << L << R;
1525 }
1526}
1527
1528/// UsualArithmeticConversions - Performs various conversions that are common to
1529/// binary operators (C99 6.3.1.8). If both operands aren't arithmetic, this
1530/// routine returns the first non-arithmetic type found. The client is
1531/// responsible for emitting appropriate error diagnostics.
1532QualType Sema::UsualArithmeticConversions(ExprResult &LHS, ExprResult &RHS,
1533 SourceLocation Loc,
1534 ArithConvKind ACK) {
1535 checkEnumArithmeticConversions(*this, LHS.get(), RHS.get(), Loc, ACK);
1536
1537 if (ACK != ACK_CompAssign) {
1538 LHS = UsualUnaryConversions(LHS.get());
1539 if (LHS.isInvalid())
1540 return QualType();
1541 }
1542
1543 RHS = UsualUnaryConversions(RHS.get());
1544 if (RHS.isInvalid())
1545 return QualType();
1546
1547 // For conversion purposes, we ignore any qualifiers.
1548 // For example, "const float" and "float" are equivalent.
1549 QualType LHSType = LHS.get()->getType().getUnqualifiedType();
1550 QualType RHSType = RHS.get()->getType().getUnqualifiedType();
1551
1552 // For conversion purposes, we ignore any atomic qualifier on the LHS.
1553 if (const AtomicType *AtomicLHS = LHSType->getAs<AtomicType>())
1554 LHSType = AtomicLHS->getValueType();
1555
1556 // If both types are identical, no conversion is needed.
1557 if (Context.hasSameType(LHSType, RHSType))
1558 return Context.getCommonSugaredType(LHSType, RHSType);
1559
1560 // If either side is a non-arithmetic type (e.g. a pointer), we are done.
1561 // The caller can deal with this (e.g. pointer + int).
1562 if (!LHSType->isArithmeticType() || !RHSType->isArithmeticType())
1563 return QualType();
1564
1565 // Apply unary and bitfield promotions to the LHS's type.
1566 QualType LHSUnpromotedType = LHSType;
1567 if (Context.isPromotableIntegerType(LHSType))
1568 LHSType = Context.getPromotedIntegerType(LHSType);
1569 QualType LHSBitfieldPromoteTy = Context.isPromotableBitField(LHS.get());
1570 if (!LHSBitfieldPromoteTy.isNull())
1571 LHSType = LHSBitfieldPromoteTy;
1572 if (LHSType != LHSUnpromotedType && ACK != ACK_CompAssign)
1573 LHS = ImpCastExprToType(LHS.get(), LHSType, CK_IntegralCast);
1574
1575 // If both types are identical, no conversion is needed.
1576 if (Context.hasSameType(LHSType, RHSType))
1577 return Context.getCommonSugaredType(LHSType, RHSType);
1578
1579 // At this point, we have two different arithmetic types.
1580
1581 // Diagnose attempts to convert between __ibm128, __float128 and long double
1582 // where such conversions currently can't be handled.
1583 if (unsupportedTypeConversion(*this, LHSType, RHSType))
1584 return QualType();
1585
1586 // Handle complex types first (C99 6.3.1.8p1).
1587 if (LHSType->isComplexType() || RHSType->isComplexType())
1588 return handleComplexConversion(*this, LHS, RHS, LHSType, RHSType,
1589 ACK == ACK_CompAssign);
1590
1591 // Now handle "real" floating types (i.e. float, double, long double).
1592 if (LHSType->isRealFloatingType() || RHSType->isRealFloatingType())
1593 return handleFloatConversion(*this, LHS, RHS, LHSType, RHSType,
1594 ACK == ACK_CompAssign);
1595
1596 // Handle GCC complex int extension.
1597 if (LHSType->isComplexIntegerType() || RHSType->isComplexIntegerType())
1598 return handleComplexIntConversion(*this, LHS, RHS, LHSType, RHSType,
1599 ACK == ACK_CompAssign);
1600
1601 if (LHSType->isFixedPointType() || RHSType->isFixedPointType())
1602 return handleFixedPointConversion(*this, LHSType, RHSType);
1603
1604 // Finally, we have two differing integer types.
1605 return handleIntegerConversion<doIntegralCast, doIntegralCast>
1606 (*this, LHS, RHS, LHSType, RHSType, ACK == ACK_CompAssign);
1607}
1608
1609//===----------------------------------------------------------------------===//
1610// Semantic Analysis for various Expression Types
1611//===----------------------------------------------------------------------===//
1612
1613
1614ExprResult
1615Sema::ActOnGenericSelectionExpr(SourceLocation KeyLoc,
1616 SourceLocation DefaultLoc,
1617 SourceLocation RParenLoc,
1618 Expr *ControllingExpr,
1619 ArrayRef<ParsedType> ArgTypes,
1620 ArrayRef<Expr *> ArgExprs) {
1621 unsigned NumAssocs = ArgTypes.size();
1622 assert(NumAssocs == ArgExprs.size())(static_cast <bool> (NumAssocs == ArgExprs.size()) ? void
(0) : __assert_fail ("NumAssocs == ArgExprs.size()", "clang/lib/Sema/SemaExpr.cpp"
, 1622, __extension__ __PRETTY_FUNCTION__))
;
1623
1624 TypeSourceInfo **Types = new TypeSourceInfo*[NumAssocs];
1625 for (unsigned i = 0; i < NumAssocs; ++i) {
1626 if (ArgTypes[i])
1627 (void) GetTypeFromParser(ArgTypes[i], &Types[i]);
1628 else
1629 Types[i] = nullptr;
1630 }
1631
1632 ExprResult ER =
1633 CreateGenericSelectionExpr(KeyLoc, DefaultLoc, RParenLoc, ControllingExpr,
1634 llvm::ArrayRef(Types, NumAssocs), ArgExprs);
1635 delete [] Types;
1636 return ER;
1637}
1638
1639ExprResult
1640Sema::CreateGenericSelectionExpr(SourceLocation KeyLoc,
1641 SourceLocation DefaultLoc,
1642 SourceLocation RParenLoc,
1643 Expr *ControllingExpr,
1644 ArrayRef<TypeSourceInfo *> Types,
1645 ArrayRef<Expr *> Exprs) {
1646 unsigned NumAssocs = Types.size();
1647 assert(NumAssocs == Exprs.size())(static_cast <bool> (NumAssocs == Exprs.size()) ? void (
0) : __assert_fail ("NumAssocs == Exprs.size()", "clang/lib/Sema/SemaExpr.cpp"
, 1647, __extension__ __PRETTY_FUNCTION__))
;
1648
1649 // Decay and strip qualifiers for the controlling expression type, and handle
1650 // placeholder type replacement. See committee discussion from WG14 DR423.
1651 {
1652 EnterExpressionEvaluationContext Unevaluated(
1653 *this, Sema::ExpressionEvaluationContext::Unevaluated);
1654 ExprResult R = DefaultFunctionArrayLvalueConversion(ControllingExpr);
1655 if (R.isInvalid())
1656 return ExprError();
1657 ControllingExpr = R.get();
1658 }
1659
1660 bool TypeErrorFound = false,
1661 IsResultDependent = ControllingExpr->isTypeDependent(),
1662 ContainsUnexpandedParameterPack
1663 = ControllingExpr->containsUnexpandedParameterPack();
1664
1665 // The controlling expression is an unevaluated operand, so side effects are
1666 // likely unintended.
1667 if (!inTemplateInstantiation() && !IsResultDependent &&
1668 ControllingExpr->HasSideEffects(Context, false))
1669 Diag(ControllingExpr->getExprLoc(),
1670 diag::warn_side_effects_unevaluated_context);
1671
1672 for (unsigned i = 0; i < NumAssocs; ++i) {
1673 if (Exprs[i]->containsUnexpandedParameterPack())
1674 ContainsUnexpandedParameterPack = true;
1675
1676 if (Types[i]) {
1677 if (Types[i]->getType()->containsUnexpandedParameterPack())
1678 ContainsUnexpandedParameterPack = true;
1679
1680 if (Types[i]->getType()->isDependentType()) {
1681 IsResultDependent = true;
1682 } else {
1683 // C11 6.5.1.1p2 "The type name in a generic association shall specify a
1684 // complete object type other than a variably modified type."
1685 unsigned D = 0;
1686 if (Types[i]->getType()->isIncompleteType())
1687 D = diag::err_assoc_type_incomplete;
1688 else if (!Types[i]->getType()->isObjectType())
1689 D = diag::err_assoc_type_nonobject;
1690 else if (Types[i]->getType()->isVariablyModifiedType())
1691 D = diag::err_assoc_type_variably_modified;
1692 else {
1693 // Because the controlling expression undergoes lvalue conversion,
1694 // array conversion, and function conversion, an association which is
1695 // of array type, function type, or is qualified can never be
1696 // reached. We will warn about this so users are less surprised by
1697 // the unreachable association. However, we don't have to handle
1698 // function types; that's not an object type, so it's handled above.
1699 //
1700 // The logic is somewhat different for C++ because C++ has different
1701 // lvalue to rvalue conversion rules than C. [conv.lvalue]p1 says,
1702 // If T is a non-class type, the type of the prvalue is the cv-
1703 // unqualified version of T. Otherwise, the type of the prvalue is T.
1704 // The result of these rules is that all qualified types in an
1705 // association in C are unreachable, and in C++, only qualified non-
1706 // class types are unreachable.
1707 unsigned Reason = 0;
1708 QualType QT = Types[i]->getType();
1709 if (QT->isArrayType())
1710 Reason = 1;
1711 else if (QT.hasQualifiers() &&
1712 (!LangOpts.CPlusPlus || !QT->isRecordType()))
1713 Reason = 2;
1714
1715 if (Reason)
1716 Diag(Types[i]->getTypeLoc().getBeginLoc(),
1717 diag::warn_unreachable_association)
1718 << QT << (Reason - 1);
1719 }
1720
1721 if (D != 0) {
1722 Diag(Types[i]->getTypeLoc().getBeginLoc(), D)
1723 << Types[i]->getTypeLoc().getSourceRange()
1724 << Types[i]->getType();
1725 TypeErrorFound = true;
1726 }
1727
1728 // C11 6.5.1.1p2 "No two generic associations in the same generic
1729 // selection shall specify compatible types."
1730 for (unsigned j = i+1; j < NumAssocs; ++j)
1731 if (Types[j] && !Types[j]->getType()->isDependentType() &&
1732 Context.typesAreCompatible(Types[i]->getType(),
1733 Types[j]->getType())) {
1734 Diag(Types[j]->getTypeLoc().getBeginLoc(),
1735 diag::err_assoc_compatible_types)
1736 << Types[j]->getTypeLoc().getSourceRange()
1737 << Types[j]->getType()
1738 << Types[i]->getType();
1739 Diag(Types[i]->getTypeLoc().getBeginLoc(),
1740 diag::note_compat_assoc)
1741 << Types[i]->getTypeLoc().getSourceRange()
1742 << Types[i]->getType();
1743 TypeErrorFound = true;
1744 }
1745 }
1746 }
1747 }
1748 if (TypeErrorFound)
1749 return ExprError();
1750
1751 // If we determined that the generic selection is result-dependent, don't
1752 // try to compute the result expression.
1753 if (IsResultDependent)
1754 return GenericSelectionExpr::Create(Context, KeyLoc, ControllingExpr, Types,
1755 Exprs, DefaultLoc, RParenLoc,
1756 ContainsUnexpandedParameterPack);
1757
1758 SmallVector<unsigned, 1> CompatIndices;
1759 unsigned DefaultIndex = -1U;
1760 // Look at the canonical type of the controlling expression in case it was a
1761 // deduced type like __auto_type. However, when issuing diagnostics, use the
1762 // type the user wrote in source rather than the canonical one.
1763 for (unsigned i = 0; i < NumAssocs; ++i) {
1764 if (!Types[i])
1765 DefaultIndex = i;
1766 else if (Context.typesAreCompatible(
1767 ControllingExpr->getType().getCanonicalType(),
1768 Types[i]->getType()))
1769 CompatIndices.push_back(i);
1770 }
1771
1772 // C11 6.5.1.1p2 "The controlling expression of a generic selection shall have
1773 // type compatible with at most one of the types named in its generic
1774 // association list."
1775 if (CompatIndices.size() > 1) {
1776 // We strip parens here because the controlling expression is typically
1777 // parenthesized in macro definitions.
1778 ControllingExpr = ControllingExpr->IgnoreParens();
1779 Diag(ControllingExpr->getBeginLoc(), diag::err_generic_sel_multi_match)
1780 << ControllingExpr->getSourceRange() << ControllingExpr->getType()
1781 << (unsigned)CompatIndices.size();
1782 for (unsigned I : CompatIndices) {
1783 Diag(Types[I]->getTypeLoc().getBeginLoc(),
1784 diag::note_compat_assoc)
1785 << Types[I]->getTypeLoc().getSourceRange()
1786 << Types[I]->getType();
1787 }
1788 return ExprError();
1789 }
1790
1791 // C11 6.5.1.1p2 "If a generic selection has no default generic association,
1792 // its controlling expression shall have type compatible with exactly one of
1793 // the types named in its generic association list."
1794 if (DefaultIndex == -1U && CompatIndices.size() == 0) {
1795 // We strip parens here because the controlling expression is typically
1796 // parenthesized in macro definitions.
1797 ControllingExpr = ControllingExpr->IgnoreParens();
1798 Diag(ControllingExpr->getBeginLoc(), diag::err_generic_sel_no_match)
1799 << ControllingExpr->getSourceRange() << ControllingExpr->getType();
1800 return ExprError();
1801 }
1802
1803 // C11 6.5.1.1p3 "If a generic selection has a generic association with a
1804 // type name that is compatible with the type of the controlling expression,
1805 // then the result expression of the generic selection is the expression
1806 // in that generic association. Otherwise, the result expression of the
1807 // generic selection is the expression in the default generic association."
1808 unsigned ResultIndex =
1809 CompatIndices.size() ? CompatIndices[0] : DefaultIndex;
1810
1811 return GenericSelectionExpr::Create(
1812 Context, KeyLoc, ControllingExpr, Types, Exprs, DefaultLoc, RParenLoc,
1813 ContainsUnexpandedParameterPack, ResultIndex);
1814}
1815
1816/// getUDSuffixLoc - Create a SourceLocation for a ud-suffix, given the
1817/// location of the token and the offset of the ud-suffix within it.
1818static SourceLocation getUDSuffixLoc(Sema &S, SourceLocation TokLoc,
1819 unsigned Offset) {
1820 return Lexer::AdvanceToTokenCharacter(TokLoc, Offset, S.getSourceManager(),
1821 S.getLangOpts());
1822}
1823
1824/// BuildCookedLiteralOperatorCall - A user-defined literal was found. Look up
1825/// the corresponding cooked (non-raw) literal operator, and build a call to it.
1826static ExprResult BuildCookedLiteralOperatorCall(Sema &S, Scope *Scope,
1827 IdentifierInfo *UDSuffix,
1828 SourceLocation UDSuffixLoc,
1829 ArrayRef<Expr*> Args,
1830 SourceLocation LitEndLoc) {
1831 assert(Args.size() <= 2 && "too many arguments for literal operator")(static_cast <bool> (Args.size() <= 2 && "too many arguments for literal operator"
) ? void (0) : __assert_fail ("Args.size() <= 2 && \"too many arguments for literal operator\""
, "clang/lib/Sema/SemaExpr.cpp", 1831, __extension__ __PRETTY_FUNCTION__
))
;
1832
1833 QualType ArgTy[2];
1834 for (unsigned ArgIdx = 0; ArgIdx != Args.size(); ++ArgIdx) {
1835 ArgTy[ArgIdx] = Args[ArgIdx]->getType();
1836 if (ArgTy[ArgIdx]->isArrayType())
1837 ArgTy[ArgIdx] = S.Context.getArrayDecayedType(ArgTy[ArgIdx]);
1838 }
1839
1840 DeclarationName OpName =
1841 S.Context.DeclarationNames.getCXXLiteralOperatorName(UDSuffix);
1842 DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc);
1843 OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc);
1844
1845 LookupResult R(S, OpName, UDSuffixLoc, Sema::LookupOrdinaryName);
1846 if (S.LookupLiteralOperator(Scope, R, llvm::ArrayRef(ArgTy, Args.size()),
1847 /*AllowRaw*/ false, /*AllowTemplate*/ false,
1848 /*AllowStringTemplatePack*/ false,
1849 /*DiagnoseMissing*/ true) == Sema::LOLR_Error)
1850 return ExprError();
1851
1852 return S.BuildLiteralOperatorCall(R, OpNameInfo, Args, LitEndLoc);
1853}
1854
1855/// ActOnStringLiteral - The specified tokens were lexed as pasted string
1856/// fragments (e.g. "foo" "bar" L"baz"). The result string has to handle string
1857/// concatenation ([C99 5.1.1.2, translation phase #6]), so it may come from
1858/// multiple tokens. However, the common case is that StringToks points to one
1859/// string.
1860///
1861ExprResult
1862Sema::ActOnStringLiteral(ArrayRef<Token> StringToks, Scope *UDLScope) {
1863 assert(!StringToks.empty() && "Must have at least one string!")(static_cast <bool> (!StringToks.empty() && "Must have at least one string!"
) ? void (0) : __assert_fail ("!StringToks.empty() && \"Must have at least one string!\""
, "clang/lib/Sema/SemaExpr.cpp", 1863, __extension__ __PRETTY_FUNCTION__
))
;
1864
1865 StringLiteralParser Literal(StringToks, PP);
1866 if (Literal.hadError)
1867 return ExprError();
1868
1869 SmallVector<SourceLocation, 4> StringTokLocs;
1870 for (const Token &Tok : StringToks)
1871 StringTokLocs.push_back(Tok.getLocation());
1872
1873 QualType CharTy = Context.CharTy;
1874 StringLiteral::StringKind Kind = StringLiteral::Ordinary;
1875 if (Literal.isWide()) {
1876 CharTy = Context.getWideCharType();
1877 Kind = StringLiteral::Wide;
1878 } else if (Literal.isUTF8()) {
1879 if (getLangOpts().Char8)
1880 CharTy = Context.Char8Ty;
1881 Kind = StringLiteral::UTF8;
1882 } else if (Literal.isUTF16()) {
1883 CharTy = Context.Char16Ty;
1884 Kind = StringLiteral::UTF16;
1885 } else if (Literal.isUTF32()) {
1886 CharTy = Context.Char32Ty;
1887 Kind = StringLiteral::UTF32;
1888 } else if (Literal.isPascal()) {
1889 CharTy = Context.UnsignedCharTy;
1890 }
1891
1892 // Warn on initializing an array of char from a u8 string literal; this
1893 // becomes ill-formed in C++2a.
1894 if (getLangOpts().CPlusPlus && !getLangOpts().CPlusPlus20 &&
1895 !getLangOpts().Char8 && Kind == StringLiteral::UTF8) {
1896 Diag(StringTokLocs.front(), diag::warn_cxx20_compat_utf8_string);
1897
1898 // Create removals for all 'u8' prefixes in the string literal(s). This
1899 // ensures C++2a compatibility (but may change the program behavior when
1900 // built by non-Clang compilers for which the execution character set is
1901 // not always UTF-8).
1902 auto RemovalDiag = PDiag(diag::note_cxx20_compat_utf8_string_remove_u8);
1903 SourceLocation RemovalDiagLoc;
1904 for (const Token &Tok : StringToks) {
1905 if (Tok.getKind() == tok::utf8_string_literal) {
1906 if (RemovalDiagLoc.isInvalid())
1907 RemovalDiagLoc = Tok.getLocation();
1908 RemovalDiag << FixItHint::CreateRemoval(CharSourceRange::getCharRange(
1909 Tok.getLocation(),
1910 Lexer::AdvanceToTokenCharacter(Tok.getLocation(), 2,
1911 getSourceManager(), getLangOpts())));
1912 }
1913 }
1914 Diag(RemovalDiagLoc, RemovalDiag);
1915 }
1916
1917 QualType StrTy =
1918 Context.getStringLiteralArrayType(CharTy, Literal.GetNumStringChars());
1919
1920 // Pass &StringTokLocs[0], StringTokLocs.size() to factory!
1921 StringLiteral *Lit = StringLiteral::Create(Context, Literal.GetString(),
1922 Kind, Literal.Pascal, StrTy,
1923 &StringTokLocs[0],
1924 StringTokLocs.size());
1925 if (Literal.getUDSuffix().empty())
1926 return Lit;
1927
1928 // We're building a user-defined literal.
1929 IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix());
1930 SourceLocation UDSuffixLoc =
1931 getUDSuffixLoc(*this, StringTokLocs[Literal.getUDSuffixToken()],
1932 Literal.getUDSuffixOffset());
1933
1934 // Make sure we're allowed user-defined literals here.
1935 if (!UDLScope)
1936 return ExprError(Diag(UDSuffixLoc, diag::err_invalid_string_udl));
1937
1938 // C++11 [lex.ext]p5: The literal L is treated as a call of the form
1939 // operator "" X (str, len)
1940 QualType SizeType = Context.getSizeType();
1941
1942 DeclarationName OpName =
1943 Context.DeclarationNames.getCXXLiteralOperatorName(UDSuffix);
1944 DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc);
1945 OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc);
1946
1947 QualType ArgTy[] = {
1948 Context.getArrayDecayedType(StrTy), SizeType
1949 };
1950
1951 LookupResult R(*this, OpName, UDSuffixLoc, LookupOrdinaryName);
1952 switch (LookupLiteralOperator(UDLScope, R, ArgTy,
1953 /*AllowRaw*/ false, /*AllowTemplate*/ true,
1954 /*AllowStringTemplatePack*/ true,
1955 /*DiagnoseMissing*/ true, Lit)) {
1956
1957 case LOLR_Cooked: {
1958 llvm::APInt Len(Context.getIntWidth(SizeType), Literal.GetNumStringChars());
1959 IntegerLiteral *LenArg = IntegerLiteral::Create(Context, Len, SizeType,
1960 StringTokLocs[0]);
1961 Expr *Args[] = { Lit, LenArg };
1962
1963 return BuildLiteralOperatorCall(R, OpNameInfo, Args, StringTokLocs.back());
1964 }
1965
1966 case LOLR_Template: {
1967 TemplateArgumentListInfo ExplicitArgs;
1968 TemplateArgument Arg(Lit);
1969 TemplateArgumentLocInfo ArgInfo(Lit);
1970 ExplicitArgs.addArgument(TemplateArgumentLoc(Arg, ArgInfo));
1971 return BuildLiteralOperatorCall(R, OpNameInfo, std::nullopt,
1972 StringTokLocs.back(), &ExplicitArgs);
1973 }
1974
1975 case LOLR_StringTemplatePack: {
1976 TemplateArgumentListInfo ExplicitArgs;
1977
1978 unsigned CharBits = Context.getIntWidth(CharTy);
1979 bool CharIsUnsigned = CharTy->isUnsignedIntegerType();
1980 llvm::APSInt Value(CharBits, CharIsUnsigned);
1981
1982 TemplateArgument TypeArg(CharTy);
1983 TemplateArgumentLocInfo TypeArgInfo(Context.getTrivialTypeSourceInfo(CharTy));
1984 ExplicitArgs.addArgument(TemplateArgumentLoc(TypeArg, TypeArgInfo));
1985
1986 for (unsigned I = 0, N = Lit->getLength(); I != N; ++I) {
1987 Value = Lit->getCodeUnit(I);
1988 TemplateArgument Arg(Context, Value, CharTy);
1989 TemplateArgumentLocInfo ArgInfo;
1990 ExplicitArgs.addArgument(TemplateArgumentLoc(Arg, ArgInfo));
1991 }
1992 return BuildLiteralOperatorCall(R, OpNameInfo, std::nullopt,
1993 StringTokLocs.back(), &ExplicitArgs);
1994 }
1995 case LOLR_Raw:
1996 case LOLR_ErrorNoDiagnostic:
1997 llvm_unreachable("unexpected literal operator lookup result")::llvm::llvm_unreachable_internal("unexpected literal operator lookup result"
, "clang/lib/Sema/SemaExpr.cpp", 1997)
;
1998 case LOLR_Error:
1999 return ExprError();
2000 }
2001 llvm_unreachable("unexpected literal operator lookup result")::llvm::llvm_unreachable_internal("unexpected literal operator lookup result"
, "clang/lib/Sema/SemaExpr.cpp", 2001)
;
2002}
2003
2004DeclRefExpr *
2005Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK,
2006 SourceLocation Loc,
2007 const CXXScopeSpec *SS) {
2008 DeclarationNameInfo NameInfo(D->getDeclName(), Loc);
2009 return BuildDeclRefExpr(D, Ty, VK, NameInfo, SS);
2010}
2011
2012DeclRefExpr *
2013Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK,
2014 const DeclarationNameInfo &NameInfo,
2015 const CXXScopeSpec *SS, NamedDecl *FoundD,
2016 SourceLocation TemplateKWLoc,
2017 const TemplateArgumentListInfo *TemplateArgs) {
2018 NestedNameSpecifierLoc NNS =
2019 SS ? SS->getWithLocInContext(Context) : NestedNameSpecifierLoc();
2020 return BuildDeclRefExpr(D, Ty, VK, NameInfo, NNS, FoundD, TemplateKWLoc,
2021 TemplateArgs);
2022}
2023
2024// CUDA/HIP: Check whether a captured reference variable is referencing a
2025// host variable in a device or host device lambda.
2026static bool isCapturingReferenceToHostVarInCUDADeviceLambda(const Sema &S,
2027 VarDecl *VD) {
2028 if (!S.getLangOpts().CUDA || !VD->hasInit())
2029 return false;
2030 assert(VD->getType()->isReferenceType())(static_cast <bool> (VD->getType()->isReferenceType
()) ? void (0) : __assert_fail ("VD->getType()->isReferenceType()"
, "clang/lib/Sema/SemaExpr.cpp", 2030, __extension__ __PRETTY_FUNCTION__
))
;
2031
2032 // Check whether the reference variable is referencing a host variable.
2033 auto *DRE = dyn_cast<DeclRefExpr>(VD->getInit());
2034 if (!DRE)
2035 return false;
2036 auto *Referee = dyn_cast<VarDecl>(DRE->getDecl());
2037 if (!Referee || !Referee->hasGlobalStorage() ||
2038 Referee->hasAttr<CUDADeviceAttr>())
2039 return false;
2040
2041 // Check whether the current function is a device or host device lambda.
2042 // Check whether the reference variable is a capture by getDeclContext()
2043 // since refersToEnclosingVariableOrCapture() is not ready at this point.
2044 auto *MD = dyn_cast_or_null<CXXMethodDecl>(S.CurContext);
2045 if (MD && MD->getParent()->isLambda() &&
2046 MD->getOverloadedOperator() == OO_Call && MD->hasAttr<CUDADeviceAttr>() &&
2047 VD->getDeclContext() != MD)
2048 return true;
2049
2050 return false;
2051}
2052
2053NonOdrUseReason Sema::getNonOdrUseReasonInCurrentContext(ValueDecl *D) {
2054 // A declaration named in an unevaluated operand never constitutes an odr-use.
2055 if (isUnevaluatedContext())
2056 return NOUR_Unevaluated;
2057
2058 // C++2a [basic.def.odr]p4:
2059 // A variable x whose name appears as a potentially-evaluated expression e
2060 // is odr-used by e unless [...] x is a reference that is usable in
2061 // constant expressions.
2062 // CUDA/HIP:
2063 // If a reference variable referencing a host variable is captured in a
2064 // device or host device lambda, the value of the referee must be copied
2065 // to the capture and the reference variable must be treated as odr-use
2066 // since the value of the referee is not known at compile time and must
2067 // be loaded from the captured.
2068 if (VarDecl *VD = dyn_cast<VarDecl>(D)) {
2069 if (VD->getType()->isReferenceType() &&
2070 !(getLangOpts().OpenMP && isOpenMPCapturedDecl(D)) &&
2071 !isCapturingReferenceToHostVarInCUDADeviceLambda(*this, VD) &&
2072 VD->isUsableInConstantExpressions(Context))
2073 return NOUR_Constant;
2074 }
2075
2076 // All remaining non-variable cases constitute an odr-use. For variables, we
2077 // need to wait and see how the expression is used.
2078 return NOUR_None;
2079}
2080
2081/// BuildDeclRefExpr - Build an expression that references a
2082/// declaration that does not require a closure capture.
2083DeclRefExpr *
2084Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK,
2085 const DeclarationNameInfo &NameInfo,
2086 NestedNameSpecifierLoc NNS, NamedDecl *FoundD,
2087 SourceLocation TemplateKWLoc,
2088 const TemplateArgumentListInfo *TemplateArgs) {
2089 bool RefersToCapturedVariable = isa<VarDecl, BindingDecl>(D) &&
2090 NeedToCaptureVariable(D, NameInfo.getLoc());
2091
2092 DeclRefExpr *E = DeclRefExpr::Create(
2093 Context, NNS, TemplateKWLoc, D, RefersToCapturedVariable, NameInfo, Ty,
2094 VK, FoundD, TemplateArgs, getNonOdrUseReasonInCurrentContext(D));
2095 MarkDeclRefReferenced(E);
2096
2097 // C++ [except.spec]p17:
2098 // An exception-specification is considered to be needed when:
2099 // - in an expression, the function is the unique lookup result or
2100 // the selected member of a set of overloaded functions.
2101 //
2102 // We delay doing this until after we've built the function reference and
2103 // marked it as used so that:
2104 // a) if the function is defaulted, we get errors from defining it before /
2105 // instead of errors from computing its exception specification, and
2106 // b) if the function is a defaulted comparison, we can use the body we
2107 // build when defining it as input to the exception specification
2108 // computation rather than computing a new body.
2109 if (const auto *FPT = Ty->getAs<FunctionProtoType>()) {
2110 if (isUnresolvedExceptionSpec(FPT->getExceptionSpecType())) {
2111 if (const auto *NewFPT = ResolveExceptionSpec(NameInfo.getLoc(), FPT))
2112 E->setType(Context.getQualifiedType(NewFPT, Ty.getQualifiers()));
2113 }
2114 }
2115
2116 if (getLangOpts().ObjCWeak && isa<VarDecl>(D) &&
2117 Ty.getObjCLifetime() == Qualifiers::OCL_Weak && !isUnevaluatedContext() &&
2118 !Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, E->getBeginLoc()))
2119 getCurFunction()->recordUseOfWeak(E);
2120
2121 const auto *FD = dyn_cast<FieldDecl>(D);
2122 if (const auto *IFD = dyn_cast<IndirectFieldDecl>(D))
2123 FD = IFD->getAnonField();
2124 if (FD) {
2125 UnusedPrivateFields.remove(FD);
2126 // Just in case we're building an illegal pointer-to-member.
2127 if (FD->isBitField())
2128 E->setObjectKind(OK_BitField);
2129 }
2130
2131 // C++ [expr.prim]/8: The expression [...] is a bit-field if the identifier
2132 // designates a bit-field.
2133 if (const auto *BD = dyn_cast<BindingDecl>(D))
2134 if (const auto *BE = BD->getBinding())
2135 E->setObjectKind(BE->getObjectKind());
2136
2137 return E;
2138}
2139
2140/// Decomposes the given name into a DeclarationNameInfo, its location, and
2141/// possibly a list of template arguments.
2142///
2143/// If this produces template arguments, it is permitted to call
2144/// DecomposeTemplateName.
2145///
2146/// This actually loses a lot of source location information for
2147/// non-standard name kinds; we should consider preserving that in
2148/// some way.
2149void
2150Sema::DecomposeUnqualifiedId(const UnqualifiedId &Id,
2151 TemplateArgumentListInfo &Buffer,
2152 DeclarationNameInfo &NameInfo,
2153 const TemplateArgumentListInfo *&TemplateArgs) {
2154 if (Id.getKind() == UnqualifiedIdKind::IK_TemplateId) {
2155 Buffer.setLAngleLoc(Id.TemplateId->LAngleLoc);
2156 Buffer.setRAngleLoc(Id.TemplateId->RAngleLoc);
2157
2158 ASTTemplateArgsPtr TemplateArgsPtr(Id.TemplateId->getTemplateArgs(),
2159 Id.TemplateId->NumArgs);
2160 translateTemplateArguments(TemplateArgsPtr, Buffer);
2161
2162 TemplateName TName = Id.TemplateId->Template.get();
2163 SourceLocation TNameLoc = Id.TemplateId->TemplateNameLoc;
2164 NameInfo = Context.getNameForTemplate(TName, TNameLoc);
2165 TemplateArgs = &Buffer;
2166 } else {
2167 NameInfo = GetNameFromUnqualifiedId(Id);
2168 TemplateArgs = nullptr;
2169 }
2170}
2171
2172static void emitEmptyLookupTypoDiagnostic(
2173 const TypoCorrection &TC, Sema &SemaRef, const CXXScopeSpec &SS,
2174 DeclarationName Typo, SourceLocation TypoLoc, ArrayRef<Expr *> Args,
2175 unsigned DiagnosticID, unsigned DiagnosticSuggestID) {
2176 DeclContext *Ctx =
2177 SS.isEmpty() ? nullptr : SemaRef.computeDeclContext(SS, false);
2178 if (!TC) {
2179 // Emit a special diagnostic for failed member lookups.
2180 // FIXME: computing the declaration context might fail here (?)
2181 if (Ctx)
2182 SemaRef.Diag(TypoLoc, diag::err_no_member) << Typo << Ctx
2183 << SS.getRange();
2184 else
2185 SemaRef.Diag(TypoLoc, DiagnosticID) << Typo;
2186 return;
2187 }
2188
2189 std::string CorrectedStr = TC.getAsString(SemaRef.getLangOpts());
2190 bool DroppedSpecifier =
2191 TC.WillReplaceSpecifier() && Typo.getAsString() == CorrectedStr;
2192 unsigned NoteID = TC.getCorrectionDeclAs<ImplicitParamDecl>()
2193 ? diag::note_implicit_param_decl
2194 : diag::note_previous_decl;
2195 if (!Ctx)
2196 SemaRef.diagnoseTypo(TC, SemaRef.PDiag(DiagnosticSuggestID) << Typo,
2197 SemaRef.PDiag(NoteID));
2198 else
2199 SemaRef.diagnoseTypo(TC, SemaRef.PDiag(diag::err_no_member_suggest)
2200 << Typo << Ctx << DroppedSpecifier
2201 << SS.getRange(),
2202 SemaRef.PDiag(NoteID));
2203}
2204
2205/// Diagnose a lookup that found results in an enclosing class during error
2206/// recovery. This usually indicates that the results were found in a dependent
2207/// base class that could not be searched as part of a template definition.
2208/// Always issues a diagnostic (though this may be only a warning in MS
2209/// compatibility mode).
2210///
2211/// Return \c true if the error is unrecoverable, or \c false if the caller
2212/// should attempt to recover using these lookup results.
2213bool Sema::DiagnoseDependentMemberLookup(const LookupResult &R) {
2214 // During a default argument instantiation the CurContext points
2215 // to a CXXMethodDecl; but we can't apply a this-> fixit inside a
2216 // function parameter list, hence add an explicit check.
2217 bool isDefaultArgument =
2218 !CodeSynthesisContexts.empty() &&
2219 CodeSynthesisContexts.back().Kind ==
2220 CodeSynthesisContext::DefaultFunctionArgumentInstantiation;
2221 const auto *CurMethod = dyn_cast<CXXMethodDecl>(CurContext);
2222 bool isInstance = CurMethod && CurMethod->isInstance() &&
2223 R.getNamingClass() == CurMethod->getParent() &&
2224 !isDefaultArgument;
2225
2226 // There are two ways we can find a class-scope declaration during template
2227 // instantiation that we did not find in the template definition: if it is a
2228 // member of a dependent base class, or if it is declared after the point of
2229 // use in the same class. Distinguish these by comparing the class in which
2230 // the member was found to the naming class of the lookup.
2231 unsigned DiagID = diag::err_found_in_dependent_base;
2232 unsigned NoteID = diag::note_member_declared_at;
2233 if (R.getRepresentativeDecl()->getDeclContext()->Equals(R.getNamingClass())) {
2234 DiagID = getLangOpts().MSVCCompat ? diag::ext_found_later_in_class
2235 : diag::err_found_later_in_class;
2236 } else if (getLangOpts().MSVCCompat) {
2237 DiagID = diag::ext_found_in_dependent_base;
2238 NoteID = diag::note_dependent_member_use;
2239 }
2240
2241 if (isInstance) {
2242 // Give a code modification hint to insert 'this->'.
2243 Diag(R.getNameLoc(), DiagID)
2244 << R.getLookupName()
2245 << FixItHint::CreateInsertion(R.getNameLoc(), "this->");
2246 CheckCXXThisCapture(R.getNameLoc());
2247 } else {
2248 // FIXME: Add a FixItHint to insert 'Base::' or 'Derived::' (assuming
2249 // they're not shadowed).
2250 Diag(R.getNameLoc(), DiagID) << R.getLookupName();
2251 }
2252
2253 for (const NamedDecl *D : R)
2254 Diag(D->getLocation(), NoteID);
2255
2256 // Return true if we are inside a default argument instantiation
2257 // and the found name refers to an instance member function, otherwise
2258 // the caller will try to create an implicit member call and this is wrong
2259 // for default arguments.
2260 //
2261 // FIXME: Is this special case necessary? We could allow the caller to
2262 // diagnose this.
2263 if (isDefaultArgument && ((*R.begin())->isCXXInstanceMember())) {
2264 Diag(R.getNameLoc(), diag::err_member_call_without_object);
2265 return true;
2266 }
2267
2268 // Tell the callee to try to recover.
2269 return false;
2270}
2271
2272/// Diagnose an empty lookup.
2273///
2274/// \return false if new lookup candidates were found
2275bool Sema::DiagnoseEmptyLookup(Scope *S, CXXScopeSpec &SS, LookupResult &R,
2276 CorrectionCandidateCallback &CCC,
2277 TemplateArgumentListInfo *ExplicitTemplateArgs,
2278 ArrayRef<Expr *> Args, TypoExpr **Out) {
2279 DeclarationName Name = R.getLookupName();
2280
2281 unsigned diagnostic = diag::err_undeclared_var_use;
2282 unsigned diagnostic_suggest = diag::err_undeclared_var_use_suggest;
2283 if (Name.getNameKind() == DeclarationName::CXXOperatorName ||
2284 Name.getNameKind() == DeclarationName::CXXLiteralOperatorName ||
2285 Name.getNameKind() == DeclarationName::CXXConversionFunctionName) {
2286 diagnostic = diag::err_undeclared_use;
2287 diagnostic_suggest = diag::err_undeclared_use_suggest;
2288 }
2289
2290 // If the original lookup was an unqualified lookup, fake an
2291 // unqualified lookup. This is useful when (for example) the
2292 // original lookup would not have found something because it was a
2293 // dependent name.
2294 DeclContext *DC = SS.isEmpty() ? CurContext : nullptr;
2295 while (DC) {
2296 if (isa<CXXRecordDecl>(DC)) {
2297 LookupQualifiedName(R, DC);
2298
2299 if (!R.empty()) {
2300 // Don't give errors about ambiguities in this lookup.
2301 R.suppressDiagnostics();
2302
2303 // If there's a best viable function among the results, only mention
2304 // that one in the notes.
2305 OverloadCandidateSet Candidates(R.getNameLoc(),
2306 OverloadCandidateSet::CSK_Normal);
2307 AddOverloadedCallCandidates(R, ExplicitTemplateArgs, Args, Candidates);
2308 OverloadCandidateSet::iterator Best;
2309 if (Candidates.BestViableFunction(*this, R.getNameLoc(), Best) ==
2310 OR_Success) {
2311 R.clear();
2312 R.addDecl(Best->FoundDecl.getDecl(), Best->FoundDecl.getAccess());
2313 R.resolveKind();
2314 }
2315
2316 return DiagnoseDependentMemberLookup(R);
2317 }
2318
2319 R.clear();
2320 }
2321
2322 DC = DC->getLookupParent();
2323 }
2324
2325 // We didn't find anything, so try to correct for a typo.
2326 TypoCorrection Corrected;
2327 if (S && Out) {
2328 SourceLocation TypoLoc = R.getNameLoc();
2329 assert(!ExplicitTemplateArgs &&(static_cast <bool> (!ExplicitTemplateArgs && "Diagnosing an empty lookup with explicit template args!"
) ? void (0) : __assert_fail ("!ExplicitTemplateArgs && \"Diagnosing an empty lookup with explicit template args!\""
, "clang/lib/Sema/SemaExpr.cpp", 2330, __extension__ __PRETTY_FUNCTION__
))
2330 "Diagnosing an empty lookup with explicit template args!")(static_cast <bool> (!ExplicitTemplateArgs && "Diagnosing an empty lookup with explicit template args!"
) ? void (0) : __assert_fail ("!ExplicitTemplateArgs && \"Diagnosing an empty lookup with explicit template args!\""
, "clang/lib/Sema/SemaExpr.cpp", 2330, __extension__ __PRETTY_FUNCTION__
))
;
2331 *Out = CorrectTypoDelayed(
2332 R.getLookupNameInfo(), R.getLookupKind(), S, &SS, CCC,
2333 [=](const TypoCorrection &TC) {
2334 emitEmptyLookupTypoDiagnostic(TC, *this, SS, Name, TypoLoc, Args,
2335 diagnostic, diagnostic_suggest);
2336 },
2337 nullptr, CTK_ErrorRecovery);
2338 if (*Out)
2339 return true;
2340 } else if (S &&
2341 (Corrected = CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(),
2342 S, &SS, CCC, CTK_ErrorRecovery))) {
2343 std::string CorrectedStr(Corrected.getAsString(getLangOpts()));
2344 bool DroppedSpecifier =
2345 Corrected.WillReplaceSpecifier() && Name.getAsString() == CorrectedStr;
2346 R.setLookupName(Corrected.getCorrection());
2347
2348 bool AcceptableWithRecovery = false;
2349 bool AcceptableWithoutRecovery = false;
2350 NamedDecl *ND = Corrected.getFoundDecl();
2351 if (ND) {
2352 if (Corrected.isOverloaded()) {
2353 OverloadCandidateSet OCS(R.getNameLoc(),
2354 OverloadCandidateSet::CSK_Normal);
2355 OverloadCandidateSet::iterator Best;
2356 for (NamedDecl *CD : Corrected) {
2357 if (FunctionTemplateDecl *FTD =
2358 dyn_cast<FunctionTemplateDecl>(CD))
2359 AddTemplateOverloadCandidate(
2360 FTD, DeclAccessPair::make(FTD, AS_none), ExplicitTemplateArgs,
2361 Args, OCS);
2362 else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(CD))
2363 if (!ExplicitTemplateArgs || ExplicitTemplateArgs->size() == 0)
2364 AddOverloadCandidate(FD, DeclAccessPair::make(FD, AS_none),
2365 Args, OCS);
2366 }
2367 switch (OCS.BestViableFunction(*this, R.getNameLoc(), Best)) {
2368 case OR_Success:
2369 ND = Best->FoundDecl;
2370 Corrected.setCorrectionDecl(ND);
2371 break;
2372 default:
2373 // FIXME: Arbitrarily pick the first declaration for the note.
2374 Corrected.setCorrectionDecl(ND);
2375 break;
2376 }
2377 }
2378 R.addDecl(ND);
2379 if (getLangOpts().CPlusPlus && ND->isCXXClassMember()) {
2380 CXXRecordDecl *Record = nullptr;
2381 if (Corrected.getCorrectionSpecifier()) {
2382 const Type *Ty = Corrected.getCorrectionSpecifier()->getAsType();
2383 Record = Ty->getAsCXXRecordDecl();
2384 }
2385 if (!Record)
2386 Record = cast<CXXRecordDecl>(
2387 ND->getDeclContext()->getRedeclContext());
2388 R.setNamingClass(Record);
2389 }
2390
2391 auto *UnderlyingND = ND->getUnderlyingDecl();
2392 AcceptableWithRecovery = isa<ValueDecl>(UnderlyingND) ||
2393 isa<FunctionTemplateDecl>(UnderlyingND);
2394 // FIXME: If we ended up with a typo for a type name or
2395 // Objective-C class name, we're in trouble because the parser
2396 // is in the wrong place to recover. Suggest the typo
2397 // correction, but don't make it a fix-it since we're not going
2398 // to recover well anyway.
2399 AcceptableWithoutRecovery = isa<TypeDecl>(UnderlyingND) ||
2400 getAsTypeTemplateDecl(UnderlyingND) ||
2401 isa<ObjCInterfaceDecl>(UnderlyingND);
2402 } else {
2403 // FIXME: We found a keyword. Suggest it, but don't provide a fix-it
2404 // because we aren't able to recover.
2405 AcceptableWithoutRecovery = true;
2406 }
2407
2408 if (AcceptableWithRecovery || AcceptableWithoutRecovery) {
2409 unsigned NoteID = Corrected.getCorrectionDeclAs<ImplicitParamDecl>()
2410 ? diag::note_implicit_param_decl
2411 : diag::note_previous_decl;
2412 if (SS.isEmpty())
2413 diagnoseTypo(Corrected, PDiag(diagnostic_suggest) << Name,
2414 PDiag(NoteID), AcceptableWithRecovery);
2415 else
2416 diagnoseTypo(Corrected, PDiag(diag::err_no_member_suggest)
2417 << Name << computeDeclContext(SS, false)
2418 << DroppedSpecifier << SS.getRange(),
2419 PDiag(NoteID), AcceptableWithRecovery);
2420
2421 // Tell the callee whether to try to recover.
2422 return !AcceptableWithRecovery;
2423 }
2424 }
2425 R.clear();
2426
2427 // Emit a special diagnostic for failed member lookups.
2428 // FIXME: computing the declaration context might fail here (?)
2429 if (!SS.isEmpty()) {
2430 Diag(R.getNameLoc(), diag::err_no_member)
2431 << Name << computeDeclContext(SS, false)
2432 << SS.getRange();
2433 return true;
2434 }
2435
2436 // Give up, we can't recover.
2437 Diag(R.getNameLoc(), diagnostic) << Name;
2438 return true;
2439}
2440
2441/// In Microsoft mode, if we are inside a template class whose parent class has
2442/// dependent base classes, and we can't resolve an unqualified identifier, then
2443/// assume the identifier is a member of a dependent base class. We can only
2444/// recover successfully in static methods, instance methods, and other contexts
2445/// where 'this' is available. This doesn't precisely match MSVC's
2446/// instantiation model, but it's close enough.
2447static Expr *
2448recoverFromMSUnqualifiedLookup(Sema &S, ASTContext &Context,
2449 DeclarationNameInfo &NameInfo,
2450 SourceLocation TemplateKWLoc,
2451 const TemplateArgumentListInfo *TemplateArgs) {
2452 // Only try to recover from lookup into dependent bases in static methods or
2453 // contexts where 'this' is available.
2454 QualType ThisType = S.getCurrentThisType();
2455 const CXXRecordDecl *RD = nullptr;
2456 if (!ThisType.isNull())
2457 RD = ThisType->getPointeeType()->getAsCXXRecordDecl();
2458 else if (auto *MD = dyn_cast<CXXMethodDecl>(S.CurContext))
2459 RD = MD->getParent();
2460 if (!RD || !RD->hasAnyDependentBases())
2461 return nullptr;
2462
2463 // Diagnose this as unqualified lookup into a dependent base class. If 'this'
2464 // is available, suggest inserting 'this->' as a fixit.
2465 SourceLocation Loc = NameInfo.getLoc();
2466 auto DB = S.Diag(Loc, diag::ext_undeclared_unqual_id_with_dependent_base);
2467 DB << NameInfo.getName() << RD;
2468
2469 if (!ThisType.isNull()) {
2470 DB << FixItHint::CreateInsertion(Loc, "this->");
2471 return CXXDependentScopeMemberExpr::Create(
2472 Context, /*This=*/nullptr, ThisType, /*IsArrow=*/true,
2473 /*Op=*/SourceLocation(), NestedNameSpecifierLoc(), TemplateKWLoc,
2474 /*FirstQualifierFoundInScope=*/nullptr, NameInfo, TemplateArgs);
2475 }
2476
2477 // Synthesize a fake NNS that points to the derived class. This will
2478 // perform name lookup during template instantiation.
2479 CXXScopeSpec SS;
2480 auto *NNS =
2481 NestedNameSpecifier::Create(Context, nullptr, true, RD->getTypeForDecl());
2482 SS.MakeTrivial(Context, NNS, SourceRange(Loc, Loc));
2483 return DependentScopeDeclRefExpr::Create(
2484 Context, SS.getWithLocInContext(Context), TemplateKWLoc, NameInfo,
2485 TemplateArgs);
2486}
2487
2488ExprResult
2489Sema::ActOnIdExpression(Scope *S, CXXScopeSpec &SS,
2490 SourceLocation TemplateKWLoc, UnqualifiedId &Id,
2491 bool HasTrailingLParen, bool IsAddressOfOperand,
2492 CorrectionCandidateCallback *CCC,
2493 bool IsInlineAsmIdentifier, Token *KeywordReplacement) {
2494 assert(!(IsAddressOfOperand && HasTrailingLParen) &&(static_cast <bool> (!(IsAddressOfOperand && HasTrailingLParen
) && "cannot be direct & operand and have a trailing lparen"
) ? void (0) : __assert_fail ("!(IsAddressOfOperand && HasTrailingLParen) && \"cannot be direct & operand and have a trailing lparen\""
, "clang/lib/Sema/SemaExpr.cpp", 2495, __extension__ __PRETTY_FUNCTION__
))
2495 "cannot be direct & operand and have a trailing lparen")(static_cast <bool> (!(IsAddressOfOperand && HasTrailingLParen
) && "cannot be direct & operand and have a trailing lparen"
) ? void (0) : __assert_fail ("!(IsAddressOfOperand && HasTrailingLParen) && \"cannot be direct & operand and have a trailing lparen\""
, "clang/lib/Sema/SemaExpr.cpp", 2495, __extension__ __PRETTY_FUNCTION__
))
;
2496 if (SS.isInvalid())
2497 return ExprError();
2498
2499 TemplateArgumentListInfo TemplateArgsBuffer;
2500
2501 // Decompose the UnqualifiedId into the following data.
2502 DeclarationNameInfo NameInfo;
2503 const TemplateArgumentListInfo *TemplateArgs;
2504 DecomposeUnqualifiedId(Id, TemplateArgsBuffer, NameInfo, TemplateArgs);
2505
2506 DeclarationName Name = NameInfo.getName();
2507 IdentifierInfo *II = Name.getAsIdentifierInfo();
2508 SourceLocation NameLoc = NameInfo.getLoc();
2509
2510 if (II && II->isEditorPlaceholder()) {
2511 // FIXME: When typed placeholders are supported we can create a typed
2512 // placeholder expression node.
2513 return ExprError();
2514 }
2515
2516 // C++ [temp.dep.expr]p3:
2517 // An id-expression is type-dependent if it contains:
2518 // -- an identifier that was declared with a dependent type,
2519 // (note: handled after lookup)
2520 // -- a template-id that is dependent,
2521 // (note: handled in BuildTemplateIdExpr)
2522 // -- a conversion-function-id that specifies a dependent type,
2523 // -- a nested-name-specifier that contains a class-name that
2524 // names a dependent type.
2525 // Determine whether this is a member of an unknown specialization;
2526 // we need to handle these differently.
2527 bool DependentID = false;
2528 if (Name.getNameKind() == DeclarationName::CXXConversionFunctionName &&
2529 Name.getCXXNameType()->isDependentType()) {
2530 DependentID = true;
2531 } else if (SS.isSet()) {
2532 if (DeclContext *DC = computeDeclContext(SS, false)) {
2533 if (RequireCompleteDeclContext(SS, DC))
2534 return ExprError();
2535 } else {
2536 DependentID = true;
2537 }
2538 }
2539
2540 if (DependentID)
2541 return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo,
2542 IsAddressOfOperand, TemplateArgs);
2543
2544 // Perform the required lookup.
2545 LookupResult R(*this, NameInfo,
2546 (Id.getKind() == UnqualifiedIdKind::IK_ImplicitSelfParam)
2547 ? LookupObjCImplicitSelfParam
2548 : LookupOrdinaryName);
2549 if (TemplateKWLoc.isValid() || TemplateArgs) {
2550 // Lookup the template name again to correctly establish the context in
2551 // which it was found. This is really unfortunate as we already did the
2552 // lookup to determine that it was a template name in the first place. If
2553 // this becomes a performance hit, we can work harder to preserve those
2554 // results until we get here but it's likely not worth it.
2555 bool MemberOfUnknownSpecialization;
2556 AssumedTemplateKind AssumedTemplate;
2557 if (LookupTemplateName(R, S, SS, QualType(), /*EnteringContext=*/false,
2558 MemberOfUnknownSpecialization, TemplateKWLoc,
2559 &AssumedTemplate))
2560 return ExprError();
2561
2562 if (MemberOfUnknownSpecialization ||
2563 (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation))
2564 return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo,
2565 IsAddressOfOperand, TemplateArgs);
2566 } else {
2567 bool IvarLookupFollowUp = II && !SS.isSet() && getCurMethodDecl();
2568 LookupParsedName(R, S, &SS, !IvarLookupFollowUp);
2569
2570 // If the result might be in a dependent base class, this is a dependent
2571 // id-expression.
2572 if (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation)
2573 return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo,
2574 IsAddressOfOperand, TemplateArgs);
2575
2576 // If this reference is in an Objective-C method, then we need to do
2577 // some special Objective-C lookup, too.
2578 if (IvarLookupFollowUp) {
2579 ExprResult E(LookupInObjCMethod(R, S, II, true));
2580 if (E.isInvalid())
2581 return ExprError();
2582
2583 if (Expr *Ex = E.getAs<Expr>())
2584 return Ex;
2585 }
2586 }
2587
2588 if (R.isAmbiguous())
2589 return ExprError();
2590
2591 // This could be an implicitly declared function reference if the language
2592 // mode allows it as a feature.
2593 if (R.empty() && HasTrailingLParen && II &&
2594 getLangOpts().implicitFunctionsAllowed()) {
2595 NamedDecl *D = ImplicitlyDefineFunction(NameLoc, *II, S);
2596 if (D) R.addDecl(D);
2597 }
2598
2599 // Determine whether this name might be a candidate for
2600 // argument-dependent lookup.
2601 bool ADL = UseArgumentDependentLookup(SS, R, HasTrailingLParen);
2602
2603 if (R.empty() && !ADL) {
2604 if (SS.isEmpty() && getLangOpts().MSVCCompat) {
2605 if (Expr *E = recoverFromMSUnqualifiedLookup(*this, Context, NameInfo,
2606 TemplateKWLoc, TemplateArgs))
2607 return E;
2608 }
2609
2610 // Don't diagnose an empty lookup for inline assembly.
2611 if (IsInlineAsmIdentifier)
2612 return ExprError();
2613
2614 // If this name wasn't predeclared and if this is not a function
2615 // call, diagnose the problem.
2616 TypoExpr *TE = nullptr;
2617 DefaultFilterCCC DefaultValidator(II, SS.isValid() ? SS.getScopeRep()
2618 : nullptr);
2619 DefaultValidator.IsAddressOfOperand = IsAddressOfOperand;
2620 assert((!CCC || CCC->IsAddressOfOperand == IsAddressOfOperand) &&(static_cast <bool> ((!CCC || CCC->IsAddressOfOperand
== IsAddressOfOperand) && "Typo correction callback misconfigured"
) ? void (0) : __assert_fail ("(!CCC || CCC->IsAddressOfOperand == IsAddressOfOperand) && \"Typo correction callback misconfigured\""
, "clang/lib/Sema/SemaExpr.cpp", 2621, __extension__ __PRETTY_FUNCTION__
))
2621 "Typo correction callback misconfigured")(static_cast <bool> ((!CCC || CCC->IsAddressOfOperand
== IsAddressOfOperand) && "Typo correction callback misconfigured"
) ? void (0) : __assert_fail ("(!CCC || CCC->IsAddressOfOperand == IsAddressOfOperand) && \"Typo correction callback misconfigured\""
, "clang/lib/Sema/SemaExpr.cpp", 2621, __extension__ __PRETTY_FUNCTION__
))
;
2622 if (CCC) {
2623 // Make sure the callback knows what the typo being diagnosed is.
2624 CCC->setTypoName(II);
2625 if (SS.isValid())
2626 CCC->setTypoNNS(SS.getScopeRep());
2627 }
2628 // FIXME: DiagnoseEmptyLookup produces bad diagnostics if we're looking for
2629 // a template name, but we happen to have always already looked up the name
2630 // before we get here if it must be a template name.
2631 if (DiagnoseEmptyLookup(S, SS, R, CCC ? *CCC : DefaultValidator, nullptr,
2632 std::nullopt, &TE)) {
2633 if (TE && KeywordReplacement) {
2634 auto &State = getTypoExprState(TE);
2635 auto BestTC = State.Consumer->getNextCorrection();
2636 if (BestTC.isKeyword()) {
2637 auto *II = BestTC.getCorrectionAsIdentifierInfo();
2638 if (State.DiagHandler)
2639 State.DiagHandler(BestTC);
2640 KeywordReplacement->startToken();
2641 KeywordReplacement->setKind(II->getTokenID());
2642 KeywordReplacement->setIdentifierInfo(II);
2643 KeywordReplacement->setLocation(BestTC.getCorrectionRange().getBegin());
2644 // Clean up the state associated with the TypoExpr, since it has
2645 // now been diagnosed (without a call to CorrectDelayedTyposInExpr).
2646 clearDelayedTypo(TE);
2647 // Signal that a correction to a keyword was performed by returning a
2648 // valid-but-null ExprResult.
2649 return (Expr*)nullptr;
2650 }
2651 State.Consumer->resetCorrectionStream();
2652 }
2653 return TE ? TE : ExprError();
2654 }
2655
2656 assert(!R.empty() &&(static_cast <bool> (!R.empty() && "DiagnoseEmptyLookup returned false but added no results"
) ? void (0) : __assert_fail ("!R.empty() && \"DiagnoseEmptyLookup returned false but added no results\""
, "clang/lib/Sema/SemaExpr.cpp", 2657, __extension__ __PRETTY_FUNCTION__
))
2657 "DiagnoseEmptyLookup returned false but added no results")(static_cast <bool> (!R.empty() && "DiagnoseEmptyLookup returned false but added no results"
) ? void (0) : __assert_fail ("!R.empty() && \"DiagnoseEmptyLookup returned false but added no results\""
, "clang/lib/Sema/SemaExpr.cpp", 2657, __extension__ __PRETTY_FUNCTION__
))
;
2658
2659 // If we found an Objective-C instance variable, let
2660 // LookupInObjCMethod build the appropriate expression to
2661 // reference the ivar.
2662 if (ObjCIvarDecl *Ivar = R.getAsSingle<ObjCIvarDecl>()) {
2663 R.clear();
2664 ExprResult E(LookupInObjCMethod(R, S, Ivar->getIdentifier()));
2665 // In a hopelessly buggy code, Objective-C instance variable
2666 // lookup fails and no expression will be built to reference it.
2667 if (!E.isInvalid() && !E.get())
2668 return ExprError();
2669 return E;
2670 }
2671 }
2672
2673 // This is guaranteed from this point on.
2674 assert(!R.empty() || ADL)(static_cast <bool> (!R.empty() || ADL) ? void (0) : __assert_fail
("!R.empty() || ADL", "clang/lib/Sema/SemaExpr.cpp", 2674, __extension__
__PRETTY_FUNCTION__))
;
2675
2676 // Check whether this might be a C++ implicit instance member access.
2677 // C++ [class.mfct.non-static]p3:
2678 // When an id-expression that is not part of a class member access
2679 // syntax and not used to form a pointer to member is used in the
2680 // body of a non-static member function of class X, if name lookup
2681 // resolves the name in the id-expression to a non-static non-type
2682 // member of some class C, the id-expression is transformed into a
2683 // class member access expression using (*this) as the
2684 // postfix-expression to the left of the . operator.
2685 //
2686 // But we don't actually need to do this for '&' operands if R
2687 // resolved to a function or overloaded function set, because the
2688 // expression is ill-formed if it actually works out to be a
2689 // non-static member function:
2690 //
2691 // C++ [expr.ref]p4:
2692 // Otherwise, if E1.E2 refers to a non-static member function. . .
2693 // [t]he expression can be used only as the left-hand operand of a
2694 // member function call.
2695 //
2696 // There are other safeguards against such uses, but it's important
2697 // to get this right here so that we don't end up making a
2698 // spuriously dependent expression if we're inside a dependent
2699 // instance method.
2700 if (!R.empty() && (*R.begin())->isCXXClassMember()) {
2701 bool MightBeImplicitMember;
2702 if (!IsAddressOfOperand)
2703 MightBeImplicitMember = true;
2704 else if (!SS.isEmpty())
2705 MightBeImplicitMember = false;
2706 else if (R.isOverloadedResult())
2707 MightBeImplicitMember = false;
2708 else if (R.isUnresolvableResult())
2709 MightBeImplicitMember = true;
2710 else
2711 MightBeImplicitMember = isa<FieldDecl>(R.getFoundDecl()) ||
2712 isa<IndirectFieldDecl>(R.getFoundDecl()) ||
2713 isa<MSPropertyDecl>(R.getFoundDecl());
2714
2715 if (MightBeImplicitMember)
2716 return BuildPossibleImplicitMemberExpr(SS, TemplateKWLoc,
2717 R, TemplateArgs, S);
2718 }
2719
2720 if (TemplateArgs || TemplateKWLoc.isValid()) {
2721
2722 // In C++1y, if this is a variable template id, then check it
2723 // in BuildTemplateIdExpr().
2724 // The single lookup result must be a variable template declaration.
2725 if (Id.getKind() == UnqualifiedIdKind::IK_TemplateId && Id.TemplateId &&
2726 Id.TemplateId->Kind == TNK_Var_template) {
2727 assert(R.getAsSingle<VarTemplateDecl>() &&(static_cast <bool> (R.getAsSingle<VarTemplateDecl>
() && "There should only be one declaration found.") ?
void (0) : __assert_fail ("R.getAsSingle<VarTemplateDecl>() && \"There should only be one declaration found.\""
, "clang/lib/Sema/SemaExpr.cpp", 2728, __extension__ __PRETTY_FUNCTION__
))
2728 "There should only be one declaration found.")(static_cast <bool> (R.getAsSingle<VarTemplateDecl>
() && "There should only be one declaration found.") ?
void (0) : __assert_fail ("R.getAsSingle<VarTemplateDecl>() && \"There should only be one declaration found.\""
, "clang/lib/Sema/SemaExpr.cpp", 2728, __extension__ __PRETTY_FUNCTION__
))
;
2729 }
2730
2731 return BuildTemplateIdExpr(SS, TemplateKWLoc, R, ADL, TemplateArgs);
2732 }
2733
2734 return BuildDeclarationNameExpr(SS, R, ADL);
2735}
2736
2737/// BuildQualifiedDeclarationNameExpr - Build a C++ qualified
2738/// declaration name, generally during template instantiation.
2739/// There's a large number of things which don't need to be done along
2740/// this path.
2741ExprResult Sema::BuildQualifiedDeclarationNameExpr(
2742 CXXScopeSpec &SS, const DeclarationNameInfo &NameInfo,
2743 bool IsAddressOfOperand, const Scope *S, TypeSourceInfo **RecoveryTSI) {
2744 if (NameInfo.getName().isDependentName())
2745 return BuildDependentDeclRefExpr(SS, /*TemplateKWLoc=*/SourceLocation(),
2746 NameInfo, /*TemplateArgs=*/nullptr);
2747
2748 DeclContext *DC = computeDeclContext(SS, false);
2749 if (!DC)
2750 return BuildDependentDeclRefExpr(SS, /*TemplateKWLoc=*/SourceLocation(),
2751 NameInfo, /*TemplateArgs=*/nullptr);
2752
2753 if (RequireCompleteDeclContext(SS, DC))
2754 return ExprError();
2755
2756 LookupResult R(*this, NameInfo, LookupOrdinaryName);
2757 LookupQualifiedName(R, DC);
2758
2759 if (R.isAmbiguous())
2760 return ExprError();
2761
2762 if (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation)
2763 return BuildDependentDeclRefExpr(SS, /*TemplateKWLoc=*/SourceLocation(),
2764 NameInfo, /*TemplateArgs=*/nullptr);
2765
2766 if (R.empty()) {
2767 // Don't diagnose problems with invalid record decl, the secondary no_member
2768 // diagnostic during template instantiation is likely bogus, e.g. if a class
2769 // is invalid because it's derived from an invalid base class, then missing
2770 // members were likely supposed to be inherited.
2771 if (const auto *CD = dyn_cast<CXXRecordDecl>(DC))
2772 if (CD->isInvalidDecl())
2773 return ExprError();
2774 Diag(NameInfo.getLoc(), diag::err_no_member)
2775 << NameInfo.getName() << DC << SS.getRange();
2776 return ExprError();
2777 }
2778
2779 if (const TypeDecl *TD = R.getAsSingle<TypeDecl>()) {
2780 // Diagnose a missing typename if this resolved unambiguously to a type in
2781 // a dependent context. If we can recover with a type, downgrade this to
2782 // a warning in Microsoft compatibility mode.
2783 unsigned DiagID = diag::err_typename_missing;
2784 if (RecoveryTSI && getLangOpts().MSVCCompat)
2785 DiagID = diag::ext_typename_missing;
2786 SourceLocation Loc = SS.getBeginLoc();
2787 auto D = Diag(Loc, DiagID);
2788 D << SS.getScopeRep() << NameInfo.getName().getAsString()
2789 << SourceRange(Loc, NameInfo.getEndLoc());
2790
2791 // Don't recover if the caller isn't expecting us to or if we're in a SFINAE
2792 // context.
2793 if (!RecoveryTSI)
2794 return ExprError();
2795
2796 // Only issue the fixit if we're prepared to recover.
2797 D << FixItHint::CreateInsertion(Loc, "typename ");
2798
2799 // Recover by pretending this was an elaborated type.
2800 QualType Ty = Context.getTypeDeclType(TD);
2801 TypeLocBuilder TLB;
2802 TLB.pushTypeSpec(Ty).setNameLoc(NameInfo.getLoc());
2803
2804 QualType ET = getElaboratedType(ETK_None, SS, Ty);
2805 ElaboratedTypeLoc QTL = TLB.push<ElaboratedTypeLoc>(ET);
2806 QTL.setElaboratedKeywordLoc(SourceLocation());
2807 QTL.setQualifierLoc(SS.getWithLocInContext(Context));
2808
2809 *RecoveryTSI = TLB.getTypeSourceInfo(Context, ET);
2810
2811 return ExprEmpty();
2812 }
2813
2814 // Defend against this resolving to an implicit member access. We usually
2815 // won't get here if this might be a legitimate a class member (we end up in
2816 // BuildMemberReferenceExpr instead), but this can be valid if we're forming
2817 // a pointer-to-member or in an unevaluated context in C++11.
2818 if (!R.empty() && (*R.begin())->isCXXClassMember() && !IsAddressOfOperand)
2819 return BuildPossibleImplicitMemberExpr(SS,
2820 /*TemplateKWLoc=*/SourceLocation(),
2821 R, /*TemplateArgs=*/nullptr, S);
2822
2823 return BuildDeclarationNameExpr(SS, R, /* ADL */ false);
2824}
2825
2826/// The parser has read a name in, and Sema has detected that we're currently
2827/// inside an ObjC method. Perform some additional checks and determine if we
2828/// should form a reference to an ivar.
2829///
2830/// Ideally, most of this would be done by lookup, but there's
2831/// actually quite a lot of extra work involved.
2832DeclResult Sema::LookupIvarInObjCMethod(LookupResult &Lookup, Scope *S,
2833 IdentifierInfo *II) {
2834 SourceLocation Loc = Lookup.getNameLoc();
2835 ObjCMethodDecl *CurMethod = getCurMethodDecl();
2836
2837 // Check for error condition which is already reported.
2838 if (!CurMethod)
2839 return DeclResult(true);
2840
2841 // There are two cases to handle here. 1) scoped lookup could have failed,
2842 // in which case we should look for an ivar. 2) scoped lookup could have
2843 // found a decl, but that decl is outside the current instance method (i.e.
2844 // a global variable). In these two cases, we do a lookup for an ivar with
2845 // this name, if the lookup sucedes, we replace it our current decl.
2846
2847 // If we're in a class method, we don't normally want to look for
2848 // ivars. But if we don't find anything else, and there's an
2849 // ivar, that's an error.
2850 bool IsClassMethod = CurMethod->isClassMethod();
2851
2852 bool LookForIvars;
2853 if (Lookup.empty())
2854 LookForIvars = true;
2855 else if (IsClassMethod)
2856 LookForIvars = false;
2857 else
2858 LookForIvars = (Lookup.isSingleResult() &&
2859 Lookup.getFoundDecl()->isDefinedOutsideFunctionOrMethod());
2860 ObjCInterfaceDecl *IFace = nullptr;
2861 if (LookForIvars) {
2862 IFace = CurMethod->getClassInterface();
2863 ObjCInterfaceDecl *ClassDeclared;
2864 ObjCIvarDecl *IV = nullptr;
2865 if (IFace && (IV = IFace->lookupInstanceVariable(II, ClassDeclared))) {
2866 // Diagnose using an ivar in a class method.
2867 if (IsClassMethod) {
2868 Diag(Loc, diag::err_ivar_use_in_class_method) << IV->getDeclName();
2869 return DeclResult(true);
2870 }
2871
2872 // Diagnose the use of an ivar outside of the declaring class.
2873 if (IV->getAccessControl() == ObjCIvarDecl::Private &&
2874 !declaresSameEntity(ClassDeclared, IFace) &&
2875 !getLangOpts().DebuggerSupport)
2876 Diag(Loc, diag::err_private_ivar_access) << IV->getDeclName();
2877
2878 // Success.
2879 return IV;
2880 }
2881 } else if (CurMethod->isInstanceMethod()) {
2882 // We should warn if a local variable hides an ivar.
2883 if (ObjCInterfaceDecl *IFace = CurMethod->getClassInterface()) {
2884 ObjCInterfaceDecl *ClassDeclared;
2885 if (ObjCIvarDecl *IV = IFace->lookupInstanceVariable(II, ClassDeclared)) {
2886 if (IV->getAccessControl() != ObjCIvarDecl::Private ||
2887 declaresSameEntity(IFace, ClassDeclared))
2888 Diag(Loc, diag::warn_ivar_use_hidden) << IV->getDeclName();
2889 }
2890 }
2891 } else if (Lookup.isSingleResult() &&
2892 Lookup.getFoundDecl()->isDefinedOutsideFunctionOrMethod()) {
2893 // If accessing a stand-alone ivar in a class method, this is an error.
2894 if (const ObjCIvarDecl *IV =
2895 dyn_cast<ObjCIvarDecl>(Lookup.getFoundDecl())) {
2896 Diag(Loc, diag::err_ivar_use_in_class_method) << IV->getDeclName();
2897 return DeclResult(true);
2898 }
2899 }
2900
2901 // Didn't encounter an error, didn't find an ivar.
2902 return DeclResult(false);
2903}
2904
2905ExprResult Sema::BuildIvarRefExpr(Scope *S, SourceLocation Loc,
2906 ObjCIvarDecl *IV) {
2907 ObjCMethodDecl *CurMethod = getCurMethodDecl();
2908 assert(CurMethod && CurMethod->isInstanceMethod() &&(static_cast <bool> (CurMethod && CurMethod->
isInstanceMethod() && "should not reference ivar from this context"
) ? void (0) : __assert_fail ("CurMethod && CurMethod->isInstanceMethod() && \"should not reference ivar from this context\""
, "clang/lib/Sema/SemaExpr.cpp", 2909, __extension__ __PRETTY_FUNCTION__
))
2909 "should not reference ivar from this context")(static_cast <bool> (CurMethod && CurMethod->
isInstanceMethod() && "should not reference ivar from this context"
) ? void (0) : __assert_fail ("CurMethod && CurMethod->isInstanceMethod() && \"should not reference ivar from this context\""
, "clang/lib/Sema/SemaExpr.cpp", 2909, __extension__ __PRETTY_FUNCTION__
))
;
2910
2911 ObjCInterfaceDecl *IFace = CurMethod->getClassInterface();
2912 assert(IFace && "should not reference ivar from this context")(static_cast <bool> (IFace && "should not reference ivar from this context"
) ? void (0) : __assert_fail ("IFace && \"should not reference ivar from this context\""
, "clang/lib/Sema/SemaExpr.cpp", 2912, __extension__ __PRETTY_FUNCTION__
))
;
2913
2914 // If we're referencing an invalid decl, just return this as a silent
2915 // error node. The error diagnostic was already emitted on the decl.
2916 if (IV->isInvalidDecl())
2917 return ExprError();
2918
2919 // Check if referencing a field with __attribute__((deprecated)).
2920 if (DiagnoseUseOfDecl(IV, Loc))
2921 return ExprError();
2922
2923 // FIXME: This should use a new expr for a direct reference, don't
2924 // turn this into Self->ivar, just return a BareIVarExpr or something.
2925 IdentifierInfo &II = Context.Idents.get("self");
2926 UnqualifiedId SelfName;
2927 SelfName.setImplicitSelfParam(&II);
2928 CXXScopeSpec SelfScopeSpec;
2929 SourceLocation TemplateKWLoc;
2930 ExprResult SelfExpr =
2931 ActOnIdExpression(S, SelfScopeSpec, TemplateKWLoc, SelfName,
2932 /*HasTrailingLParen=*/false,
2933 /*IsAddressOfOperand=*/false);
2934 if (SelfExpr.isInvalid())
2935 return ExprError();
2936
2937 SelfExpr = DefaultLvalueConversion(SelfExpr.get());
2938 if (SelfExpr.isInvalid())
2939 return ExprError();
2940
2941 MarkAnyDeclReferenced(Loc, IV, true);
2942
2943 ObjCMethodFamily MF = CurMethod->getMethodFamily();
2944 if (MF != OMF_init && MF != OMF_dealloc && MF != OMF_finalize &&
2945 !IvarBacksCurrentMethodAccessor(IFace, CurMethod, IV))
2946 Diag(Loc, diag::warn_direct_ivar_access) << IV->getDeclName();
2947
2948 ObjCIvarRefExpr *Result = new (Context)
2949 ObjCIvarRefExpr(IV, IV->getUsageType(SelfExpr.get()->getType()), Loc,
2950 IV->getLocation(), SelfExpr.get(), true, true);
2951
2952 if (IV->getType().getObjCLifetime() == Qualifiers::OCL_Weak) {
2953 if (!isUnevaluatedContext() &&
2954 !Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, Loc))
2955 getCurFunction()->recordUseOfWeak(Result);
2956 }
2957 if (getLangOpts().ObjCAutoRefCount && !isUnevaluatedContext())
2958 if (const BlockDecl *BD = CurContext->getInnermostBlockDecl())
2959 ImplicitlyRetainedSelfLocs.push_back({Loc, BD});
2960
2961 return Result;
2962}
2963
2964/// The parser has read a name in, and Sema has detected that we're currently
2965/// inside an ObjC method. Perform some additional checks and determine if we
2966/// should form a reference to an ivar. If so, build an expression referencing
2967/// that ivar.
2968ExprResult
2969Sema::LookupInObjCMethod(LookupResult &Lookup, Scope *S,
2970 IdentifierInfo *II, bool AllowBuiltinCreation) {
2971 // FIXME: Integrate this lookup step into LookupParsedName.
2972 DeclResult Ivar = LookupIvarInObjCMethod(Lookup, S, II);
2973 if (Ivar.isInvalid())
2974 return ExprError();
2975 if (Ivar.isUsable())
2976 return BuildIvarRefExpr(S, Lookup.getNameLoc(),
2977 cast<ObjCIvarDecl>(Ivar.get()));
2978
2979 if (Lookup.empty() && II && AllowBuiltinCreation)
2980 LookupBuiltin(Lookup);
2981
2982 // Sentinel value saying that we didn't do anything special.
2983 return ExprResult(false);
2984}
2985
2986/// Cast a base object to a member's actual type.
2987///
2988/// There are two relevant checks:
2989///
2990/// C++ [class.access.base]p7:
2991///
2992/// If a class member access operator [...] is used to access a non-static
2993/// data member or non-static member function, the reference is ill-formed if
2994/// the left operand [...] cannot be implicitly converted to a pointer to the
2995/// naming class of the right operand.
2996///
2997/// C++ [expr.ref]p7:
2998///
2999/// If E2 is a non-static data member or a non-static member function, the
3000/// program is ill-formed if the class of which E2 is directly a member is an
3001/// ambiguous base (11.8) of the naming class (11.9.3) of E2.
3002///
3003/// Note that the latter check does not consider access; the access of the
3004/// "real" base class is checked as appropriate when checking the access of the
3005/// member name.
3006ExprResult
3007Sema::PerformObjectMemberConversion(Expr *From,
3008 NestedNameSpecifier *Qualifier,
3009 NamedDecl *FoundDecl,
3010 NamedDecl *Member) {
3011 const auto *RD = dyn_cast<CXXRecordDecl>(Member->getDeclContext());
3012 if (!RD)
3013 return From;
3014
3015 QualType DestRecordType;
3016 QualType DestType;
3017 QualType FromRecordType;
3018 QualType FromType = From->getType();
3019 bool PointerConversions = false;
3020 if (isa<FieldDecl>(Member)) {
3021 DestRecordType = Context.getCanonicalType(Context.getTypeDeclType(RD));
3022 auto FromPtrType = FromType->getAs<PointerType>();
3023 DestRecordType = Context.getAddrSpaceQualType(
3024 DestRecordType, FromPtrType
3025 ? FromType->getPointeeType().getAddressSpace()
3026 : FromType.getAddressSpace());
3027
3028 if (FromPtrType) {
3029 DestType = Context.getPointerType(DestRecordType);
3030 FromRecordType = FromPtrType->getPointeeType();
3031 PointerConversions = true;
3032 } else {
3033 DestType = DestRecordType;
3034 FromRecordType = FromType;
3035 }
3036 } else if (const auto *Method = dyn_cast<CXXMethodDecl>(Member)) {
3037 if (Method->isStatic())
3038 return From;
3039
3040 DestType = Method->getThisType();
3041 DestRecordType = DestType->getPointeeType();
3042
3043 if (FromType->getAs<PointerType>()) {
3044 FromRecordType = FromType->getPointeeType();
3045 PointerConversions = true;
3046 } else {
3047 FromRecordType = FromType;
3048 DestType = DestRecordType;
3049 }
3050
3051 LangAS FromAS = FromRecordType.getAddressSpace();
3052 LangAS DestAS = DestRecordType.getAddressSpace();
3053 if (FromAS != DestAS) {
3054 QualType FromRecordTypeWithoutAS =
3055 Context.removeAddrSpaceQualType(FromRecordType);
3056 QualType FromTypeWithDestAS =
3057 Context.getAddrSpaceQualType(FromRecordTypeWithoutAS, DestAS);
3058 if (PointerConversions)
3059 FromTypeWithDestAS = Context.getPointerType(FromTypeWithDestAS);
3060 From = ImpCastExprToType(From, FromTypeWithDestAS,
3061 CK_AddressSpaceConversion, From->getValueKind())
3062 .get();
3063 }
3064 } else {
3065 // No conversion necessary.
3066 return From;
3067 }
3068
3069 if (DestType->isDependentType() || FromType->isDependentType())
3070 return From;
3071
3072 // If the unqualified types are the same, no conversion is necessary.
3073 if (Context.hasSameUnqualifiedType(FromRecordType, DestRecordType))
3074 return From;
3075
3076 SourceRange FromRange = From->getSourceRange();
3077 SourceLocation FromLoc = FromRange.getBegin();
3078
3079 ExprValueKind VK = From->getValueKind();
3080
3081 // C++ [class.member.lookup]p8:
3082 // [...] Ambiguities can often be resolved by qualifying a name with its
3083 // class name.
3084 //
3085 // If the member was a qualified name and the qualified referred to a
3086 // specific base subobject type, we'll cast to that intermediate type
3087 // first and then to the object in which the member is declared. That allows
3088 // one to resolve ambiguities in, e.g., a diamond-shaped hierarchy such as:
3089 //
3090 // class Base { public: int x; };
3091 // class Derived1 : public Base { };
3092 // class Derived2 : public Base { };
3093 // class VeryDerived : public Derived1, public Derived2 { void f(); };
3094 //
3095 // void VeryDerived::f() {
3096 // x = 17; // error: ambiguous base subobjects
3097 // Derived1::x = 17; // okay, pick the Base subobject of Derived1
3098 // }
3099 if (Qualifier && Qualifier->getAsType()) {
3100 QualType QType = QualType(Qualifier->getAsType(), 0);
3101 assert(QType->isRecordType() && "lookup done with non-record type")(static_cast <bool> (QType->isRecordType() &&
"lookup done with non-record type") ? void (0) : __assert_fail
("QType->isRecordType() && \"lookup done with non-record type\""
, "clang/lib/Sema/SemaExpr.cpp", 3101, __extension__ __PRETTY_FUNCTION__
))
;
3102
3103 QualType QRecordType = QualType(QType->castAs<RecordType>(), 0);
3104
3105 // In C++98, the qualifier type doesn't actually have to be a base
3106 // type of the object type, in which case we just ignore it.
3107 // Otherwise build the appropriate casts.
3108 if (IsDerivedFrom(FromLoc, FromRecordType, QRecordType)) {
3109 CXXCastPath BasePath;
3110 if (CheckDerivedToBaseConversion(FromRecordType, QRecordType,
3111 FromLoc, FromRange, &BasePath))
3112 return ExprError();
3113
3114 if (PointerConversions)
3115 QType = Context.getPointerType(QType);
3116 From = ImpCastExprToType(From, QType, CK_UncheckedDerivedToBase,
3117 VK, &BasePath).get();
3118
3119 FromType = QType;
3120 FromRecordType = QRecordType;
3121
3122 // If the qualifier type was the same as the destination type,
3123 // we're done.
3124 if (Context.hasSameUnqualifiedType(FromRecordType, DestRecordType))
3125 return From;
3126 }
3127 }
3128
3129 CXXCastPath BasePath;
3130 if (CheckDerivedToBaseConversion(FromRecordType, DestRecordType,
3131 FromLoc, FromRange, &BasePath,
3132 /*IgnoreAccess=*/true))
3133 return ExprError();
3134
3135 return ImpCastExprToType(From, DestType, CK_UncheckedDerivedToBase,
3136 VK, &BasePath);
3137}
3138
3139bool Sema::UseArgumentDependentLookup(const CXXScopeSpec &SS,
3140 const LookupResult &R,
3141 bool HasTrailingLParen) {
3142 // Only when used directly as the postfix-expression of a call.
3143 if (!HasTrailingLParen)
3144 return false;
3145
3146 // Never if a scope specifier was provided.
3147 if (SS.isSet())
3148 return false;
3149
3150 // Only in C++ or ObjC++.
3151 if (!getLangOpts().CPlusPlus)
3152 return false;
3153
3154 // Turn off ADL when we find certain kinds of declarations during
3155 // normal lookup:
3156 for (const NamedDecl *D : R) {
3157 // C++0x [basic.lookup.argdep]p3:
3158 // -- a declaration of a class member
3159 // Since using decls preserve this property, we check this on the
3160 // original decl.
3161 if (D->isCXXClassMember())
3162 return false;
3163
3164 // C++0x [basic.lookup.argdep]p3:
3165 // -- a block-scope function declaration that is not a
3166 // using-declaration
3167 // NOTE: we also trigger this for function templates (in fact, we
3168 // don't check the decl type at all, since all other decl types
3169 // turn off ADL anyway).
3170 if (isa<UsingShadowDecl>(D))
3171 D = cast<UsingShadowDecl>(D)->getTargetDecl();
3172 else if (D->getLexicalDeclContext()->isFunctionOrMethod())
3173 return false;
3174
3175 // C++0x [basic.lookup.argdep]p3:
3176 // -- a declaration that is neither a function or a function
3177 // template
3178 // And also for builtin functions.
3179 if (const auto *FDecl = dyn_cast<FunctionDecl>(D)) {
3180 // But also builtin functions.
3181 if (FDecl->getBuiltinID() && FDecl->isImplicit())
3182 return false;
3183 } else if (!isa<FunctionTemplateDecl>(D))
3184 return false;
3185 }
3186
3187 return true;
3188}
3189
3190
3191/// Diagnoses obvious problems with the use of the given declaration
3192/// as an expression. This is only actually called for lookups that
3193/// were not overloaded, and it doesn't promise that the declaration
3194/// will in fact be used.
3195static bool CheckDeclInExpr(Sema &S, SourceLocation Loc, NamedDecl *D,
3196 bool AcceptInvalid) {
3197 if (D->isInvalidDecl() && !AcceptInvalid)
3198 return true;
3199
3200 if (isa<TypedefNameDecl>(D)) {
3201 S.Diag(Loc, diag::err_unexpected_typedef) << D->getDeclName();
3202 return true;
3203 }
3204
3205 if (isa<ObjCInterfaceDecl>(D)) {
3206 S.Diag(Loc, diag::err_unexpected_interface) << D->getDeclName();
3207 return true;
3208 }
3209
3210 if (isa<NamespaceDecl>(D)) {
3211 S.Diag(Loc, diag::err_unexpected_namespace) << D->getDeclName();
3212 return true;
3213 }
3214
3215 return false;
3216}
3217
3218// Certain multiversion types should be treated as overloaded even when there is
3219// only one result.
3220static bool ShouldLookupResultBeMultiVersionOverload(const LookupResult &R) {
3221 assert(R.isSingleResult() && "Expected only a single result")(static_cast <bool> (R.isSingleResult() && "Expected only a single result"
) ? void (0) : __assert_fail ("R.isSingleResult() && \"Expected only a single result\""
, "clang/lib/Sema/SemaExpr.cpp", 3221, __extension__ __PRETTY_FUNCTION__
))
;
3222 const auto *FD = dyn_cast<FunctionDecl>(R.getFoundDecl());
3223 return FD &&
3224 (FD->isCPUDispatchMultiVersion() || FD->isCPUSpecificMultiVersion());
3225}
3226
3227ExprResult Sema::BuildDeclarationNameExpr(const CXXScopeSpec &SS,
3228 LookupResult &R, bool NeedsADL,
3229 bool AcceptInvalidDecl) {
3230 // If this is a single, fully-resolved result and we don't need ADL,
3231 // just build an ordinary singleton decl ref.
3232 if (!NeedsADL && R.isSingleResult() &&
3233 !R.getAsSingle<FunctionTemplateDecl>() &&
3234 !ShouldLookupResultBeMultiVersionOverload(R))
3235 return BuildDeclarationNameExpr(SS, R.getLookupNameInfo(), R.getFoundDecl(),
3236 R.getRepresentativeDecl(), nullptr,
3237 AcceptInvalidDecl);
3238
3239 // We only need to check the declaration if there's exactly one
3240 // result, because in the overloaded case the results can only be
3241 // functions and function templates.
3242 if (R.isSingleResult() && !ShouldLookupResultBeMultiVersionOverload(R) &&
3243 CheckDeclInExpr(*this, R.getNameLoc(), R.getFoundDecl(),
3244 AcceptInvalidDecl))
3245 return ExprError();
3246
3247 // Otherwise, just build an unresolved lookup expression. Suppress
3248 // any lookup-related diagnostics; we'll hash these out later, when
3249 // we've picked a target.
3250 R.suppressDiagnostics();
3251
3252 UnresolvedLookupExpr *ULE
3253 = UnresolvedLookupExpr::Create(Context, R.getNamingClass(),
3254 SS.getWithLocInContext(Context),
3255 R.getLookupNameInfo(),
3256 NeedsADL, R.isOverloadedResult(),
3257 R.begin(), R.end());
3258
3259 return ULE;
3260}
3261
3262static void diagnoseUncapturableValueReferenceOrBinding(Sema &S,
3263 SourceLocation loc,
3264 ValueDecl *var);
3265
3266/// Complete semantic analysis for a reference to the given declaration.
3267ExprResult Sema::BuildDeclarationNameExpr(
3268 const CXXScopeSpec &SS, const DeclarationNameInfo &NameInfo, NamedDecl *D,
3269 NamedDecl *FoundD, const TemplateArgumentListInfo *TemplateArgs,
3270 bool AcceptInvalidDecl) {
3271 assert(D && "Cannot refer to a NULL declaration")(static_cast <bool> (D && "Cannot refer to a NULL declaration"
) ? void (0) : __assert_fail ("D && \"Cannot refer to a NULL declaration\""
, "clang/lib/Sema/SemaExpr.cpp", 3271, __extension__ __PRETTY_FUNCTION__
))
;
3272 assert(!isa<FunctionTemplateDecl>(D) &&(static_cast <bool> (!isa<FunctionTemplateDecl>(D
) && "Cannot refer unambiguously to a function template"
) ? void (0) : __assert_fail ("!isa<FunctionTemplateDecl>(D) && \"Cannot refer unambiguously to a function template\""
, "clang/lib/Sema/SemaExpr.cpp", 3273, __extension__ __PRETTY_FUNCTION__
))
3273 "Cannot refer unambiguously to a function template")(static_cast <bool> (!isa<FunctionTemplateDecl>(D
) && "Cannot refer unambiguously to a function template"
) ? void (0) : __assert_fail ("!isa<FunctionTemplateDecl>(D) && \"Cannot refer unambiguously to a function template\""
, "clang/lib/Sema/SemaExpr.cpp", 3273, __extension__ __PRETTY_FUNCTION__
))
;
3274
3275 SourceLocation Loc = NameInfo.getLoc();
3276 if (CheckDeclInExpr(*this, Loc, D, AcceptInvalidDecl)) {
3277 // Recovery from invalid cases (e.g. D is an invalid Decl).
3278 // We use the dependent type for the RecoveryExpr to prevent bogus follow-up
3279 // diagnostics, as invalid decls use int as a fallback type.
3280 return CreateRecoveryExpr(NameInfo.getBeginLoc(), NameInfo.getEndLoc(), {});
3281 }
3282
3283 if (TemplateDecl *Template = dyn_cast<TemplateDecl>(D)) {
3284 // Specifically diagnose references to class templates that are missing
3285 // a template argument list.
3286 diagnoseMissingTemplateArguments(TemplateName(Template), Loc);
3287 return ExprError();
3288 }
3289
3290 // Make sure that we're referring to a value.
3291 if (!isa<ValueDecl, UnresolvedUsingIfExistsDecl>(D)) {
3292 Diag(Loc, diag::err_ref_non_value) << D << SS.getRange();
3293 Diag(D->getLocation(), diag::note_declared_at);
3294 return ExprError();
3295 }
3296
3297 // Check whether this declaration can be used. Note that we suppress
3298 // this check when we're going to perform argument-dependent lookup
3299 // on this function name, because this might not be the function
3300 // that overload resolution actually selects.
3301 if (DiagnoseUseOfDecl(D, Loc))
3302 return ExprError();
3303
3304 auto *VD = cast<ValueDecl>(D);
3305
3306 // Only create DeclRefExpr's for valid Decl's.
3307 if (VD->isInvalidDecl() && !AcceptInvalidDecl)
3308 return ExprError();
3309
3310 // Handle members of anonymous structs and unions. If we got here,
3311 // and the reference is to a class member indirect field, then this
3312 // must be the subject of a pointer-to-member expression.
3313 if (auto *IndirectField = dyn_cast<IndirectFieldDecl>(VD);
3314 IndirectField && !IndirectField->isCXXClassMember())
3315 return BuildAnonymousStructUnionMemberReference(SS, NameInfo.getLoc(),
3316 IndirectField);
3317
3318 QualType type = VD->getType();
3319 if (type.isNull())
3320 return ExprError();
3321 ExprValueKind valueKind = VK_PRValue;
3322
3323 // In 'T ...V;', the type of the declaration 'V' is 'T...', but the type of
3324 // a reference to 'V' is simply (unexpanded) 'T'. The type, like the value,
3325 // is expanded by some outer '...' in the context of the use.
3326 type = type.getNonPackExpansionType();
3327
3328 switch (D->getKind()) {
3329 // Ignore all the non-ValueDecl kinds.
3330#define ABSTRACT_DECL(kind)
3331#define VALUE(type, base)
3332#define DECL(type, base) case Decl::type:
3333#include "clang/AST/DeclNodes.inc"
3334 llvm_unreachable("invalid value decl kind")::llvm::llvm_unreachable_internal("invalid value decl kind", "clang/lib/Sema/SemaExpr.cpp"
, 3334)
;
3335
3336 // These shouldn't make it here.
3337 case Decl::ObjCAtDefsField:
3338 llvm_unreachable("forming non-member reference to ivar?")::llvm::llvm_unreachable_internal("forming non-member reference to ivar?"
, "clang/lib/Sema/SemaExpr.cpp", 3338)
;
3339
3340 // Enum constants are always r-values and never references.
3341 // Unresolved using declarations are dependent.
3342 case Decl::EnumConstant:
3343 case Decl::UnresolvedUsingValue:
3344 case Decl::OMPDeclareReduction:
3345 case Decl::OMPDeclareMapper:
3346 valueKind = VK_PRValue;
3347 break;
3348
3349 // Fields and indirect fields that got here must be for
3350 // pointer-to-member expressions; we just call them l-values for
3351 // internal consistency, because this subexpression doesn't really
3352 // exist in the high-level semantics.
3353 case Decl::Field:
3354 case Decl::IndirectField:
3355 case Decl::ObjCIvar:
3356 assert(getLangOpts().CPlusPlus && "building reference to field in C?")(static_cast <bool> (getLangOpts().CPlusPlus &&
"building reference to field in C?") ? void (0) : __assert_fail
("getLangOpts().CPlusPlus && \"building reference to field in C?\""
, "clang/lib/Sema/SemaExpr.cpp", 3356, __extension__ __PRETTY_FUNCTION__
))
;
3357
3358 // These can't have reference type in well-formed programs, but
3359 // for internal consistency we do this anyway.
3360 type = type.getNonReferenceType();
3361 valueKind = VK_LValue;
3362 break;
3363
3364 // Non-type template parameters are either l-values or r-values
3365 // depending on the type.
3366 case Decl::NonTypeTemplateParm: {
3367 if (const ReferenceType *reftype = type->getAs<ReferenceType>()) {
3368 type = reftype->getPointeeType();
3369 valueKind = VK_LValue; // even if the parameter is an r-value reference
3370 break;
3371 }
3372
3373 // [expr.prim.id.unqual]p2:
3374 // If the entity is a template parameter object for a template
3375 // parameter of type T, the type of the expression is const T.
3376 // [...] The expression is an lvalue if the entity is a [...] template
3377 // parameter object.
3378 if (type->isRecordType()) {
3379 type = type.getUnqualifiedType().withConst();
3380 valueKind = VK_LValue;
3381 break;
3382 }
3383
3384 // For non-references, we need to strip qualifiers just in case
3385 // the template parameter was declared as 'const int' or whatever.
3386 valueKind = VK_PRValue;
3387 type = type.getUnqualifiedType();
3388 break;
3389 }
3390
3391 case Decl::Var:
3392 case Decl::VarTemplateSpecialization:
3393 case Decl::VarTemplatePartialSpecialization:
3394 case Decl::Decomposition:
3395 case Decl::OMPCapturedExpr:
3396 // In C, "extern void blah;" is valid and is an r-value.
3397 if (!getLangOpts().CPlusPlus && !type.hasQualifiers() &&
3398 type->isVoidType()) {
3399 valueKind = VK_PRValue;
3400 break;
3401 }
3402 [[fallthrough]];
3403
3404 case Decl::ImplicitParam:
3405 case Decl::ParmVar: {
3406 // These are always l-values.
3407 valueKind = VK_LValue;
3408 type = type.getNonReferenceType();
3409
3410 // FIXME: Does the addition of const really only apply in
3411 // potentially-evaluated contexts? Since the variable isn't actually
3412 // captured in an unevaluated context, it seems that the answer is no.
3413 if (!isUnevaluatedContext()) {
3414 QualType CapturedType = getCapturedDeclRefType(cast<VarDecl>(VD), Loc);
3415 if (!CapturedType.isNull())
3416 type = CapturedType;
3417 }
3418
3419 break;
3420 }
3421
3422 case Decl::Binding:
3423 // These are always lvalues.
3424 valueKind = VK_LValue;
3425 type = type.getNonReferenceType();
3426 break;
3427
3428 case Decl::Function: {
3429 if (unsigned BID = cast<FunctionDecl>(VD)->getBuiltinID()) {
3430 if (!Context.BuiltinInfo.isDirectlyAddressable(BID)) {
3431 type = Context.BuiltinFnTy;
3432 valueKind = VK_PRValue;
3433 break;
3434 }
3435 }
3436
3437 const FunctionType *fty = type->castAs<FunctionType>();
3438
3439 // If we're referring to a function with an __unknown_anytype
3440 // result type, make the entire expression __unknown_anytype.
3441 if (fty->getReturnType() == Context.UnknownAnyTy) {
3442 type = Context.UnknownAnyTy;
3443 valueKind = VK_PRValue;
3444 break;
3445 }
3446
3447 // Functions are l-values in C++.
3448 if (getLangOpts().CPlusPlus) {
3449 valueKind = VK_LValue;
3450 break;
3451 }
3452
3453 // C99 DR 316 says that, if a function type comes from a
3454 // function definition (without a prototype), that type is only
3455 // used for checking compatibility. Therefore, when referencing
3456 // the function, we pretend that we don't have the full function
3457 // type.
3458 if (!cast<FunctionDecl>(VD)->hasPrototype() && isa<FunctionProtoType>(fty))
3459 type = Context.getFunctionNoProtoType(fty->getReturnType(),
3460 fty->getExtInfo());
3461
3462 // Functions are r-values in C.
3463 valueKind = VK_PRValue;
3464 break;
3465 }
3466
3467 case Decl::CXXDeductionGuide:
3468 llvm_unreachable("building reference to deduction guide")::llvm::llvm_unreachable_internal("building reference to deduction guide"
, "clang/lib/Sema/SemaExpr.cpp", 3468)
;
3469
3470 case Decl::MSProperty:
3471 case Decl::MSGuid:
3472 case Decl::TemplateParamObject:
3473 // FIXME: Should MSGuidDecl and template parameter objects be subject to
3474 // capture in OpenMP, or duplicated between host and device?
3475 valueKind = VK_LValue;
3476 break;
3477
3478 case Decl::UnnamedGlobalConstant:
3479 valueKind = VK_LValue;
3480 break;
3481
3482 case Decl::CXXMethod:
3483 // If we're referring to a method with an __unknown_anytype
3484 // result type, make the entire expression __unknown_anytype.
3485 // This should only be possible with a type written directly.
3486 if (const FunctionProtoType *proto =
3487 dyn_cast<FunctionProtoType>(VD->getType()))
3488 if (proto->getReturnType() == Context.UnknownAnyTy) {
3489 type = Context.UnknownAnyTy;
3490 valueKind = VK_PRValue;
3491 break;
3492 }
3493
3494 // C++ methods are l-values if static, r-values if non-static.
3495 if (cast<CXXMethodDecl>(VD)->isStatic()) {
3496 valueKind = VK_LValue;
3497 break;
3498 }
3499 [[fallthrough]];
3500
3501 case Decl::CXXConversion:
3502 case Decl::CXXDestructor:
3503 case Decl::CXXConstructor:
3504 valueKind = VK_PRValue;
3505 break;
3506 }
3507
3508 auto *E =
3509 BuildDeclRefExpr(VD, type, valueKind, NameInfo, &SS, FoundD,
3510 /*FIXME: TemplateKWLoc*/ SourceLocation(), TemplateArgs);
3511 // Clang AST consumers assume a DeclRefExpr refers to a valid decl. We
3512 // wrap a DeclRefExpr referring to an invalid decl with a dependent-type
3513 // RecoveryExpr to avoid follow-up semantic analysis (thus prevent bogus
3514 // diagnostics).
3515 if (VD->isInvalidDecl() && E)
3516 return CreateRecoveryExpr(E->getBeginLoc(), E->getEndLoc(), {E});
3517 return E;
3518}
3519
3520static void ConvertUTF8ToWideString(unsigned CharByteWidth, StringRef Source,
3521 SmallString<32> &Target) {
3522 Target.resize(CharByteWidth * (Source.size() + 1));
3523 char *ResultPtr = &Target[0];
3524 const llvm::UTF8 *ErrorPtr;
3525 bool success =
3526 llvm::ConvertUTF8toWide(CharByteWidth, Source, ResultPtr, ErrorPtr);
3527 (void)success;
3528 assert(success)(static_cast <bool> (success) ? void (0) : __assert_fail
("success", "clang/lib/Sema/SemaExpr.cpp", 3528, __extension__
__PRETTY_FUNCTION__))
;
3529 Target.resize(ResultPtr - &Target[0]);
3530}
3531
3532ExprResult Sema::BuildPredefinedExpr(SourceLocation Loc,
3533 PredefinedExpr::IdentKind IK) {
3534 // Pick the current block, lambda, captured statement or function.
3535 Decl *currentDecl = nullptr;
3536 if (const BlockScopeInfo *BSI = getCurBlock())
3537 currentDecl = BSI->TheDecl;
3538 else if (const LambdaScopeInfo *LSI = getCurLambda())
3539 currentDecl = LSI->CallOperator;
3540 else if (const CapturedRegionScopeInfo *CSI = getCurCapturedRegion())
3541 currentDecl = CSI->TheCapturedDecl;
3542 else
3543 currentDecl = getCurFunctionOrMethodDecl();
3544
3545 if (!currentDecl) {
3546 Diag(Loc, diag::ext_predef_outside_function);
3547 currentDecl = Context.getTranslationUnitDecl();
3548 }
3549
3550 QualType ResTy;
3551 StringLiteral *SL = nullptr;
3552 if (cast<DeclContext>(currentDecl)->isDependentContext())
3553 ResTy = Context.DependentTy;
3554 else {
3555 // Pre-defined identifiers are of type char[x], where x is the length of
3556 // the string.
3557 auto Str = PredefinedExpr::ComputeName(IK, currentDecl);
3558 unsigned Length = Str.length();
3559
3560 llvm::APInt LengthI(32, Length + 1);
3561 if (IK == PredefinedExpr::LFunction || IK == PredefinedExpr::LFuncSig) {
3562 ResTy =
3563 Context.adjustStringLiteralBaseType(Context.WideCharTy.withConst());
3564 SmallString<32> RawChars;
3565 ConvertUTF8ToWideString(Context.getTypeSizeInChars(ResTy).getQuantity(),
3566 Str, RawChars);
3567 ResTy = Context.getConstantArrayType(ResTy, LengthI, nullptr,
3568 ArrayType::Normal,
3569 /*IndexTypeQuals*/ 0);
3570 SL = StringLiteral::Create(Context, RawChars, StringLiteral::Wide,
3571 /*Pascal*/ false, ResTy, Loc);
3572 } else {
3573 ResTy = Context.adjustStringLiteralBaseType(Context.CharTy.withConst());
3574 ResTy = Context.getConstantArrayType(ResTy, LengthI, nullptr,
3575 ArrayType::Normal,
3576 /*IndexTypeQuals*/ 0);
3577 SL = StringLiteral::Create(Context, Str, StringLiteral::Ordinary,
3578 /*Pascal*/ false, ResTy, Loc);
3579 }
3580 }
3581
3582 return PredefinedExpr::Create(Context, Loc, ResTy, IK, SL);
3583}
3584
3585ExprResult Sema::BuildSYCLUniqueStableNameExpr(SourceLocation OpLoc,
3586 SourceLocation LParen,
3587 SourceLocation RParen,
3588 TypeSourceInfo *TSI) {
3589 return SYCLUniqueStableNameExpr::Create(Context, OpLoc, LParen, RParen, TSI);
3590}
3591
3592ExprResult Sema::ActOnSYCLUniqueStableNameExpr(SourceLocation OpLoc,
3593 SourceLocation LParen,
3594 SourceLocation RParen,
3595 ParsedType ParsedTy) {
3596 TypeSourceInfo *TSI = nullptr;
3597 QualType Ty = GetTypeFromParser(ParsedTy, &TSI);
3598
3599 if (Ty.isNull())
3600 return ExprError();
3601 if (!TSI)
3602 TSI = Context.getTrivialTypeSourceInfo(Ty, LParen);
3603
3604 return BuildSYCLUniqueStableNameExpr(OpLoc, LParen, RParen, TSI);
3605}
3606
3607ExprResult Sema::ActOnPredefinedExpr(SourceLocation Loc, tok::TokenKind Kind) {
3608 PredefinedExpr::IdentKind IK;
3609
3610 switch (Kind) {
3611 default: llvm_unreachable("Unknown simple primary expr!")::llvm::llvm_unreachable_internal("Unknown simple primary expr!"
, "clang/lib/Sema/SemaExpr.cpp", 3611)
;
3612 case tok::kw___func__: IK = PredefinedExpr::Func; break; // [C99 6.4.2.2]
3613 case tok::kw___FUNCTION__: IK = PredefinedExpr::Function; break;
3614 case tok::kw___FUNCDNAME__: IK = PredefinedExpr::FuncDName; break; // [MS]
3615 case tok::kw___FUNCSIG__: IK = PredefinedExpr::FuncSig; break; // [MS]
3616 case tok::kw_L__FUNCTION__: IK = PredefinedExpr::LFunction; break; // [MS]
3617 case tok::kw_L__FUNCSIG__: IK = PredefinedExpr::LFuncSig; break; // [MS]
3618 case tok::kw___PRETTY_FUNCTION__: IK = PredefinedExpr::PrettyFunction; break;
3619 }
3620
3621 return BuildPredefinedExpr(Loc, IK);
3622}
3623
3624ExprResult Sema::ActOnCharacterConstant(const Token &Tok, Scope *UDLScope) {
3625 SmallString<16> CharBuffer;
3626 bool Invalid = false;
3627 StringRef ThisTok = PP.getSpelling(Tok, CharBuffer, &Invalid);
3628 if (Invalid)
3629 return ExprError();
3630
3631 CharLiteralParser Literal(ThisTok.begin(), ThisTok.end(), Tok.getLocation(),
3632 PP, Tok.getKind());
3633 if (Literal.hadError())
3634 return ExprError();
3635
3636 QualType Ty;
3637 if (Literal.isWide())
3638 Ty = Context.WideCharTy; // L'x' -> wchar_t in C and C++.
3639 else if (Literal.isUTF8() && getLangOpts().C2x)
3640 Ty = Context.UnsignedCharTy; // u8'x' -> unsigned char in C2x
3641 else if (Literal.isUTF8() && getLangOpts().Char8)
3642 Ty = Context.Char8Ty; // u8'x' -> char8_t when it exists.
3643 else if (Literal.isUTF16())
3644 Ty = Context.Char16Ty; // u'x' -> char16_t in C11 and C++11.
3645 else if (Literal.isUTF32())
3646 Ty = Context.Char32Ty; // U'x' -> char32_t in C11 and C++11.
3647 else if (!getLangOpts().CPlusPlus || Literal.isMultiChar())
3648 Ty = Context.IntTy; // 'x' -> int in C, 'wxyz' -> int in C++.
3649 else
3650 Ty = Context.CharTy; // 'x' -> char in C++;
3651 // u8'x' -> char in C11-C17 and in C++ without char8_t.
3652
3653 CharacterLiteral::CharacterKind Kind = CharacterLiteral::Ascii;
3654 if (Literal.isWide())
3655 Kind = CharacterLiteral::Wide;
3656 else if (Literal.isUTF16())
3657 Kind = CharacterLiteral::UTF16;
3658 else if (Literal.isUTF32())
3659 Kind = CharacterLiteral::UTF32;
3660 else if (Literal.isUTF8())
3661 Kind = CharacterLiteral::UTF8;
3662
3663 Expr *Lit = new (Context) CharacterLiteral(Literal.getValue(), Kind, Ty,
3664 Tok.getLocation());
3665
3666 if (Literal.getUDSuffix().empty())
3667 return Lit;
3668
3669 // We're building a user-defined literal.
3670 IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix());
3671 SourceLocation UDSuffixLoc =
3672 getUDSuffixLoc(*this, Tok.getLocation(), Literal.getUDSuffixOffset());
3673
3674 // Make sure we're allowed user-defined literals here.
3675 if (!UDLScope)
3676 return ExprError(Diag(UDSuffixLoc, diag::err_invalid_character_udl));
3677
3678 // C++11 [lex.ext]p6: The literal L is treated as a call of the form
3679 // operator "" X (ch)
3680 return BuildCookedLiteralOperatorCall(*this, UDLScope, UDSuffix, UDSuffixLoc,
3681 Lit, Tok.getLocation());
3682}
3683
3684ExprResult Sema::ActOnIntegerConstant(SourceLocation Loc, uint64_t Val) {
3685 unsigned IntSize = Context.getTargetInfo().getIntWidth();
3686 return IntegerLiteral::Create(Context, llvm::APInt(IntSize, Val),
3687 Context.IntTy, Loc);
3688}
3689
3690static Expr *BuildFloatingLiteral(Sema &S, NumericLiteralParser &Literal,
3691 QualType Ty, SourceLocation Loc) {
3692 const llvm::fltSemantics &Format = S.Context.getFloatTypeSemantics(Ty);
3693
3694 using llvm::APFloat;
3695 APFloat Val(Format);
3696
3697 APFloat::opStatus result = Literal.GetFloatValue(Val);
3698
3699 // Overflow is always an error, but underflow is only an error if
3700 // we underflowed to zero (APFloat reports denormals as underflow).
3701 if ((result & APFloat::opOverflow) ||
3702 ((result & APFloat::opUnderflow) && Val.isZero())) {
3703 unsigned diagnostic;
3704 SmallString<20> buffer;
3705 if (result & APFloat::opOverflow) {
3706 diagnostic = diag::warn_float_overflow;
3707 APFloat::getLargest(Format).toString(buffer);
3708 } else {
3709 diagnostic = diag::warn_float_underflow;
3710 APFloat::getSmallest(Format).toString(buffer);
3711 }
3712
3713 S.Diag(Loc, diagnostic)
3714 << Ty
3715 << StringRef(buffer.data(), buffer.size());
3716 }
3717
3718 bool isExact = (result == APFloat::opOK);
3719 return FloatingLiteral::Create(S.Context, Val, isExact, Ty, Loc);
3720}
3721
3722bool Sema::CheckLoopHintExpr(Expr *E, SourceLocation Loc) {
3723 assert(E && "Invalid expression")(static_cast <bool> (E && "Invalid expression")
? void (0) : __assert_fail ("E && \"Invalid expression\""
, "clang/lib/Sema/SemaExpr.cpp", 3723, __extension__ __PRETTY_FUNCTION__
))
;
3724
3725 if (E->isValueDependent())
3726 return false;
3727
3728 QualType QT = E->getType();
3729 if (!QT->isIntegerType() || QT->isBooleanType() || QT->isCharType()) {
3730 Diag(E->getExprLoc(), diag::err_pragma_loop_invalid_argument_type) << QT;
3731 return true;
3732 }
3733
3734 llvm::APSInt ValueAPS;
3735 ExprResult R = VerifyIntegerConstantExpression(E, &ValueAPS);
3736
3737 if (R.isInvalid())
3738 return true;
3739
3740 bool ValueIsPositive = ValueAPS.isStrictlyPositive();
3741 if (!ValueIsPositive || ValueAPS.getActiveBits() > 31) {
3742 Diag(E->getExprLoc(), diag::err_pragma_loop_invalid_argument_value)
3743 << toString(ValueAPS, 10) << ValueIsPositive;
3744 return true;
3745 }
3746
3747 return false;
3748}
3749
3750ExprResult Sema::ActOnNumericConstant(const Token &Tok, Scope *UDLScope) {
3751 // Fast path for a single digit (which is quite common). A single digit
3752 // cannot have a trigraph, escaped newline, radix prefix, or suffix.
3753 if (Tok.getLength() == 1) {
3754 const char Val = PP.getSpellingOfSingleCharacterNumericConstant(Tok);
3755 return ActOnIntegerConstant(Tok.getLocation(), Val-'0');
3756 }
3757
3758 SmallString<128> SpellingBuffer;
3759 // NumericLiteralParser wants to overread by one character. Add padding to
3760 // the buffer in case the token is copied to the buffer. If getSpelling()
3761 // returns a StringRef to the memory buffer, it should have a null char at
3762 // the EOF, so it is also safe.
3763 SpellingBuffer.resize(Tok.getLength() + 1);
3764
3765 // Get the spelling of the token, which eliminates trigraphs, etc.
3766 bool Invalid = false;
3767 StringRef TokSpelling = PP.getSpelling(Tok, SpellingBuffer, &Invalid);
3768 if (Invalid)
3769 return ExprError();
3770
3771 NumericLiteralParser Literal(TokSpelling, Tok.getLocation(),
3772 PP.getSourceManager(), PP.getLangOpts(),
3773 PP.getTargetInfo(), PP.getDiagnostics());
3774 if (Literal.hadError)
3775 return ExprError();
3776
3777 if (Literal.hasUDSuffix()) {
3778 // We're building a user-defined literal.
3779 const IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix());
3780 SourceLocation UDSuffixLoc =
3781 getUDSuffixLoc(*this, Tok.getLocation(), Literal.getUDSuffixOffset());
3782
3783 // Make sure we're allowed user-defined literals here.
3784 if (!UDLScope)
3785 return ExprError(Diag(UDSuffixLoc, diag::err_invalid_numeric_udl));
3786
3787 QualType CookedTy;
3788 if (Literal.isFloatingLiteral()) {
3789 // C++11 [lex.ext]p4: If S contains a literal operator with parameter type
3790 // long double, the literal is treated as a call of the form
3791 // operator "" X (f L)
3792 CookedTy = Context.LongDoubleTy;
3793 } else {
3794 // C++11 [lex.ext]p3: If S contains a literal operator with parameter type
3795 // unsigned long long, the literal is treated as a call of the form
3796 // operator "" X (n ULL)
3797 CookedTy = Context.UnsignedLongLongTy;
3798 }
3799
3800 DeclarationName OpName =
3801 Context.DeclarationNames.getCXXLiteralOperatorName(UDSuffix);
3802 DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc);
3803 OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc);
3804
3805 SourceLocation TokLoc = Tok.getLocation();
3806
3807 // Perform literal operator lookup to determine if we're building a raw
3808 // literal or a cooked one.
3809 LookupResult R(*this, OpName, UDSuffixLoc, LookupOrdinaryName);
3810 switch (LookupLiteralOperator(UDLScope, R, CookedTy,
3811 /*AllowRaw*/ true, /*AllowTemplate*/ true,
3812 /*AllowStringTemplatePack*/ false,
3813 /*DiagnoseMissing*/ !Literal.isImaginary)) {
3814 case LOLR_ErrorNoDiagnostic:
3815 // Lookup failure for imaginary constants isn't fatal, there's still the
3816 // GNU extension producing _Complex types.
3817 break;
3818 case LOLR_Error:
3819 return ExprError();
3820 case LOLR_Cooked: {
3821 Expr *Lit;
3822 if (Literal.isFloatingLiteral()) {
3823 Lit = BuildFloatingLiteral(*this, Literal, CookedTy, Tok.getLocation());
3824 } else {
3825 llvm::APInt ResultVal(Context.getTargetInfo().getLongLongWidth(), 0);
3826 if (Literal.GetIntegerValue(ResultVal))
3827 Diag(Tok.getLocation(), diag::err_integer_literal_too_large)
3828 << /* Unsigned */ 1;
3829 Lit = IntegerLiteral::Create(Context, ResultVal, CookedTy,
3830 Tok.getLocation());
3831 }
3832 return BuildLiteralOperatorCall(R, OpNameInfo, Lit, TokLoc);
3833 }
3834
3835 case LOLR_Raw: {
3836 // C++11 [lit.ext]p3, p4: If S contains a raw literal operator, the
3837 // literal is treated as a call of the form
3838 // operator "" X ("n")
3839 unsigned Length = Literal.getUDSuffixOffset();
3840 QualType StrTy = Context.getConstantArrayType(
3841 Context.adjustStringLiteralBaseType(Context.CharTy.withConst()),
3842 llvm::APInt(32, Length + 1), nullptr, ArrayType::Normal, 0);
3843 Expr *Lit =
3844 StringLiteral::Create(Context, StringRef(TokSpelling.data(), Length),
3845 StringLiteral::Ordinary,
3846 /*Pascal*/ false, StrTy, &TokLoc, 1);
3847 return BuildLiteralOperatorCall(R, OpNameInfo, Lit, TokLoc);
3848 }
3849
3850 case LOLR_Template: {
3851 // C++11 [lit.ext]p3, p4: Otherwise (S contains a literal operator
3852 // template), L is treated as a call fo the form
3853 // operator "" X <'c1', 'c2', ... 'ck'>()
3854 // where n is the source character sequence c1 c2 ... ck.
3855 TemplateArgumentListInfo ExplicitArgs;
3856 unsigned CharBits = Context.getIntWidth(Context.CharTy);
3857 bool CharIsUnsigned = Context.CharTy->isUnsignedIntegerType();
3858 llvm::APSInt Value(CharBits, CharIsUnsigned);
3859 for (unsigned I = 0, N = Literal.getUDSuffixOffset(); I != N; ++I) {
3860 Value = TokSpelling[I];
3861 TemplateArgument Arg(Context, Value, Context.CharTy);
3862 TemplateArgumentLocInfo ArgInfo;
3863 ExplicitArgs.addArgument(TemplateArgumentLoc(Arg, ArgInfo));
3864 }
3865 return BuildLiteralOperatorCall(R, OpNameInfo, std::nullopt, TokLoc,
3866 &ExplicitArgs);
3867 }
3868 case LOLR_StringTemplatePack:
3869 llvm_unreachable("unexpected literal operator lookup result")::llvm::llvm_unreachable_internal("unexpected literal operator lookup result"
, "clang/lib/Sema/SemaExpr.cpp", 3869)
;
3870 }
3871 }
3872
3873 Expr *Res;
3874
3875 if (Literal.isFixedPointLiteral()) {
3876 QualType Ty;
3877
3878 if (Literal.isAccum) {
3879 if (Literal.isHalf) {
3880 Ty = Context.ShortAccumTy;
3881 } else if (Literal.isLong) {
3882 Ty = Context.LongAccumTy;
3883 } else {
3884 Ty = Context.AccumTy;
3885 }
3886 } else if (Literal.isFract) {
3887 if (Literal.isHalf) {
3888 Ty = Context.ShortFractTy;
3889 } else if (Literal.isLong) {
3890 Ty = Context.LongFractTy;
3891 } else {
3892 Ty = Context.FractTy;
3893 }
3894 }
3895
3896 if (Literal.isUnsigned) Ty = Context.getCorrespondingUnsignedType(Ty);
3897
3898 bool isSigned = !Literal.isUnsigned;
3899 unsigned scale = Context.getFixedPointScale(Ty);
3900 unsigned bit_width = Context.getTypeInfo(Ty).Width;
3901
3902 llvm::APInt Val(bit_width, 0, isSigned);
3903 bool Overflowed = Literal.GetFixedPointValue(Val, scale);
3904 bool ValIsZero = Val.isZero() && !Overflowed;
3905
3906 auto MaxVal = Context.getFixedPointMax(Ty).getValue();
3907 if (Literal.isFract && Val == MaxVal + 1 && !ValIsZero)
3908 // Clause 6.4.4 - The value of a constant shall be in the range of
3909 // representable values for its type, with exception for constants of a
3910 // fract type with a value of exactly 1; such a constant shall denote
3911 // the maximal value for the type.
3912 --Val;
3913 else if (Val.ugt(MaxVal) || Overflowed)
3914 Diag(Tok.getLocation(), diag::err_too_large_for_fixed_point);
3915
3916 Res = FixedPointLiteral::CreateFromRawInt(Context, Val, Ty,
3917 Tok.getLocation(), scale);
3918 } else if (Literal.isFloatingLiteral()) {
3919 QualType Ty;
3920 if (Literal.isHalf){
3921 if (getOpenCLOptions().isAvailableOption("cl_khr_fp16", getLangOpts()))
3922 Ty = Context.HalfTy;
3923 else {
3924 Diag(Tok.getLocation(), diag::err_half_const_requires_fp16);
3925 return ExprError();
3926 }
3927 } else if (Literal.isFloat)
3928 Ty = Context.FloatTy;
3929 else if (Literal.isLong)
3930 Ty = Context.LongDoubleTy;
3931 else if (Literal.isFloat16)
3932 Ty = Context.Float16Ty;
3933 else if (Literal.isFloat128)
3934 Ty = Context.Float128Ty;
3935 else
3936 Ty = Context.DoubleTy;
3937
3938 Res = BuildFloatingLiteral(*this, Literal, Ty, Tok.getLocation());
3939
3940 if (Ty == Context.DoubleTy) {
3941 if (getLangOpts().SinglePrecisionConstants) {
3942 if (Ty->castAs<BuiltinType>()->getKind() != BuiltinType::Float) {
3943 Res = ImpCastExprToType(Res, Context.FloatTy, CK_FloatingCast).get();
3944 }
3945 } else if (getLangOpts().OpenCL && !getOpenCLOptions().isAvailableOption(
3946 "cl_khr_fp64", getLangOpts())) {
3947 // Impose single-precision float type when cl_khr_fp64 is not enabled.
3948 Diag(Tok.getLocation(), diag::warn_double_const_requires_fp64)
3949 << (getLangOpts().getOpenCLCompatibleVersion() >= 300);
3950 Res = ImpCastExprToType(Res, Context.FloatTy, CK_FloatingCast).get();
3951 }
3952 }
3953 } else if (!Literal.isIntegerLiteral()) {
3954 return ExprError();
3955 } else {
3956 QualType Ty;
3957
3958 // 'z/uz' literals are a C++23 feature.
3959 if (Literal.isSizeT)
3960 Diag(Tok.getLocation(), getLangOpts().CPlusPlus
3961 ? getLangOpts().CPlusPlus23
3962 ? diag::warn_cxx20_compat_size_t_suffix
3963 : diag::ext_cxx23_size_t_suffix
3964 : diag::err_cxx23_size_t_suffix);
3965
3966 // 'wb/uwb' literals are a C2x feature. We support _BitInt as a type in C++,
3967 // but we do not currently support the suffix in C++ mode because it's not
3968 // entirely clear whether WG21 will prefer this suffix to return a library
3969 // type such as std::bit_int instead of returning a _BitInt.
3970 if (Literal.isBitInt && !getLangOpts().CPlusPlus)
3971 PP.Diag(Tok.getLocation(), getLangOpts().C2x
3972 ? diag::warn_c2x_compat_bitint_suffix
3973 : diag::ext_c2x_bitint_suffix);
3974
3975 // Get the value in the widest-possible width. What is "widest" depends on
3976 // whether the literal is a bit-precise integer or not. For a bit-precise
3977 // integer type, try to scan the source to determine how many bits are
3978 // needed to represent the value. This may seem a bit expensive, but trying
3979 // to get the integer value from an overly-wide APInt is *extremely*
3980 // expensive, so the naive approach of assuming
3981 // llvm::IntegerType::MAX_INT_BITS is a big performance hit.
3982 unsigned BitsNeeded =
3983 Literal.isBitInt ? llvm::APInt::getSufficientBitsNeeded(
3984 Literal.getLiteralDigits(), Literal.getRadix())
3985 : Context.getTargetInfo().getIntMaxTWidth();
3986 llvm::APInt ResultVal(BitsNeeded, 0);
3987
3988 if (Literal.GetIntegerValue(ResultVal)) {
3989 // If this value didn't fit into uintmax_t, error and force to ull.
3990 Diag(Tok.getLocation(), diag::err_integer_literal_too_large)
3991 << /* Unsigned */ 1;
3992 Ty = Context.UnsignedLongLongTy;
3993 assert(Context.getTypeSize(Ty) == ResultVal.getBitWidth() &&(static_cast <bool> (Context.getTypeSize(Ty) == ResultVal
.getBitWidth() && "long long is not intmax_t?") ? void
(0) : __assert_fail ("Context.getTypeSize(Ty) == ResultVal.getBitWidth() && \"long long is not intmax_t?\""
, "clang/lib/Sema/SemaExpr.cpp", 3994, __extension__ __PRETTY_FUNCTION__
))
3994 "long long is not intmax_t?")(static_cast <bool> (Context.getTypeSize(Ty) == ResultVal
.getBitWidth() && "long long is not intmax_t?") ? void
(0) : __assert_fail ("Context.getTypeSize(Ty) == ResultVal.getBitWidth() && \"long long is not intmax_t?\""
, "clang/lib/Sema/SemaExpr.cpp", 3994, __extension__ __PRETTY_FUNCTION__
))
;
3995 } else {
3996 // If this value fits into a ULL, try to figure out what else it fits into
3997 // according to the rules of C99 6.4.4.1p5.
3998
3999 // Octal, Hexadecimal, and integers with a U suffix are allowed to
4000 // be an unsigned int.
4001 bool AllowUnsigned = Literal.isUnsigned || Literal.getRadix() != 10;
4002
4003 // Check from smallest to largest, picking the smallest type we can.
4004 unsigned Width = 0;
4005
4006 // Microsoft specific integer suffixes are explicitly sized.
4007 if (Literal.MicrosoftInteger) {
4008 if (Literal.MicrosoftInteger == 8 && !Literal.isUnsigned) {
4009 Width = 8;
4010 Ty = Context.CharTy;
4011 } else {
4012 Width = Literal.MicrosoftInteger;
4013 Ty = Context.getIntTypeForBitwidth(Width,
4014 /*Signed=*/!Literal.isUnsigned);
4015 }
4016 }
4017
4018 // Bit-precise integer literals are automagically-sized based on the
4019 // width required by the literal.
4020 if (Literal.isBitInt) {
4021 // The signed version has one more bit for the sign value. There are no
4022 // zero-width bit-precise integers, even if the literal value is 0.
4023 Width = std::max(ResultVal.getActiveBits(), 1u) +
4024 (Literal.isUnsigned ? 0u : 1u);
4025
4026 // Diagnose if the width of the constant is larger than BITINT_MAXWIDTH,
4027 // and reset the type to the largest supported width.
4028 unsigned int MaxBitIntWidth =
4029 Context.getTargetInfo().getMaxBitIntWidth();
4030 if (Width > MaxBitIntWidth) {
4031 Diag(Tok.getLocation(), diag::err_integer_literal_too_large)
4032 << Literal.isUnsigned;
4033 Width = MaxBitIntWidth;
4034 }
4035
4036 // Reset the result value to the smaller APInt and select the correct
4037 // type to be used. Note, we zext even for signed values because the
4038 // literal itself is always an unsigned value (a preceeding - is a
4039 // unary operator, not part of the literal).
4040 ResultVal = ResultVal.zextOrTrunc(Width);
4041 Ty = Context.getBitIntType(Literal.isUnsigned, Width);
4042 }
4043
4044 // Check C++23 size_t literals.
4045 if (Literal.isSizeT) {
4046 assert(!Literal.MicrosoftInteger &&(static_cast <bool> (!Literal.MicrosoftInteger &&
"size_t literals can't be Microsoft literals") ? void (0) : __assert_fail
("!Literal.MicrosoftInteger && \"size_t literals can't be Microsoft literals\""
, "clang/lib/Sema/SemaExpr.cpp", 4047, __extension__ __PRETTY_FUNCTION__
))
4047 "size_t literals can't be Microsoft literals")(static_cast <bool> (!Literal.MicrosoftInteger &&
"size_t literals can't be Microsoft literals") ? void (0) : __assert_fail
("!Literal.MicrosoftInteger && \"size_t literals can't be Microsoft literals\""
, "clang/lib/Sema/SemaExpr.cpp", 4047, __extension__ __PRETTY_FUNCTION__
))
;
4048 unsigned SizeTSize = Context.getTargetInfo().getTypeWidth(
4049 Context.getTargetInfo().getSizeType());
4050
4051 // Does it fit in size_t?
4052 if (ResultVal.isIntN(SizeTSize)) {
4053 // Does it fit in ssize_t?
4054 if (!Literal.isUnsigned && ResultVal[SizeTSize - 1] == 0)
4055 Ty = Context.getSignedSizeType();
4056 else if (AllowUnsigned)
4057 Ty = Context.getSizeType();
4058 Width = SizeTSize;
4059 }
4060 }
4061
4062 if (Ty.isNull() && !Literal.isLong && !Literal.isLongLong &&
4063 !Literal.isSizeT) {
4064 // Are int/unsigned possibilities?
4065 unsigned IntSize = Context.getTargetInfo().getIntWidth();
4066
4067 // Does it fit in a unsigned int?
4068 if (ResultVal.isIntN(IntSize)) {
4069 // Does it fit in a signed int?
4070 if (!Literal.isUnsigned && ResultVal[IntSize-1] == 0)
4071 Ty = Context.IntTy;
4072 else if (AllowUnsigned)
4073 Ty = Context.UnsignedIntTy;
4074 Width = IntSize;
4075 }
4076 }
4077
4078 // Are long/unsigned long possibilities?
4079 if (Ty.isNull() && !Literal.isLongLong && !Literal.isSizeT) {
4080 unsigned LongSize = Context.getTargetInfo().getLongWidth();
4081
4082 // Does it fit in a unsigned long?
4083 if (ResultVal.isIntN(LongSize)) {
4084 // Does it fit in a signed long?
4085 if (!Literal.isUnsigned && ResultVal[LongSize-1] == 0)
4086 Ty = Context.LongTy;
4087 else if (AllowUnsigned)
4088 Ty = Context.UnsignedLongTy;
4089 // Check according to the rules of C90 6.1.3.2p5. C++03 [lex.icon]p2
4090 // is compatible.
4091 else if (!getLangOpts().C99 && !getLangOpts().CPlusPlus11) {
4092 const unsigned LongLongSize =
4093 Context.getTargetInfo().getLongLongWidth();
4094 Diag(Tok.getLocation(),
4095 getLangOpts().CPlusPlus
4096 ? Literal.isLong
4097 ? diag::warn_old_implicitly_unsigned_long_cxx
4098 : /*C++98 UB*/ diag::
4099 ext_old_implicitly_unsigned_long_cxx
4100 : diag::warn_old_implicitly_unsigned_long)
4101 << (LongLongSize > LongSize ? /*will have type 'long long'*/ 0
4102 : /*will be ill-formed*/ 1);
4103 Ty = Context.UnsignedLongTy;
4104 }
4105 Width = LongSize;
4106 }
4107 }
4108
4109 // Check long long if needed.
4110 if (Ty.isNull() && !Literal.isSizeT) {
4111 unsigned LongLongSize = Context.getTargetInfo().getLongLongWidth();
4112
4113 // Does it fit in a unsigned long long?
4114 if (ResultVal.isIntN(LongLongSize)) {
4115 // Does it fit in a signed long long?
4116 // To be compatible with MSVC, hex integer literals ending with the
4117 // LL or i64 suffix are always signed in Microsoft mode.
4118 if (!Literal.isUnsigned && (ResultVal[LongLongSize-1] == 0 ||
4119 (getLangOpts().MSVCCompat && Literal.isLongLong)))
4120 Ty = Context.LongLongTy;
4121 else if (AllowUnsigned)
4122 Ty = Context.UnsignedLongLongTy;
4123 Width = LongLongSize;
4124
4125 // 'long long' is a C99 or C++11 feature, whether the literal
4126 // explicitly specified 'long long' or we needed the extra width.
4127 if (getLangOpts().CPlusPlus)
4128 Diag(Tok.getLocation(), getLangOpts().CPlusPlus11
4129 ? diag::warn_cxx98_compat_longlong
4130 : diag::ext_cxx11_longlong);
4131 else if (!getLangOpts().C99)
4132 Diag(Tok.getLocation(), diag::ext_c99_longlong);
4133 }
4134 }
4135
4136 // If we still couldn't decide a type, we either have 'size_t' literal
4137 // that is out of range, or a decimal literal that does not fit in a
4138 // signed long long and has no U suffix.
4139 if (Ty.isNull()) {
4140 if (Literal.isSizeT)
4141 Diag(Tok.getLocation(), diag::err_size_t_literal_too_large)
4142 << Literal.isUnsigned;
4143 else
4144 Diag(Tok.getLocation(),
4145 diag::ext_integer_literal_too_large_for_signed);
4146 Ty = Context.UnsignedLongLongTy;
4147 Width = Context.getTargetInfo().getLongLongWidth();
4148 }
4149
4150 if (ResultVal.getBitWidth() != Width)
4151 ResultVal = ResultVal.trunc(Width);
4152 }
4153 Res = IntegerLiteral::Create(Context, ResultVal, Ty, Tok.getLocation());
4154 }
4155
4156 // If this is an imaginary literal, create the ImaginaryLiteral wrapper.
4157 if (Literal.isImaginary) {
4158 Res = new (Context) ImaginaryLiteral(Res,
4159 Context.getComplexType(Res->getType()));
4160
4161 Diag(Tok.getLocation(), diag::ext_imaginary_constant);
4162 }
4163 return Res;
4164}
4165
4166ExprResult Sema::ActOnParenExpr(SourceLocation L, SourceLocation R, Expr *E) {
4167 assert(E && "ActOnParenExpr() missing expr")(static_cast <bool> (E && "ActOnParenExpr() missing expr"
) ? void (0) : __assert_fail ("E && \"ActOnParenExpr() missing expr\""
, "clang/lib/Sema/SemaExpr.cpp", 4167, __extension__ __PRETTY_FUNCTION__
))
;
4168 QualType ExprTy = E->getType();
4169 if (getLangOpts().ProtectParens && CurFPFeatures.getAllowFPReassociate() &&
4170 !E->isLValue() && ExprTy->hasFloatingRepresentation())
4171 return BuildBuiltinCallExpr(R, Builtin::BI__arithmetic_fence, E);
4172 return new (Context) ParenExpr(L, R, E);
4173}
4174
4175static bool CheckVecStepTraitOperandType(Sema &S, QualType T,
4176 SourceLocation Loc,
4177 SourceRange ArgRange) {
4178 // [OpenCL 1.1 6.11.12] "The vec_step built-in function takes a built-in
4179 // scalar or vector data type argument..."
4180 // Every built-in scalar type (OpenCL 1.1 6.1.1) is either an arithmetic
4181 // type (C99 6.2.5p18) or void.
4182 if (!(T->isArithmeticType() || T->isVoidType() || T->isVectorType())) {
4183 S.Diag(Loc, diag::err_vecstep_non_scalar_vector_type)
4184 << T << ArgRange;
4185 return true;
4186 }
4187
4188 assert((T->isVoidType() || !T->isIncompleteType()) &&(static_cast <bool> ((T->isVoidType() || !T->isIncompleteType
()) && "Scalar types should always be complete") ? void
(0) : __assert_fail ("(T->isVoidType() || !T->isIncompleteType()) && \"Scalar types should always be complete\""
, "clang/lib/Sema/SemaExpr.cpp", 4189, __extension__ __PRETTY_FUNCTION__
))
4189 "Scalar types should always be complete")(static_cast <bool> ((T->isVoidType() || !T->isIncompleteType
()) && "Scalar types should always be complete") ? void
(0) : __assert_fail ("(T->isVoidType() || !T->isIncompleteType()) && \"Scalar types should always be complete\""
, "clang/lib/Sema/SemaExpr.cpp", 4189, __extension__ __PRETTY_FUNCTION__
))
;
4190 return false;
4191}
4192
4193static bool CheckExtensionTraitOperandType(Sema &S, QualType T,
4194 SourceLocation Loc,
4195 SourceRange ArgRange,
4196 UnaryExprOrTypeTrait TraitKind) {
4197 // Invalid types must be hard errors for SFINAE in C++.
4198 if (S.LangOpts.CPlusPlus)
4199 return true;
4200
4201 // C99 6.5.3.4p1:
4202 if (T->isFunctionType() &&
4203 (TraitKind == UETT_SizeOf || TraitKind == UETT_AlignOf ||
4204 TraitKind == UETT_PreferredAlignOf)) {
4205 // sizeof(function)/alignof(function) is allowed as an extension.
4206 S.Diag(Loc, diag::ext_sizeof_alignof_function_type)
4207 << getTraitSpelling(TraitKind) << ArgRange;
4208 return false;
4209 }
4210
4211 // Allow sizeof(void)/alignof(void) as an extension, unless in OpenCL where
4212 // this is an error (OpenCL v1.1 s6.3.k)
4213 if (T->isVoidType()) {
4214 unsigned DiagID = S.LangOpts.OpenCL ? diag::err_opencl_sizeof_alignof_type
4215 : diag::ext_sizeof_alignof_void_type;
4216 S.Diag(Loc, DiagID) << getTraitSpelling(TraitKind) << ArgRange;
4217 return false;
4218 }
4219
4220 return true;
4221}
4222
4223static bool CheckObjCTraitOperandConstraints(Sema &S, QualType T,
4224 SourceLocation Loc,
4225 SourceRange ArgRange,
4226 UnaryExprOrTypeTrait TraitKind) {
4227 // Reject sizeof(interface) and sizeof(interface<proto>) if the
4228 // runtime doesn't allow it.
4229 if (!S.LangOpts.ObjCRuntime.allowsSizeofAlignof() && T->isObjCObjectType()) {
4230 S.Diag(Loc, diag::err_sizeof_nonfragile_interface)
4231 << T << (TraitKind == UETT_SizeOf)
4232 << ArgRange;
4233 return true;
4234 }
4235
4236 return false;
4237}
4238
4239/// Check whether E is a pointer from a decayed array type (the decayed
4240/// pointer type is equal to T) and emit a warning if it is.
4241static void warnOnSizeofOnArrayDecay(Sema &S, SourceLocation Loc, QualType T,
4242 const Expr *E) {
4243 // Don't warn if the operation changed the type.
4244 if (T != E->getType())
4245 return;
4246
4247 // Now look for array decays.
4248 const auto *ICE = dyn_cast<ImplicitCastExpr>(E);
4249 if (!ICE || ICE->getCastKind() != CK_ArrayToPointerDecay)
4250 return;
4251
4252 S.Diag(Loc, diag::warn_sizeof_array_decay) << ICE->getSourceRange()
4253 << ICE->getType()
4254 << ICE->getSubExpr()->getType();
4255}
4256
4257/// Check the constraints on expression operands to unary type expression
4258/// and type traits.
4259///
4260/// Completes any types necessary and validates the constraints on the operand
4261/// expression. The logic mostly mirrors the type-based overload, but may modify
4262/// the expression as it completes the type for that expression through template
4263/// instantiation, etc.
4264bool Sema::CheckUnaryExprOrTypeTraitOperand(Expr *E,
4265 UnaryExprOrTypeTrait ExprKind) {
4266 QualType ExprTy = E->getType();
4267 assert(!ExprTy->isReferenceType())(static_cast <bool> (!ExprTy->isReferenceType()) ? void
(0) : __assert_fail ("!ExprTy->isReferenceType()", "clang/lib/Sema/SemaExpr.cpp"
, 4267, __extension__ __PRETTY_FUNCTION__))
;
4268
4269 bool IsUnevaluatedOperand =
4270 (ExprKind == UETT_SizeOf || ExprKind == UETT_AlignOf ||
4271 ExprKind == UETT_PreferredAlignOf || ExprKind == UETT_VecStep);
4272 if (IsUnevaluatedOperand) {
4273 ExprResult Result = CheckUnevaluatedOperand(E);
4274 if (Result.isInvalid())
4275 return true;
4276 E = Result.get();
4277 }
4278
4279 // The operand for sizeof and alignof is in an unevaluated expression context,
4280 // so side effects could result in unintended consequences.
4281 // Exclude instantiation-dependent expressions, because 'sizeof' is sometimes
4282 // used to build SFINAE gadgets.
4283 // FIXME: Should we consider instantiation-dependent operands to 'alignof'?
4284 if (IsUnevaluatedOperand && !inTemplateInstantiation() &&
4285 !E->isInstantiationDependent() &&
4286 !E->getType()->isVariableArrayType() &&
4287 E->HasSideEffects(Context, false))
4288 Diag(E->getExprLoc(), diag::warn_side_effects_unevaluated_context);
4289
4290 if (ExprKind == UETT_VecStep)
4291 return CheckVecStepTraitOperandType(*this, ExprTy, E->getExprLoc(),
4292 E->getSourceRange());
4293
4294 // Explicitly list some types as extensions.
4295 if (!CheckExtensionTraitOperandType(*this, ExprTy, E->getExprLoc(),
4296 E->getSourceRange(), ExprKind))
4297 return false;
4298
4299 // 'alignof' applied to an expression only requires the base element type of
4300 // the expression to be complete. 'sizeof' requires the expression's type to
4301 // be complete (and will attempt to complete it if it's an array of unknown
4302 // bound).
4303 if (ExprKind == UETT_AlignOf || ExprKind == UETT_PreferredAlignOf) {
4304 if (RequireCompleteSizedType(
4305 E->getExprLoc(), Context.getBaseElementType(E->getType()),
4306 diag::err_sizeof_alignof_incomplete_or_sizeless_type,
4307 getTraitSpelling(ExprKind), E->getSourceRange()))
4308 return true;
4309 } else {
4310 if (RequireCompleteSizedExprType(
4311 E, diag::err_sizeof_alignof_incomplete_or_sizeless_type,
4312 getTraitSpelling(ExprKind), E->getSourceRange()))
4313 return true;
4314 }
4315
4316 // Completing the expression's type may have changed it.
4317 ExprTy = E->getType();
4318 assert(!ExprTy->isReferenceType())(static_cast <bool> (!ExprTy->isReferenceType()) ? void
(0) : __assert_fail ("!ExprTy->isReferenceType()", "clang/lib/Sema/SemaExpr.cpp"
, 4318, __extension__ __PRETTY_FUNCTION__))
;
4319
4320 if (ExprTy->isFunctionType()) {
4321 Diag(E->getExprLoc(), diag::err_sizeof_alignof_function_type)
4322 << getTraitSpelling(ExprKind) << E->getSourceRange();
4323 return true;
4324 }
4325
4326 if (CheckObjCTraitOperandConstraints(*this, ExprTy, E->getExprLoc(),
4327 E->getSourceRange(), ExprKind))
4328 return true;
4329
4330 if (ExprKind == UETT_SizeOf) {
4331 if (const auto *DeclRef = dyn_cast<DeclRefExpr>(E->IgnoreParens())) {
4332 if (const auto *PVD = dyn_cast<ParmVarDecl>(DeclRef->getFoundDecl())) {
4333 QualType OType = PVD->getOriginalType();
4334 QualType Type = PVD->getType();
4335 if (Type->isPointerType() && OType->isArrayType()) {
4336 Diag(E->getExprLoc(), diag::warn_sizeof_array_param)
4337 << Type << OType;
4338 Diag(PVD->getLocation(), diag::note_declared_at);
4339 }
4340 }
4341 }
4342
4343 // Warn on "sizeof(array op x)" and "sizeof(x op array)", where the array
4344 // decays into a pointer and returns an unintended result. This is most
4345 // likely a typo for "sizeof(array) op x".
4346 if (const auto *BO = dyn_cast<BinaryOperator>(E->IgnoreParens())) {
4347 warnOnSizeofOnArrayDecay(*this, BO->getOperatorLoc(), BO->getType(),
4348 BO->getLHS());
4349 warnOnSizeofOnArrayDecay(*this, BO->getOperatorLoc(), BO->getType(),
4350 BO->getRHS());
4351 }
4352 }
4353
4354 return false;
4355}
4356
4357/// Check the constraints on operands to unary expression and type
4358/// traits.
4359///
4360/// This will complete any types necessary, and validate the various constraints
4361/// on those operands.
4362///
4363/// The UsualUnaryConversions() function is *not* called by this routine.
4364/// C99 6.3.2.1p[2-4] all state:
4365/// Except when it is the operand of the sizeof operator ...
4366///
4367/// C++ [expr.sizeof]p4
4368/// The lvalue-to-rvalue, array-to-pointer, and function-to-pointer
4369/// standard conversions are not applied to the operand of sizeof.
4370///
4371/// This policy is followed for all of the unary trait expressions.
4372bool Sema::CheckUnaryExprOrTypeTraitOperand(QualType ExprType,
4373 SourceLocation OpLoc,
4374 SourceRange ExprRange,
4375 UnaryExprOrTypeTrait ExprKind) {
4376 if (ExprType->isDependentType())
4377 return false;
4378
4379 // C++ [expr.sizeof]p2:
4380 // When applied to a reference or a reference type, the result
4381 // is the size of the referenced type.
4382 // C++11 [expr.alignof]p3:
4383 // When alignof is applied to a reference type, the result
4384 // shall be the alignment of the referenced type.
4385 if (const ReferenceType *Ref = ExprType->getAs<ReferenceType>())
4386 ExprType = Ref->getPointeeType();
4387
4388 // C11 6.5.3.4/3, C++11 [expr.alignof]p3:
4389 // When alignof or _Alignof is applied to an array type, the result
4390 // is the alignment of the element type.
4391 if (ExprKind == UETT_AlignOf || ExprKind == UETT_PreferredAlignOf ||
4392 ExprKind == UETT_OpenMPRequiredSimdAlign)
4393 ExprType = Context.getBaseElementType(ExprType);
4394
4395 if (ExprKind == UETT_VecStep)
4396 return CheckVecStepTraitOperandType(*this, ExprType, OpLoc, ExprRange);
4397
4398 // Explicitly list some types as extensions.
4399 if (!CheckExtensionTraitOperandType(*this, ExprType, OpLoc, ExprRange,
4400 ExprKind))
4401 return false;
4402
4403 if (RequireCompleteSizedType(
4404 OpLoc, ExprType, diag::err_sizeof_alignof_incomplete_or_sizeless_type,
4405 getTraitSpelling(ExprKind), ExprRange))
4406 return true;
4407
4408 if (ExprType->isFunctionType()) {
4409 Diag(OpLoc, diag::err_sizeof_alignof_function_type)
4410 << getTraitSpelling(ExprKind) << ExprRange;
4411 return true;
4412 }
4413
4414 if (CheckObjCTraitOperandConstraints(*this, ExprType, OpLoc, ExprRange,
4415 ExprKind))
4416 return true;
4417
4418 return false;
4419}
4420
4421static bool CheckAlignOfExpr(Sema &S, Expr *E, UnaryExprOrTypeTrait ExprKind) {
4422 // Cannot know anything else if the expression is dependent.
4423 if (E->isTypeDependent())
4424 return false;
4425
4426 if (E->getObjectKind() == OK_BitField) {
4427 S.Diag(E->getExprLoc(), diag::err_sizeof_alignof_typeof_bitfield)
4428 << 1 << E->getSourceRange();
4429 return true;
4430 }
4431
4432 ValueDecl *D = nullptr;
4433 Expr *Inner = E->IgnoreParens();
4434 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Inner)) {
4435 D = DRE->getDecl();
4436 } else if (MemberExpr *ME = dyn_cast<MemberExpr>(Inner)) {
4437 D = ME->getMemberDecl();
4438 }
4439
4440 // If it's a field, require the containing struct to have a
4441 // complete definition so that we can compute the layout.
4442 //
4443 // This can happen in C++11 onwards, either by naming the member
4444 // in a way that is not transformed into a member access expression
4445 // (in an unevaluated operand, for instance), or by naming the member
4446 // in a trailing-return-type.
4447 //
4448 // For the record, since __alignof__ on expressions is a GCC
4449 // extension, GCC seems to permit this but always gives the
4450 // nonsensical answer 0.
4451 //
4452 // We don't really need the layout here --- we could instead just
4453 // directly check for all the appropriate alignment-lowing
4454 // attributes --- but that would require duplicating a lot of
4455 // logic that just isn't worth duplicating for such a marginal
4456 // use-case.
4457 if (FieldDecl *FD = dyn_cast_or_null<FieldDecl>(D)) {
4458 // Fast path this check, since we at least know the record has a
4459 // definition if we can find a member of it.
4460 if (!FD->getParent()->isCompleteDefinition()) {
4461 S.Diag(E->getExprLoc(), diag::err_alignof_member_of_incomplete_type)
4462 << E->getSourceRange();
4463 return true;
4464 }
4465
4466 // Otherwise, if it's a field, and the field doesn't have
4467 // reference type, then it must have a complete type (or be a
4468 // flexible array member, which we explicitly want to
4469 // white-list anyway), which makes the following checks trivial.
4470 if (!FD->getType()->isReferenceType())
4471 return false;
4472 }
4473
4474 return S.CheckUnaryExprOrTypeTraitOperand(E, ExprKind);
4475}
4476
4477bool Sema::CheckVecStepExpr(Expr *E) {
4478 E = E->IgnoreParens();
4479
4480 // Cannot know anything else if the expression is dependent.
4481 if (E->isTypeDependent())
4482 return false;
4483
4484 return CheckUnaryExprOrTypeTraitOperand(E, UETT_VecStep);
4485}
4486
4487static void captureVariablyModifiedType(ASTContext &Context, QualType T,
4488 CapturingScopeInfo *CSI) {
4489 assert(T->isVariablyModifiedType())(static_cast <bool> (T->isVariablyModifiedType()) ? void
(0) : __assert_fail ("T->isVariablyModifiedType()", "clang/lib/Sema/SemaExpr.cpp"
, 4489, __extension__ __PRETTY_FUNCTION__))
;
4490 assert(CSI != nullptr)(static_cast <bool> (CSI != nullptr) ? void (0) : __assert_fail
("CSI != nullptr", "clang/lib/Sema/SemaExpr.cpp", 4490, __extension__
__PRETTY_FUNCTION__))
;
4491
4492 // We're going to walk down into the type and look for VLA expressions.
4493 do {
4494 const Type *Ty = T.getTypePtr();
4495 switch (Ty->getTypeClass()) {
4496#define TYPE(Class, Base)
4497#define ABSTRACT_TYPE(Class, Base)
4498#define NON_CANONICAL_TYPE(Class, Base)
4499#define DEPENDENT_TYPE(Class, Base) case Type::Class:
4500#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base)
4501#include "clang/AST/TypeNodes.inc"
4502 T = QualType();
4503 break;
4504 // These types are never variably-modified.
4505 case Type::Builtin:
4506 case Type::Complex:
4507 case Type::Vector:
4508 case Type::ExtVector:
4509 case Type::ConstantMatrix:
4510 case Type::Record:
4511 case Type::Enum:
4512 case Type::TemplateSpecialization:
4513 case Type::ObjCObject:
4514 case Type::ObjCInterface:
4515 case Type::ObjCObjectPointer:
4516 case Type::ObjCTypeParam:
4517 case Type::Pipe:
4518 case Type::BitInt:
4519 llvm_unreachable("type class is never variably-modified!")::llvm::llvm_unreachable_internal("type class is never variably-modified!"
, "clang/lib/Sema/SemaExpr.cpp", 4519)
;
4520 case Type::Elaborated:
4521 T = cast<ElaboratedType>(Ty)->getNamedType();
4522 break;
4523 case Type::Adjusted:
4524 T = cast<AdjustedType>(Ty)->getOriginalType();
4525 break;
4526 case Type::Decayed:
4527 T = cast<DecayedType>(Ty)->getPointeeType();
4528 break;
4529 case Type::Pointer:
4530 T = cast<PointerType>(Ty)->getPointeeType();
4531 break;
4532 case Type::BlockPointer:
4533 T = cast<BlockPointerType>(Ty)->getPointeeType();
4534 break;
4535 case Type::LValueReference:
4536 case Type::RValueReference:
4537 T = cast<ReferenceType>(Ty)->getPointeeType();
4538 break;
4539 case Type::MemberPointer:
4540 T = cast<MemberPointerType>(Ty)->getPointeeType();
4541 break;
4542 case Type::ConstantArray:
4543 case Type::IncompleteArray:
4544 // Losing element qualification here is fine.
4545 T = cast<ArrayType>(Ty)->getElementType();
4546 break;
4547 case Type::VariableArray: {
4548 // Losing element qualification here is fine.
4549 const VariableArrayType *VAT = cast<VariableArrayType>(Ty);
4550
4551 // Unknown size indication requires no size computation.
4552 // Otherwise, evaluate and record it.
4553 auto Size = VAT->getSizeExpr();
4554 if (Size && !CSI->isVLATypeCaptured(VAT) &&
4555 (isa<CapturedRegionScopeInfo>(CSI) || isa<LambdaScopeInfo>(CSI)))
4556 CSI->addVLATypeCapture(Size->getExprLoc(), VAT, Context.getSizeType());
4557
4558 T = VAT->getElementType();
4559 break;
4560 }
4561 case Type::FunctionProto:
4562 case Type::FunctionNoProto:
4563 T = cast<FunctionType>(Ty)->getReturnType();
4564 break;
4565 case Type::Paren:
4566 case Type::TypeOf:
4567 case Type::UnaryTransform:
4568 case Type::Attributed:
4569 case Type::BTFTagAttributed:
4570 case Type::SubstTemplateTypeParm:
4571 case Type::MacroQualified:
4572 // Keep walking after single level desugaring.
4573 T = T.getSingleStepDesugaredType(Context);
4574 break;
4575 case Type::Typedef:
4576 T = cast<TypedefType>(Ty)->desugar();
4577 break;
4578 case Type::Decltype:
4579 T = cast<DecltypeType>(Ty)->desugar();
4580 break;
4581 case Type::Using:
4582 T = cast<UsingType>(Ty)->desugar();
4583 break;
4584 case Type::Auto:
4585 case Type::DeducedTemplateSpecialization:
4586 T = cast<DeducedType>(Ty)->getDeducedType();
4587 break;
4588 case Type::TypeOfExpr:
4589 T = cast<TypeOfExprType>(Ty)->getUnderlyingExpr()->getType();
4590 break;
4591 case Type::Atomic:
4592 T = cast<AtomicType>(Ty)->getValueType();
4593 break;
4594 }
4595 } while (!T.isNull() && T->isVariablyModifiedType());
4596}
4597
4598/// Build a sizeof or alignof expression given a type operand.
4599ExprResult
4600Sema::CreateUnaryExprOrTypeTraitExpr(TypeSourceInfo *TInfo,
4601 SourceLocation OpLoc,
4602 UnaryExprOrTypeTrait ExprKind,
4603 SourceRange R) {
4604 if (!TInfo)
4605 return ExprError();
4606
4607 QualType T = TInfo->getType();
4608
4609 if (!T->isDependentType() &&
4610 CheckUnaryExprOrTypeTraitOperand(T, OpLoc, R, ExprKind))
4611 return ExprError();
4612
4613 if (T->isVariablyModifiedType() && FunctionScopes.size() > 1) {
4614 if (auto *TT = T->getAs<TypedefType>()) {
4615 for (auto I = FunctionScopes.rbegin(),
4616 E = std::prev(FunctionScopes.rend());
4617 I != E; ++I) {
4618 auto *CSI = dyn_cast<CapturingScopeInfo>(*I);
4619 if (CSI == nullptr)
4620 break;
4621 DeclContext *DC = nullptr;
4622 if (auto *LSI = dyn_cast<LambdaScopeInfo>(CSI))
4623 DC = LSI->CallOperator;
4624 else if (auto *CRSI = dyn_cast<CapturedRegionScopeInfo>(CSI))
4625 DC = CRSI->TheCapturedDecl;
4626 else if (auto *BSI = dyn_cast<BlockScopeInfo>(CSI))
4627 DC = BSI->TheDecl;
4628 if (DC) {
4629 if (DC->containsDecl(TT->getDecl()))
4630 break;
4631 captureVariablyModifiedType(Context, T, CSI);
4632 }
4633 }
4634 }
4635 }
4636
4637 // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t.
4638 if (isUnevaluatedContext() && ExprKind == UETT_SizeOf &&
4639 TInfo->getType()->isVariablyModifiedType())
4640 TInfo = TransformToPotentiallyEvaluated(TInfo);
4641
4642 return new (Context) UnaryExprOrTypeTraitExpr(
4643 ExprKind, TInfo, Context.getSizeType(), OpLoc, R.getEnd());
4644}
4645
4646/// Build a sizeof or alignof expression given an expression
4647/// operand.
4648ExprResult
4649Sema::CreateUnaryExprOrTypeTraitExpr(Expr *E, SourceLocation OpLoc,
4650 UnaryExprOrTypeTrait ExprKind) {
4651 ExprResult PE = CheckPlaceholderExpr(E);
4652 if (PE.isInvalid())
4653 return ExprError();
4654
4655 E = PE.get();
4656
4657 // Verify that the operand is valid.
4658 bool isInvalid = false;
4659 if (E->isTypeDependent()) {
4660 // Delay type-checking for type-dependent expressions.
4661 } else if (ExprKind == UETT_AlignOf || ExprKind == UETT_PreferredAlignOf) {
4662 isInvalid = CheckAlignOfExpr(*this, E, ExprKind);
4663 } else if (ExprKind == UETT_VecStep) {
4664 isInvalid = CheckVecStepExpr(E);
4665 } else if (ExprKind == UETT_OpenMPRequiredSimdAlign) {
4666 Diag(E->getExprLoc(), diag::err_openmp_default_simd_align_expr);
4667 isInvalid = true;
4668 } else if (E->refersToBitField()) { // C99 6.5.3.4p1.
4669 Diag(E->getExprLoc(), diag::err_sizeof_alignof_typeof_bitfield) << 0;
4670 isInvalid = true;
4671 } else {
4672 isInvalid = CheckUnaryExprOrTypeTraitOperand(E, UETT_SizeOf);
4673 }
4674
4675 if (isInvalid)
4676 return ExprError();
4677
4678 if (ExprKind == UETT_SizeOf && E->getType()->isVariableArrayType()) {
4679 PE = TransformToPotentiallyEvaluated(E);
4680 if (PE.isInvalid()) return ExprError();
4681 E = PE.get();
4682 }
4683
4684 // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t.
4685 return new (Context) UnaryExprOrTypeTraitExpr(
4686 ExprKind, E, Context.getSizeType(), OpLoc, E->getSourceRange().getEnd());
4687}
4688
4689/// ActOnUnaryExprOrTypeTraitExpr - Handle @c sizeof(type) and @c sizeof @c
4690/// expr and the same for @c alignof and @c __alignof
4691/// Note that the ArgRange is invalid if isType is false.
4692ExprResult
4693Sema::ActOnUnaryExprOrTypeTraitExpr(SourceLocation OpLoc,
4694 UnaryExprOrTypeTrait ExprKind, bool IsType,
4695 void *TyOrEx, SourceRange ArgRange) {
4696 // If error parsing type, ignore.
4697 if (!TyOrEx) return ExprError();
4698
4699 if (IsType) {
4700 TypeSourceInfo *TInfo;
4701 (void) GetTypeFromParser(ParsedType::getFromOpaquePtr(TyOrEx), &TInfo);
4702 return CreateUnaryExprOrTypeTraitExpr(TInfo, OpLoc, ExprKind, ArgRange);
4703 }
4704
4705 Expr *ArgEx = (Expr *)TyOrEx;
4706 ExprResult Result = CreateUnaryExprOrTypeTraitExpr(ArgEx, OpLoc, ExprKind);
4707 return Result;
4708}
4709
4710static QualType CheckRealImagOperand(Sema &S, ExprResult &V, SourceLocation Loc,
4711 bool IsReal) {
4712 if (V.get()->isTypeDependent())
4713 return S.Context.DependentTy;
4714
4715 // _Real and _Imag are only l-values for normal l-values.
4716 if (V.get()->getObjectKind() != OK_Ordinary) {
4717 V = S.DefaultLvalueConversion(V.get());
4718 if (V.isInvalid())
4719 return QualType();
4720 }
4721
4722 // These operators return the element type of a complex type.
4723 if (const ComplexType *CT = V.get()->getType()->getAs<ComplexType>())
4724 return CT->getElementType();
4725
4726 // Otherwise they pass through real integer and floating point types here.
4727 if (V.get()->getType()->isArithmeticType())
4728 return V.get()->getType();
4729
4730 // Test for placeholders.
4731 ExprResult PR = S.CheckPlaceholderExpr(V.get());
4732 if (PR.isInvalid()) return QualType();
4733 if (PR.get() != V.get()) {
4734 V = PR;
4735 return CheckRealImagOperand(S, V, Loc, IsReal);
4736 }
4737
4738 // Reject anything else.
4739 S.Diag(Loc, diag::err_realimag_invalid_type) << V.get()->getType()
4740 << (IsReal ? "__real" : "__imag");
4741 return QualType();
4742}
4743
4744
4745
4746ExprResult
4747Sema::ActOnPostfixUnaryOp(Scope *S, SourceLocation OpLoc,
4748 tok::TokenKind Kind, Expr *Input) {
4749 UnaryOperatorKind Opc;
4750 switch (Kind) {
4751 default: llvm_unreachable("Unknown unary op!")::llvm::llvm_unreachable_internal("Unknown unary op!", "clang/lib/Sema/SemaExpr.cpp"
, 4751)
;
4752 case tok::plusplus: Opc = UO_PostInc; break;
4753 case tok::minusminus: Opc = UO_PostDec; break;
4754 }
4755
4756 // Since this might is a postfix expression, get rid of ParenListExprs.
4757 ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Input);
4758 if (Result.isInvalid()) return ExprError();
4759 Input = Result.get();
4760
4761 return BuildUnaryOp(S, OpLoc, Opc, Input);
4762}
4763
4764/// Diagnose if arithmetic on the given ObjC pointer is illegal.
4765///
4766/// \return true on error
4767static bool checkArithmeticOnObjCPointer(Sema &S,
4768 SourceLocation opLoc,
4769 Expr *op) {
4770 assert(op->getType()->isObjCObjectPointerType())(static_cast <bool> (op->getType()->isObjCObjectPointerType
()) ? void (0) : __assert_fail ("op->getType()->isObjCObjectPointerType()"
, "clang/lib/Sema/SemaExpr.cpp", 4770, __extension__ __PRETTY_FUNCTION__
))
;
4771 if (S.LangOpts.ObjCRuntime.allowsPointerArithmetic() &&
4772 !S.LangOpts.ObjCSubscriptingLegacyRuntime)
4773 return false;
4774
4775 S.Diag(opLoc, diag::err_arithmetic_nonfragile_interface)
4776 << op->getType()->castAs<ObjCObjectPointerType>()->getPointeeType()
4777 << op->getSourceRange();
4778 return true;
4779}
4780
4781static bool isMSPropertySubscriptExpr(Sema &S, Expr *Base) {
4782 auto *BaseNoParens = Base->IgnoreParens();
4783 if (auto *MSProp = dyn_cast<MSPropertyRefExpr>(BaseNoParens))
4784 return MSProp->getPropertyDecl()->getType()->isArrayType();
4785 return isa<MSPropertySubscriptExpr>(BaseNoParens);
4786}
4787
4788// Returns the type used for LHS[RHS], given one of LHS, RHS is type-dependent.
4789// Typically this is DependentTy, but can sometimes be more precise.
4790//
4791// There are cases when we could determine a non-dependent type:
4792// - LHS and RHS may have non-dependent types despite being type-dependent
4793// (e.g. unbounded array static members of the current instantiation)
4794// - one may be a dependent-sized array with known element type
4795// - one may be a dependent-typed valid index (enum in current instantiation)
4796//
4797// We *always* return a dependent type, in such cases it is DependentTy.
4798// This avoids creating type-dependent expressions with non-dependent types.
4799// FIXME: is this important to avoid? See https://reviews.llvm.org/D107275
4800static QualType getDependentArraySubscriptType(Expr *LHS, Expr *RHS,
4801 const ASTContext &Ctx) {
4802 assert(LHS->isTypeDependent() || RHS->isTypeDependent())(static_cast <bool> (LHS->isTypeDependent() || RHS->
isTypeDependent()) ? void (0) : __assert_fail ("LHS->isTypeDependent() || RHS->isTypeDependent()"
, "clang/lib/Sema/SemaExpr.cpp", 4802, __extension__ __PRETTY_FUNCTION__
))
;
4803 QualType LTy = LHS->getType(), RTy = RHS->getType();
4804 QualType Result = Ctx.DependentTy;
4805 if (RTy->isIntegralOrUnscopedEnumerationType()) {
4806 if (const PointerType *PT = LTy->getAs<PointerType>())
4807 Result = PT->getPointeeType();
4808 else if (const ArrayType *AT = LTy->getAsArrayTypeUnsafe())
4809 Result = AT->getElementType();
4810 } else if (LTy->isIntegralOrUnscopedEnumerationType()) {
4811 if (const PointerType *PT = RTy->getAs<PointerType>())
4812 Result = PT->getPointeeType();
4813 else if (const ArrayType *AT = RTy->getAsArrayTypeUnsafe())
4814 Result = AT->getElementType();
4815 }
4816 // Ensure we return a dependent type.
4817 return Result->isDependentType() ? Result : Ctx.DependentTy;
4818}
4819
4820static bool checkArgsForPlaceholders(Sema &S, MultiExprArg args);
4821
4822ExprResult Sema::ActOnArraySubscriptExpr(Scope *S, Expr *base,
4823 SourceLocation lbLoc,
4824 MultiExprArg ArgExprs,
4825 SourceLocation rbLoc) {
4826
4827 if (base && !base->getType().isNull() &&
4828 base->hasPlaceholderType(BuiltinType::OMPArraySection))
4829 return ActOnOMPArraySectionExpr(base, lbLoc, ArgExprs.front(), SourceLocation(),
4830 SourceLocation(), /*Length*/ nullptr,
4831 /*Stride=*/nullptr, rbLoc);
4832
4833 // Since this might be a postfix expression, get rid of ParenListExprs.
4834 if (isa<ParenListExpr>(base)) {
4835 ExprResult result = MaybeConvertParenListExprToParenExpr(S, base);
4836 if (result.isInvalid())
4837 return ExprError();
4838 base = result.get();
4839 }
4840
4841 // Check if base and idx form a MatrixSubscriptExpr.
4842 //
4843 // Helper to check for comma expressions, which are not allowed as indices for
4844 // matrix subscript expressions.
4845 auto CheckAndReportCommaError = [this, base, rbLoc](Expr *E) {
4846 if (isa<BinaryOperator>(E) && cast<BinaryOperator>(E)->isCommaOp()) {
4847 Diag(E->getExprLoc(), diag::err_matrix_subscript_comma)
4848 << SourceRange(base->getBeginLoc(), rbLoc);
4849 return true;
4850 }
4851 return false;
4852 };
4853 // The matrix subscript operator ([][])is considered a single operator.
4854 // Separating the index expressions by parenthesis is not allowed.
4855 if (base->hasPlaceholderType(BuiltinType::IncompleteMatrixIdx) &&
4856 !isa<MatrixSubscriptExpr>(base)) {
4857 Diag(base->getExprLoc(), diag::err_matrix_separate_incomplete_index)
4858 << SourceRange(base->getBeginLoc(), rbLoc);
4859 return ExprError();
4860 }
4861 // If the base is a MatrixSubscriptExpr, try to create a new
4862 // MatrixSubscriptExpr.
4863 auto *matSubscriptE = dyn_cast<MatrixSubscriptExpr>(base);
4864 if (matSubscriptE) {
4865 assert(ArgExprs.size() == 1)(static_cast <bool> (ArgExprs.size() == 1) ? void (0) :
__assert_fail ("ArgExprs.size() == 1", "clang/lib/Sema/SemaExpr.cpp"
, 4865, __extension__ __PRETTY_FUNCTION__))
;
4866 if (CheckAndReportCommaError(ArgExprs.front()))
4867 return ExprError();
4868
4869 assert(matSubscriptE->isIncomplete() &&(static_cast <bool> (matSubscriptE->isIncomplete() &&
"base has to be an incomplete matrix subscript") ? void (0) :
__assert_fail ("matSubscriptE->isIncomplete() && \"base has to be an incomplete matrix subscript\""
, "clang/lib/Sema/SemaExpr.cpp", 4870, __extension__ __PRETTY_FUNCTION__
))
4870 "base has to be an incomplete matrix subscript")(static_cast <bool> (matSubscriptE->isIncomplete() &&
"base has to be an incomplete matrix subscript") ? void (0) :
__assert_fail ("matSubscriptE->isIncomplete() && \"base has to be an incomplete matrix subscript\""
, "clang/lib/Sema/SemaExpr.cpp", 4870, __extension__ __PRETTY_FUNCTION__
))
;
4871 return CreateBuiltinMatrixSubscriptExpr(matSubscriptE->getBase(),
4872 matSubscriptE->getRowIdx(),
4873 ArgExprs.front(), rbLoc);
4874 }
4875
4876 // Handle any non-overload placeholder types in the base and index
4877 // expressions. We can't handle overloads here because the other
4878 // operand might be an overloadable type, in which case the overload
4879 // resolution for the operator overload should get the first crack
4880 // at the overload.
4881 bool IsMSPropertySubscript = false;
4882 if (base->getType()->isNonOverloadPlaceholderType()) {
4883 IsMSPropertySubscript = isMSPropertySubscriptExpr(*this, base);
4884 if (!IsMSPropertySubscript) {
4885 ExprResult result = CheckPlaceholderExpr(base);
4886 if (result.isInvalid())
4887 return ExprError();
4888 base = result.get();
4889 }
4890 }
4891
4892 // If the base is a matrix type, try to create a new MatrixSubscriptExpr.
4893 if (base->getType()->isMatrixType()) {
4894 assert(ArgExprs.size() == 1)(static_cast <bool> (ArgExprs.size() == 1) ? void (0) :
__assert_fail ("ArgExprs.size() == 1", "clang/lib/Sema/SemaExpr.cpp"
, 4894, __extension__ __PRETTY_FUNCTION__))
;
4895 if (CheckAndReportCommaError(ArgExprs.front()))
4896 return ExprError();
4897
4898 return CreateBuiltinMatrixSubscriptExpr(base, ArgExprs.front(), nullptr,
4899 rbLoc);
4900 }
4901
4902 if (ArgExprs.size() == 1 && getLangOpts().CPlusPlus20) {
4903 Expr *idx = ArgExprs[0];
4904 if ((isa<BinaryOperator>(idx) && cast<BinaryOperator>(idx)->isCommaOp()) ||
4905 (isa<CXXOperatorCallExpr>(idx) &&
4906 cast<CXXOperatorCallExpr>(idx)->getOperator() == OO_Comma)) {
4907 Diag(idx->getExprLoc(), diag::warn_deprecated_comma_subscript)
4908 << SourceRange(base->getBeginLoc(), rbLoc);
4909 }
4910 }
4911
4912 if (ArgExprs.size() == 1 &&
4913 ArgExprs[0]->getType()->isNonOverloadPlaceholderType()) {
4914 ExprResult result = CheckPlaceholderExpr(ArgExprs[0]);
4915 if (result.isInvalid())
4916 return ExprError();
4917 ArgExprs[0] = result.get();
4918 } else {
4919 if (checkArgsForPlaceholders(*this, ArgExprs))
4920 return ExprError();
4921 }
4922
4923 // Build an unanalyzed expression if either operand is type-dependent.
4924 if (getLangOpts().CPlusPlus && ArgExprs.size() == 1 &&
4925 (base->isTypeDependent() ||
4926 Expr::hasAnyTypeDependentArguments(ArgExprs)) &&
4927 !isa<PackExpansionExpr>(ArgExprs[0])) {
4928 return new (Context) ArraySubscriptExpr(
4929 base, ArgExprs.front(),
4930 getDependentArraySubscriptType(base, ArgExprs.front(), getASTContext()),
4931 VK_LValue, OK_Ordinary, rbLoc);
4932 }
4933
4934 // MSDN, property (C++)
4935 // https://msdn.microsoft.com/en-us/library/yhfk0thd(v=vs.120).aspx
4936 // This attribute can also be used in the declaration of an empty array in a
4937 // class or structure definition. For example:
4938 // __declspec(property(get=GetX, put=PutX)) int x[];
4939 // The above statement indicates that x[] can be used with one or more array
4940 // indices. In this case, i=p->x[a][b] will be turned into i=p->GetX(a, b),
4941 // and p->x[a][b] = i will be turned into p->PutX(a, b, i);
4942 if (IsMSPropertySubscript) {
4943 assert(ArgExprs.size() == 1)(static_cast <bool> (ArgExprs.size() == 1) ? void (0) :
__assert_fail ("ArgExprs.size() == 1", "clang/lib/Sema/SemaExpr.cpp"
, 4943, __extension__ __PRETTY_FUNCTION__))
;
4944 // Build MS property subscript expression if base is MS property reference
4945 // or MS property subscript.
4946 return new (Context)
4947 MSPropertySubscriptExpr(base, ArgExprs.front(), Context.PseudoObjectTy,
4948 VK_LValue, OK_Ordinary, rbLoc);
4949 }
4950
4951 // Use C++ overloaded-operator rules if either operand has record
4952 // type. The spec says to do this if either type is *overloadable*,
4953 // but enum types can't declare subscript operators or conversion
4954 // operators, so there's nothing interesting for overload resolution
4955 // to do if there aren't any record types involved.
4956 //
4957 // ObjC pointers have their own subscripting logic that is not tied
4958 // to overload resolution and so should not take this path.
4959 if (getLangOpts().CPlusPlus && !base->getType()->isObjCObjectPointerType() &&
4960 ((base->getType()->isRecordType() ||
4961 (ArgExprs.size() != 1 || isa<PackExpansionExpr>(ArgExprs[0]) ||
4962 ArgExprs[0]->getType()->isRecordType())))) {
4963 return CreateOverloadedArraySubscriptExpr(lbLoc, rbLoc, base, ArgExprs);
4964 }
4965
4966 ExprResult Res =
4967 CreateBuiltinArraySubscriptExpr(base, lbLoc, ArgExprs.front(), rbLoc);
4968
4969 if (!Res.isInvalid() && isa<ArraySubscriptExpr>(Res.get()))
4970 CheckSubscriptAccessOfNoDeref(cast<ArraySubscriptExpr>(Res.get()));
4971
4972 return Res;
4973}
4974
4975ExprResult Sema::tryConvertExprToType(Expr *E, QualType Ty) {
4976 InitializedEntity Entity = InitializedEntity::InitializeTemporary(Ty);
4977 InitializationKind Kind =
4978 InitializationKind::CreateCopy(E->getBeginLoc(), SourceLocation());
4979 InitializationSequence InitSeq(*this, Entity, Kind, E);
4980 return InitSeq.Perform(*this, Entity, Kind, E);
4981}
4982
4983ExprResult Sema::CreateBuiltinMatrixSubscriptExpr(Expr *Base, Expr *RowIdx,
4984 Expr *ColumnIdx,
4985 SourceLocation RBLoc) {
4986 ExprResult BaseR = CheckPlaceholderExpr(Base);
4987 if (BaseR.isInvalid())
4988 return BaseR;
4989 Base = BaseR.get();
4990
4991 ExprResult RowR = CheckPlaceholderExpr(RowIdx);
4992 if (RowR.isInvalid())
4993 return RowR;
4994 RowIdx = RowR.get();
4995
4996 if (!ColumnIdx)
4997 return new (Context) MatrixSubscriptExpr(
4998 Base, RowIdx, ColumnIdx, Context.IncompleteMatrixIdxTy, RBLoc);
4999
5000 // Build an unanalyzed expression if any of the operands is type-dependent.
5001 if (Base->isTypeDependent() || RowIdx->isTypeDependent() ||
5002 ColumnIdx->isTypeDependent())
5003 return new (Context) MatrixSubscriptExpr(Base, RowIdx, ColumnIdx,
5004 Context.DependentTy, RBLoc);
5005
5006 ExprResult ColumnR = CheckPlaceholderExpr(ColumnIdx);
5007 if (ColumnR.isInvalid())
5008 return ColumnR;
5009 ColumnIdx = ColumnR.get();
5010
5011 // Check that IndexExpr is an integer expression. If it is a constant
5012 // expression, check that it is less than Dim (= the number of elements in the
5013 // corresponding dimension).
5014 auto IsIndexValid = [&](Expr *IndexExpr, unsigned Dim,
5015 bool IsColumnIdx) -> Expr * {
5016 if (!IndexExpr->getType()->isIntegerType() &&
5017 !IndexExpr->isTypeDependent()) {
5018 Diag(IndexExpr->getBeginLoc(), diag::err_matrix_index_not_integer)
5019 << IsColumnIdx;
5020 return nullptr;
5021 }
5022
5023 if (std::optional<llvm::APSInt> Idx =
5024 IndexExpr->getIntegerConstantExpr(Context)) {
5025 if ((*Idx < 0 || *Idx >= Dim)) {
5026 Diag(IndexExpr->getBeginLoc(), diag::err_matrix_index_outside_range)
5027 << IsColumnIdx << Dim;
5028 return nullptr;
5029 }
5030 }
5031
5032 ExprResult ConvExpr =
5033 tryConvertExprToType(IndexExpr, Context.getSizeType());
5034 assert(!ConvExpr.isInvalid() &&(static_cast <bool> (!ConvExpr.isInvalid() && "should be able to convert any integer type to size type"
) ? void (0) : __assert_fail ("!ConvExpr.isInvalid() && \"should be able to convert any integer type to size type\""
, "clang/lib/Sema/SemaExpr.cpp", 5035, __extension__ __PRETTY_FUNCTION__
))
5035 "should be able to convert any integer type to size type")(static_cast <bool> (!ConvExpr.isInvalid() && "should be able to convert any integer type to size type"
) ? void (0) : __assert_fail ("!ConvExpr.isInvalid() && \"should be able to convert any integer type to size type\""
, "clang/lib/Sema/SemaExpr.cpp", 5035, __extension__ __PRETTY_FUNCTION__
))
;
5036 return ConvExpr.get();
5037 };
5038
5039 auto *MTy = Base->getType()->getAs<ConstantMatrixType>();
5040 RowIdx = IsIndexValid(RowIdx, MTy->getNumRows(), false);
5041 ColumnIdx = IsIndexValid(ColumnIdx, MTy->getNumColumns(), true);
5042 if (!RowIdx || !ColumnIdx)
5043 return ExprError();
5044
5045 return new (Context) MatrixSubscriptExpr(Base, RowIdx, ColumnIdx,
5046 MTy->getElementType(), RBLoc);
5047}
5048
5049void Sema::CheckAddressOfNoDeref(const Expr *E) {
5050 ExpressionEvaluationContextRecord &LastRecord = ExprEvalContexts.back();
5051 const Expr *StrippedExpr = E->IgnoreParenImpCasts();
5052
5053 // For expressions like `&(*s).b`, the base is recorded and what should be
5054 // checked.
5055 const MemberExpr *Member = nullptr;
5056 while ((Member = dyn_cast<MemberExpr>(StrippedExpr)) && !Member->isArrow())
5057 StrippedExpr = Member->getBase()->IgnoreParenImpCasts();
5058
5059 LastRecord.PossibleDerefs.erase(StrippedExpr);
5060}
5061
5062void Sema::CheckSubscriptAccessOfNoDeref(const ArraySubscriptExpr *E) {
5063 if (isUnevaluatedContext())
5064 return;
5065
5066 QualType ResultTy = E->getType();
5067 ExpressionEvaluationContextRecord &LastRecord = ExprEvalContexts.back();
5068
5069 // Bail if the element is an array since it is not memory access.
5070 if (isa<ArrayType>(ResultTy))
5071 return;
5072
5073 if (ResultTy->hasAttr(attr::NoDeref)) {
5074 LastRecord.PossibleDerefs.insert(E);
5075 return;
5076 }
5077
5078 // Check if the base type is a pointer to a member access of a struct
5079 // marked with noderef.
5080 const Expr *Base = E->getBase();
5081 QualType BaseTy = Base->getType();
5082 if (!(isa<ArrayType>(BaseTy) || isa<PointerType>(BaseTy)))
5083 // Not a pointer access
5084 return;
5085
5086 const MemberExpr *Member = nullptr;
5087 while ((Member = dyn_cast<MemberExpr>(Base->IgnoreParenCasts())) &&
5088 Member->isArrow())
5089 Base = Member->getBase();
5090
5091 if (const auto *Ptr = dyn_cast<PointerType>(Base->getType())) {
5092 if (Ptr->getPointeeType()->hasAttr(attr::NoDeref))
5093 LastRecord.PossibleDerefs.insert(E);
5094 }
5095}
5096
5097ExprResult Sema::ActOnOMPArraySectionExpr(Expr *Base, SourceLocation LBLoc,
5098 Expr *LowerBound,
5099 SourceLocation ColonLocFirst,
5100 SourceLocation ColonLocSecond,
5101 Expr *Length, Expr *Stride,
5102 SourceLocation RBLoc) {
5103 if (Base->hasPlaceholderType() &&
5104 !Base->hasPlaceholderType(BuiltinType::OMPArraySection)) {
5105 ExprResult Result = CheckPlaceholderExpr(Base);
5106 if (Result.isInvalid())
5107 return ExprError();
5108 Base = Result.get();
5109 }
5110 if (LowerBound && LowerBound->getType()->isNonOverloadPlaceholderType()) {
5111 ExprResult Result = CheckPlaceholderExpr(LowerBound);
5112 if (Result.isInvalid())
5113 return ExprError();
5114 Result = DefaultLvalueConversion(Result.get());
5115 if (Result.isInvalid())
5116 return ExprError();
5117 LowerBound = Result.get();
5118 }
5119 if (Length && Length->getType()->isNonOverloadPlaceholderType()) {
5120 ExprResult Result = CheckPlaceholderExpr(Length);
5121 if (Result.isInvalid())
5122 return ExprError();
5123 Result = DefaultLvalueConversion(Result.get());
5124 if (Result.isInvalid())
5125 return ExprError();
5126 Length = Result.get();
5127 }
5128 if (Stride && Stride->getType()->isNonOverloadPlaceholderType()) {
5129 ExprResult Result = CheckPlaceholderExpr(Stride);
5130 if (Result.isInvalid())
5131 return ExprError();
5132 Result = DefaultLvalueConversion(Result.get());
5133 if (Result.isInvalid())
5134 return ExprError();
5135 Stride = Result.get();
5136 }
5137
5138 // Build an unanalyzed expression if either operand is type-dependent.
5139 if (Base->isTypeDependent() ||
5140 (LowerBound &&
5141 (LowerBound->isTypeDependent() || LowerBound->isValueDependent())) ||
5142 (Length && (Length->isTypeDependent() || Length->isValueDependent())) ||
5143 (Stride && (Stride->isTypeDependent() || Stride->isValueDependent()))) {
5144 return new (Context) OMPArraySectionExpr(
5145 Base, LowerBound, Length, Stride, Context.DependentTy, VK_LValue,
5146 OK_Ordinary, ColonLocFirst, ColonLocSecond, RBLoc);
5147 }
5148
5149 // Perform default conversions.
5150 QualType OriginalTy = OMPArraySectionExpr::getBaseOriginalType(Base);
5151 QualType ResultTy;
5152 if (OriginalTy->isAnyPointerType()) {
5153 ResultTy = OriginalTy->getPointeeType();
5154 } else if (OriginalTy->isArrayType()) {
5155 ResultTy = OriginalTy->getAsArrayTypeUnsafe()->getElementType();
5156 } else {
5157 return ExprError(
5158 Diag(Base->getExprLoc(), diag::err_omp_typecheck_section_value)
5159 << Base->getSourceRange());
5160 }
5161 // C99 6.5.2.1p1
5162 if (LowerBound) {
5163 auto Res = PerformOpenMPImplicitIntegerConversion(LowerBound->getExprLoc(),
5164 LowerBound);
5165 if (Res.isInvalid())
5166 return ExprError(Diag(LowerBound->getExprLoc(),
5167 diag::err_omp_typecheck_section_not_integer)
5168 << 0 << LowerBound->getSourceRange());
5169 LowerBound = Res.get();
5170
5171 if (LowerBound->getType()->isSpecificBuiltinType(BuiltinType::Char_S) ||
5172 LowerBound->getType()->isSpecificBuiltinType(BuiltinType::Char_U))
5173 Diag(LowerBound->getExprLoc(), diag::warn_omp_section_is_char)
5174 << 0 << LowerBound->getSourceRange();
5175 }
5176 if (Length) {
5177 auto Res =
5178 PerformOpenMPImplicitIntegerConversion(Length->getExprLoc(), Length);
5179 if (Res.isInvalid())
5180 return ExprError(Diag(Length->getExprLoc(),
5181 diag::err_omp_typecheck_section_not_integer)
5182 << 1 << Length->getSourceRange());
5183 Length = Res.get();
5184
5185 if (Length->getType()->isSpecificBuiltinType(BuiltinType::Char_S) ||
5186 Length->getType()->isSpecificBuiltinType(BuiltinType::Char_U))
5187 Diag(Length->getExprLoc(), diag::warn_omp_section_is_char)
5188 << 1 << Length->getSourceRange();
5189 }
5190 if (Stride) {
5191 ExprResult Res =
5192 PerformOpenMPImplicitIntegerConversion(Stride->getExprLoc(), Stride);
5193 if (Res.isInvalid())
5194 return ExprError(Diag(Stride->getExprLoc(),
5195 diag::err_omp_typecheck_section_not_integer)
5196 << 1 << Stride->getSourceRange());
5197 Stride = Res.get();
5198
5199 if (Stride->getType()->isSpecificBuiltinType(BuiltinType::Char_S) ||
5200 Stride->getType()->isSpecificBuiltinType(BuiltinType::Char_U))
5201 Diag(Stride->getExprLoc(), diag::warn_omp_section_is_char)
5202 << 1 << Stride->getSourceRange();
5203 }
5204
5205 // C99 6.5.2.1p1: "shall have type "pointer to *object* type". Similarly,
5206 // C++ [expr.sub]p1: The type "T" shall be a completely-defined object
5207 // type. Note that functions are not objects, and that (in C99 parlance)
5208 // incomplete types are not object types.
5209 if (ResultTy->isFunctionType()) {
5210 Diag(Base->getExprLoc(), diag::err_omp_section_function_type)
5211 << ResultTy << Base->getSourceRange();
5212 return ExprError();
5213 }
5214
5215 if (RequireCompleteType(Base->getExprLoc(), ResultTy,
5216 diag::err_omp_section_incomplete_type, Base))
5217 return ExprError();
5218
5219 if (LowerBound && !OriginalTy->isAnyPointerType()) {
5220 Expr::EvalResult Result;
5221 if (LowerBound->EvaluateAsInt(Result, Context)) {
5222 // OpenMP 5.0, [2.1.5 Array Sections]
5223 // The array section must be a subset of the original array.
5224 llvm::APSInt LowerBoundValue = Result.Val.getInt();
5225 if (LowerBoundValue.isNegative()) {
5226 Diag(LowerBound->getExprLoc(), diag::err_omp_section_not_subset_of_array)
5227 << LowerBound->getSourceRange();
5228 return ExprError();
5229 }
5230 }
5231 }
5232
5233 if (Length) {
5234 Expr::EvalResult Result;
5235 if (Length->EvaluateAsInt(Result, Context)) {
5236 // OpenMP 5.0, [2.1.5 Array Sections]
5237 // The length must evaluate to non-negative integers.
5238 llvm::APSInt LengthValue = Result.Val.getInt();
5239 if (LengthValue.isNegative()) {
5240 Diag(Length->getExprLoc(), diag::err_omp_section_length_negative)
5241 << toString(LengthValue, /*Radix=*/10, /*Signed=*/true)
5242 << Length->getSourceRange();
5243 return ExprError();
5244 }
5245 }
5246 } else if (ColonLocFirst.isValid() &&
5247 (OriginalTy.isNull() || (!OriginalTy->isConstantArrayType() &&
5248 !OriginalTy->isVariableArrayType()))) {
5249 // OpenMP 5.0, [2.1.5 Array Sections]
5250 // When the size of the array dimension is not known, the length must be
5251 // specified explicitly.
5252 Diag(ColonLocFirst, diag::err_omp_section_length_undefined)
5253 << (!OriginalTy.isNull() && OriginalTy->isArrayType());
5254 return ExprError();
5255 }
5256
5257 if (Stride) {
5258 Expr::EvalResult Result;
5259 if (Stride->EvaluateAsInt(Result, Context)) {
5260 // OpenMP 5.0, [2.1.5 Array Sections]
5261 // The stride must evaluate to a positive integer.
5262 llvm::APSInt StrideValue = Result.Val.getInt();
5263 if (!StrideValue.isStrictlyPositive()) {
5264 Diag(Stride->getExprLoc(), diag::err_omp_section_stride_non_positive)
5265 << toString(StrideValue, /*Radix=*/10, /*Signed=*/true)
5266 << Stride->getSourceRange();
5267 return ExprError();
5268 }
5269 }
5270 }
5271
5272 if (!Base->hasPlaceholderType(BuiltinType::OMPArraySection)) {
5273 ExprResult Result = DefaultFunctionArrayLvalueConversion(Base);
5274 if (Result.isInvalid())
5275 return ExprError();
5276 Base = Result.get();
5277 }
5278 return new (Context) OMPArraySectionExpr(
5279 Base, LowerBound, Length, Stride, Context.OMPArraySectionTy, VK_LValue,
5280 OK_Ordinary, ColonLocFirst, ColonLocSecond, RBLoc);
5281}
5282
5283ExprResult Sema::ActOnOMPArrayShapingExpr(Expr *Base, SourceLocation LParenLoc,
5284 SourceLocation RParenLoc,
5285 ArrayRef<Expr *> Dims,
5286 ArrayRef<SourceRange> Brackets) {
5287 if (Base->hasPlaceholderType()) {
5288 ExprResult Result = CheckPlaceholderExpr(Base);
5289 if (Result.isInvalid())
5290 return ExprError();
5291 Result = DefaultLvalueConversion(Result.get());
5292 if (Result.isInvalid())
5293 return ExprError();
5294 Base = Result.get();
5295 }
5296 QualType BaseTy = Base->getType();
5297 // Delay analysis of the types/expressions if instantiation/specialization is
5298 // required.
5299 if (!BaseTy->isPointerType() && Base->isTypeDependent())
5300 return OMPArrayShapingExpr::Create(Context, Context.DependentTy, Base,
5301 LParenLoc, RParenLoc, Dims, Brackets);
5302 if (!BaseTy->isPointerType() ||
5303 (!Base->isTypeDependent() &&
5304 BaseTy->getPointeeType()->isIncompleteType()))
5305 return ExprError(Diag(Base->getExprLoc(),
5306 diag::err_omp_non_pointer_type_array_shaping_base)
5307 << Base->getSourceRange());
5308
5309 SmallVector<Expr *, 4> NewDims;
5310 bool ErrorFound = false;
5311 for (Expr *Dim : Dims) {
5312 if (Dim->hasPlaceholderType()) {
5313 ExprResult Result = CheckPlaceholderExpr(Dim);
5314 if (Result.isInvalid()) {
5315 ErrorFound = true;
5316 continue;
5317 }
5318 Result = DefaultLvalueConversion(Result.get());
5319 if (Result.isInvalid()) {
5320 ErrorFound = true;
5321 continue;
5322 }
5323 Dim = Result.get();
5324 }
5325 if (!Dim->isTypeDependent()) {
5326 ExprResult Result =
5327 PerformOpenMPImplicitIntegerConversion(Dim->getExprLoc(), Dim);
5328 if (Result.isInvalid()) {
5329 ErrorFound = true;
5330 Diag(Dim->getExprLoc(), diag::err_omp_typecheck_shaping_not_integer)
5331 << Dim->getSourceRange();
5332 continue;
5333 }
5334 Dim = Result.get();
5335 Expr::EvalResult EvResult;
5336 if (!Dim->isValueDependent() && Dim->EvaluateAsInt(EvResult, Context)) {
5337 // OpenMP 5.0, [2.1.4 Array Shaping]
5338 // Each si is an integral type expression that must evaluate to a
5339 // positive integer.
5340 llvm::APSInt Value = EvResult.Val.getInt();
5341 if (!Value.isStrictlyPositive()) {
5342 Diag(Dim->getExprLoc(), diag::err_omp_shaping_dimension_not_positive)
5343 << toString(Value, /*Radix=*/10, /*Signed=*/true)
5344 << Dim->getSourceRange();
5345 ErrorFound = true;
5346 continue;
5347 }
5348 }
5349 }
5350 NewDims.push_back(Dim);
5351 }
5352 if (ErrorFound)
5353 return ExprError();
5354 return OMPArrayShapingExpr::Create(Context, Context.OMPArrayShapingTy, Base,
5355 LParenLoc, RParenLoc, NewDims, Brackets);
5356}
5357
5358ExprResult Sema::ActOnOMPIteratorExpr(Scope *S, SourceLocation IteratorKwLoc,
5359 SourceLocation LLoc, SourceLocation RLoc,
5360 ArrayRef<OMPIteratorData> Data) {
5361 SmallVector<OMPIteratorExpr::IteratorDefinition, 4> ID;
5362 bool IsCorrect = true;
5363 for (const OMPIteratorData &D : Data) {
5364 TypeSourceInfo *TInfo = nullptr;
5365 SourceLocation StartLoc;
5366 QualType DeclTy;
5367 if (!D.Type.getAsOpaquePtr()) {
5368 // OpenMP 5.0, 2.1.6 Iterators
5369 // In an iterator-specifier, if the iterator-type is not specified then
5370 // the type of that iterator is of int type.
5371 DeclTy = Context.IntTy;
5372 StartLoc = D.DeclIdentLoc;
5373 } else {
5374 DeclTy = GetTypeFromParser(D.Type, &TInfo);
5375 StartLoc = TInfo->getTypeLoc().getBeginLoc();
5376 }
5377
5378 bool IsDeclTyDependent = DeclTy->isDependentType() ||
5379 DeclTy->containsUnexpandedParameterPack() ||
5380 DeclTy->isInstantiationDependentType();
5381 if (!IsDeclTyDependent) {
5382 if (!DeclTy->isIntegralType(Context) && !DeclTy->isAnyPointerType()) {
5383 // OpenMP 5.0, 2.1.6 Iterators, Restrictions, C/C++
5384 // The iterator-type must be an integral or pointer type.
5385 Diag(StartLoc, diag::err_omp_iterator_not_integral_or_pointer)
5386 << DeclTy;
5387 IsCorrect = false;
5388 continue;
5389 }
5390 if (DeclTy.isConstant(Context)) {
5391 // OpenMP 5.0, 2.1.6 Iterators, Restrictions, C/C++
5392 // The iterator-type must not be const qualified.
5393 Diag(StartLoc, diag::err_omp_iterator_not_integral_or_pointer)
5394 << DeclTy;
5395 IsCorrect = false;
5396 continue;
5397 }
5398 }
5399
5400 // Iterator declaration.
5401 assert(D.DeclIdent && "Identifier expected.")(static_cast <bool> (D.DeclIdent && "Identifier expected."
) ? void (0) : __assert_fail ("D.DeclIdent && \"Identifier expected.\""
, "clang/lib/Sema/SemaExpr.cpp", 5401, __extension__ __PRETTY_FUNCTION__
))
;
5402 // Always try to create iterator declarator to avoid extra error messages
5403 // about unknown declarations use.
5404 auto *VD = VarDecl::Create(Context, CurContext, StartLoc, D.DeclIdentLoc,
5405 D.DeclIdent, DeclTy, TInfo, SC_None);
5406 VD->setImplicit();
5407 if (S) {
5408 // Check for conflicting previous declaration.
5409 DeclarationNameInfo NameInfo(VD->getDeclName(), D.DeclIdentLoc);
5410 LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
5411 ForVisibleRedeclaration);
5412 Previous.suppressDiagnostics();
5413 LookupName(Previous, S);
5414
5415 FilterLookupForScope(Previous, CurContext, S, /*ConsiderLinkage=*/false,
5416 /*AllowInlineNamespace=*/false);
5417 if (!Previous.empty()) {
5418 NamedDecl *Old = Previous.getRepresentativeDecl();
5419 Diag(D.DeclIdentLoc, diag::err_redefinition) << VD->getDeclName();
5420 Diag(Old->getLocation(), diag::note_previous_definition);
5421 } else {
5422 PushOnScopeChains(VD, S);
5423 }
5424 } else {
5425 CurContext->addDecl(VD);
5426 }
5427
5428 /// Act on the iterator variable declaration.
5429 ActOnOpenMPIteratorVarDecl(VD);
5430
5431 Expr *Begin = D.Range.Begin;
5432 if (!IsDeclTyDependent && Begin && !Begin->isTypeDependent()) {
5433 ExprResult BeginRes =
5434 PerformImplicitConversion(Begin, DeclTy, AA_Converting);
5435 Begin = BeginRes.get();
5436 }
5437 Expr *End = D.Range.End;
5438 if (!IsDeclTyDependent && End && !End->isTypeDependent()) {
5439 ExprResult EndRes = PerformImplicitConversion(End, DeclTy, AA_Converting);
5440 End = EndRes.get();
5441 }
5442 Expr *Step = D.Range.Step;
5443 if (!IsDeclTyDependent && Step && !Step->isTypeDependent()) {
5444 if (!Step->getType()->isIntegralType(Context)) {
5445 Diag(Step->getExprLoc(), diag::err_omp_iterator_step_not_integral)
5446 << Step << Step->getSourceRange();
5447 IsCorrect = false;
5448 continue;
5449 }
5450 std::optional<llvm::APSInt> Result =
5451 Step->getIntegerConstantExpr(Context);
5452 // OpenMP 5.0, 2.1.6 Iterators, Restrictions
5453 // If the step expression of a range-specification equals zero, the
5454 // behavior is unspecified.
5455 if (Result && Result->isZero()) {
5456 Diag(Step->getExprLoc(), diag::err_omp_iterator_step_constant_zero)
5457 << Step << Step->getSourceRange();
5458 IsCorrect = false;
5459 continue;
5460 }
5461 }
5462 if (!Begin || !End || !IsCorrect) {
5463 IsCorrect = false;
5464 continue;
5465 }
5466 OMPIteratorExpr::IteratorDefinition &IDElem = ID.emplace_back();
5467 IDElem.IteratorDecl = VD;
5468 IDElem.AssignmentLoc = D.AssignLoc;
5469 IDElem.Range.Begin = Begin;
5470 IDElem.Range.End = End;
5471 IDElem.Range.Step = Step;
5472 IDElem.ColonLoc = D.ColonLoc;
5473 IDElem.SecondColonLoc = D.SecColonLoc;
5474 }
5475 if (!IsCorrect) {
5476 // Invalidate all created iterator declarations if error is found.
5477 for (const OMPIteratorExpr::IteratorDefinition &D : ID) {
5478 if (Decl *ID = D.IteratorDecl)
5479 ID->setInvalidDecl();
5480 }
5481 return ExprError();
5482 }
5483 SmallVector<OMPIteratorHelperData, 4> Helpers;
5484 if (!CurContext->isDependentContext()) {
5485 // Build number of ityeration for each iteration range.
5486 // Ni = ((Stepi > 0) ? ((Endi + Stepi -1 - Begini)/Stepi) :
5487 // ((Begini-Stepi-1-Endi) / -Stepi);
5488 for (OMPIteratorExpr::IteratorDefinition &D : ID) {
5489 // (Endi - Begini)
5490 ExprResult Res = CreateBuiltinBinOp(D.AssignmentLoc, BO_Sub, D.Range.End,
5491 D.Range.Begin);
5492 if(!Res.isUsable()) {
5493 IsCorrect = false;
5494 continue;
5495 }
5496 ExprResult St, St1;
5497 if (D.Range.Step) {
5498 St = D.Range.Step;
5499 // (Endi - Begini) + Stepi
5500 Res = CreateBuiltinBinOp(D.AssignmentLoc, BO_Add, Res.get(), St.get());
5501 if (!Res.isUsable()) {
5502 IsCorrect = false;
5503 continue;
5504 }
5505 // (Endi - Begini) + Stepi - 1
5506 Res =
5507 CreateBuiltinBinOp(D.AssignmentLoc, BO_Sub, Res.get(),
5508 ActOnIntegerConstant(D.AssignmentLoc, 1).get());
5509 if (!Res.isUsable()) {
5510 IsCorrect = false;
5511 continue;
5512 }
5513 // ((Endi - Begini) + Stepi - 1) / Stepi
5514 Res = CreateBuiltinBinOp(D.AssignmentLoc, BO_Div, Res.get(), St.get());
5515 if (!Res.isUsable()) {
5516 IsCorrect = false;
5517 continue;
5518 }
5519 St1 = CreateBuiltinUnaryOp(D.AssignmentLoc, UO_Minus, D.Range.Step);
5520 // (Begini - Endi)
5521 ExprResult Res1 = CreateBuiltinBinOp(D.AssignmentLoc, BO_Sub,
5522 D.Range.Begin, D.Range.End);
5523 if (!Res1.isUsable()) {
5524 IsCorrect = false;
5525 continue;
5526 }
5527 // (Begini - Endi) - Stepi
5528 Res1 =
5529 CreateBuiltinBinOp(D.AssignmentLoc, BO_Add, Res1.get(), St1.get());
5530 if (!Res1.isUsable()) {
5531 IsCorrect = false;
5532 continue;
5533 }
5534 // (Begini - Endi) - Stepi - 1
5535 Res1 =
5536 CreateBuiltinBinOp(D.AssignmentLoc, BO_Sub, Res1.get(),
5537 ActOnIntegerConstant(D.AssignmentLoc, 1).get());
5538 if (!Res1.isUsable()) {
5539 IsCorrect = false;
5540 continue;
5541 }
5542 // ((Begini - Endi) - Stepi - 1) / (-Stepi)
5543 Res1 =
5544 CreateBuiltinBinOp(D.AssignmentLoc, BO_Div, Res1.get(), St1.get());
5545 if (!Res1.isUsable()) {
5546 IsCorrect = false;
5547 continue;
5548 }
5549 // Stepi > 0.
5550 ExprResult CmpRes =
5551 CreateBuiltinBinOp(D.AssignmentLoc, BO_GT, D.Range.Step,
5552 ActOnIntegerConstant(D.AssignmentLoc, 0).get());
5553 if (!CmpRes.isUsable()) {
5554 IsCorrect = false;
5555 continue;
5556 }
5557 Res = ActOnConditionalOp(D.AssignmentLoc, D.AssignmentLoc, CmpRes.get(),
5558 Res.get(), Res1.get());
5559 if (!Res.isUsable()) {
5560 IsCorrect = false;
5561 continue;
5562 }
5563 }
5564 Res = ActOnFinishFullExpr(Res.get(), /*DiscardedValue=*/false);
5565 if (!Res.isUsable()) {
5566 IsCorrect = false;
5567 continue;
5568 }
5569
5570 // Build counter update.
5571 // Build counter.
5572 auto *CounterVD =
5573 VarDecl::Create(Context, CurContext, D.IteratorDecl->getBeginLoc(),
5574 D.IteratorDecl->getBeginLoc(), nullptr,
5575 Res.get()->getType(), nullptr, SC_None);
5576 CounterVD->setImplicit();
5577 ExprResult RefRes =
5578 BuildDeclRefExpr(CounterVD, CounterVD->getType(), VK_LValue,
5579 D.IteratorDecl->getBeginLoc());
5580 // Build counter update.
5581 // I = Begini + counter * Stepi;
5582 ExprResult UpdateRes;
5583 if (D.Range.Step) {
5584 UpdateRes = CreateBuiltinBinOp(
5585 D.AssignmentLoc, BO_Mul,
5586 DefaultLvalueConversion(RefRes.get()).get(), St.get());
5587 } else {
5588 UpdateRes = DefaultLvalueConversion(RefRes.get());
5589 }
5590 if (!UpdateRes.isUsable()) {
5591 IsCorrect = false;
5592 continue;
5593 }
5594 UpdateRes = CreateBuiltinBinOp(D.AssignmentLoc, BO_Add, D.Range.Begin,
5595 UpdateRes.get());
5596 if (!UpdateRes.isUsable()) {
5597 IsCorrect = false;
5598 continue;
5599 }
5600 ExprResult VDRes =
5601 BuildDeclRefExpr(cast<VarDecl>(D.IteratorDecl),
5602 cast<VarDecl>(D.IteratorDecl)->getType(), VK_LValue,
5603 D.IteratorDecl->getBeginLoc());
5604 UpdateRes = CreateBuiltinBinOp(D.AssignmentLoc, BO_Assign, VDRes.get(),
5605 UpdateRes.get());
5606 if (!UpdateRes.isUsable()) {
5607 IsCorrect = false;
5608 continue;
5609 }
5610 UpdateRes =
5611 ActOnFinishFullExpr(UpdateRes.get(), /*DiscardedValue=*/true);
5612 if (!UpdateRes.isUsable()) {
5613 IsCorrect = false;
5614 continue;
5615 }
5616 ExprResult CounterUpdateRes =
5617 CreateBuiltinUnaryOp(D.AssignmentLoc, UO_PreInc, RefRes.get());
5618 if (!CounterUpdateRes.isUsable()) {
5619 IsCorrect = false;
5620 continue;
5621 }
5622 CounterUpdateRes =
5623 ActOnFinishFullExpr(CounterUpdateRes.get(), /*DiscardedValue=*/true);
5624 if (!CounterUpdateRes.isUsable()) {
5625 IsCorrect = false;
5626 continue;
5627 }
5628 OMPIteratorHelperData &HD = Helpers.emplace_back();
5629 HD.CounterVD = CounterVD;
5630 HD.Upper = Res.get();
5631 HD.Update = UpdateRes.get();
5632 HD.CounterUpdate = CounterUpdateRes.get();
5633 }
5634 } else {
5635 Helpers.assign(ID.size(), {});
5636 }
5637 if (!IsCorrect) {
5638 // Invalidate all created iterator declarations if error is found.
5639 for (const OMPIteratorExpr::IteratorDefinition &D : ID) {
5640 if (Decl *ID = D.IteratorDecl)
5641 ID->setInvalidDecl();
5642 }
5643 return ExprError();
5644 }
5645 return OMPIteratorExpr::Create(Context, Context.OMPIteratorTy, IteratorKwLoc,
5646 LLoc, RLoc, ID, Helpers);
5647}
5648
5649ExprResult
5650Sema::CreateBuiltinArraySubscriptExpr(Expr *Base, SourceLocation LLoc,
5651 Expr *Idx, SourceLocation RLoc) {
5652 Expr *LHSExp = Base;
5653 Expr *RHSExp = Idx;
5654
5655 ExprValueKind VK = VK_LValue;
5656 ExprObjectKind OK = OK_Ordinary;
5657
5658 // Per C++ core issue 1213, the result is an xvalue if either operand is
5659 // a non-lvalue array, and an lvalue otherwise.
5660 if (getLangOpts().CPlusPlus11) {
5661 for (auto *Op : {LHSExp, RHSExp}) {
5662 Op = Op->IgnoreImplicit();
5663 if (Op->getType()->isArrayType() && !Op->isLValue())
5664 VK = VK_XValue;
5665 }
5666 }
5667
5668 // Perform default conversions.
5669 if (!LHSExp->getType()->getAs<VectorType>()) {
5670 ExprResult Result = DefaultFunctionArrayLvalueConversion(LHSExp);
5671 if (Result.isInvalid())
5672 return ExprError();
5673 LHSExp = Result.get();
5674 }
5675 ExprResult Result = DefaultFunctionArrayLvalueConversion(RHSExp);
5676 if (Result.isInvalid())
5677 return ExprError();
5678 RHSExp = Result.get();
5679
5680 QualType LHSTy = LHSExp->getType(), RHSTy = RHSExp->getType();
5681
5682 // C99 6.5.2.1p2: the expression e1[e2] is by definition precisely equivalent
5683 // to the expression *((e1)+(e2)). This means the array "Base" may actually be
5684 // in the subscript position. As a result, we need to derive the array base
5685 // and index from the expression types.
5686 Expr *BaseExpr, *IndexExpr;
5687 QualType ResultType;
5688 if (LHSTy->isDependentType() || RHSTy->isDependentType()) {
5689 BaseExpr = LHSExp;
5690 IndexExpr = RHSExp;
5691 ResultType =
5692 getDependentArraySubscriptType(LHSExp, RHSExp, getASTContext());
5693 } else if (const PointerType *PTy = LHSTy->getAs<PointerType>()) {
5694 BaseExpr = LHSExp;
5695 IndexExpr = RHSExp;
5696 ResultType = PTy->getPointeeType();
5697 } else if (const ObjCObjectPointerType *PTy =
5698 LHSTy->getAs<ObjCObjectPointerType>()) {
5699 BaseExpr = LHSExp;
5700 IndexExpr = RHSExp;
5701
5702 // Use custom logic if this should be the pseudo-object subscript
5703 // expression.
5704 if (!LangOpts.isSubscriptPointerArithmetic())
5705 return BuildObjCSubscriptExpression(RLoc, BaseExpr, IndexExpr, nullptr,
5706 nullptr);
5707
5708 ResultType = PTy->getPointeeType();
5709 } else if (const PointerType *PTy = RHSTy->getAs<PointerType>()) {
5710 // Handle the uncommon case of "123[Ptr]".
5711 BaseExpr = RHSExp;
5712 IndexExpr = LHSExp;
5713 ResultType = PTy->getPointeeType();
5714 } else if (const ObjCObjectPointerType *PTy =
5715 RHSTy->getAs<ObjCObjectPointerType>()) {
5716 // Handle the uncommon case of "123[Ptr]".
5717 BaseExpr = RHSExp;
5718 IndexExpr = LHSExp;
5719 ResultType = PTy->getPointeeType();
5720 if (!LangOpts.isSubscriptPointerArithmetic()) {
5721 Diag(LLoc, diag::err_subscript_nonfragile_interface)
5722 << ResultType << BaseExpr->getSourceRange();
5723 return ExprError();
5724 }
5725 } else if (const VectorType *VTy = LHSTy->getAs<VectorType>()) {
5726 BaseExpr = LHSExp; // vectors: V[123]
5727 IndexExpr = RHSExp;
5728 // We apply C++ DR1213 to vector subscripting too.
5729 if (getLangOpts().CPlusPlus11 && LHSExp->isPRValue()) {
5730 ExprResult Materialized = TemporaryMaterializationConversion(LHSExp);
5731 if (Materialized.isInvalid())
5732 return ExprError();
5733 LHSExp = Materialized.get();
5734 }
5735 VK = LHSExp->getValueKind();
5736 if (VK != VK_PRValue)
5737 OK = OK_VectorComponent;
5738
5739 ResultType = VTy->getElementType();
5740 QualType BaseType = BaseExpr->getType();
5741 Qualifiers BaseQuals = BaseType.getQualifiers();
5742 Qualifiers MemberQuals = ResultType.getQualifiers();
5743 Qualifiers Combined = BaseQuals + MemberQuals;
5744 if (Combined != MemberQuals)
5745 ResultType = Context.getQualifiedType(ResultType, Combined);
5746 } else if (LHSTy->isBuiltinType() &&
5747 LHSTy->getAs<BuiltinType>()->isVLSTBuiltinType()) {
5748 const BuiltinType *BTy = LHSTy->getAs<BuiltinType>();
5749 if (BTy->isSVEBool())
5750 return ExprError(Diag(LLoc, diag::err_subscript_svbool_t)
5751 << LHSExp->getSourceRange() << RHSExp->getSourceRange());
5752
5753 BaseExpr = LHSExp;
5754 IndexExpr = RHSExp;
5755 if (getLangOpts().CPlusPlus11 && LHSExp->isPRValue()) {
5756 ExprResult Materialized = TemporaryMaterializationConversion(LHSExp);
5757 if (Materialized.isInvalid())
5758 return ExprError();
5759 LHSExp = Materialized.get();
5760 }
5761 VK = LHSExp->getValueKind();
5762 if (VK != VK_PRValue)
5763 OK = OK_VectorComponent;
5764
5765 ResultType = BTy->getSveEltType(Context);
5766
5767 QualType BaseType = BaseExpr->getType();
5768 Qualifiers BaseQuals = BaseType.getQualifiers();
5769 Qualifiers MemberQuals = ResultType.getQualifiers();
5770 Qualifiers Combined = BaseQuals + MemberQuals;
5771 if (Combined != MemberQuals)
5772 ResultType = Context.getQualifiedType(ResultType, Combined);
5773 } else if (LHSTy->isArrayType()) {
5774 // If we see an array that wasn't promoted by
5775 // DefaultFunctionArrayLvalueConversion, it must be an array that
5776 // wasn't promoted because of the C90 rule that doesn't
5777 // allow promoting non-lvalue arrays. Warn, then
5778 // force the promotion here.
5779 Diag(LHSExp->getBeginLoc(), diag::ext_subscript_non_lvalue)
5780 << LHSExp->getSourceRange();
5781 LHSExp = ImpCastExprToType(LHSExp, Context.getArrayDecayedType(LHSTy),
5782 CK_ArrayToPointerDecay).get();
5783 LHSTy = LHSExp->getType();
5784
5785 BaseExpr = LHSExp;
5786 IndexExpr = RHSExp;
5787 ResultType = LHSTy->castAs<PointerType>()->getPointeeType();
5788 } else if (RHSTy->isArrayType()) {
5789 // Same as previous, except for 123[f().a] case
5790 Diag(RHSExp->getBeginLoc(), diag::ext_subscript_non_lvalue)
5791 << RHSExp->getSourceRange();
5792 RHSExp = ImpCastExprToType(RHSExp, Context.getArrayDecayedType(RHSTy),
5793 CK_ArrayToPointerDecay).get();
5794 RHSTy = RHSExp->getType();
5795
5796 BaseExpr = RHSExp;
5797 IndexExpr = LHSExp;
5798 ResultType = RHSTy->castAs<PointerType>()->getPointeeType();
5799 } else {
5800 return ExprError(Diag(LLoc, diag::err_typecheck_subscript_value)
5801 << LHSExp->getSourceRange() << RHSExp->getSourceRange());
5802 }
5803 // C99 6.5.2.1p1
5804 if (!IndexExpr->getType()->isIntegerType() && !IndexExpr->isTypeDependent())
5805 return ExprError(Diag(LLoc, diag::err_typecheck_subscript_not_integer)
5806 << IndexExpr->getSourceRange());
5807
5808 if ((IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_S) ||
5809 IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_U))
5810 && !IndexExpr->isTypeDependent())
5811 Diag(LLoc, diag::warn_subscript_is_char) << IndexExpr->getSourceRange();
5812
5813 // C99 6.5.2.1p1: "shall have type "pointer to *object* type". Similarly,
5814 // C++ [expr.sub]p1: The type "T" shall be a completely-defined object
5815 // type. Note that Functions are not objects, and that (in C99 parlance)
5816 // incomplete types are not object types.
5817 if (ResultType->isFunctionType()) {
5818 Diag(BaseExpr->getBeginLoc(), diag::err_subscript_function_type)
5819 << ResultType << BaseExpr->getSourceRange();
5820 return ExprError();
5821 }
5822
5823 if (ResultType->isVoidType() && !getLangOpts().CPlusPlus) {
5824 // GNU extension: subscripting on pointer to void
5825 Diag(LLoc, diag::ext_gnu_subscript_void_type)
5826 << BaseExpr->getSourceRange();
5827
5828 // C forbids expressions of unqualified void type from being l-values.
5829 // See IsCForbiddenLValueType.
5830 if (!ResultType.hasQualifiers())
5831 VK = VK_PRValue;
5832 } else if (!ResultType->isDependentType() &&
5833 RequireCompleteSizedType(
5834 LLoc, ResultType,
5835 diag::err_subscript_incomplete_or_sizeless_type, BaseExpr))
5836 return ExprError();
5837
5838 assert(VK == VK_PRValue || LangOpts.CPlusPlus ||(static_cast <bool> (VK == VK_PRValue || LangOpts.CPlusPlus
|| !ResultType.isCForbiddenLValueType()) ? void (0) : __assert_fail
("VK == VK_PRValue || LangOpts.CPlusPlus || !ResultType.isCForbiddenLValueType()"
, "clang/lib/Sema/SemaExpr.cpp", 5839, __extension__ __PRETTY_FUNCTION__
))
5839 !ResultType.isCForbiddenLValueType())(static_cast <bool> (VK == VK_PRValue || LangOpts.CPlusPlus
|| !ResultType.isCForbiddenLValueType()) ? void (0) : __assert_fail
("VK == VK_PRValue || LangOpts.CPlusPlus || !ResultType.isCForbiddenLValueType()"
, "clang/lib/Sema/SemaExpr.cpp", 5839, __extension__ __PRETTY_FUNCTION__
))
;
5840
5841 if (LHSExp->IgnoreParenImpCasts()->getType()->isVariablyModifiedType() &&
5842 FunctionScopes.size() > 1) {
5843 if (auto *TT =
5844 LHSExp->IgnoreParenImpCasts()->getType()->getAs<TypedefType>()) {
5845 for (auto I = FunctionScopes.rbegin(),
5846 E = std::prev(FunctionScopes.rend());
5847 I != E; ++I) {
5848 auto *CSI = dyn_cast<CapturingScopeInfo>(*I);
5849 if (CSI == nullptr)
5850 break;
5851 DeclContext *DC = nullptr;
5852 if (auto *LSI = dyn_cast<LambdaScopeInfo>(CSI))
5853 DC = LSI->CallOperator;
5854 else if (auto *CRSI = dyn_cast<CapturedRegionScopeInfo>(CSI))
5855 DC = CRSI->TheCapturedDecl;
5856 else if (auto *BSI = dyn_cast<BlockScopeInfo>(CSI))
5857 DC = BSI->TheDecl;
5858 if (DC) {
5859 if (DC->containsDecl(TT->getDecl()))
5860 break;
5861 captureVariablyModifiedType(
5862 Context, LHSExp->IgnoreParenImpCasts()->getType(), CSI);
5863 }
5864 }
5865 }
5866 }
5867
5868 return new (Context)
5869 ArraySubscriptExpr(LHSExp, RHSExp, ResultType, VK, OK, RLoc);
5870}
5871
5872bool Sema::CheckCXXDefaultArgExpr(SourceLocation CallLoc, FunctionDecl *FD,
5873 ParmVarDecl *Param, Expr *RewrittenInit,
5874 bool SkipImmediateInvocations) {
5875 if (Param->hasUnparsedDefaultArg()) {
5876 assert(!RewrittenInit && "Should not have a rewritten init expression yet")(static_cast <bool> (!RewrittenInit && "Should not have a rewritten init expression yet"
) ? void (0) : __assert_fail ("!RewrittenInit && \"Should not have a rewritten init expression yet\""
, "clang/lib/Sema/SemaExpr.cpp", 5876, __extension__ __PRETTY_FUNCTION__
))
;
5877 // If we've already cleared out the location for the default argument,
5878 // that means we're parsing it right now.
5879 if (!UnparsedDefaultArgLocs.count(Param)) {
5880 Diag(Param->getBeginLoc(), diag::err_recursive_default_argument) << FD;
5881 Diag(CallLoc, diag::note_recursive_default_argument_used_here);
5882 Param->setInvalidDecl();
5883 return true;
5884 }
5885
5886 Diag(CallLoc, diag::err_use_of_default_argument_to_function_declared_later)
5887 << FD << cast<CXXRecordDecl>(FD->getDeclContext());
5888 Diag(UnparsedDefaultArgLocs[Param],
5889 diag::note_default_argument_declared_here);
5890 return true;
5891 }
5892
5893 if (Param->hasUninstantiatedDefaultArg()) {
5894 assert(!RewrittenInit && "Should not have a rewitten init expression yet")(static_cast <bool> (!RewrittenInit && "Should not have a rewitten init expression yet"
) ? void (0) : __assert_fail ("!RewrittenInit && \"Should not have a rewitten init expression yet\""
, "clang/lib/Sema/SemaExpr.cpp", 5894, __extension__ __PRETTY_FUNCTION__
))
;
5895 if (InstantiateDefaultArgument(CallLoc, FD, Param))
5896 return true;
5897 }
5898
5899 Expr *Init = RewrittenInit ? RewrittenInit : Param->getInit();
5900 assert(Init && "default argument but no initializer?")(static_cast <bool> (Init && "default argument but no initializer?"
) ? void (0) : __assert_fail ("Init && \"default argument but no initializer?\""
, "clang/lib/Sema/SemaExpr.cpp", 5900, __extension__ __PRETTY_FUNCTION__
))
;
5901
5902 // If the default expression creates temporaries, we need to
5903 // push them to the current stack of expression temporaries so they'll
5904 // be properly destroyed.
5905 // FIXME: We should really be rebuilding the default argument with new
5906 // bound temporaries; see the comment in PR5810.
5907 // We don't need to do that with block decls, though, because
5908 // blocks in default argument expression can never capture anything.
5909 if (auto *InitWithCleanup = dyn_cast<ExprWithCleanups>(Init)) {
5910 // Set the "needs cleanups" bit regardless of whether there are
5911 // any explicit objects.
5912 Cleanup.setExprNeedsCleanups(InitWithCleanup->cleanupsHaveSideEffects());
5913 // Append all the objects to the cleanup list. Right now, this
5914 // should always be a no-op, because blocks in default argument
5915 // expressions should never be able to capture anything.
5916 assert(!InitWithCleanup->getNumObjects() &&(static_cast <bool> (!InitWithCleanup->getNumObjects
() && "default argument expression has capturing blocks?"
) ? void (0) : __assert_fail ("!InitWithCleanup->getNumObjects() && \"default argument expression has capturing blocks?\""
, "clang/lib/Sema/SemaExpr.cpp", 5917, __extension__ __PRETTY_FUNCTION__
))
5917 "default argument expression has capturing blocks?")(static_cast <bool> (!InitWithCleanup->getNumObjects
() && "default argument expression has capturing blocks?"
) ? void (0) : __assert_fail ("!InitWithCleanup->getNumObjects() && \"default argument expression has capturing blocks?\""
, "clang/lib/Sema/SemaExpr.cpp", 5917, __extension__ __PRETTY_FUNCTION__
))
;
5918 }
5919 // C++ [expr.const]p15.1:
5920 // An expression or conversion is in an immediate function context if it is
5921 // potentially evaluated and [...] its innermost enclosing non-block scope
5922 // is a function parameter scope of an immediate function.
5923 EnterExpressionEvaluationContext EvalContext(
5924 *this,
5925 FD->isConsteval() ? ExpressionEvaluationContext::ImmediateFunctionContext
5926 : ExpressionEvaluationContext::PotentiallyEvaluated,
5927 Param);
5928 ExprEvalContexts.back().IsCurrentlyCheckingDefaultArgumentOrInitializer =
5929 SkipImmediateInvocations;
5930 runWithSufficientStackSpace(CallLoc, [&] {
5931 MarkDeclarationsReferencedInExpr(Init, /*SkipLocalVariables=*/true);
5932 });
5933 return false;
5934}
5935
5936struct ImmediateCallVisitor : public RecursiveASTVisitor<ImmediateCallVisitor> {
5937 bool HasImmediateCalls = false;
5938
5939 bool shouldVisitImplicitCode() const { return true; }
5940
5941 bool VisitCallExpr(CallExpr *E) {
5942 if (const FunctionDecl *FD = E->getDirectCallee())
5943 HasImmediateCalls |= FD->isConsteval();
5944 return RecursiveASTVisitor<ImmediateCallVisitor>::VisitStmt(E);
5945 }
5946
5947 // SourceLocExpr are not immediate invocations
5948 // but CXXDefaultInitExpr/CXXDefaultArgExpr containing a SourceLocExpr
5949 // need to be rebuilt so that they refer to the correct SourceLocation and
5950 // DeclContext.
5951 bool VisitSourceLocExpr(SourceLocExpr *E) {
5952 HasImmediateCalls = true;
5953 return RecursiveASTVisitor<ImmediateCallVisitor>::VisitStmt(E);
5954 }
5955
5956 // A nested lambda might have parameters with immediate invocations
5957 // in their default arguments.
5958 // The compound statement is not visited (as it does not constitute a
5959 // subexpression).
5960 // FIXME: We should consider visiting and transforming captures
5961 // with init expressions.
5962 bool VisitLambdaExpr(LambdaExpr *E) {
5963 return VisitCXXMethodDecl(E->getCallOperator());
5964 }
5965
5966 // Blocks don't support default parameters, and, as for lambdas,
5967 // we don't consider their body a subexpression.
5968 bool VisitBlockDecl(BlockDecl *B) { return false; }
5969
5970 bool VisitCompoundStmt(CompoundStmt *B) { return false; }
5971
5972 bool VisitCXXDefaultArgExpr(CXXDefaultArgExpr *E) {
5973 return TraverseStmt(E->getExpr());
5974 }
5975
5976 bool VisitCXXDefaultInitExpr(CXXDefaultInitExpr *E) {
5977 return TraverseStmt(E->getExpr());
5978 }
5979};
5980
5981struct EnsureImmediateInvocationInDefaultArgs
5982 : TreeTransform<EnsureImmediateInvocationInDefaultArgs> {
5983 EnsureImmediateInvocationInDefaultArgs(Sema &SemaRef)
5984 : TreeTransform(SemaRef) {}
5985
5986 // Lambda can only have immediate invocations in the default
5987 // args of their parameters, which is transformed upon calling the closure.
5988 // The body is not a subexpression, so we have nothing to do.
5989 // FIXME: Immediate calls in capture initializers should be transformed.
5990 ExprResult TransformLambdaExpr(LambdaExpr *E) { return E; }
5991 ExprResult TransformBlockExpr(BlockExpr *E) { return E; }
5992
5993 // Make sure we don't rebuild the this pointer as it would
5994 // cause it to incorrectly point it to the outermost class
5995 // in the case of nested struct initialization.
5996 ExprResult TransformCXXThisExpr(CXXThisExpr *E) { return E; }
5997};
5998
5999ExprResult Sema::BuildCXXDefaultArgExpr(SourceLocation CallLoc,
6000 FunctionDecl *FD, ParmVarDecl *Param,
6001 Expr *Init) {
6002 assert(Param->hasDefaultArg() && "can't build nonexistent default arg")(static_cast <bool> (Param->hasDefaultArg() &&
"can't build nonexistent default arg") ? void (0) : __assert_fail
("Param->hasDefaultArg() && \"can't build nonexistent default arg\""
, "clang/lib/Sema/SemaExpr.cpp", 6002, __extension__ __PRETTY_FUNCTION__
))
;
6003
6004 bool NestedDefaultChecking = isCheckingDefaultArgumentOrInitializer();
6005
6006 std::optional<ExpressionEvaluationContextRecord::InitializationContext>
6007 InitializationContext =
6008 OutermostDeclarationWithDelayedImmediateInvocations();
6009 if (!InitializationContext.has_value())
6010 InitializationContext.emplace(CallLoc, Param, CurContext);
6011
6012 if (!Init && !Param->hasUnparsedDefaultArg()) {
6013 // Mark that we are replacing a default argument first.
6014 // If we are instantiating a template we won't have to
6015 // retransform immediate calls.
6016 // C++ [expr.const]p15.1:
6017 // An expression or conversion is in an immediate function context if it
6018 // is potentially evaluated and [...] its innermost enclosing non-block
6019 // scope is a function parameter scope of an immediate function.
6020 EnterExpressionEvaluationContext EvalContext(
6021 *this,
6022 FD->isConsteval()
6023 ? ExpressionEvaluationContext::ImmediateFunctionContext
6024 : ExpressionEvaluationContext::PotentiallyEvaluated,
6025 Param);
6026
6027 if (Param->hasUninstantiatedDefaultArg()) {
6028 if (InstantiateDefaultArgument(CallLoc, FD, Param))
6029 return ExprError();
6030 }
6031 // CWG2631
6032 // An immediate invocation that is not evaluated where it appears is
6033 // evaluated and checked for whether it is a constant expression at the
6034 // point where the enclosing initializer is used in a function call.
6035 ImmediateCallVisitor V;
6036 if (!NestedDefaultChecking)
6037 V.TraverseDecl(Param);
6038 if (V.HasImmediateCalls) {
6039 ExprEvalContexts.back().DelayedDefaultInitializationContext = {
6040 CallLoc, Param, CurContext};
6041 EnsureImmediateInvocationInDefaultArgs Immediate(*this);
6042 ExprResult Res;
6043 runWithSufficientStackSpace(CallLoc, [&] {
6044 Res = Immediate.TransformInitializer(Param->getInit(),
6045 /*NotCopy=*/false);
6046 });
6047 if (Res.isInvalid())
6048 return ExprError();
6049 Res = ConvertParamDefaultArgument(Param, Res.get(),
6050 Res.get()->getBeginLoc());
6051 if (Res.isInvalid())
6052 return ExprError();
6053 Init = Res.get();
6054 }
6055 }
6056
6057 if (CheckCXXDefaultArgExpr(
6058 CallLoc, FD, Param, Init,
6059 /*SkipImmediateInvocations=*/NestedDefaultChecking))
6060 return ExprError();
6061
6062 return CXXDefaultArgExpr::Create(Context, InitializationContext->Loc, Param,
6063 Init, InitializationContext->Context);
6064}
6065
6066ExprResult Sema::BuildCXXDefaultInitExpr(SourceLocation Loc, FieldDecl *Field) {
6067 assert(Field->hasInClassInitializer())(static_cast <bool> (Field->hasInClassInitializer())
? void (0) : __assert_fail ("Field->hasInClassInitializer()"
, "clang/lib/Sema/SemaExpr.cpp", 6067, __extension__ __PRETTY_FUNCTION__
))
;
6068
6069 // If we might have already tried and failed to instantiate, don't try again.
6070 if (Field->isInvalidDecl())
6071 return ExprError();
6072
6073 auto *ParentRD = cast<CXXRecordDecl>(Field->getParent());
6074
6075 std::optional<ExpressionEvaluationContextRecord::InitializationContext>
6076 InitializationContext =
6077 OutermostDeclarationWithDelayedImmediateInvocations();
6078 if (!InitializationContext.has_value())
6079 InitializationContext.emplace(Loc, Field, CurContext);
6080
6081 Expr *Init = nullptr;
6082
6083 bool NestedDefaultChecking = isCheckingDefaultArgumentOrInitializer();
6084
6085 EnterExpressionEvaluationContext EvalContext(
6086 *this, ExpressionEvaluationContext::PotentiallyEvaluated, Field);
6087
6088 if (!Field->getInClassInitializer()) {
6089 // Maybe we haven't instantiated the in-class initializer. Go check the
6090 // pattern FieldDecl to see if it has one.
6091 if (isTemplateInstantiation(ParentRD->getTemplateSpecializationKind())) {
6092 CXXRecordDecl *ClassPattern = ParentRD->getTemplateInstantiationPattern();
6093 DeclContext::lookup_result Lookup =
6094 ClassPattern->lookup(Field->getDeclName());
6095
6096 FieldDecl *Pattern = nullptr;
6097 for (auto *L : Lookup) {
6098 if ((Pattern = dyn_cast<FieldDecl>(L)))
6099 break;
6100 }
6101 assert(Pattern && "We must have set the Pattern!")(static_cast <bool> (Pattern && "We must have set the Pattern!"
) ? void (0) : __assert_fail ("Pattern && \"We must have set the Pattern!\""
, "clang/lib/Sema/SemaExpr.cpp", 6101, __extension__ __PRETTY_FUNCTION__
))
;
6102 if (!Pattern->hasInClassInitializer() ||
6103 InstantiateInClassInitializer(Loc, Field, Pattern,
6104 getTemplateInstantiationArgs(Field))) {
6105 Field->setInvalidDecl();
6106 return ExprError();
6107 }
6108 }
6109 }
6110
6111 // CWG2631
6112 // An immediate invocation that is not evaluated where it appears is
6113 // evaluated and checked for whether it is a constant expression at the
6114 // point where the enclosing initializer is used in a [...] a constructor
6115 // definition, or an aggregate initialization.
6116 ImmediateCallVisitor V;
6117 if (!NestedDefaultChecking)
6118 V.TraverseDecl(Field);
6119 if (V.HasImmediateCalls) {
6120 ExprEvalContexts.back().DelayedDefaultInitializationContext = {Loc, Field,
6121 CurContext};
6122 ExprEvalContexts.back().IsCurrentlyCheckingDefaultArgumentOrInitializer =
6123 NestedDefaultChecking;
6124
6125 EnsureImmediateInvocationInDefaultArgs Immediate(*this);
6126 ExprResult Res;
6127 runWithSufficientStackSpace(Loc, [&] {
6128 Res = Immediate.TransformInitializer(Field->getInClassInitializer(),
6129 /*CXXDirectInit=*/false);
6130 });
6131 if (!Res.isInvalid())
6132 Res = ConvertMemberDefaultInitExpression(Field, Res.get(), Loc);
6133 if (Res.isInvalid()) {
6134 Field->setInvalidDecl();
6135 return ExprError();
6136 }
6137 Init = Res.get();
6138 }
6139
6140 if (Field->getInClassInitializer()) {
6141 Expr *E = Init ? Init : Field->getInClassInitializer();
6142 if (!NestedDefaultChecking)
6143 runWithSufficientStackSpace(Loc, [&] {
6144 MarkDeclarationsReferencedInExpr(E, /*SkipLocalVariables=*/false);
6145 });
6146 // C++11 [class.base.init]p7:
6147 // The initialization of each base and member constitutes a
6148 // full-expression.
6149 ExprResult Res = ActOnFinishFullExpr(E, /*DiscardedValue=*/false);
6150 if (Res.isInvalid()) {
6151 Field->setInvalidDecl();
6152 return ExprError();
6153 }
6154 Init = Res.get();
6155
6156 return CXXDefaultInitExpr::Create(Context, InitializationContext->Loc,
6157 Field, InitializationContext->Context,
6158 Init);
6159 }
6160
6161 // DR1351:
6162 // If the brace-or-equal-initializer of a non-static data member
6163 // invokes a defaulted default constructor of its class or of an
6164 // enclosing class in a potentially evaluated subexpression, the
6165 // program is ill-formed.
6166 //
6167 // This resolution is unworkable: the exception specification of the
6168 // default constructor can be needed in an unevaluated context, in
6169 // particular, in the operand of a noexcept-expression, and we can be
6170 // unable to compute an exception specification for an enclosed class.
6171 //
6172 // Any attempt to resolve the exception specification of a defaulted default
6173 // constructor before the initializer is lexically complete will ultimately
6174 // come here at which point we can diagnose it.
6175 RecordDecl *OutermostClass = ParentRD->getOuterLexicalRecordContext();
6176 Diag(Loc, diag::err_default_member_initializer_not_yet_parsed)
6177 << OutermostClass << Field;
6178 Diag(Field->getEndLoc(),
6179 diag::note_default_member_initializer_not_yet_parsed);
6180 // Recover by marking the field invalid, unless we're in a SFINAE context.
6181 if (!isSFINAEContext())
6182 Field->setInvalidDecl();
6183 return ExprError();
6184}
6185
6186Sema::VariadicCallType
6187Sema::getVariadicCallType(FunctionDecl *FDecl, const FunctionProtoType *Proto,
6188 Expr *Fn) {
6189 if (Proto && Proto->isVariadic()) {
6190 if (isa_and_nonnull<CXXConstructorDecl>(FDecl))
6191 return VariadicConstructor;
6192 else if (Fn && Fn->getType()->isBlockPointerType())
6193 return VariadicBlock;
6194 else if (FDecl) {
6195 if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(FDecl))
6196 if (Method->isInstance())
6197 return VariadicMethod;
6198 } else if (Fn && Fn->getType() == Context.BoundMemberTy)
6199 return VariadicMethod;
6200 return VariadicFunction;
6201 }
6202 return VariadicDoesNotApply;
6203}
6204
6205namespace {
6206class FunctionCallCCC final : public FunctionCallFilterCCC {
6207public:
6208 FunctionCallCCC(Sema &SemaRef, const IdentifierInfo *FuncName,
6209 unsigned NumArgs, MemberExpr *ME)
6210 : FunctionCallFilterCCC(SemaRef, NumArgs, false, ME),
6211 FunctionName(FuncName) {}
6212
6213 bool ValidateCandidate(const TypoCorrection &candidate) override {
6214 if (!candidate.getCorrectionSpecifier() ||
6215 candidate.getCorrectionAsIdentifierInfo() != FunctionName) {
6216 return false;
6217 }
6218
6219 return FunctionCallFilterCCC::ValidateCandidate(candidate);
6220 }
6221
6222 std::unique_ptr<CorrectionCandidateCallback> clone() override {
6223 return std::make_unique<FunctionCallCCC>(*this);
6224 }
6225
6226private:
6227 const IdentifierInfo *const FunctionName;
6228};
6229}
6230
6231static TypoCorrection TryTypoCorrectionForCall(Sema &S, Expr *Fn,
6232 FunctionDecl *FDecl,
6233 ArrayRef<Expr *> Args) {
6234 MemberExpr *ME = dyn_cast<MemberExpr>(Fn);
6235 DeclarationName FuncName = FDecl->getDeclName();
6236 SourceLocation NameLoc = ME ? ME->getMemberLoc() : Fn->getBeginLoc();
6237
6238 FunctionCallCCC CCC(S, FuncName.getAsIdentifierInfo(), Args.size(), ME);
6239 if (TypoCorrection Corrected = S.CorrectTypo(
6240 DeclarationNameInfo(FuncName, NameLoc), Sema::LookupOrdinaryName,
6241 S.getScopeForContext(S.CurContext), nullptr, CCC,
6242 Sema::CTK_ErrorRecovery)) {
6243 if (NamedDecl *ND = Corrected.getFoundDecl()) {
6244 if (Corrected.isOverloaded()) {
6245 OverloadCandidateSet OCS(NameLoc, OverloadCandidateSet::CSK_Normal);
6246 OverloadCandidateSet::iterator Best;
6247 for (NamedDecl *CD : Corrected) {
6248 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(CD))
6249 S.AddOverloadCandidate(FD, DeclAccessPair::make(FD, AS_none), Args,
6250 OCS);
6251 }
6252 switch (OCS.BestViableFunction(S, NameLoc, Best)) {
6253 case OR_Success:
6254 ND = Best->FoundDecl;
6255 Corrected.setCorrectionDecl(ND);
6256 break;
6257 default:
6258 break;
6259 }
6260 }
6261 ND = ND->getUnderlyingDecl();
6262 if (isa<ValueDecl>(ND) || isa<FunctionTemplateDecl>(ND))
6263 return Corrected;
6264 }
6265 }
6266 return TypoCorrection();
6267}
6268
6269/// ConvertArgumentsForCall - Converts the arguments specified in
6270/// Args/NumArgs to the parameter types of the function FDecl with
6271/// function prototype Proto. Call is the call expression itself, and
6272/// Fn is the function expression. For a C++ member function, this
6273/// routine does not attempt to convert the object argument. Returns
6274/// true if the call is ill-formed.
6275bool
6276Sema::ConvertArgumentsForCall(CallExpr *Call, Expr *Fn,
6277 FunctionDecl *FDecl,
6278 const FunctionProtoType *Proto,
6279 ArrayRef<Expr *> Args,
6280 SourceLocation RParenLoc,
6281 bool IsExecConfig) {
6282 // Bail out early if calling a builtin with custom typechecking.
6283 if (FDecl)
6284 if (unsigned ID = FDecl->getBuiltinID())
6285 if (Context.BuiltinInfo.hasCustomTypechecking(ID))
6286 return false;
6287
6288 // C99 6.5.2.2p7 - the arguments are implicitly converted, as if by
6289 // assignment, to the types of the corresponding parameter, ...
6290 unsigned NumParams = Proto->getNumParams();
6291 bool Invalid = false;
6292 unsigned MinArgs = FDecl ? FDecl->getMinRequiredArguments() : NumParams;
6293 unsigned FnKind = Fn->getType()->isBlockPointerType()
6294 ? 1 /* block */
6295 : (IsExecConfig ? 3 /* kernel function (exec config) */
6296 : 0 /* function */);
6297
6298 // If too few arguments are available (and we don't have default
6299 // arguments for the remaining parameters), don't make the call.
6300 if (Args.size() < NumParams) {
6301 if (Args.size() < MinArgs) {
6302 TypoCorrection TC;
6303 if (FDecl && (TC = TryTypoCorrectionForCall(*this, Fn, FDecl, Args))) {
6304 unsigned diag_id =
6305 MinArgs == NumParams && !Proto->isVariadic()
6306 ? diag::err_typecheck_call_too_few_args_suggest
6307 : diag::err_typecheck_call_too_few_args_at_least_suggest;
6308 diagnoseTypo(TC, PDiag(diag_id) << FnKind << MinArgs
6309 << static_cast<unsigned>(Args.size())
6310 << TC.getCorrectionRange());
6311 } else if (MinArgs == 1 && FDecl && FDecl->getParamDecl(0)->getDeclName())
6312 Diag(RParenLoc,
6313 MinArgs == NumParams && !Proto->isVariadic()
6314 ? diag::err_typecheck_call_too_few_args_one
6315 : diag::err_typecheck_call_too_few_args_at_least_one)
6316 << FnKind << FDecl->getParamDecl(0) << Fn->getSourceRange();
6317 else
6318 Diag(RParenLoc, MinArgs == NumParams && !Proto->isVariadic()
6319 ? diag::err_typecheck_call_too_few_args
6320 : diag::err_typecheck_call_too_few_args_at_least)
6321 << FnKind << MinArgs << static_cast<unsigned>(Args.size())
6322 << Fn->getSourceRange();
6323
6324 // Emit the location of the prototype.
6325 if (!TC && FDecl && !FDecl->getBuiltinID() && !IsExecConfig)
6326 Diag(FDecl->getLocation(), diag::note_callee_decl) << FDecl;
6327
6328 return true;
6329 }
6330 // We reserve space for the default arguments when we create
6331 // the call expression, before calling ConvertArgumentsForCall.
6332 assert((Call->getNumArgs() == NumParams) &&(static_cast <bool> ((Call->getNumArgs() == NumParams
) && "We should have reserved space for the default arguments before!"
) ? void (0) : __assert_fail ("(Call->getNumArgs() == NumParams) && \"We should have reserved space for the default arguments before!\""
, "clang/lib/Sema/SemaExpr.cpp", 6333, __extension__ __PRETTY_FUNCTION__
))
6333 "We should have reserved space for the default arguments before!")(static_cast <bool> ((Call->getNumArgs() == NumParams
) && "We should have reserved space for the default arguments before!"
) ? void (0) : __assert_fail ("(Call->getNumArgs() == NumParams) && \"We should have reserved space for the default arguments before!\""
, "clang/lib/Sema/SemaExpr.cpp", 6333, __extension__ __PRETTY_FUNCTION__
))
;
6334 }
6335
6336 // If too many are passed and not variadic, error on the extras and drop
6337 // them.
6338 if (Args.size() > NumParams) {
6339 if (!Proto->isVariadic()) {
6340 TypoCorrection TC;
6341 if (FDecl && (TC = TryTypoCorrectionForCall(*this, Fn, FDecl, Args))) {
6342 unsigned diag_id =
6343 MinArgs == NumParams && !Proto->isVariadic()
6344 ? diag::err_typecheck_call_too_many_args_suggest
6345 : diag::err_typecheck_call_too_many_args_at_most_suggest;
6346 diagnoseTypo(TC, PDiag(diag_id) << FnKind << NumParams
6347 << static_cast<unsigned>(Args.size())
6348 << TC.getCorrectionRange());
6349 } else if (NumParams == 1 && FDecl &&
6350 FDecl->getParamDecl(0)->getDeclName())
6351 Diag(Args[NumParams]->getBeginLoc(),
6352 MinArgs == NumParams
6353 ? diag::err_typecheck_call_too_many_args_one
6354 : diag::err_typecheck_call_too_many_args_at_most_one)
6355 << FnKind << FDecl->getParamDecl(0)
6356 << static_cast<unsigned>(Args.size()) << Fn->getSourceRange()
6357 << SourceRange(Args[NumParams]->getBeginLoc(),
6358 Args.back()->getEndLoc());
6359 else
6360 Diag(Args[NumParams]->getBeginLoc(),
6361 MinArgs == NumParams
6362 ? diag::err_typecheck_call_too_many_args
6363 : diag::err_typecheck_call_too_many_args_at_most)
6364 << FnKind << NumParams << static_cast<unsigned>(Args.size())
6365 << Fn->getSourceRange()
6366 << SourceRange(Args[NumParams]->getBeginLoc(),
6367 Args.back()->getEndLoc());
6368
6369 // Emit the location of the prototype.
6370 if (!TC && FDecl && !FDecl->getBuiltinID() && !IsExecConfig)
6371 Diag(FDecl->getLocation(), diag::note_callee_decl) << FDecl;
6372
6373 // This deletes the extra arguments.
6374 Call->shrinkNumArgs(NumParams);
6375 return true;
6376 }
6377 }
6378 SmallVector<Expr *, 8> AllArgs;
6379 VariadicCallType CallType = getVariadicCallType(FDecl, Proto, Fn);
6380
6381 Invalid = GatherArgumentsForCall(Call->getBeginLoc(), FDecl, Proto, 0, Args,
6382 AllArgs, CallType);
6383 if (Invalid)
6384 return true;
6385 unsigned TotalNumArgs = AllArgs.size();
6386 for (unsigned i = 0; i < TotalNumArgs; ++i)
6387 Call->setArg(i, AllArgs[i]);
6388
6389 Call->computeDependence();
6390 return false;
6391}
6392
6393bool Sema::GatherArgumentsForCall(SourceLocation CallLoc, FunctionDecl *FDecl,
6394 const FunctionProtoType *Proto,
6395 unsigned FirstParam, ArrayRef<Expr *> Args,
6396 SmallVectorImpl<Expr *> &AllArgs,
6397 VariadicCallType CallType, bool AllowExplicit,
6398 bool IsListInitialization) {
6399 unsigned NumParams = Proto->getNumParams();
6400 bool Invalid = false;
6401 size_t ArgIx = 0;
6402 // Continue to check argument types (even if we have too few/many args).
6403 for (unsigned i = FirstParam; i < NumParams; i++) {
6404 QualType ProtoArgType = Proto->getParamType(i);
6405
6406 Expr *Arg;
6407 ParmVarDecl *Param = FDecl ? FDecl->getParamDecl(i) : nullptr;
6408 if (ArgIx < Args.size()) {
6409 Arg = Args[ArgIx++];
6410
6411 if (RequireCompleteType(Arg->getBeginLoc(), ProtoArgType,
6412 diag::err_call_incomplete_argument, Arg))
6413 return true;
6414
6415 // Strip the unbridged-cast placeholder expression off, if applicable.
6416 bool CFAudited = false;
6417 if (Arg->getType() == Context.ARCUnbridgedCastTy &&
6418 FDecl && FDecl->hasAttr<CFAuditedTransferAttr>() &&
6419 (!Param || !Param->hasAttr<CFConsumedAttr>()))
6420 Arg = stripARCUnbridgedCast(Arg);
6421 else if (getLangOpts().ObjCAutoRefCount &&
6422 FDecl && FDecl->hasAttr<CFAuditedTransferAttr>() &&
6423 (!Param || !Param->hasAttr<CFConsumedAttr>()))
6424 CFAudited = true;
6425
6426 if (Proto->getExtParameterInfo(i).isNoEscape() &&
6427 ProtoArgType->isBlockPointerType())
6428 if (auto *BE = dyn_cast<BlockExpr>(Arg->IgnoreParenNoopCasts(Context)))
6429 BE->getBlockDecl()->setDoesNotEscape();
6430
6431 InitializedEntity Entity =
6432 Param ? InitializedEntity::InitializeParameter(Context, Param,
6433 ProtoArgType)
6434 : InitializedEntity::InitializeParameter(
6435 Context, ProtoArgType, Proto->isParamConsumed(i));
6436
6437 // Remember that parameter belongs to a CF audited API.
6438 if (CFAudited)
6439 Entity.setParameterCFAudited();
6440
6441 ExprResult ArgE = PerformCopyInitialization(
6442 Entity, SourceLocation(), Arg, IsListInitialization, AllowExplicit);
6443 if (ArgE.isInvalid())
6444 return true;
6445
6446 Arg = ArgE.getAs<Expr>();
6447 } else {
6448 assert(Param && "can't use default arguments without a known callee")(static_cast <bool> (Param && "can't use default arguments without a known callee"
) ? void (0) : __assert_fail ("Param && \"can't use default arguments without a known callee\""
, "clang/lib/Sema/SemaExpr.cpp", 6448, __extension__ __PRETTY_FUNCTION__
))
;
6449
6450 ExprResult ArgExpr = BuildCXXDefaultArgExpr(CallLoc, FDecl, Param);
6451 if (ArgExpr.isInvalid())
6452 return true;
6453
6454 Arg = ArgExpr.getAs<Expr>();
6455 }
6456
6457 // Check for array bounds violations for each argument to the call. This
6458 // check only triggers warnings when the argument isn't a more complex Expr
6459 // with its own checking, such as a BinaryOperator.
6460 CheckArrayAccess(Arg);
6461
6462 // Check for violations of C99 static array rules (C99 6.7.5.3p7).
6463 CheckStaticArrayArgument(CallLoc, Param, Arg);
6464
6465 AllArgs.push_back(Arg);
6466 }
6467
6468 // If this is a variadic call, handle args passed through "...".
6469 if (CallType != VariadicDoesNotApply) {
6470 // Assume that extern "C" functions with variadic arguments that
6471 // return __unknown_anytype aren't *really* variadic.
6472 if (Proto->getReturnType() == Context.UnknownAnyTy && FDecl &&
6473 FDecl->isExternC()) {
6474 for (Expr *A : Args.slice(ArgIx)) {
6475 QualType paramType; // ignored
6476 ExprResult arg = checkUnknownAnyArg(CallLoc, A, paramType);
6477 Invalid |= arg.isInvalid();
6478 AllArgs.push_back(arg.get());
6479 }
6480
6481 // Otherwise do argument promotion, (C99 6.5.2.2p7).
6482 } else {
6483 for (Expr *A : Args.slice(ArgIx)) {
6484 ExprResult Arg = DefaultVariadicArgumentPromotion(A, CallType, FDecl);
6485 Invalid |= Arg.isInvalid();
6486 AllArgs.push_back(Arg.get());
6487 }
6488 }
6489
6490 // Check for array bounds violations.
6491 for (Expr *A : Args.slice(ArgIx))
6492 CheckArrayAccess(A);
6493 }
6494 return Invalid;
6495}
6496
6497static void DiagnoseCalleeStaticArrayParam(Sema &S, ParmVarDecl *PVD) {
6498 TypeLoc TL = PVD->getTypeSourceInfo()->getTypeLoc();
6499 if (DecayedTypeLoc DTL = TL.getAs<DecayedTypeLoc>())
6500 TL = DTL.getOriginalLoc();
6501 if (ArrayTypeLoc ATL = TL.getAs<ArrayTypeLoc>())
6502 S.Diag(PVD->getLocation(), diag::note_callee_static_array)
6503 << ATL.getLocalSourceRange();
6504}
6505
6506/// CheckStaticArrayArgument - If the given argument corresponds to a static
6507/// array parameter, check that it is non-null, and that if it is formed by
6508/// array-to-pointer decay, the underlying array is sufficiently large.
6509///
6510/// C99 6.7.5.3p7: If the keyword static also appears within the [ and ] of the
6511/// array type derivation, then for each call to the function, the value of the
6512/// corresponding actual argument shall provide access to the first element of
6513/// an array with at least as many elements as specified by the size expression.
6514void
6515Sema::CheckStaticArrayArgument(SourceLocation CallLoc,
6516 ParmVarDecl *Param,
6517 const Expr *ArgExpr) {
6518 // Static array parameters are not supported in C++.
6519 if (!Param || getLangOpts().CPlusPlus)
6520 return;
6521
6522 QualType OrigTy = Param->getOriginalType();
6523
6524 const ArrayType *AT = Context.getAsArrayType(OrigTy);
6525 if (!AT || AT->getSizeModifier() != ArrayType::Static)
6526 return;
6527
6528 if (ArgExpr->isNullPointerConstant(Context,
6529 Expr::NPC_NeverValueDependent)) {
6530 Diag(CallLoc, diag::warn_null_arg) << ArgExpr->getSourceRange();
6531 DiagnoseCalleeStaticArrayParam(*this, Param);
6532 return;
6533 }
6534
6535 const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT);
6536 if (!CAT)
6537 return;
6538
6539 const ConstantArrayType *ArgCAT =
6540 Context.getAsConstantArrayType(ArgExpr->IgnoreParenCasts()->getType());
6541 if (!ArgCAT)
6542 return;
6543
6544 if (getASTContext().hasSameUnqualifiedType(CAT->getElementType(),
6545 ArgCAT->getElementType())) {
6546 if (ArgCAT->getSize().ult(CAT->getSize())) {
6547 Diag(CallLoc, diag::warn_static_array_too_small)
6548 << ArgExpr->getSourceRange()
6549 << (unsigned)ArgCAT->getSize().getZExtValue()
6550 << (unsigned)CAT->getSize().getZExtValue() << 0;
6551 DiagnoseCalleeStaticArrayParam(*this, Param);
6552 }
6553 return;
6554 }
6555
6556 std::optional<CharUnits> ArgSize =
6557 getASTContext().getTypeSizeInCharsIfKnown(ArgCAT);
6558 std::optional<CharUnits> ParmSize =
6559 getASTContext().getTypeSizeInCharsIfKnown(CAT);
6560 if (ArgSize && ParmSize && *ArgSize < *ParmSize) {
6561 Diag(CallLoc, diag::warn_static_array_too_small)
6562 << ArgExpr->getSourceRange() << (unsigned)ArgSize->getQuantity()
6563 << (unsigned)ParmSize->getQuantity() << 1;
6564 DiagnoseCalleeStaticArrayParam(*this, Param);
6565 }
6566}
6567
6568/// Given a function expression of unknown-any type, try to rebuild it
6569/// to have a function type.
6570static ExprResult rebuildUnknownAnyFunction(Sema &S, Expr *fn);
6571
6572/// Is the given type a placeholder that we need to lower out
6573/// immediately during argument processing?
6574static bool isPlaceholderToRemoveAsArg(QualType type) {
6575 // Placeholders are never sugared.
6576 const BuiltinType *placeholder = dyn_cast<BuiltinType>(type);
6577 if (!placeholder) return false;
6578
6579 switch (placeholder->getKind()) {
6580 // Ignore all the non-placeholder types.
6581#define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
6582 case BuiltinType::Id:
6583#include "clang/Basic/OpenCLImageTypes.def"
6584#define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \
6585 case BuiltinType::Id:
6586#include "clang/Basic/OpenCLExtensionTypes.def"
6587 // In practice we'll never use this, since all SVE types are sugared
6588 // via TypedefTypes rather than exposed directly as BuiltinTypes.
6589#define SVE_TYPE(Name, Id, SingletonId) \
6590 case BuiltinType::Id:
6591#include "clang/Basic/AArch64SVEACLETypes.def"
6592#define PPC_VECTOR_TYPE(Name, Id, Size) \
6593 case BuiltinType::Id:
6594#include "clang/Basic/PPCTypes.def"
6595#define RVV_TYPE(Name, Id, SingletonId) case BuiltinType::Id:
6596#include "clang/Basic/RISCVVTypes.def"
6597#define WASM_TYPE(Name, Id, SingletonId) case BuiltinType::Id:
6598#include "clang/Basic/WebAssemblyReferenceTypes.def"
6599#define PLACEHOLDER_TYPE(ID, SINGLETON_ID)
6600#define BUILTIN_TYPE(ID, SINGLETON_ID) case BuiltinType::ID:
6601#include "clang/AST/BuiltinTypes.def"
6602 return false;
6603
6604 // We cannot lower out overload sets; they might validly be resolved
6605 // by the call machinery.
6606 case BuiltinType::Overload:
6607 return false;
6608
6609 // Unbridged casts in ARC can be handled in some call positions and
6610 // should be left in place.
6611 case BuiltinType::ARCUnbridgedCast:
6612 return false;
6613
6614 // Pseudo-objects should be converted as soon as possible.
6615 case BuiltinType::PseudoObject:
6616 return true;
6617
6618 // The debugger mode could theoretically but currently does not try
6619 // to resolve unknown-typed arguments based on known parameter types.
6620 case BuiltinType::UnknownAny:
6621 return true;
6622
6623 // These are always invalid as call arguments and should be reported.
6624 case BuiltinType::BoundMember:
6625 case BuiltinType::BuiltinFn:
6626 case BuiltinType::IncompleteMatrixIdx:
6627 case BuiltinType::OMPArraySection:
6628 case BuiltinType::OMPArrayShaping:
6629 case BuiltinType::OMPIterator:
6630 return true;
6631
6632 }
6633 llvm_unreachable("bad builtin type kind")::llvm::llvm_unreachable_internal("bad builtin type kind", "clang/lib/Sema/SemaExpr.cpp"
, 6633)
;
6634}
6635
6636/// Check an argument list for placeholders that we won't try to
6637/// handle later.
6638static bool checkArgsForPlaceholders(Sema &S, MultiExprArg args) {
6639 // Apply this processing to all the arguments at once instead of
6640 // dying at the first failure.
6641 bool hasInvalid = false;
6642 for (size_t i = 0, e = args.size(); i != e; i++) {
6643 if (isPlaceholderToRemoveAsArg(args[i]->getType())) {
6644 ExprResult result = S.CheckPlaceholderExpr(args[i]);
6645 if (result.isInvalid()) hasInvalid = true;
6646 else args[i] = result.get();
6647 }
6648 }
6649 return hasInvalid;
6650}
6651
6652/// If a builtin function has a pointer argument with no explicit address
6653/// space, then it should be able to accept a pointer to any address
6654/// space as input. In order to do this, we need to replace the
6655/// standard builtin declaration with one that uses the same address space
6656/// as the call.
6657///
6658/// \returns nullptr If this builtin is not a candidate for a rewrite i.e.
6659/// it does not contain any pointer arguments without
6660/// an address space qualifer. Otherwise the rewritten
6661/// FunctionDecl is returned.
6662/// TODO: Handle pointer return types.
6663static FunctionDecl *rewriteBuiltinFunctionDecl(Sema *Sema, ASTContext &Context,
6664 FunctionDecl *FDecl,
6665 MultiExprArg ArgExprs) {
6666
6667 QualType DeclType = FDecl->getType();
6668 const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(DeclType);
6669
6670 if (!Context.BuiltinInfo.hasPtrArgsOrResult(FDecl->getBuiltinID()) || !FT ||
6671 ArgExprs.size() < FT->getNumParams())
6672 return nullptr;
6673
6674 bool NeedsNewDecl = false;
6675 unsigned i = 0;
6676 SmallVector<QualType, 8> OverloadParams;
6677
6678 for (QualType ParamType : FT->param_types()) {
6679
6680 // Convert array arguments to pointer to simplify type lookup.
6681 ExprResult ArgRes =
6682 Sema->DefaultFunctionArrayLvalueConversion(ArgExprs[i++]);
6683 if (ArgRes.isInvalid())
6684 return nullptr;
6685 Expr *Arg = ArgRes.get();
6686 QualType ArgType = Arg->getType();
6687 if (!ParamType->isPointerType() || ParamType.hasAddressSpace() ||
6688 !ArgType->isPointerType() ||
6689 !ArgType->getPointeeType().hasAddressSpace() ||
6690 isPtrSizeAddressSpace(ArgType->getPointeeType().getAddressSpace())) {
6691 OverloadParams.push_back(ParamType);
6692 continue;
6693 }
6694
6695 QualType PointeeType = ParamType->getPointeeType();
6696 if (PointeeType.hasAddressSpace())
6697 continue;
6698
6699 NeedsNewDecl = true;
6700 LangAS AS = ArgType->getPointeeType().getAddressSpace();
6701
6702 PointeeType = Context.getAddrSpaceQualType(PointeeType, AS);
6703 OverloadParams.push_back(Context.getPointerType(PointeeType));
6704 }
6705
6706 if (!NeedsNewDecl)
6707 return nullptr;
6708
6709 FunctionProtoType::ExtProtoInfo EPI;
6710 EPI.Variadic = FT->isVariadic();
6711 QualType OverloadTy = Context.getFunctionType(FT->getReturnType(),
6712 OverloadParams, EPI);
6713 DeclContext *Parent = FDecl->getParent();
6714 FunctionDecl *OverloadDecl = FunctionDecl::Create(
6715 Context, Parent, FDecl->getLocation(), FDecl->getLocation(),
6716 FDecl->getIdentifier(), OverloadTy,
6717 /*TInfo=*/nullptr, SC_Extern, Sema->getCurFPFeatures().isFPConstrained(),
6718 false,
6719 /*hasPrototype=*/true);
6720 SmallVector<ParmVarDecl*, 16> Params;
6721 FT = cast<FunctionProtoType>(OverloadTy);
6722 for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i) {
6723 QualType ParamType = FT->getParamType(i);
6724 ParmVarDecl *Parm =
6725 ParmVarDecl::Create(Context, OverloadDecl, SourceLocation(),
6726 SourceLocation(), nullptr, ParamType,
6727 /*TInfo=*/nullptr, SC_None, nullptr);
6728 Parm->setScopeInfo(0, i);
6729 Params.push_back(Parm);
6730 }
6731 OverloadDecl->setParams(Params);
6732 Sema->mergeDeclAttributes(OverloadDecl, FDecl);
6733 return OverloadDecl;
6734}
6735
6736static void checkDirectCallValidity(Sema &S, const Expr *Fn,
6737 FunctionDecl *Callee,
6738 MultiExprArg ArgExprs) {
6739 // `Callee` (when called with ArgExprs) may be ill-formed. enable_if (and
6740 // similar attributes) really don't like it when functions are called with an
6741 // invalid number of args.
6742 if (S.TooManyArguments(Callee->getNumParams(), ArgExprs.size(),
6743 /*PartialOverloading=*/false) &&
6744 !Callee->isVariadic())
6745 return;
6746 if (Callee->getMinRequiredArguments() > ArgExprs.size())
6747 return;
6748
6749 if (const EnableIfAttr *Attr =
6750 S.CheckEnableIf(Callee, Fn->getBeginLoc(), ArgExprs, true)) {
6751 S.Diag(Fn->getBeginLoc(),
6752 isa<CXXMethodDecl>(Callee)
6753 ? diag::err_ovl_no_viable_member_function_in_call
6754 : diag::err_ovl_no_viable_function_in_call)
6755 << Callee << Callee->getSourceRange();
6756 S.Diag(Callee->getLocation(),
6757 diag::note_ovl_candidate_disabled_by_function_cond_attr)
6758 << Attr->getCond()->getSourceRange() << Attr->getMessage();
6759 return;
6760 }
6761}
6762
6763static bool enclosingClassIsRelatedToClassInWhichMembersWereFound(
6764 const UnresolvedMemberExpr *const UME, Sema &S) {
6765
6766 const auto GetFunctionLevelDCIfCXXClass =
6767 [](Sema &S) -> const CXXRecordDecl * {
6768 const DeclContext *const DC = S.getFunctionLevelDeclContext();
6769 if (!DC || !DC->getParent())
6770 return nullptr;
6771
6772 // If the call to some member function was made from within a member
6773 // function body 'M' return return 'M's parent.
6774 if (const auto *MD = dyn_cast<CXXMethodDecl>(DC))
6775 return MD->getParent()->getCanonicalDecl();
6776 // else the call was made from within a default member initializer of a
6777 // class, so return the class.
6778 if (const auto *RD = dyn_cast<CXXRecordDecl>(DC))
6779 return RD->getCanonicalDecl();
6780 return nullptr;
6781 };
6782 // If our DeclContext is neither a member function nor a class (in the
6783 // case of a lambda in a default member initializer), we can't have an
6784 // enclosing 'this'.
6785
6786 const CXXRecordDecl *const CurParentClass = GetFunctionLevelDCIfCXXClass(S);
6787 if (!CurParentClass)
6788 return false;
6789
6790 // The naming class for implicit member functions call is the class in which
6791 // name lookup starts.
6792 const CXXRecordDecl *const NamingClass =
6793 UME->getNamingClass()->getCanonicalDecl();
6794 assert(NamingClass && "Must have naming class even for implicit access")(static_cast <bool> (NamingClass && "Must have naming class even for implicit access"
) ? void (0) : __assert_fail ("NamingClass && \"Must have naming class even for implicit access\""
, "clang/lib/Sema/SemaExpr.cpp", 6794, __extension__ __PRETTY_FUNCTION__
))
;
6795
6796 // If the unresolved member functions were found in a 'naming class' that is
6797 // related (either the same or derived from) to the class that contains the
6798 // member function that itself contained the implicit member access.
6799
6800 return CurParentClass == NamingClass ||
6801 CurParentClass->isDerivedFrom(NamingClass);
6802}
6803
6804static void
6805tryImplicitlyCaptureThisIfImplicitMemberFunctionAccessWithDependentArgs(
6806 Sema &S, const UnresolvedMemberExpr *const UME, SourceLocation CallLoc) {
6807
6808 if (!UME)
6809 return;
6810
6811 LambdaScopeInfo *const CurLSI = S.getCurLambda();
6812 // Only try and implicitly capture 'this' within a C++ Lambda if it hasn't
6813 // already been captured, or if this is an implicit member function call (if
6814 // it isn't, an attempt to capture 'this' should already have been made).
6815 if (!CurLSI || CurLSI->ImpCaptureStyle == CurLSI->ImpCap_None ||
6816 !UME->isImplicitAccess() || CurLSI->isCXXThisCaptured())
6817 return;
6818
6819 // Check if the naming class in which the unresolved members were found is
6820 // related (same as or is a base of) to the enclosing class.
6821
6822 if (!enclosingClassIsRelatedToClassInWhichMembersWereFound(UME, S))
6823 return;
6824
6825
6826 DeclContext *EnclosingFunctionCtx = S.CurContext->getParent()->getParent();
6827 // If the enclosing function is not dependent, then this lambda is
6828 // capture ready, so if we can capture this, do so.
6829 if (!EnclosingFunctionCtx->isDependentContext()) {
6830 // If the current lambda and all enclosing lambdas can capture 'this' -
6831 // then go ahead and capture 'this' (since our unresolved overload set
6832 // contains at least one non-static member function).
6833 if (!S.CheckCXXThisCapture(CallLoc, /*Explcit*/ false, /*Diagnose*/ false))
6834 S.CheckCXXThisCapture(CallLoc);
6835 } else if (S.CurContext->isDependentContext()) {
6836 // ... since this is an implicit member reference, that might potentially
6837 // involve a 'this' capture, mark 'this' for potential capture in
6838 // enclosing lambdas.
6839 if (CurLSI->ImpCaptureStyle != CurLSI->ImpCap_None)
6840 CurLSI->addPotentialThisCapture(CallLoc);
6841 }
6842}
6843
6844// Once a call is fully resolved, warn for unqualified calls to specific
6845// C++ standard functions, like move and forward.
6846static void DiagnosedUnqualifiedCallsToStdFunctions(Sema &S, CallExpr *Call) {
6847 // We are only checking unary move and forward so exit early here.
6848 if (Call->getNumArgs() != 1)
6849 return;
6850
6851 Expr *E = Call->getCallee()->IgnoreParenImpCasts();
6852 if (!E || isa<UnresolvedLookupExpr>(E))
6853 return;
6854 DeclRefExpr *DRE = dyn_cast_or_null<DeclRefExpr>(E);
6855 if (!DRE || !DRE->getLocation().isValid())
6856 return;
6857
6858 if (DRE->getQualifier())
6859 return;
6860
6861 const FunctionDecl *FD = Call->getDirectCallee();
6862 if (!FD)
6863 return;
6864
6865 // Only warn for some functions deemed more frequent or problematic.
6866 unsigned BuiltinID = FD->getBuiltinID();
6867 if (BuiltinID != Builtin::BImove && BuiltinID != Builtin::BIforward)
6868 return;
6869
6870 S.Diag(DRE->getLocation(), diag::warn_unqualified_call_to_std_cast_function)
6871 << FD->getQualifiedNameAsString()
6872 << FixItHint::CreateInsertion(DRE->getLocation(), "std::");
6873}
6874
6875ExprResult Sema::ActOnCallExpr(Scope *Scope, Expr *Fn, SourceLocation LParenLoc,
6876 MultiExprArg ArgExprs, SourceLocation RParenLoc,
6877 Expr *ExecConfig) {
6878 ExprResult Call =
6879 BuildCallExpr(Scope, Fn, LParenLoc, ArgExprs, RParenLoc, ExecConfig,
6880 /*IsExecConfig=*/false, /*AllowRecovery=*/true);
6881 if (Call.isInvalid())
6882 return Call;
6883
6884 // Diagnose uses of the C++20 "ADL-only template-id call" feature in earlier
6885 // language modes.
6886 if (auto *ULE = dyn_cast<UnresolvedLookupExpr>(Fn)) {
6887 if (ULE->hasExplicitTemplateArgs() &&
6888 ULE->decls_begin() == ULE->decls_end()) {
6889 Diag(Fn->getExprLoc(), getLangOpts().CPlusPlus20
6890 ? diag::warn_cxx17_compat_adl_only_template_id
6891 : diag::ext_adl_only_template_id)
6892 << ULE->getName();
6893 }
6894 }
6895
6896 if (LangOpts.OpenMP)
6897 Call = ActOnOpenMPCall(Call, Scope, LParenLoc, ArgExprs, RParenLoc,
6898 ExecConfig);
6899 if (LangOpts.CPlusPlus) {
6900 CallExpr *CE = dyn_cast<CallExpr>(Call.get());
6901 if (CE)
6902 DiagnosedUnqualifiedCallsToStdFunctions(*this, CE);
6903 }
6904 return Call;
6905}
6906
6907/// BuildCallExpr - Handle a call to Fn with the specified array of arguments.
6908/// This provides the location of the left/right parens and a list of comma
6909/// locations.
6910ExprResult Sema::BuildCallExpr(Scope *Scope, Expr *Fn, SourceLocation LParenLoc,
6911 MultiExprArg ArgExprs, SourceLocation RParenLoc,
6912 Expr *ExecConfig, bool IsExecConfig,
6913 bool AllowRecovery) {
6914 // Since this might be a postfix expression, get rid of ParenListExprs.
6915 ExprResult Result = MaybeConvertParenListExprToParenExpr(Scope, Fn);
6916 if (Result.isInvalid()) return ExprError();
6917 Fn = Result.get();
6918
6919 if (checkArgsForPlaceholders(*this, ArgExprs))
6920 return ExprError();
6921
6922 if (getLangOpts().CPlusPlus) {
6923 // If this is a pseudo-destructor expression, build the call immediately.
6924 if (isa<CXXPseudoDestructorExpr>(Fn)) {
6925 if (!ArgExprs.empty()) {
6926 // Pseudo-destructor calls should not have any arguments.
6927 Diag(Fn->getBeginLoc(), diag::err_pseudo_dtor_call_with_args)
6928 << FixItHint::CreateRemoval(
6929 SourceRange(ArgExprs.front()->getBeginLoc(),
6930 ArgExprs.back()->getEndLoc()));
6931 }
6932
6933 return CallExpr::Create(Context, Fn, /*Args=*/{}, Context.VoidTy,
6934 VK_PRValue, RParenLoc, CurFPFeatureOverrides());
6935 }
6936 if (Fn->getType() == Context.PseudoObjectTy) {
6937 ExprResult result = CheckPlaceholderExpr(Fn);
6938 if (result.isInvalid()) return ExprError();
6939 Fn = result.get();
6940 }
6941
6942 // Determine whether this is a dependent call inside a C++ template,
6943 // in which case we won't do any semantic analysis now.
6944 if (Fn->isTypeDependent() || Expr::hasAnyTypeDependentArguments(ArgExprs)) {
6945 if (ExecConfig) {
6946 return CUDAKernelCallExpr::Create(Context, Fn,
6947 cast<CallExpr>(ExecConfig), ArgExprs,
6948 Context.DependentTy, VK_PRValue,
6949 RParenLoc, CurFPFeatureOverrides());
6950 } else {
6951
6952 tryImplicitlyCaptureThisIfImplicitMemberFunctionAccessWithDependentArgs(
6953 *this, dyn_cast<UnresolvedMemberExpr>(Fn->IgnoreParens()),
6954 Fn->getBeginLoc());
6955
6956 return CallExpr::Create(Context, Fn, ArgExprs, Context.DependentTy,
6957 VK_PRValue, RParenLoc, CurFPFeatureOverrides());
6958 }
6959 }
6960
6961 // Determine whether this is a call to an object (C++ [over.call.object]).
6962 if (Fn->getType()->isRecordType())
6963 return BuildCallToObjectOfClassType(Scope, Fn, LParenLoc, ArgExprs,
6964 RParenLoc);
6965
6966 if (Fn->getType() == Context.UnknownAnyTy) {
6967 ExprResult result = rebuildUnknownAnyFunction(*this, Fn);
6968 if (result.isInvalid()) return ExprError();
6969 Fn = result.get();
6970 }
6971
6972 if (Fn->getType() == Context.BoundMemberTy) {
6973 return BuildCallToMemberFunction(Scope, Fn, LParenLoc, ArgExprs,
6974 RParenLoc, ExecConfig, IsExecConfig,
6975 AllowRecovery);
6976 }
6977 }
6978
6979 // Check for overloaded calls. This can happen even in C due to extensions.
6980 if (Fn->getType() == Context.OverloadTy) {
6981 OverloadExpr::FindResult find = OverloadExpr::find(Fn);
6982
6983 // We aren't supposed to apply this logic if there's an '&' involved.
6984 if (!find.HasFormOfMemberPointer) {
6985 if (Expr::hasAnyTypeDependentArguments(ArgExprs))
6986 return CallExpr::Create(Context, Fn, ArgExprs, Context.DependentTy,
6987 VK_PRValue, RParenLoc, CurFPFeatureOverrides());
6988 OverloadExpr *ovl = find.Expression;
6989 if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(ovl))
6990 return BuildOverloadedCallExpr(
6991 Scope, Fn, ULE, LParenLoc, ArgExprs, RParenLoc, ExecConfig,
6992 /*AllowTypoCorrection=*/true, find.IsAddressOfOperand);
6993 return BuildCallToMemberFunction(Scope, Fn, LParenLoc, ArgExprs,
6994 RParenLoc, ExecConfig, IsExecConfig,
6995 AllowRecovery);
6996 }
6997 }
6998
6999 // If we're directly calling a function, get the appropriate declaration.
7000 if (Fn->getType() == Context.UnknownAnyTy) {
7001 ExprResult result = rebuildUnknownAnyFunction(*this, Fn);
7002 if (result.isInvalid()) return ExprError();
7003 Fn = result.get();
7004 }
7005
7006 Expr *NakedFn = Fn->IgnoreParens();
7007
7008 bool CallingNDeclIndirectly = false;
7009 NamedDecl *NDecl = nullptr;
7010 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(NakedFn)) {
7011 if (UnOp->getOpcode() == UO_AddrOf) {
7012 CallingNDeclIndirectly = true;
7013 NakedFn = UnOp->getSubExpr()->IgnoreParens();
7014 }
7015 }
7016
7017 if (auto *DRE = dyn_cast<DeclRefExpr>(NakedFn)) {
7018 NDecl = DRE->getDecl();
7019
7020 FunctionDecl *FDecl = dyn_cast<FunctionDecl>(NDecl);
7021 if (FDecl && FDecl->getBuiltinID()) {
7022 // Rewrite the function decl for this builtin by replacing parameters
7023 // with no explicit address space with the address space of the arguments
7024 // in ArgExprs.
7025 if ((FDecl =
7026 rewriteBuiltinFunctionDecl(this, Context, FDecl, ArgExprs))) {
7027 NDecl = FDecl;
7028 Fn = DeclRefExpr::Create(
7029 Context, FDecl->getQualifierLoc(), SourceLocation(), FDecl, false,
7030 SourceLocation(), FDecl->getType(), Fn->getValueKind(), FDecl,
7031 nullptr, DRE->isNonOdrUse());
7032 }
7033 }
7034 } else if (auto *ME = dyn_cast<MemberExpr>(NakedFn))
7035 NDecl = ME->getMemberDecl();
7036
7037 if (FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(NDecl)) {
7038 if (CallingNDeclIndirectly && !checkAddressOfFunctionIsAvailable(
7039 FD, /*Complain=*/true, Fn->getBeginLoc()))
7040 return ExprError();
7041
7042 checkDirectCallValidity(*this, Fn, FD, ArgExprs);
7043
7044 // If this expression is a call to a builtin function in HIP device
7045 // compilation, allow a pointer-type argument to default address space to be
7046 // passed as a pointer-type parameter to a non-default address space.
7047 // If Arg is declared in the default address space and Param is declared
7048 // in a non-default address space, perform an implicit address space cast to
7049 // the parameter type.
7050 if (getLangOpts().HIP && getLangOpts().CUDAIsDevice && FD &&
7051 FD->getBuiltinID()) {
7052 for (unsigned Idx = 0; Idx < FD->param_size(); ++Idx) {
7053 ParmVarDecl *Param = FD->getParamDecl(Idx);
7054 if (!ArgExprs[Idx] || !Param || !Param->getType()->isPointerType() ||
7055 !ArgExprs[Idx]->getType()->isPointerType())
7056 continue;
7057
7058 auto ParamAS = Param->getType()->getPointeeType().getAddressSpace();
7059 auto ArgTy = ArgExprs[Idx]->getType();
7060 auto ArgPtTy = ArgTy->getPointeeType();
7061 auto ArgAS = ArgPtTy.getAddressSpace();
7062
7063 // Add address space cast if target address spaces are different
7064 bool NeedImplicitASC =
7065 ParamAS != LangAS::Default && // Pointer params in generic AS don't need special handling.
7066 ( ArgAS == LangAS::Default || // We do allow implicit conversion from generic AS
7067 // or from specific AS which has target AS matching that of Param.
7068 getASTContext().getTargetAddressSpace(ArgAS) == getASTContext().getTargetAddressSpace(ParamAS));
7069 if (!NeedImplicitASC)
7070 continue;
7071
7072 // First, ensure that the Arg is an RValue.
7073 if (ArgExprs[Idx]->isGLValue()) {
7074 ArgExprs[Idx] = ImplicitCastExpr::Create(
7075 Context, ArgExprs[Idx]->getType(), CK_NoOp, ArgExprs[Idx],
7076 nullptr, VK_PRValue, FPOptionsOverride());
7077 }
7078
7079 // Construct a new arg type with address space of Param
7080 Qualifiers ArgPtQuals = ArgPtTy.getQualifiers();
7081 ArgPtQuals.setAddressSpace(ParamAS);
7082 auto NewArgPtTy =
7083 Context.getQualifiedType(ArgPtTy.getUnqualifiedType(), ArgPtQuals);
7084 auto NewArgTy =
7085 Context.getQualifiedType(Context.getPointerType(NewArgPtTy),
7086 ArgTy.getQualifiers());
7087
7088 // Finally perform an implicit address space cast
7089 ArgExprs[Idx] = ImpCastExprToType(ArgExprs[Idx], NewArgTy,
7090 CK_AddressSpaceConversion)
7091 .get();
7092 }
7093 }
7094 }
7095
7096 if (Context.isDependenceAllowed() &&
7097 (Fn->isTypeDependent() || Expr::hasAnyTypeDependentArguments(ArgExprs))) {
7098 assert(!getLangOpts().CPlusPlus)(static_cast <bool> (!getLangOpts().CPlusPlus) ? void (
0) : __assert_fail ("!getLangOpts().CPlusPlus", "clang/lib/Sema/SemaExpr.cpp"
, 7098, __extension__ __PRETTY_FUNCTION__))
;
7099 assert((Fn->containsErrors() ||(static_cast <bool> ((Fn->containsErrors() || llvm::
any_of(ArgExprs, [](clang::Expr *E) { return E->containsErrors
(); })) && "should only occur in error-recovery path."
) ? void (0) : __assert_fail ("(Fn->containsErrors() || llvm::any_of(ArgExprs, [](clang::Expr *E) { return E->containsErrors(); })) && \"should only occur in error-recovery path.\""
, "clang/lib/Sema/SemaExpr.cpp", 7102, __extension__ __PRETTY_FUNCTION__
))
7100 llvm::any_of(ArgExprs,(static_cast <bool> ((Fn->containsErrors() || llvm::
any_of(ArgExprs, [](clang::Expr *E) { return E->containsErrors
(); })) && "should only occur in error-recovery path."
) ? void (0) : __assert_fail ("(Fn->containsErrors() || llvm::any_of(ArgExprs, [](clang::Expr *E) { return E->containsErrors(); })) && \"should only occur in error-recovery path.\""
, "clang/lib/Sema/SemaExpr.cpp", 7102, __extension__ __PRETTY_FUNCTION__
))
7101 [](clang::Expr *E) { return E->containsErrors(); })) &&(static_cast <bool> ((Fn->containsErrors() || llvm::
any_of(ArgExprs, [](clang::Expr *E) { return E->containsErrors
(); })) && "should only occur in error-recovery path."
) ? void (0) : __assert_fail ("(Fn->containsErrors() || llvm::any_of(ArgExprs, [](clang::Expr *E) { return E->containsErrors(); })) && \"should only occur in error-recovery path.\""
, "clang/lib/Sema/SemaExpr.cpp", 7102, __extension__ __PRETTY_FUNCTION__
))
7102 "should only occur in error-recovery path.")(static_cast <bool> ((Fn->containsErrors() || llvm::
any_of(ArgExprs, [](clang::Expr *E) { return E->containsErrors
(); })) && "should only occur in error-recovery path."
) ? void (0) : __assert_fail ("(Fn->containsErrors() || llvm::any_of(ArgExprs, [](clang::Expr *E) { return E->containsErrors(); })) && \"should only occur in error-recovery path.\""
, "clang/lib/Sema/SemaExpr.cpp", 7102, __extension__ __PRETTY_FUNCTION__
))
;
7103 QualType ReturnType =
7104 llvm::isa_and_nonnull<FunctionDecl>(NDecl)
7105 ? cast<FunctionDecl>(NDecl)->getCallResultType()
7106 : Context.DependentTy;
7107 return CallExpr::Create(Context, Fn, ArgExprs, ReturnType,
7108 Expr::getValueKindForType(ReturnType), RParenLoc,
7109 CurFPFeatureOverrides());
7110 }
7111 return BuildResolvedCallExpr(Fn, NDecl, LParenLoc, ArgExprs, RParenLoc,
7112 ExecConfig, IsExecConfig);
7113}
7114
7115/// BuildBuiltinCallExpr - Create a call to a builtin function specified by Id
7116// with the specified CallArgs
7117Expr *Sema::BuildBuiltinCallExpr(SourceLocation Loc, Builtin::ID Id,
7118 MultiExprArg CallArgs) {
7119 StringRef Name = Context.BuiltinInfo.getName(Id);
7120 LookupResult R(*this, &Context.Idents.get(Name), Loc,
7121 Sema::LookupOrdinaryName);
7122 LookupName(R, TUScope, /*AllowBuiltinCreation=*/true);
7123
7124 auto *BuiltInDecl = R.getAsSingle<FunctionDecl>();
7125 assert(BuiltInDecl && "failed to find builtin declaration")(static_cast <bool> (BuiltInDecl && "failed to find builtin declaration"
) ? void (0) : __assert_fail ("BuiltInDecl && \"failed to find builtin declaration\""
, "clang/lib/Sema/SemaExpr.cpp", 7125, __extension__ __PRETTY_FUNCTION__
))
;
7126
7127 ExprResult DeclRef =
7128 BuildDeclRefExpr(BuiltInDecl, BuiltInDecl->getType(), VK_LValue, Loc);
7129 assert(DeclRef.isUsable() && "Builtin reference cannot fail")(static_cast <bool> (DeclRef.isUsable() && "Builtin reference cannot fail"
) ? void (0) : __assert_fail ("DeclRef.isUsable() && \"Builtin reference cannot fail\""
, "clang/lib/Sema/SemaExpr.cpp", 7129, __extension__ __PRETTY_FUNCTION__
))
;
7130
7131 ExprResult Call =
7132 BuildCallExpr(/*Scope=*/nullptr, DeclRef.get(), Loc, CallArgs, Loc);
7133
7134 assert(!Call.isInvalid() && "Call to builtin cannot fail!")(static_cast <bool> (!Call.isInvalid() && "Call to builtin cannot fail!"
) ? void (0) : __assert_fail ("!Call.isInvalid() && \"Call to builtin cannot fail!\""
, "clang/lib/Sema/SemaExpr.cpp", 7134, __extension__ __PRETTY_FUNCTION__
))
;
7135 return Call.get();
7136}
7137
7138/// Parse a __builtin_astype expression.
7139///
7140/// __builtin_astype( value, dst type )
7141///
7142ExprResult Sema::ActOnAsTypeExpr(Expr *E, ParsedType ParsedDestTy,
7143 SourceLocation BuiltinLoc,
7144 SourceLocation RParenLoc) {
7145 QualType DstTy = GetTypeFromParser(ParsedDestTy);
7146 return BuildAsTypeExpr(E, DstTy, BuiltinLoc, RParenLoc);
7147}
7148
7149/// Create a new AsTypeExpr node (bitcast) from the arguments.
7150ExprResult Sema::BuildAsTypeExpr(Expr *E, QualType DestTy,
7151 SourceLocation BuiltinLoc,
7152 SourceLocation RParenLoc) {
7153 ExprValueKind VK = VK_PRValue;
7154 ExprObjectKind OK = OK_Ordinary;
7155 QualType SrcTy = E->getType();
7156 if (!SrcTy->isDependentType() &&
7157 Context.getTypeSize(DestTy) != Context.getTypeSize(SrcTy))
7158 return ExprError(
7159 Diag(BuiltinLoc, diag::err_invalid_astype_of_different_size)
7160 << DestTy << SrcTy << E->getSourceRange());
7161 return new (Context) AsTypeExpr(E, DestTy, VK, OK, BuiltinLoc, RParenLoc);
7162}
7163
7164/// ActOnConvertVectorExpr - create a new convert-vector expression from the
7165/// provided arguments.
7166///
7167/// __builtin_convertvector( value, dst type )
7168///
7169ExprResult Sema::ActOnConvertVectorExpr(Expr *E, ParsedType ParsedDestTy,
7170 SourceLocation BuiltinLoc,
7171 SourceLocation RParenLoc) {
7172 TypeSourceInfo *TInfo;
7173 GetTypeFromParser(ParsedDestTy, &TInfo);
7174 return SemaConvertVectorExpr(E, TInfo, BuiltinLoc, RParenLoc);
7175}
7176
7177/// BuildResolvedCallExpr - Build a call to a resolved expression,
7178/// i.e. an expression not of \p OverloadTy. The expression should
7179/// unary-convert to an expression of function-pointer or
7180/// block-pointer type.
7181///
7182/// \param NDecl the declaration being called, if available
7183ExprResult Sema::BuildResolvedCallExpr(Expr *Fn, NamedDecl *NDecl,
7184 SourceLocation LParenLoc,
7185 ArrayRef<Expr *> Args,
7186 SourceLocation RParenLoc, Expr *Config,
7187 bool IsExecConfig, ADLCallKind UsesADL) {
7188 FunctionDecl *FDecl = dyn_cast_or_null<FunctionDecl>(NDecl);
1
Assuming null pointer is passed into cast
7189 unsigned BuiltinID = (FDecl
1.1
'FDecl' is null
? FDecl->getBuiltinID() : 0);
2
'?' condition is false
7190
7191 // Functions with 'interrupt' attribute cannot be called directly.
7192 if (FDecl
2.1
'FDecl' is null
&& FDecl->hasAttr<AnyX86InterruptAttr>()) {
7193 Diag(Fn->getExprLoc(), diag::err_anyx86_interrupt_called);
7194 return ExprError();
7195 }
7196
7197 // Interrupt handlers don't save off the VFP regs automatically on ARM,
7198 // so there's some risk when calling out to non-interrupt handler functions
7199 // that the callee might not preserve them. This is easy to diagnose here,
7200 // but can be very challenging to debug.
7201 // Likewise, X86 interrupt handlers may only call routines with attribute
7202 // no_caller_saved_registers since there is no efficient way to
7203 // save and restore the non-GPR state.
7204 if (auto *Caller = getCurFunctionDecl()) {
3
Assuming 'Caller' is null
4
Taking false branch
7205 if (Caller->hasAttr<ARMInterruptAttr>()) {
7206 bool VFP = Context.getTargetInfo().hasFeature("vfp");
7207 if (VFP && (!FDecl || !FDecl->hasAttr<ARMInterruptAttr>())) {
7208 Diag(Fn->getExprLoc(), diag::warn_arm_interrupt_calling_convention);
7209 if (FDecl)
7210 Diag(FDecl->getLocation(), diag::note_callee_decl) << FDecl;
7211 }
7212 }
7213 if (Caller->hasAttr<AnyX86InterruptAttr>() &&
7214 ((!FDecl || !FDecl->hasAttr<AnyX86NoCallerSavedRegistersAttr>()))) {
7215 Diag(Fn->getExprLoc(), diag::warn_anyx86_interrupt_regsave);
7216 if (FDecl)
7217 Diag(FDecl->getLocation(), diag::note_callee_decl) << FDecl;
7218 }
7219 }
7220
7221 // Promote the function operand.
7222 // We special-case function promotion here because we only allow promoting
7223 // builtin functions to function pointers in the callee of a call.
7224 ExprResult Result;
7225 QualType ResultTy;
7226 if (BuiltinID
4.1
'BuiltinID' is 0
&&
5
Taking false branch
7227 Fn->getType()->isSpecificBuiltinType(BuiltinType::BuiltinFn)) {
7228 // Extract the return type from the (builtin) function pointer type.
7229 // FIXME Several builtins still have setType in
7230 // Sema::CheckBuiltinFunctionCall. One should review their definitions in
7231 // Builtins.def to ensure they are correct before removing setType calls.
7232 QualType FnPtrTy = Context.getPointerType(FDecl->getType());
7233 Result = ImpCastExprToType(Fn, FnPtrTy, CK_BuiltinFnToFnPtr).get();
7234 ResultTy = FDecl->getCallResultType();
7235 } else {
7236 Result = CallExprUnaryConversions(Fn);
7237 ResultTy = Context.BoolTy;
7238 }
7239 if (Result.isInvalid())
6
Assuming the condition is false
7
Taking false branch
7240 return ExprError();
7241 Fn = Result.get();
7242
7243 // Check for a valid function type, but only if it is not a builtin which
7244 // requires custom type checking. These will be handled by
7245 // CheckBuiltinFunctionCall below just after creation of the call expression.
7246 const FunctionType *FuncT = nullptr;
7247 if (!BuiltinID
7.1
'BuiltinID' is 0
|| !Context.BuiltinInfo.hasCustomTypechecking(BuiltinID)) {
7248 retry:
7249 if (const PointerType *PT
8.1
'PT' is null
= Fn->getType()->getAs<PointerType>()) {
8
Assuming the object is not a 'const class clang::PointerType *'
9
Taking false branch
7250 // C99 6.5.2.2p1 - "The expression that denotes the called function shall
7251 // have type pointer to function".
7252 FuncT = PT->getPointeeType()->getAs<FunctionType>();
7253 if (!FuncT)
7254 return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function)
7255 << Fn->getType() << Fn->getSourceRange());
7256 } else if (const BlockPointerType *BPT =
11
Assuming 'BPT' is non-null
12
Taking true branch
7257 Fn->getType()->getAs<BlockPointerType>()) {
10
Assuming the object is a 'const class clang::BlockPointerType *'
7258 FuncT = BPT->getPointeeType()->castAs<FunctionType>();
13
The object is a 'const class clang::FunctionType *'
14
Value assigned to 'FuncT'
7259 } else {
7260 // Handle calls to expressions of unknown-any type.
7261 if (Fn->getType() == Context.UnknownAnyTy) {
7262 ExprResult rewrite = rebuildUnknownAnyFunction(*this, Fn);
7263 if (rewrite.isInvalid())
7264 return ExprError();
7265 Fn = rewrite.get();
7266 goto retry;
7267 }
7268
7269 return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function)
7270 << Fn->getType() << Fn->getSourceRange());
7271 }
7272 }
7273
7274 // Get the number of parameters in the function prototype, if any.
7275 // We will allocate space for max(Args.size(), NumParams) arguments
7276 // in the call expression.
7277 const auto *Proto = dyn_cast_or_null<FunctionProtoType>(FuncT);
15
Assuming null pointer is passed into cast
7278 unsigned NumParams = Proto
15.1
'Proto' is null
? Proto->getNumParams() : 0;
16
'?' condition is false
7279
7280 CallExpr *TheCall;
7281 if (Config) {
17
Assuming 'Config' is non-null
7282 assert(UsesADL == ADLCallKind::NotADL &&(static_cast <bool> (UsesADL == ADLCallKind::NotADL &&
"CUDAKernelCallExpr should not use ADL") ? void (0) : __assert_fail
("UsesADL == ADLCallKind::NotADL && \"CUDAKernelCallExpr should not use ADL\""
, "clang/lib/Sema/SemaExpr.cpp", 7283, __extension__ __PRETTY_FUNCTION__
))
18
Taking true branch
19
Assuming 'UsesADL' is equal to NotADL
20
'?' condition is true
7283 "CUDAKernelCallExpr should not use ADL")(static_cast <bool> (UsesADL == ADLCallKind::NotADL &&
"CUDAKernelCallExpr should not use ADL") ? void (0) : __assert_fail
("UsesADL == ADLCallKind::NotADL && \"CUDAKernelCallExpr should not use ADL\""
, "clang/lib/Sema/SemaExpr.cpp", 7283, __extension__ __PRETTY_FUNCTION__
))
;
7284 TheCall = CUDAKernelCallExpr::Create(Context, Fn, cast<CallExpr>(Config),
21
'Config' is a 'CastReturnType'
7285 Args, ResultTy, VK_PRValue, RParenLoc,
7286 CurFPFeatureOverrides(), NumParams);
7287 } else {
7288 TheCall =
7289 CallExpr::Create(Context, Fn, Args, ResultTy, VK_PRValue, RParenLoc,
7290 CurFPFeatureOverrides(), NumParams, UsesADL);
7291 }
7292
7293 if (!Context.isDependenceAllowed()) {
7294 // Forget about the nulled arguments since typo correction
7295 // do not handle them well.
7296 TheCall->shrinkNumArgs(Args.size());
7297 // C cannot always handle TypoExpr nodes in builtin calls and direct
7298 // function calls as their argument checking don't necessarily handle
7299 // dependent types properly, so make sure any TypoExprs have been
7300 // dealt with.
7301 ExprResult Result = CorrectDelayedTyposInExpr(TheCall);
7302 if (!Result.isUsable()) return ExprError();
7303 CallExpr *TheOldCall = TheCall;
7304 TheCall = dyn_cast<CallExpr>(Result.get());
7305 bool CorrectedTypos = TheCall != TheOldCall;
7306 if (!TheCall) return Result;
7307 Args = llvm::ArrayRef(TheCall->getArgs(), TheCall->getNumArgs());
7308
7309 // A new call expression node was created if some typos were corrected.
7310 // However it may not have been constructed with enough storage. In this
7311 // case, rebuild the node with enough storage. The waste of space is
7312 // immaterial since this only happens when some typos were corrected.
7313 if (CorrectedTypos && Args.size() < NumParams) {
7314 if (Config)
7315 TheCall = CUDAKernelCallExpr::Create(
7316 Context, Fn, cast<CallExpr>(Config), Args, ResultTy, VK_PRValue,
7317 RParenLoc, CurFPFeatureOverrides(), NumParams);
7318 else
7319 TheCall =
7320 CallExpr::Create(Context, Fn, Args, ResultTy, VK_PRValue, RParenLoc,
7321 CurFPFeatureOverrides(), NumParams, UsesADL);
7322 }
7323 // We can now handle the nulled arguments for the default arguments.
7324 TheCall->setNumArgsUnsafe(std::max<unsigned>(Args.size(), NumParams));
7325 }
7326
7327 // Bail out early if calling a builtin with custom type checking.
7328 if (BuiltinID
21.1
'BuiltinID' is 0
&& Context.BuiltinInfo.hasCustomTypechecking(BuiltinID))
7329 return CheckBuiltinFunctionCall(FDecl, BuiltinID, TheCall);
7330
7331 if (getLangOpts().CUDA) {
22
Assuming field 'CUDA' is not equal to 0
23
Taking true branch
7332 if (Config
23.1
'Config' is non-null
) {
7333 // CUDA: Kernel calls must be to global functions
7334 if (FDecl
23.2
'FDecl' is null
&& !FDecl->hasAttr<CUDAGlobalAttr>())
7335 return ExprError(Diag(LParenLoc,diag::err_kern_call_not_global_function)
7336 << FDecl << Fn->getSourceRange());
7337
7338 // CUDA: Kernel function must have 'void' return type
7339 if (!FuncT->getReturnType()->isVoidType() &&
24
Called C++ object pointer is null
7340 !FuncT->getReturnType()->getAs<AutoType>() &&
7341 !FuncT->getReturnType()->isInstantiationDependentType())
7342 return ExprError(Diag(LParenLoc, diag::err_kern_type_not_void_return)
7343 << Fn->getType() << Fn->getSourceRange());
7344 } else {
7345 // CUDA: Calls to global functions must be configured
7346 if (FDecl && FDecl->hasAttr<CUDAGlobalAttr>())
7347 return ExprError(Diag(LParenLoc, diag::err_global_call_not_config)
7348 << FDecl << Fn->getSourceRange());
7349 }
7350 }
7351
7352 // Check for a valid return type
7353 if (CheckCallReturnType(FuncT->getReturnType(), Fn->getBeginLoc(), TheCall,
7354 FDecl))
7355 return ExprError();
7356
7357 // We know the result type of the call, set it.
7358 TheCall->setType(FuncT->getCallResultType(Context));
7359 TheCall->setValueKind(Expr::getValueKindForType(FuncT->getReturnType()));
7360
7361 if (Proto) {
7362 if (ConvertArgumentsForCall(TheCall, Fn, FDecl, Proto, Args, RParenLoc,
7363 IsExecConfig))
7364 return ExprError();
7365 } else {
7366 assert(isa<FunctionNoProtoType>(FuncT) && "Unknown FunctionType!")(static_cast <bool> (isa<FunctionNoProtoType>(FuncT
) && "Unknown FunctionType!") ? void (0) : __assert_fail
("isa<FunctionNoProtoType>(FuncT) && \"Unknown FunctionType!\""
, "clang/lib/Sema/SemaExpr.cpp", 7366, __extension__ __PRETTY_FUNCTION__
))
;
7367
7368 if (FDecl) {
7369 // Check if we have too few/too many template arguments, based
7370 // on our knowledge of the function definition.
7371 const FunctionDecl *Def = nullptr;
7372 if (FDecl->hasBody(Def) && Args.size() != Def->param_size()) {
7373 Proto = Def->getType()->getAs<FunctionProtoType>();
7374 if (!Proto || !(Proto->isVariadic() && Args.size() >= Def->param_size()))
7375 Diag(RParenLoc, diag::warn_call_wrong_number_of_arguments)
7376 << (Args.size() > Def->param_size()) << FDecl << Fn->getSourceRange();
7377 }
7378
7379 // If the function we're calling isn't a function prototype, but we have
7380 // a function prototype from a prior declaratiom, use that prototype.
7381 if (!FDecl->hasPrototype())
7382 Proto = FDecl->getType()->getAs<FunctionProtoType>();
7383 }
7384
7385 // If we still haven't found a prototype to use but there are arguments to
7386 // the call, diagnose this as calling a function without a prototype.
7387 // However, if we found a function declaration, check to see if
7388 // -Wdeprecated-non-prototype was disabled where the function was declared.
7389 // If so, we will silence the diagnostic here on the assumption that this
7390 // interface is intentional and the user knows what they're doing. We will
7391 // also silence the diagnostic if there is a function declaration but it
7392 // was implicitly defined (the user already gets diagnostics about the
7393 // creation of the implicit function declaration, so the additional warning
7394 // is not helpful).
7395 if (!Proto && !Args.empty() &&
7396 (!FDecl || (!FDecl->isImplicit() &&
7397 !Diags.isIgnored(diag::warn_strict_uses_without_prototype,
7398 FDecl->getLocation()))))
7399 Diag(LParenLoc, diag::warn_strict_uses_without_prototype)
7400 << (FDecl != nullptr) << FDecl;
7401
7402 // Promote the arguments (C99 6.5.2.2p6).
7403 for (unsigned i = 0, e = Args.size(); i != e; i++) {
7404 Expr *Arg = Args[i];
7405
7406 if (Proto && i < Proto->getNumParams()) {
7407 InitializedEntity Entity = InitializedEntity::InitializeParameter(
7408 Context, Proto->getParamType(i), Proto->isParamConsumed(i));
7409 ExprResult ArgE =
7410 PerformCopyInitialization(Entity, SourceLocation(), Arg);
7411 if (ArgE.isInvalid())
7412 return true;
7413
7414 Arg = ArgE.getAs<Expr>();
7415
7416 } else {
7417 ExprResult ArgE = DefaultArgumentPromotion(Arg);
7418
7419 if (ArgE.isInvalid())
7420 return true;
7421
7422 Arg = ArgE.getAs<Expr>();
7423 }
7424
7425 if (RequireCompleteType(Arg->getBeginLoc(), Arg->getType(),
7426 diag::err_call_incomplete_argument, Arg))
7427 return ExprError();
7428
7429 TheCall->setArg(i, Arg);
7430 }
7431 TheCall->computeDependence();
7432 }
7433
7434 if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(FDecl))
7435 if (!Method->isStatic())
7436 return ExprError(Diag(LParenLoc, diag::err_member_call_without_object)
7437 << Fn->getSourceRange());
7438
7439 // Check for sentinels
7440 if (NDecl)
7441 DiagnoseSentinelCalls(NDecl, LParenLoc, Args);
7442
7443 // Warn for unions passing across security boundary (CMSE).
7444 if (FuncT != nullptr && FuncT->getCmseNSCallAttr()) {
7445 for (unsigned i = 0, e = Args.size(); i != e; i++) {
7446 if (const auto *RT =
7447 dyn_cast<RecordType>(Args[i]->getType().getCanonicalType())) {
7448 if (RT->getDecl()->isOrContainsUnion())
7449 Diag(Args[i]->getBeginLoc(), diag::warn_cmse_nonsecure_union)
7450 << 0 << i;
7451 }
7452 }
7453 }
7454
7455 // Do special checking on direct calls to functions.
7456 if (FDecl) {
7457 if (CheckFunctionCall(FDecl, TheCall, Proto))
7458 return ExprError();
7459
7460 checkFortifiedBuiltinMemoryFunction(FDecl, TheCall);
7461
7462 if (BuiltinID)
7463 return CheckBuiltinFunctionCall(FDecl, BuiltinID, TheCall);
7464 } else if (NDecl) {
7465 if (CheckPointerCall(NDecl, TheCall, Proto))
7466 return ExprError();
7467 } else {
7468 if (CheckOtherCall(TheCall, Proto))
7469 return ExprError();
7470 }
7471
7472 return CheckForImmediateInvocation(MaybeBindToTemporary(TheCall), FDecl);
7473}
7474
7475ExprResult
7476Sema::ActOnCompoundLiteral(SourceLocation LParenLoc, ParsedType Ty,
7477 SourceLocation RParenLoc, Expr *InitExpr) {
7478 assert(Ty && "ActOnCompoundLiteral(): missing type")(static_cast <bool> (Ty && "ActOnCompoundLiteral(): missing type"
) ? void (0) : __assert_fail ("Ty && \"ActOnCompoundLiteral(): missing type\""
, "clang/lib/Sema/SemaExpr.cpp", 7478, __extension__ __PRETTY_FUNCTION__
))
;
7479 assert(InitExpr && "ActOnCompoundLiteral(): missing expression")(static_cast <bool> (InitExpr && "ActOnCompoundLiteral(): missing expression"
) ? void (0) : __assert_fail ("InitExpr && \"ActOnCompoundLiteral(): missing expression\""
, "clang/lib/Sema/SemaExpr.cpp", 7479, __extension__ __PRETTY_FUNCTION__
))
;
7480
7481 TypeSourceInfo *TInfo;
7482 QualType literalType = GetTypeFromParser(Ty, &TInfo);
7483 if (!TInfo)
7484 TInfo = Context.getTrivialTypeSourceInfo(literalType);
7485
7486 return BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc, InitExpr);
7487}
7488
7489ExprResult
7490Sema::BuildCompoundLiteralExpr(SourceLocation LParenLoc, TypeSourceInfo *TInfo,
7491 SourceLocation RParenLoc, Expr *LiteralExpr) {
7492 QualType literalType = TInfo->getType();
7493
7494 if (literalType->isArrayType()) {
7495 if (RequireCompleteSizedType(
7496 LParenLoc, Context.getBaseElementType(literalType),
7497 diag::err_array_incomplete_or_sizeless_type,
7498 SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd())))
7499 return ExprError();
7500 if (literalType->isVariableArrayType()) {
7501 // C2x 6.7.9p4: An entity of variable length array type shall not be
7502 // initialized except by an empty initializer.
7503 //
7504 // The C extension warnings are issued from ParseBraceInitializer() and
7505 // do not need to be issued here. However, we continue to issue an error
7506 // in the case there are initializers or we are compiling C++. We allow
7507 // use of VLAs in C++, but it's not clear we want to allow {} to zero
7508 // init a VLA in C++ in all cases (such as with non-trivial constructors).
7509 // FIXME: should we allow this construct in C++ when it makes sense to do
7510 // so?
7511 std::optional<unsigned> NumInits;
7512 if (const auto *ILE = dyn_cast<InitListExpr>(LiteralExpr))
7513 NumInits = ILE->getNumInits();
7514 if ((LangOpts.CPlusPlus || NumInits.value_or(0)) &&
7515 !tryToFixVariablyModifiedVarType(TInfo, literalType, LParenLoc,
7516 diag::err_variable_object_no_init))
7517 return ExprError();
7518 }
7519 } else if (!literalType->isDependentType() &&
7520 RequireCompleteType(LParenLoc, literalType,
7521 diag::err_typecheck_decl_incomplete_type,
7522 SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd())))
7523 return ExprError();
7524
7525 InitializedEntity Entity
7526 = InitializedEntity::InitializeCompoundLiteralInit(TInfo);
7527 InitializationKind Kind
7528 = InitializationKind::CreateCStyleCast(LParenLoc,
7529 SourceRange(LParenLoc, RParenLoc),
7530 /*InitList=*/true);
7531 InitializationSequence InitSeq(*this, Entity, Kind, LiteralExpr);
7532 ExprResult Result = InitSeq.Perform(*this, Entity, Kind, LiteralExpr,
7533 &literalType);
7534 if (Result.isInvalid())
7535 return ExprError();
7536 LiteralExpr = Result.get();
7537
7538 bool isFileScope = !CurContext->isFunctionOrMethod();
7539
7540 // In C, compound literals are l-values for some reason.
7541 // For GCC compatibility, in C++, file-scope array compound literals with
7542 // constant initializers are also l-values, and compound literals are
7543 // otherwise prvalues.
7544 //
7545 // (GCC also treats C++ list-initialized file-scope array prvalues with
7546 // constant initializers as l-values, but that's non-conforming, so we don't
7547 // follow it there.)
7548 //
7549 // FIXME: It would be better to handle the lvalue cases as materializing and
7550 // lifetime-extending a temporary object, but our materialized temporaries
7551 // representation only supports lifetime extension from a variable, not "out
7552 // of thin air".
7553 // FIXME: For C++, we might want to instead lifetime-extend only if a pointer
7554 // is bound to the result of applying array-to-pointer decay to the compound
7555 // literal.
7556 // FIXME: GCC supports compound literals of reference type, which should
7557 // obviously have a value kind derived from the kind of reference involved.
7558 ExprValueKind VK =
7559 (getLangOpts().CPlusPlus && !(isFileScope && literalType->isArrayType()))
7560 ? VK_PRValue
7561 : VK_LValue;
7562
7563 if (isFileScope)
7564 if (auto ILE = dyn_cast<InitListExpr>(LiteralExpr))
7565 for (unsigned i = 0, j = ILE->getNumInits(); i != j; i++) {
7566 Expr *Init = ILE->getInit(i);
7567 ILE->setInit(i, ConstantExpr::Create(Context, Init));
7568 }
7569
7570 auto *E = new (Context) CompoundLiteralExpr(LParenLoc, TInfo, literalType,
7571 VK, LiteralExpr, isFileScope);
7572 if (isFileScope) {
7573 if (!LiteralExpr->isTypeDependent() &&
7574 !LiteralExpr->isValueDependent() &&
7575 !literalType->isDependentType()) // C99 6.5.2.5p3
7576 if (CheckForConstantInitializer(LiteralExpr, literalType))
7577 return ExprError();
7578 } else if (literalType.getAddressSpace() != LangAS::opencl_private &&
7579 literalType.getAddressSpace() != LangAS::Default) {
7580 // Embedded-C extensions to C99 6.5.2.5:
7581 // "If the compound literal occurs inside the body of a function, the
7582 // type name shall not be qualified by an address-space qualifier."
7583 Diag(LParenLoc, diag::err_compound_literal_with_address_space)
7584 << SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd());
7585 return ExprError();
7586 }
7587
7588 if (!isFileScope && !getLangOpts().CPlusPlus) {
7589 // Compound literals that have automatic storage duration are destroyed at
7590 // the end of the scope in C; in C++, they're just temporaries.
7591
7592 // Emit diagnostics if it is or contains a C union type that is non-trivial
7593 // to destruct.
7594 if (E->getType().hasNonTrivialToPrimitiveDestructCUnion())
7595 checkNonTrivialCUnion(E->getType(), E->getExprLoc(),
7596 NTCUC_CompoundLiteral, NTCUK_Destruct);
7597
7598 // Diagnose jumps that enter or exit the lifetime of the compound literal.
7599 if (literalType.isDestructedType()) {
7600 Cleanup.setExprNeedsCleanups(true);
7601 ExprCleanupObjects.push_back(E);
7602 getCurFunction()->setHasBranchProtectedScope();
7603 }
7604 }
7605
7606 if (E->getType().hasNonTrivialToPrimitiveDefaultInitializeCUnion() ||
7607 E->getType().hasNonTrivialToPrimitiveCopyCUnion())
7608 checkNonTrivialCUnionInInitializer(E->getInitializer(),
7609 E->getInitializer()->getExprLoc());
7610
7611 return MaybeBindToTemporary(E);
7612}
7613
7614ExprResult
7615Sema::ActOnInitList(SourceLocation LBraceLoc, MultiExprArg InitArgList,
7616 SourceLocation RBraceLoc) {
7617 // Only produce each kind of designated initialization diagnostic once.
7618 SourceLocation FirstDesignator;
7619 bool DiagnosedArrayDesignator = false;
7620 bool DiagnosedNestedDesignator = false;
7621 bool DiagnosedMixedDesignator = false;
7622
7623 // Check that any designated initializers are syntactically valid in the
7624 // current language mode.
7625 for (unsigned I = 0, E = InitArgList.size(); I != E; ++I) {
7626 if (auto *DIE = dyn_cast<DesignatedInitExpr>(InitArgList[I])) {
7627 if (FirstDesignator.isInvalid())
7628 FirstDesignator = DIE->getBeginLoc();
7629
7630 if (!getLangOpts().CPlusPlus)
7631 break;
7632
7633 if (!DiagnosedNestedDesignator && DIE->size() > 1) {
7634 DiagnosedNestedDesignator = true;
7635 Diag(DIE->getBeginLoc(), diag::ext_designated_init_nested)
7636 << DIE->getDesignatorsSourceRange();
7637 }
7638
7639 for (auto &Desig : DIE->designators()) {
7640 if (!Desig.isFieldDesignator() && !DiagnosedArrayDesignator) {
7641 DiagnosedArrayDesignator = true;
7642 Diag(Desig.getBeginLoc(), diag::ext_designated_init_array)
7643 << Desig.getSourceRange();
7644 }
7645 }
7646
7647 if (!DiagnosedMixedDesignator &&
7648 !isa<DesignatedInitExpr>(InitArgList[0])) {
7649 DiagnosedMixedDesignator = true;
7650 Diag(DIE->getBeginLoc(), diag::ext_designated_init_mixed)
7651 << DIE->getSourceRange();
7652 Diag(InitArgList[0]->getBeginLoc(), diag::note_designated_init_mixed)
7653 << InitArgList[0]->getSourceRange();
7654 }
7655 } else if (getLangOpts().CPlusPlus && !DiagnosedMixedDesignator &&
7656 isa<DesignatedInitExpr>(InitArgList[0])) {
7657 DiagnosedMixedDesignator = true;
7658 auto *DIE = cast<DesignatedInitExpr>(InitArgList[0]);
7659 Diag(DIE->getBeginLoc(), diag::ext_designated_init_mixed)
7660 << DIE->getSourceRange();
7661 Diag(InitArgList[I]->getBeginLoc(), diag::note_designated_init_mixed)
7662 << InitArgList[I]->getSourceRange();
7663 }
7664 }
7665
7666 if (FirstDesignator.isValid()) {
7667 // Only diagnose designated initiaization as a C++20 extension if we didn't
7668 // already diagnose use of (non-C++20) C99 designator syntax.
7669 if (getLangOpts().CPlusPlus && !DiagnosedArrayDesignator &&
7670 !DiagnosedNestedDesignator && !DiagnosedMixedDesignator) {
7671 Diag(FirstDesignator, getLangOpts().CPlusPlus20
7672 ? diag::warn_cxx17_compat_designated_init
7673 : diag::ext_cxx_designated_init);
7674 } else if (!getLangOpts().CPlusPlus && !getLangOpts().C99) {
7675 Diag(FirstDesignator, diag::ext_designated_init);
7676 }
7677 }
7678
7679 return BuildInitList(LBraceLoc, InitArgList, RBraceLoc);
7680}
7681
7682ExprResult
7683Sema::BuildInitList(SourceLocation LBraceLoc, MultiExprArg InitArgList,
7684 SourceLocation RBraceLoc) {
7685 // Semantic analysis for initializers is done by ActOnDeclarator() and
7686 // CheckInitializer() - it requires knowledge of the object being initialized.
7687
7688 // Immediately handle non-overload placeholders. Overloads can be
7689 // resolved contextually, but everything else here can't.
7690 for (unsigned I = 0, E = InitArgList.size(); I != E; ++I) {
7691 if (InitArgList[I]->getType()->isNonOverloadPlaceholderType()) {
7692 ExprResult result = CheckPlaceholderExpr(InitArgList[I]);
7693
7694 // Ignore failures; dropping the entire initializer list because
7695 // of one failure would be terrible for indexing/etc.
7696 if (result.isInvalid()) continue;
7697
7698 InitArgList[I] = result.get();
7699 }
7700 }
7701
7702 InitListExpr *E = new (Context) InitListExpr(Context, LBraceLoc, InitArgList,
7703 RBraceLoc);
7704 E->setType(Context.VoidTy); // FIXME: just a place holder for now.
7705 return E;
7706}
7707
7708/// Do an explicit extend of the given block pointer if we're in ARC.
7709void Sema::maybeExtendBlockObject(ExprResult &E) {
7710 assert(E.get()->getType()->isBlockPointerType())(static_cast <bool> (E.get()->getType()->isBlockPointerType
()) ? void (0) : __assert_fail ("E.get()->getType()->isBlockPointerType()"
, "clang/lib/Sema/SemaExpr.cpp", 7710, __extension__ __PRETTY_FUNCTION__
))
;
7711 assert(E.get()->isPRValue())(static_cast <bool> (E.get()->isPRValue()) ? void (0
) : __assert_fail ("E.get()->isPRValue()", "clang/lib/Sema/SemaExpr.cpp"
, 7711, __extension__ __PRETTY_FUNCTION__))
;
7712
7713 // Only do this in an r-value context.
7714 if (!getLangOpts().ObjCAutoRefCount) return;
7715
7716 E = ImplicitCastExpr::Create(
7717 Context, E.get()->getType(), CK_ARCExtendBlockObject, E.get(),
7718 /*base path*/ nullptr, VK_PRValue, FPOptionsOverride());
7719 Cleanup.setExprNeedsCleanups(true);
7720}
7721
7722/// Prepare a conversion of the given expression to an ObjC object
7723/// pointer type.
7724CastKind Sema::PrepareCastToObjCObjectPointer(ExprResult &E) {
7725 QualType type = E.get()->getType();
7726 if (type->isObjCObjectPointerType()) {
7727 return CK_BitCast;
7728 } else if (type->isBlockPointerType()) {
7729 maybeExtendBlockObject(E);
7730 return CK_BlockPointerToObjCPointerCast;
7731 } else {
7732 assert(type->isPointerType())(static_cast <bool> (type->isPointerType()) ? void (
0) : __assert_fail ("type->isPointerType()", "clang/lib/Sema/SemaExpr.cpp"
, 7732, __extension__ __PRETTY_FUNCTION__))
;
7733 return CK_CPointerToObjCPointerCast;
7734 }
7735}
7736
7737/// Prepares for a scalar cast, performing all the necessary stages
7738/// except the final cast and returning the kind required.
7739CastKind Sema::PrepareScalarCast(ExprResult &Src, QualType DestTy) {
7740 // Both Src and Dest are scalar types, i.e. arithmetic or pointer.
7741 // Also, callers should have filtered out the invalid cases with
7742 // pointers. Everything else should be possible.
7743
7744 QualType SrcTy = Src.get()->getType();
7745 if (Context.hasSameUnqualifiedType(SrcTy, DestTy))
7746 return CK_NoOp;
7747
7748 switch (Type::ScalarTypeKind SrcKind = SrcTy->getScalarTypeKind()) {
7749 case Type::STK_MemberPointer:
7750 llvm_unreachable("member pointer type in C")::llvm::llvm_unreachable_internal("member pointer type in C",
"clang/lib/Sema/SemaExpr.cpp", 7750)
;
7751
7752 case Type::STK_CPointer:
7753 case Type::STK_BlockPointer:
7754 case Type::STK_ObjCObjectPointer:
7755 switch (DestTy->getScalarTypeKind()) {
7756 case Type::STK_CPointer: {
7757 LangAS SrcAS = SrcTy->getPointeeType().getAddressSpace();
7758 LangAS DestAS = DestTy->getPointeeType().getAddressSpace();
7759 if (SrcAS != DestAS)
7760 return CK_AddressSpaceConversion;
7761 if (Context.hasCvrSimilarType(SrcTy, DestTy))
7762 return CK_NoOp;
7763 return CK_BitCast;
7764 }
7765 case Type::STK_BlockPointer:
7766 return (SrcKind == Type::STK_BlockPointer
7767 ? CK_BitCast : CK_AnyPointerToBlockPointerCast);
7768 case Type::STK_ObjCObjectPointer:
7769 if (SrcKind == Type::STK_ObjCObjectPointer)
7770 return CK_BitCast;
7771 if (SrcKind == Type::STK_CPointer)
7772 return CK_CPointerToObjCPointerCast;
7773 maybeExtendBlockObject(Src);
7774 return CK_BlockPointerToObjCPointerCast;
7775 case Type::STK_Bool:
7776 return CK_PointerToBoolean;
7777 case Type::STK_Integral:
7778 return CK_PointerToIntegral;
7779 case Type::STK_Floating:
7780 case Type::STK_FloatingComplex:
7781 case Type::STK_IntegralComplex:
7782 case Type::STK_MemberPointer:
7783 case Type::STK_FixedPoint:
7784 llvm_unreachable("illegal cast from pointer")::llvm::llvm_unreachable_internal("illegal cast from pointer"
, "clang/lib/Sema/SemaExpr.cpp", 7784)
;
7785 }
7786 llvm_unreachable("Should have returned before this")::llvm::llvm_unreachable_internal("Should have returned before this"
, "clang/lib/Sema/SemaExpr.cpp", 7786)
;
7787
7788 case Type::STK_FixedPoint:
7789 switch (DestTy->getScalarTypeKind()) {
7790 case Type::STK_FixedPoint:
7791 return CK_FixedPointCast;
7792 case Type::STK_Bool:
7793 return CK_FixedPointToBoolean;
7794 case Type::STK_Integral:
7795 return CK_FixedPointToIntegral;
7796 case Type::STK_Floating:
7797 return CK_FixedPointToFloating;
7798 case Type::STK_IntegralComplex:
7799 case Type::STK_FloatingComplex:
7800 Diag(Src.get()->getExprLoc(),
7801 diag::err_unimplemented_conversion_with_fixed_point_type)
7802 << DestTy;
7803 return CK_IntegralCast;
7804 case Type::STK_CPointer:
7805 case Type::STK_ObjCObjectPointer:
7806 case Type::STK_BlockPointer:
7807 case Type::STK_MemberPointer:
7808 llvm_unreachable("illegal cast to pointer type")::llvm::llvm_unreachable_internal("illegal cast to pointer type"
, "clang/lib/Sema/SemaExpr.cpp", 7808)
;
7809 }
7810 llvm_unreachable("Should have returned before this")::llvm::llvm_unreachable_internal("Should have returned before this"
, "clang/lib/Sema/SemaExpr.cpp", 7810)
;
7811
7812 case Type::STK_Bool: // casting from bool is like casting from an integer
7813 case Type::STK_Integral:
7814 switch (DestTy->getScalarTypeKind()) {
7815 case Type::STK_CPointer:
7816 case Type::STK_ObjCObjectPointer:
7817 case Type::STK_BlockPointer:
7818 if (Src.get()->isNullPointerConstant(Context,
7819 Expr::NPC_ValueDependentIsNull))
7820 return CK_NullToPointer;
7821 return CK_IntegralToPointer;
7822 case Type::STK_Bool:
7823 return CK_IntegralToBoolean;
7824 case Type::STK_Integral:
7825 return CK_IntegralCast;
7826 case Type::STK_Floating:
7827 return CK_IntegralToFloating;
7828 case Type::STK_IntegralComplex:
7829 Src = ImpCastExprToType(Src.get(),
7830 DestTy->castAs<ComplexType>()->getElementType(),
7831 CK_IntegralCast);
7832 return CK_IntegralRealToComplex;
7833 case Type::STK_FloatingComplex:
7834 Src = ImpCastExprToType(Src.get(),
7835 DestTy->castAs<ComplexType>()->getElementType(),
7836 CK_IntegralToFloating);
7837 return CK_FloatingRealToComplex;
7838 case Type::STK_MemberPointer:
7839 llvm_unreachable("member pointer type in C")::llvm::llvm_unreachable_internal("member pointer type in C",
"clang/lib/Sema/SemaExpr.cpp", 7839)
;
7840 case Type::STK_FixedPoint:
7841 return CK_IntegralToFixedPoint;
7842 }
7843 llvm_unreachable("Should have returned before this")::llvm::llvm_unreachable_internal("Should have returned before this"
, "clang/lib/Sema/SemaExpr.cpp", 7843)
;
7844
7845 case Type::STK_Floating:
7846 switch (DestTy->getScalarTypeKind()) {
7847 case Type::STK_Floating:
7848 return CK_FloatingCast;
7849 case Type::STK_Bool:
7850 return CK_FloatingToBoolean;
7851 case Type::STK_Integral:
7852 return CK_FloatingToIntegral;
7853 case Type::STK_FloatingComplex:
7854 Src = ImpCastExprToType(Src.get(),
7855 DestTy->castAs<ComplexType>()->getElementType(),
7856 CK_FloatingCast);
7857 return CK_FloatingRealToComplex;
7858 case Type::STK_IntegralComplex:
7859 Src = ImpCastExprToType(Src.get(),
7860 DestTy->castAs<ComplexType>()->getElementType(),
7861 CK_FloatingToIntegral);
7862 return CK_IntegralRealToComplex;
7863 case Type::STK_CPointer:
7864 case Type::STK_ObjCObjectPointer:
7865 case Type::STK_BlockPointer:
7866 llvm_unreachable("valid float->pointer cast?")::llvm::llvm_unreachable_internal("valid float->pointer cast?"
, "clang/lib/Sema/SemaExpr.cpp", 7866)
;
7867 case Type::STK_MemberPointer:
7868 llvm_unreachable("member pointer type in C")::llvm::llvm_unreachable_internal("member pointer type in C",
"clang/lib/Sema/SemaExpr.cpp", 7868)
;
7869 case Type::STK_FixedPoint:
7870 return CK_FloatingToFixedPoint;
7871 }
7872 llvm_unreachable("Should have returned before this")::llvm::llvm_unreachable_internal("Should have returned before this"
, "clang/lib/Sema/SemaExpr.cpp", 7872)
;
7873
7874 case Type::STK_FloatingComplex:
7875 switch (DestTy->getScalarTypeKind()) {
7876 case Type::STK_FloatingComplex:
7877 return CK_FloatingComplexCast;
7878 case Type::STK_IntegralComplex:
7879 return CK_FloatingComplexToIntegralComplex;
7880 case Type::STK_Floating: {
7881 QualType ET = SrcTy->castAs<ComplexType>()->getElementType();
7882 if (Context.hasSameType(ET, DestTy))
7883 return CK_FloatingComplexToReal;
7884 Src = ImpCastExprToType(Src.get(), ET, CK_FloatingComplexToReal);
7885 return CK_FloatingCast;
7886 }
7887 case Type::STK_Bool:
7888 return CK_FloatingComplexToBoolean;
7889 case Type::STK_Integral:
7890 Src = ImpCastExprToType(Src.get(),
7891 SrcTy->castAs<ComplexType>()->getElementType(),
7892 CK_FloatingComplexToReal);
7893 return CK_FloatingToIntegral;
7894 case Type::STK_CPointer:
7895 case Type::STK_ObjCObjectPointer:
7896 case Type::STK_BlockPointer:
7897 llvm_unreachable("valid complex float->pointer cast?")::llvm::llvm_unreachable_internal("valid complex float->pointer cast?"
, "clang/lib/Sema/SemaExpr.cpp", 7897)
;
7898 case Type::STK_MemberPointer:
7899 llvm_unreachable("member pointer type in C")::llvm::llvm_unreachable_internal("member pointer type in C",
"clang/lib/Sema/SemaExpr.cpp", 7899)
;
7900 case Type::STK_FixedPoint:
7901 Diag(Src.get()->getExprLoc(),
7902 diag::err_unimplemented_conversion_with_fixed_point_type)
7903 << SrcTy;
7904 return CK_IntegralCast;
7905 }
7906 llvm_unreachable("Should have returned before this")::llvm::llvm_unreachable_internal("Should have returned before this"
, "clang/lib/Sema/SemaExpr.cpp", 7906)
;
7907
7908 case Type::STK_IntegralComplex:
7909 switch (DestTy->getScalarTypeKind()) {
7910 case Type::STK_FloatingComplex:
7911 return CK_IntegralComplexToFloatingComplex;
7912 case Type::STK_IntegralComplex:
7913 return CK_IntegralComplexCast;
7914 case Type::STK_Integral: {
7915 QualType ET = SrcTy->castAs<ComplexType>()->getElementType();
7916 if (Context.hasSameType(ET, DestTy))
7917 return CK_IntegralComplexToReal;
7918 Src = ImpCastExprToType(Src.get(), ET, CK_IntegralComplexToReal);
7919 return CK_IntegralCast;
7920 }
7921 case Type::STK_Bool:
7922 return CK_IntegralComplexToBoolean;
7923 case Type::STK_Floating:
7924 Src = ImpCastExprToType(Src.get(),
7925 SrcTy->castAs<ComplexType>()->getElementType(),
7926 CK_IntegralComplexToReal);
7927 return CK_IntegralToFloating;
7928 case Type::STK_CPointer:
7929 case Type::STK_ObjCObjectPointer:
7930 case Type::STK_BlockPointer:
7931 llvm_unreachable("valid complex int->pointer cast?")::llvm::llvm_unreachable_internal("valid complex int->pointer cast?"
, "clang/lib/Sema/SemaExpr.cpp", 7931)
;
7932 case Type::STK_MemberPointer:
7933 llvm_unreachable("member pointer type in C")::llvm::llvm_unreachable_internal("member pointer type in C",
"clang/lib/Sema/SemaExpr.cpp", 7933)
;
7934 case Type::STK_FixedPoint:
7935 Diag(Src.get()->getExprLoc(),
7936 diag::err_unimplemented_conversion_with_fixed_point_type)
7937 << SrcTy;
7938 return CK_IntegralCast;
7939 }
7940 llvm_unreachable("Should have returned before this")::llvm::llvm_unreachable_internal("Should have returned before this"
, "clang/lib/Sema/SemaExpr.cpp", 7940)
;
7941 }
7942
7943 llvm_unreachable("Unhandled scalar cast")::llvm::llvm_unreachable_internal("Unhandled scalar cast", "clang/lib/Sema/SemaExpr.cpp"
, 7943)
;
7944}
7945
7946static bool breakDownVectorType(QualType type, uint64_t &len,
7947 QualType &eltType) {
7948 // Vectors are simple.
7949 if (const VectorType *vecType = type->getAs<VectorType>()) {
7950 len = vecType->getNumElements();
7951 eltType = vecType->getElementType();
7952 assert(eltType->isScalarType())(static_cast <bool> (eltType->isScalarType()) ? void
(0) : __assert_fail ("eltType->isScalarType()", "clang/lib/Sema/SemaExpr.cpp"
, 7952, __extension__ __PRETTY_FUNCTION__))
;
7953 return true;
7954 }
7955
7956 // We allow lax conversion to and from non-vector types, but only if
7957 // they're real types (i.e. non-complex, non-pointer scalar types).
7958 if (!type->isRealType()) return false;
7959
7960 len = 1;
7961 eltType = type;
7962 return true;
7963}
7964
7965/// Are the two types SVE-bitcast-compatible types? I.e. is bitcasting from the
7966/// first SVE type (e.g. an SVE VLAT) to the second type (e.g. an SVE VLST)
7967/// allowed?
7968///
7969/// This will also return false if the two given types do not make sense from
7970/// the perspective of SVE bitcasts.
7971bool Sema::isValidSveBitcast(QualType srcTy, QualType destTy) {
7972 assert(srcTy->isVectorType() || destTy->isVectorType())(static_cast <bool> (srcTy->isVectorType() || destTy
->isVectorType()) ? void (0) : __assert_fail ("srcTy->isVectorType() || destTy->isVectorType()"
, "clang/lib/Sema/SemaExpr.cpp", 7972, __extension__ __PRETTY_FUNCTION__
))
;
7973
7974 auto ValidScalableConversion = [](QualType FirstType, QualType SecondType) {
7975 if (!FirstType->isSVESizelessBuiltinType())
7976 return false;
7977
7978 const auto *VecTy = SecondType->getAs<VectorType>();
7979 return VecTy &&
7980 VecTy->getVectorKind() == VectorType::SveFixedLengthDataVector;
7981 };
7982
7983 return ValidScalableConversion(srcTy, destTy) ||
7984 ValidScalableConversion(destTy, srcTy);
7985}
7986
7987/// Are the two types RVV-bitcast-compatible types? I.e. is bitcasting from the
7988/// first RVV type (e.g. an RVV scalable type) to the second type (e.g. an RVV
7989/// VLS type) allowed?
7990///
7991/// This will also return false if the two given types do not make sense from
7992/// the perspective of RVV bitcasts.
7993bool Sema::isValidRVVBitcast(QualType srcTy, QualType destTy) {
7994 assert(srcTy->isVectorType() || destTy->isVectorType())(static_cast <bool> (srcTy->isVectorType() || destTy
->isVectorType()) ? void (0) : __assert_fail ("srcTy->isVectorType() || destTy->isVectorType()"
, "clang/lib/Sema/SemaExpr.cpp", 7994, __extension__ __PRETTY_FUNCTION__
))
;
7995
7996 auto ValidScalableConversion = [](QualType FirstType, QualType SecondType) {
7997 if (!FirstType->isRVVSizelessBuiltinType())
7998 return false;
7999
8000 const auto *VecTy = SecondType->getAs<VectorType>();
8001 return VecTy &&
8002 VecTy->getVectorKind() == VectorType::RVVFixedLengthDataVector;
8003 };
8004
8005 return ValidScalableConversion(srcTy, destTy) ||
8006 ValidScalableConversion(destTy, srcTy);
8007}
8008
8009/// Are the two types matrix types and do they have the same dimensions i.e.
8010/// do they have the same number of rows and the same number of columns?
8011bool Sema::areMatrixTypesOfTheSameDimension(QualType srcTy, QualType destTy) {
8012 if (!destTy->isMatrixType() || !srcTy->isMatrixType())
8013 return false;
8014
8015 const ConstantMatrixType *matSrcType = srcTy->getAs<ConstantMatrixType>();
8016 const ConstantMatrixType *matDestType = destTy->getAs<ConstantMatrixType>();
8017
8018 return matSrcType->getNumRows() == matDestType->getNumRows() &&
8019 matSrcType->getNumColumns() == matDestType->getNumColumns();
8020}
8021
8022bool Sema::areVectorTypesSameSize(QualType SrcTy, QualType DestTy) {
8023 assert(DestTy->isVectorType() || SrcTy->isVectorType())(static_cast <bool> (DestTy->isVectorType() || SrcTy
->isVectorType()) ? void (0) : __assert_fail ("DestTy->isVectorType() || SrcTy->isVectorType()"
, "clang/lib/Sema/SemaExpr.cpp", 8023, __extension__ __PRETTY_FUNCTION__
))
;
8024
8025 uint64_t SrcLen, DestLen;
8026 QualType SrcEltTy, DestEltTy;
8027 if (!breakDownVectorType(SrcTy, SrcLen, SrcEltTy))
8028 return false;
8029 if (!breakDownVectorType(DestTy, DestLen, DestEltTy))
8030 return false;
8031
8032 // ASTContext::getTypeSize will return the size rounded up to a
8033 // power of 2, so instead of using that, we need to use the raw
8034 // element size multiplied by the element count.
8035 uint64_t SrcEltSize = Context.getTypeSize(SrcEltTy);
8036 uint64_t DestEltSize = Context.getTypeSize(DestEltTy);
8037
8038 return (SrcLen * SrcEltSize == DestLen * DestEltSize);
8039}
8040
8041// This returns true if at least one of the types is an altivec vector.
8042bool Sema::anyAltivecTypes(QualType SrcTy, QualType DestTy) {
8043 assert((DestTy->isVectorType() || SrcTy->isVectorType()) &&(static_cast <bool> ((DestTy->isVectorType() || SrcTy
->isVectorType()) && "expected at least one type to be a vector here"
) ? void (0) : __assert_fail ("(DestTy->isVectorType() || SrcTy->isVectorType()) && \"expected at least one type to be a vector here\""
, "clang/lib/Sema/SemaExpr.cpp", 8044, __extension__ __PRETTY_FUNCTION__
))
8044 "expected at least one type to be a vector here")(static_cast <bool> ((DestTy->isVectorType() || SrcTy
->isVectorType()) && "expected at least one type to be a vector here"
) ? void (0) : __assert_fail ("(DestTy->isVectorType() || SrcTy->isVectorType()) && \"expected at least one type to be a vector here\""
, "clang/lib/Sema/SemaExpr.cpp", 8044, __extension__ __PRETTY_FUNCTION__
))
;
8045
8046 bool IsSrcTyAltivec =
8047 SrcTy->isVectorType() && ((SrcTy->castAs<VectorType>()->getVectorKind() ==
8048 VectorType::AltiVecVector) ||
8049 (SrcTy->castAs<VectorType>()->getVectorKind() ==
8050 VectorType::AltiVecBool) ||
8051 (SrcTy->castAs<VectorType>()->getVectorKind() ==
8052 VectorType::AltiVecPixel));
8053
8054 bool IsDestTyAltivec = DestTy->isVectorType() &&
8055 ((DestTy->castAs<VectorType>()->getVectorKind() ==
8056 VectorType::AltiVecVector) ||
8057 (DestTy->castAs<VectorType>()->getVectorKind() ==
8058 VectorType::AltiVecBool) ||
8059 (DestTy->castAs<VectorType>()->getVectorKind() ==
8060 VectorType::AltiVecPixel));
8061
8062 return (IsSrcTyAltivec || IsDestTyAltivec);
8063}
8064
8065/// Are the two types lax-compatible vector types? That is, given
8066/// that one of them is a vector, do they have equal storage sizes,
8067/// where the storage size is the number of elements times the element
8068/// size?
8069///
8070/// This will also return false if either of the types is neither a
8071/// vector nor a real type.
8072bool Sema::areLaxCompatibleVectorTypes(QualType srcTy, QualType destTy) {
8073 assert(destTy->isVectorType() || srcTy->isVectorType())(static_cast <bool> (destTy->isVectorType() || srcTy
->isVectorType()) ? void (0) : __assert_fail ("destTy->isVectorType() || srcTy->isVectorType()"
, "clang/lib/Sema/SemaExpr.cpp", 8073, __extension__ __PRETTY_FUNCTION__
))
;
8074
8075 // Disallow lax conversions between scalars and ExtVectors (these
8076 // conversions are allowed for other vector types because common headers
8077 // depend on them). Most scalar OP ExtVector cases are handled by the
8078 // splat path anyway, which does what we want (convert, not bitcast).
8079 // What this rules out for ExtVectors is crazy things like char4*float.
8080 if (srcTy->isScalarType() && destTy->isExtVectorType()) return false;
8081 if (destTy->isScalarType() && srcTy->isExtVectorType()) return false;
8082
8083 return areVectorTypesSameSize(srcTy, destTy);
8084}
8085
8086/// Is this a legal conversion between two types, one of which is
8087/// known to be a vector type?
8088bool Sema::isLaxVectorConversion(QualType srcTy, QualType destTy) {
8089 assert(destTy->isVectorType() || srcTy->isVectorType())(static_cast <bool> (destTy->isVectorType() || srcTy
->isVectorType()) ? void (0) : __assert_fail ("destTy->isVectorType() || srcTy->isVectorType()"
, "clang/lib/Sema/SemaExpr.cpp", 8089, __extension__ __PRETTY_FUNCTION__
))
;
8090
8091 switch (Context.getLangOpts().getLaxVectorConversions()) {
8092 case LangOptions::LaxVectorConversionKind::None:
8093 return false;
8094
8095 case LangOptions::LaxVectorConversionKind::Integer:
8096 if (!srcTy->isIntegralOrEnumerationType()) {
8097 auto *Vec = srcTy->getAs<VectorType>();
8098 if (!Vec || !Vec->getElementType()->isIntegralOrEnumerationType())
8099 return false;
8100 }
8101 if (!destTy->isIntegralOrEnumerationType()) {
8102 auto *Vec = destTy->getAs<VectorType>();
8103 if (!Vec || !Vec->getElementType()->isIntegralOrEnumerationType())
8104 return false;
8105 }
8106 // OK, integer (vector) -> integer (vector) bitcast.
8107 break;
8108
8109 case LangOptions::LaxVectorConversionKind::All:
8110 break;
8111 }
8112
8113 return areLaxCompatibleVectorTypes(srcTy, destTy);
8114}
8115
8116bool Sema::CheckMatrixCast(SourceRange R, QualType DestTy, QualType SrcTy,
8117 CastKind &Kind) {
8118 if (SrcTy->isMatrixType() && DestTy->isMatrixType()) {
8119 if (!areMatrixTypesOfTheSameDimension(SrcTy, DestTy)) {
8120 return Diag(R.getBegin(), diag::err_invalid_conversion_between_matrixes)
8121 << DestTy << SrcTy << R;
8122 }
8123 } else if (SrcTy->isMatrixType()) {
8124 return Diag(R.getBegin(),
8125 diag::err_invalid_conversion_between_matrix_and_type)
8126 << SrcTy << DestTy << R;
8127 } else if (DestTy->isMatrixType()) {
8128 return Diag(R.getBegin(),
8129 diag::err_invalid_conversion_between_matrix_and_type)
8130 << DestTy << SrcTy << R;
8131 }
8132
8133 Kind = CK_MatrixCast;
8134 return false;
8135}
8136
8137bool Sema::CheckVectorCast(SourceRange R, QualType VectorTy, QualType Ty,
8138 CastKind &Kind) {
8139 assert(VectorTy->isVectorType() && "Not a vector type!")(static_cast <bool> (VectorTy->isVectorType() &&
"Not a vector type!") ? void (0) : __assert_fail ("VectorTy->isVectorType() && \"Not a vector type!\""
, "clang/lib/Sema/SemaExpr.cpp", 8139, __extension__ __PRETTY_FUNCTION__
))
;
8140
8141 if (Ty->isVectorType() || Ty->isIntegralType(Context)) {
8142 if (!areLaxCompatibleVectorTypes(Ty, VectorTy))
8143 return Diag(R.getBegin(),
8144 Ty->isVectorType() ?
8145 diag::err_invalid_conversion_between_vectors :
8146 diag::err_invalid_conversion_between_vector_and_integer)
8147 << VectorTy << Ty << R;
8148 } else
8149 return Diag(R.getBegin(),
8150 diag::err_invalid_conversion_between_vector_and_scalar)
8151 << VectorTy << Ty << R;
8152
8153 Kind = CK_BitCast;
8154 return false;
8155}
8156
8157ExprResult Sema::prepareVectorSplat(QualType VectorTy, Expr *SplattedExpr) {
8158 QualType DestElemTy = VectorTy->castAs<VectorType>()->getElementType();
8159
8160 if (DestElemTy == SplattedExpr->getType())
8161 return SplattedExpr;
8162
8163 assert(DestElemTy->isFloatingType() ||(static_cast <bool> (DestElemTy->isFloatingType() ||
DestElemTy->isIntegralOrEnumerationType()) ? void (0) : __assert_fail
("DestElemTy->isFloatingType() || DestElemTy->isIntegralOrEnumerationType()"
, "clang/lib/Sema/SemaExpr.cpp", 8164, __extension__ __PRETTY_FUNCTION__
))
8164 DestElemTy->isIntegralOrEnumerationType())(static_cast <bool> (DestElemTy->isFloatingType() ||
DestElemTy->isIntegralOrEnumerationType()) ? void (0) : __assert_fail
("DestElemTy->isFloatingType() || DestElemTy->isIntegralOrEnumerationType()"
, "clang/lib/Sema/SemaExpr.cpp", 8164, __extension__ __PRETTY_FUNCTION__
))
;
8165
8166 CastKind CK;
8167 if (VectorTy->isExtVectorType() && SplattedExpr->getType()->isBooleanType()) {
8168 // OpenCL requires that we convert `true` boolean expressions to -1, but
8169 // only when splatting vectors.
8170 if (DestElemTy->isFloatingType()) {
8171 // To avoid having to have a CK_BooleanToSignedFloating cast kind, we cast
8172 // in two steps: boolean to signed integral, then to floating.
8173 ExprResult CastExprRes = ImpCastExprToType(SplattedExpr, Context.IntTy,
8174 CK_BooleanToSignedIntegral);
8175 SplattedExpr = CastExprRes.get();
8176 CK = CK_IntegralToFloating;
8177 } else {
8178 CK = CK_BooleanToSignedIntegral;
8179 }
8180 } else {
8181 ExprResult CastExprRes = SplattedExpr;
8182 CK = PrepareScalarCast(CastExprRes, DestElemTy);
8183 if (CastExprRes.isInvalid())
8184 return ExprError();
8185 SplattedExpr = CastExprRes.get();
8186 }
8187 return ImpCastExprToType(SplattedExpr, DestElemTy, CK);
8188}
8189
8190ExprResult Sema::CheckExtVectorCast(SourceRange R, QualType DestTy,
8191 Expr *CastExpr, CastKind &Kind) {
8192 assert(DestTy->isExtVectorType() && "Not an extended vector type!")(static_cast <bool> (DestTy->isExtVectorType() &&
"Not an extended vector type!") ? void (0) : __assert_fail (
"DestTy->isExtVectorType() && \"Not an extended vector type!\""
, "clang/lib/Sema/SemaExpr.cpp", 8192, __extension__ __PRETTY_FUNCTION__
))
;
8193
8194 QualType SrcTy = CastExpr->getType();
8195
8196 // If SrcTy is a VectorType, the total size must match to explicitly cast to
8197 // an ExtVectorType.
8198 // In OpenCL, casts between vectors of different types are not allowed.
8199 // (See OpenCL 6.2).
8200 if (SrcTy->isVectorType()) {
8201 if (!areLaxCompatibleVectorTypes(SrcTy, DestTy) ||
8202 (getLangOpts().OpenCL &&
8203 !Context.hasSameUnqualifiedType(DestTy, SrcTy))) {
8204 Diag(R.getBegin(),diag::err_invalid_conversion_between_ext_vectors)
8205 << DestTy << SrcTy << R;
8206 return ExprError();
8207 }
8208 Kind = CK_BitCast;
8209 return CastExpr;
8210 }
8211
8212 // All non-pointer scalars can be cast to ExtVector type. The appropriate
8213 // conversion will take place first from scalar to elt type, and then
8214 // splat from elt type to vector.
8215 if (SrcTy->isPointerType())
8216 return Diag(R.getBegin(),
8217 diag::err_invalid_conversion_between_vector_and_scalar)
8218 << DestTy << SrcTy << R;
8219
8220 Kind = CK_VectorSplat;
8221 return prepareVectorSplat(DestTy, CastExpr);
8222}
8223
8224ExprResult
8225Sema::ActOnCastExpr(Scope *S, SourceLocation LParenLoc,
8226 Declarator &D, ParsedType &Ty,
8227 SourceLocation RParenLoc, Expr *CastExpr) {
8228 assert(!D.isInvalidType() && (CastExpr != nullptr) &&(static_cast <bool> (!D.isInvalidType() && (CastExpr
!= nullptr) && "ActOnCastExpr(): missing type or expr"
) ? void (0) : __assert_fail ("!D.isInvalidType() && (CastExpr != nullptr) && \"ActOnCastExpr(): missing type or expr\""
, "clang/lib/Sema/SemaExpr.cpp", 8229, __extension__ __PRETTY_FUNCTION__
))
8229 "ActOnCastExpr(): missing type or expr")(static_cast <bool> (!D.isInvalidType() && (CastExpr
!= nullptr) && "ActOnCastExpr(): missing type or expr"
) ? void (0) : __assert_fail ("!D.isInvalidType() && (CastExpr != nullptr) && \"ActOnCastExpr(): missing type or expr\""
, "clang/lib/Sema/SemaExpr.cpp", 8229, __extension__ __PRETTY_FUNCTION__
))
;
8230
8231 TypeSourceInfo *castTInfo = GetTypeForDeclaratorCast(D, CastExpr->getType());
8232 if (D.isInvalidType())
8233 return ExprError();
8234
8235 if (getLangOpts().CPlusPlus) {
8236 // Check that there are no default arguments (C++ only).
8237 CheckExtraCXXDefaultArguments(D);
8238 } else {
8239 // Make sure any TypoExprs have been dealt with.
8240 ExprResult Res = CorrectDelayedTyposInExpr(CastExpr);
8241 if (!Res.isUsable())
8242 return ExprError();
8243 CastExpr = Res.get();
8244 }
8245
8246 checkUnusedDeclAttributes(D);
8247
8248 QualType castType = castTInfo->getType();
8249 Ty = CreateParsedType(castType, castTInfo);
8250
8251 bool isVectorLiteral = false;
8252
8253 // Check for an altivec or OpenCL literal,
8254 // i.e. all the elements are integer constants.
8255 ParenExpr *PE = dyn_cast<ParenExpr>(CastExpr);
8256 ParenListExpr *PLE = dyn_cast<ParenListExpr>(CastExpr);
8257 if ((getLangOpts().AltiVec || getLangOpts().ZVector || getLangOpts().OpenCL)
8258 && castType->isVectorType() && (PE || PLE)) {
8259 if (PLE && PLE->getNumExprs() == 0) {
8260 Diag(PLE->getExprLoc(), diag::err_altivec_empty_initializer);
8261 return ExprError();
8262 }
8263 if (PE || PLE->getNumExprs() == 1) {
8264 Expr *E = (PE ? PE->getSubExpr() : PLE->getExpr(0));
8265 if (!E->isTypeDependent() && !E->getType()->isVectorType())
8266 isVectorLiteral = true;
8267 }
8268 else
8269 isVectorLiteral = true;
8270 }
8271
8272 // If this is a vector initializer, '(' type ')' '(' init, ..., init ')'
8273 // then handle it as such.
8274 if (isVectorLiteral)
8275 return BuildVectorLiteral(LParenLoc, RParenLoc, CastExpr, castTInfo);
8276
8277 // If the Expr being casted is a ParenListExpr, handle it specially.
8278 // This is not an AltiVec-style cast, so turn the ParenListExpr into a
8279 // sequence of BinOp comma operators.
8280 if (isa<ParenListExpr>(CastExpr)) {
8281 ExprResult Result = MaybeConvertParenListExprToParenExpr(S, CastExpr);
8282 if (Result.isInvalid()) return ExprError();
8283 CastExpr = Result.get();
8284 }
8285
8286 if (getLangOpts().CPlusPlus && !castType->isVoidType())
8287 Diag(LParenLoc, diag::warn_old_style_cast) << CastExpr->getSourceRange();
8288
8289 CheckTollFreeBridgeCast(castType, CastExpr);
8290
8291 CheckObjCBridgeRelatedCast(castType, CastExpr);
8292
8293 DiscardMisalignedMemberAddress(castType.getTypePtr(), CastExpr);
8294
8295 return BuildCStyleCastExpr(LParenLoc, castTInfo, RParenLoc, CastExpr);
8296}
8297
8298ExprResult Sema::BuildVectorLiteral(SourceLocation LParenLoc,
8299 SourceLocation RParenLoc, Expr *E,
8300 TypeSourceInfo *TInfo) {
8301 assert((isa<ParenListExpr>(E) || isa<ParenExpr>(E)) &&(static_cast <bool> ((isa<ParenListExpr>(E) || isa
<ParenExpr>(E)) && "Expected paren or paren list expression"
) ? void (0) : __assert_fail ("(isa<ParenListExpr>(E) || isa<ParenExpr>(E)) && \"Expected paren or paren list expression\""
, "clang/lib/Sema/SemaExpr.cpp", 8302, __extension__ __PRETTY_FUNCTION__
))
8302 "Expected paren or paren list expression")(static_cast <bool> ((isa<ParenListExpr>(E) || isa
<ParenExpr>(E)) && "Expected paren or paren list expression"
) ? void (0) : __assert_fail ("(isa<ParenListExpr>(E) || isa<ParenExpr>(E)) && \"Expected paren or paren list expression\""
, "clang/lib/Sema/SemaExpr.cpp", 8302, __extension__ __PRETTY_FUNCTION__
))
;
8303
8304 Expr **exprs;
8305 unsigned numExprs;
8306 Expr *subExpr;
8307 SourceLocation LiteralLParenLoc, LiteralRParenLoc;
8308 if (ParenListExpr *PE = dyn_cast<ParenListExpr>(E)) {
8309 LiteralLParenLoc = PE->getLParenLoc();
8310 LiteralRParenLoc = PE->getRParenLoc();
8311 exprs = PE->getExprs();
8312 numExprs = PE->getNumExprs();
8313 } else { // isa<ParenExpr> by assertion at function entrance
8314 LiteralLParenLoc = cast<ParenExpr>(E)->getLParen();
8315 LiteralRParenLoc = cast<ParenExpr>(E)->getRParen();
8316 subExpr = cast<ParenExpr>(E)->getSubExpr();
8317 exprs = &subExpr;
8318 numExprs = 1;
8319 }
8320
8321 QualType Ty = TInfo->getType();
8322 assert(Ty->isVectorType() && "Expected vector type")(static_cast <bool> (Ty->isVectorType() && "Expected vector type"
) ? void (0) : __assert_fail ("Ty->isVectorType() && \"Expected vector type\""
, "clang/lib/Sema/SemaExpr.cpp", 8322, __extension__ __PRETTY_FUNCTION__
))
;
8323
8324 SmallVector<Expr *, 8> initExprs;
8325 const VectorType *VTy = Ty->castAs<VectorType>();
8326 unsigned numElems = VTy->getNumElements();
8327
8328 // '(...)' form of vector initialization in AltiVec: the number of
8329 // initializers must be one or must match the size of the vector.
8330 // If a single value is specified in the initializer then it will be
8331 // replicated to all the components of the vector
8332 if (CheckAltivecInitFromScalar(E->getSourceRange(), Ty,
8333 VTy->getElementType()))
8334 return ExprError();
8335 if (ShouldSplatAltivecScalarInCast(VTy)) {
8336 // The number of initializers must be one or must match the size of the
8337 // vector. If a single value is specified in the initializer then it will
8338 // be replicated to all the components of the vector
8339 if (numExprs == 1) {
8340 QualType ElemTy = VTy->getElementType();
8341 ExprResult Literal = DefaultLvalueConversion(exprs[0]);
8342 if (Literal.isInvalid())
8343 return ExprError();
8344 Literal = ImpCastExprToType(Literal.get(), ElemTy,
8345 PrepareScalarCast(Literal, ElemTy));
8346 return BuildCStyleCastExpr(LParenLoc, TInfo, RParenLoc, Literal.get());
8347 }
8348 else if (numExprs < numElems) {
8349 Diag(E->getExprLoc(),
8350 diag::err_incorrect_number_of_vector_initializers);
8351 return ExprError();
8352 }
8353 else
8354 initExprs.append(exprs, exprs + numExprs);
8355 }
8356 else {
8357 // For OpenCL, when the number of initializers is a single value,
8358 // it will be replicated to all components of the vector.
8359 if (getLangOpts().OpenCL &&
8360 VTy->getVectorKind() == VectorType::GenericVector &&
8361 numExprs == 1) {
8362 QualType ElemTy = VTy->getElementType();
8363 ExprResult Literal = DefaultLvalueConversion(exprs[0]);
8364 if (Literal.isInvalid())
8365 return ExprError();
8366 Literal = ImpCastExprToType(Literal.get(), ElemTy,
8367 PrepareScalarCast(Literal, ElemTy));
8368 return BuildCStyleCastExpr(LParenLoc, TInfo, RParenLoc, Literal.get());
8369 }
8370
8371 initExprs.append(exprs, exprs + numExprs);
8372 }
8373 // FIXME: This means that pretty-printing the final AST will produce curly
8374 // braces instead of the original commas.
8375 InitListExpr *initE = new (Context) InitListExpr(Context, LiteralLParenLoc,
8376 initExprs, LiteralRParenLoc);
8377 initE->setType(Ty);
8378 return BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc, initE);
8379}
8380
8381/// This is not an AltiVec-style cast or or C++ direct-initialization, so turn
8382/// the ParenListExpr into a sequence of comma binary operators.
8383ExprResult
8384Sema::MaybeConvertParenListExprToParenExpr(Scope *S, Expr *OrigExpr) {
8385 ParenListExpr *E = dyn_cast<ParenListExpr>(OrigExpr);
8386 if (!E)
8387 return OrigExpr;
8388
8389 ExprResult Result(E->getExpr(0));
8390
8391 for (unsigned i = 1, e = E->getNumExprs(); i != e && !Result.isInvalid(); ++i)
8392 Result = ActOnBinOp(S, E->getExprLoc(), tok::comma, Result.get(),
8393 E->getExpr(i));
8394
8395 if (Result.isInvalid()) return ExprError();
8396
8397 return ActOnParenExpr(E->getLParenLoc(), E->getRParenLoc(), Result.get());
8398}
8399
8400ExprResult Sema::ActOnParenListExpr(SourceLocation L,
8401 SourceLocation R,
8402 MultiExprArg Val) {
8403 return ParenListExpr::Create(Context, L, Val, R);
8404}
8405
8406/// Emit a specialized diagnostic when one expression is a null pointer
8407/// constant and the other is not a pointer. Returns true if a diagnostic is
8408/// emitted.
8409bool Sema::DiagnoseConditionalForNull(Expr *LHSExpr, Expr *RHSExpr,
8410 SourceLocation QuestionLoc) {
8411 Expr *NullExpr = LHSExpr;
8412 Expr *NonPointerExpr = RHSExpr;
8413 Expr::NullPointerConstantKind NullKind =
8414 NullExpr->isNullPointerConstant(Context,
8415 Expr::NPC_ValueDependentIsNotNull);
8416
8417 if (NullKind == Expr::NPCK_NotNull) {
8418 NullExpr = RHSExpr;
8419 NonPointerExpr = LHSExpr;
8420 NullKind =
8421 NullExpr->isNullPointerConstant(Context,
8422 Expr::NPC_ValueDependentIsNotNull);
8423 }
8424
8425 if (NullKind == Expr::NPCK_NotNull)
8426 return false;
8427
8428 if (NullKind == Expr::NPCK_ZeroExpression)
8429 return false;
8430
8431 if (NullKind == Expr::NPCK_ZeroLiteral) {
8432 // In this case, check to make sure that we got here from a "NULL"
8433 // string in the source code.
8434 NullExpr = NullExpr->IgnoreParenImpCasts();
8435 SourceLocation loc = NullExpr->getExprLoc();
8436 if (!findMacroSpelling(loc, "NULL"))
8437 return false;
8438 }
8439
8440 int DiagType = (NullKind == Expr::NPCK_CXX11_nullptr);
8441 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands_null)
8442 << NonPointerExpr->getType() << DiagType
8443 << NonPointerExpr->getSourceRange();
8444 return true;
8445}
8446
8447/// Return false if the condition expression is valid, true otherwise.
8448static bool checkCondition(Sema &S, Expr *Cond, SourceLocation QuestionLoc) {
8449 QualType CondTy = Cond->getType();
8450
8451 // OpenCL v1.1 s6.3.i says the condition cannot be a floating point type.
8452 if (S.getLangOpts().OpenCL && CondTy->isFloatingType()) {
8453 S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_nonfloat)
8454 << CondTy << Cond->getSourceRange();
8455 return true;
8456 }
8457
8458 // C99 6.5.15p2
8459 if (CondTy->isScalarType()) return false;
8460
8461 S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_scalar)
8462 << CondTy << Cond->getSourceRange();
8463 return true;
8464}
8465
8466/// Return false if the NullExpr can be promoted to PointerTy,
8467/// true otherwise.
8468static bool checkConditionalNullPointer(Sema &S, ExprResult &NullExpr,
8469 QualType PointerTy) {
8470 if ((!PointerTy->isAnyPointerType() && !PointerTy->isBlockPointerType()) ||
8471 !NullExpr.get()->isNullPointerConstant(S.Context,
8472 Expr::NPC_ValueDependentIsNull))
8473 return true;
8474
8475 NullExpr = S.ImpCastExprToType(NullExpr.get(), PointerTy, CK_NullToPointer);
8476 return false;
8477}
8478
8479/// Checks compatibility between two pointers and return the resulting
8480/// type.
8481static QualType checkConditionalPointerCompatibility(Sema &S, ExprResult &LHS,
8482 ExprResult &RHS,
8483 SourceLocation Loc) {
8484 QualType LHSTy = LHS.get()->getType();
8485 QualType RHSTy = RHS.get()->getType();
8486
8487 if (S.Context.hasSameType(LHSTy, RHSTy)) {
8488 // Two identical pointers types are always compatible.
8489 return S.Context.getCommonSugaredType(LHSTy, RHSTy);
8490 }
8491
8492 QualType lhptee, rhptee;
8493
8494 // Get the pointee types.
8495 bool IsBlockPointer = false;
8496 if (const BlockPointerType *LHSBTy = LHSTy->getAs<BlockPointerType>()) {
8497 lhptee = LHSBTy->getPointeeType();
8498 rhptee = RHSTy->castAs<BlockPointerType>()->getPointeeType();
8499 IsBlockPointer = true;
8500 } else {
8501 lhptee = LHSTy->castAs<PointerType>()->getPointeeType();
8502 rhptee = RHSTy->castAs<PointerType>()->getPointeeType();
8503 }
8504
8505 // C99 6.5.15p6: If both operands are pointers to compatible types or to
8506 // differently qualified versions of compatible types, the result type is
8507 // a pointer to an appropriately qualified version of the composite
8508 // type.
8509
8510 // Only CVR-qualifiers exist in the standard, and the differently-qualified
8511 // clause doesn't make sense for our extensions. E.g. address space 2 should
8512 // be incompatible with address space 3: they may live on different devices or
8513 // anything.
8514 Qualifiers lhQual = lhptee.getQualifiers();
8515 Qualifiers rhQual = rhptee.getQualifiers();
8516
8517 LangAS ResultAddrSpace = LangAS::Default;
8518 LangAS LAddrSpace = lhQual.getAddressSpace();
8519 LangAS RAddrSpace = rhQual.getAddressSpace();
8520
8521 // OpenCL v1.1 s6.5 - Conversion between pointers to distinct address
8522 // spaces is disallowed.
8523 if (lhQual.isAddressSpaceSupersetOf(rhQual))
8524 ResultAddrSpace = LAddrSpace;
8525 else if (rhQual.isAddressSpaceSupersetOf(lhQual))
8526 ResultAddrSpace = RAddrSpace;
8527 else {
8528 S.Diag(Loc, diag::err_typecheck_op_on_nonoverlapping_address_space_pointers)
8529 << LHSTy << RHSTy << 2 << LHS.get()->getSourceRange()
8530 << RHS.get()->getSourceRange();
8531 return QualType();
8532 }
8533
8534 unsigned MergedCVRQual = lhQual.getCVRQualifiers() | rhQual.getCVRQualifiers();
8535 auto LHSCastKind = CK_BitCast, RHSCastKind = CK_BitCast;
8536 lhQual.removeCVRQualifiers();
8537 rhQual.removeCVRQualifiers();
8538
8539 // OpenCL v2.0 specification doesn't extend compatibility of type qualifiers
8540 // (C99 6.7.3) for address spaces. We assume that the check should behave in
8541 // the same manner as it's defined for CVR qualifiers, so for OpenCL two
8542 // qual types are compatible iff
8543 // * corresponded types are compatible
8544 // * CVR qualifiers are equal
8545 // * address spaces are equal
8546 // Thus for conditional operator we merge CVR and address space unqualified
8547 // pointees and if there is a composite type we return a pointer to it with
8548 // merged qualifiers.
8549 LHSCastKind =
8550 LAddrSpace == ResultAddrSpace ? CK_BitCast : CK_AddressSpaceConversion;
8551 RHSCastKind =
8552 RAddrSpace == ResultAddrSpace ? CK_BitCast : CK_AddressSpaceConversion;
8553 lhQual.removeAddressSpace();
8554 rhQual.removeAddressSpace();
8555
8556 lhptee = S.Context.getQualifiedType(lhptee.getUnqualifiedType(), lhQual);
8557 rhptee = S.Context.getQualifiedType(rhptee.getUnqualifiedType(), rhQual);
8558
8559 QualType CompositeTy = S.Context.mergeTypes(
8560 lhptee, rhptee, /*OfBlockPointer=*/false, /*Unqualified=*/false,
8561 /*BlockReturnType=*/false, /*IsConditionalOperator=*/true);
8562
8563 if (CompositeTy.isNull()) {
8564 // In this situation, we assume void* type. No especially good
8565 // reason, but this is what gcc does, and we do have to pick
8566 // to get a consistent AST.
8567 QualType incompatTy;
8568 incompatTy = S.Context.getPointerType(
8569 S.Context.getAddrSpaceQualType(S.Context.VoidTy, ResultAddrSpace));
8570 LHS = S.ImpCastExprToType(LHS.get(), incompatTy, LHSCastKind);
8571 RHS = S.ImpCastExprToType(RHS.get(), incompatTy, RHSCastKind);
8572
8573 // FIXME: For OpenCL the warning emission and cast to void* leaves a room
8574 // for casts between types with incompatible address space qualifiers.
8575 // For the following code the compiler produces casts between global and
8576 // local address spaces of the corresponded innermost pointees:
8577 // local int *global *a;
8578 // global int *global *b;
8579 // a = (0 ? a : b); // see C99 6.5.16.1.p1.
8580 S.Diag(Loc, diag::ext_typecheck_cond_incompatible_pointers)
8581 << LHSTy << RHSTy << LHS.get()->getSourceRange()
8582 << RHS.get()->getSourceRange();
8583
8584 return incompatTy;
8585 }
8586
8587 // The pointer types are compatible.
8588 // In case of OpenCL ResultTy should have the address space qualifier
8589 // which is a superset of address spaces of both the 2nd and the 3rd
8590 // operands of the conditional operator.
8591 QualType ResultTy = [&, ResultAddrSpace]() {
8592 if (S.getLangOpts().OpenCL) {
8593 Qualifiers CompositeQuals = CompositeTy.getQualifiers();
8594 CompositeQuals.setAddressSpace(ResultAddrSpace);
8595 return S.Context
8596 .getQualifiedType(CompositeTy.getUnqualifiedType(), CompositeQuals)
8597 .withCVRQualifiers(MergedCVRQual);
8598 }
8599 return CompositeTy.withCVRQualifiers(MergedCVRQual);
8600 }();
8601 if (IsBlockPointer)
8602 ResultTy = S.Context.getBlockPointerType(ResultTy);
8603 else
8604 ResultTy = S.Context.getPointerType(ResultTy);
8605
8606 LHS = S.ImpCastExprToType(LHS.get(), ResultTy, LHSCastKind);
8607 RHS = S.ImpCastExprToType(RHS.get(), ResultTy, RHSCastKind);
8608 return ResultTy;
8609}
8610
8611/// Return the resulting type when the operands are both block pointers.
8612static QualType checkConditionalBlockPointerCompatibility(Sema &S,
8613 ExprResult &LHS,
8614 ExprResult &RHS,
8615 SourceLocation Loc) {
8616 QualType LHSTy = LHS.get()->getType();
8617 QualType RHSTy = RHS.get()->getType();
8618
8619 if (!LHSTy->isBlockPointerType() || !RHSTy->isBlockPointerType()) {
8620 if (LHSTy->isVoidPointerType() || RHSTy->isVoidPointerType()) {
8621 QualType destType = S.Context.getPointerType(S.Context.VoidTy);
8622 LHS = S.ImpCastExprToType(LHS.get(), destType, CK_BitCast);
8623 RHS = S.ImpCastExprToType(RHS.get(), destType, CK_BitCast);
8624 return destType;
8625 }
8626 S.Diag(Loc, diag::err_typecheck_cond_incompatible_operands)
8627 << LHSTy << RHSTy << LHS.get()->getSourceRange()
8628 << RHS.get()->getSourceRange();
8629 return QualType();
8630 }
8631
8632 // We have 2 block pointer types.
8633 return checkConditionalPointerCompatibility(S, LHS, RHS, Loc);
8634}
8635
8636/// Return the resulting type when the operands are both pointers.
8637static QualType
8638checkConditionalObjectPointersCompatibility(Sema &S, ExprResult &LHS,
8639 ExprResult &RHS,
8640 SourceLocation Loc) {
8641 // get the pointer types
8642 QualType LHSTy = LHS.get()->getType();
8643 QualType RHSTy = RHS.get()->getType();
8644
8645 // get the "pointed to" types
8646 QualType lhptee = LHSTy->castAs<PointerType>()->getPointeeType();
8647 QualType rhptee = RHSTy->castAs<PointerType>()->getPointeeType();
8648
8649 // ignore qualifiers on void (C99 6.5.15p3, clause 6)
8650 if (lhptee->isVoidType() && rhptee->isIncompleteOrObjectType()) {
8651 // Figure out necessary qualifiers (C99 6.5.15p6)
8652 QualType destPointee
8653 = S.Context.getQualifiedType(lhptee, rhptee.getQualifiers());
8654 QualType destType = S.Context.getPointerType(destPointee);
8655 // Add qualifiers if necessary.
8656 LHS = S.ImpCastExprToType(LHS.get(), destType, CK_NoOp);
8657 // Promote to void*.
8658 RHS = S.ImpCastExprToType(RHS.get(), destType, CK_BitCast);
8659 return destType;
8660 }
8661 if (rhptee->isVoidType() && lhptee->isIncompleteOrObjectType()) {
8662 QualType destPointee
8663 = S.Context.getQualifiedType(rhptee, lhptee.getQualifiers());
8664 QualType destType = S.Context.getPointerType(destPointee);
8665 // Add qualifiers if necessary.
8666 RHS = S.ImpCastExprToType(RHS.get(), destType, CK_NoOp);
8667 // Promote to void*.
8668 LHS = S.ImpCastExprToType(LHS.get(), destType, CK_BitCast);
8669 return destType;
8670 }
8671
8672 return checkConditionalPointerCompatibility(S, LHS, RHS, Loc);
8673}
8674
8675/// Return false if the first expression is not an integer and the second
8676/// expression is not a pointer, true otherwise.
8677static bool checkPointerIntegerMismatch(Sema &S, ExprResult &Int,
8678 Expr* PointerExpr, SourceLocation Loc,
8679 bool IsIntFirstExpr) {
8680 if (!PointerExpr->getType()->isPointerType() ||
8681 !Int.get()->getType()->isIntegerType())
8682 return false;
8683
8684 Expr *Expr1 = IsIntFirstExpr ? Int.get() : PointerExpr;
8685 Expr *Expr2 = IsIntFirstExpr ? PointerExpr : Int.get();
8686
8687 S.Diag(Loc, diag::ext_typecheck_cond_pointer_integer_mismatch)
8688 << Expr1->getType() << Expr2->getType()
8689 << Expr1->getSourceRange() << Expr2->getSourceRange();
8690 Int = S.ImpCastExprToType(Int.get(), PointerExpr->getType(),
8691 CK_IntegralToPointer);
8692 return true;
8693}
8694
8695/// Simple conversion between integer and floating point types.
8696///
8697/// Used when handling the OpenCL conditional operator where the
8698/// condition is a vector while the other operands are scalar.
8699///
8700/// OpenCL v1.1 s6.3.i and s6.11.6 together require that the scalar
8701/// types are either integer or floating type. Between the two
8702/// operands, the type with the higher rank is defined as the "result
8703/// type". The other operand needs to be promoted to the same type. No
8704/// other type promotion is allowed. We cannot use
8705/// UsualArithmeticConversions() for this purpose, since it always
8706/// promotes promotable types.
8707static QualType OpenCLArithmeticConversions(Sema &S, ExprResult &LHS,
8708 ExprResult &RHS,
8709 SourceLocation QuestionLoc) {
8710 LHS = S.DefaultFunctionArrayLvalueConversion(LHS.get());
8711 if (LHS.isInvalid())
8712 return QualType();
8713 RHS = S.DefaultFunctionArrayLvalueConversion(RHS.get());
8714 if (RHS.isInvalid())
8715 return QualType();
8716
8717 // For conversion purposes, we ignore any qualifiers.
8718 // For example, "const float" and "float" are equivalent.
8719 QualType LHSType =
8720 S.Context.getCanonicalType(LHS.get()->getType()).getUnqualifiedType();
8721 QualType RHSType =
8722 S.Context.getCanonicalType(RHS.get()->getType()).getUnqualifiedType();
8723
8724 if (!LHSType->isIntegerType() && !LHSType->isRealFloatingType()) {
8725 S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_int_float)
8726 << LHSType << LHS.get()->getSourceRange();
8727 return QualType();
8728 }
8729
8730 if (!RHSType->isIntegerType() && !RHSType->isRealFloatingType()) {
8731 S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_int_float)
8732 << RHSType << RHS.get()->getSourceRange();
8733 return QualType();
8734 }
8735
8736 // If both types are identical, no conversion is needed.
8737 if (LHSType == RHSType)
8738 return LHSType;
8739
8740 // Now handle "real" floating types (i.e. float, double, long double).
8741 if (LHSType->isRealFloatingType() || RHSType->isRealFloatingType())
8742 return handleFloatConversion(S, LHS, RHS, LHSType, RHSType,
8743 /*IsCompAssign = */ false);
8744
8745 // Finally, we have two differing integer types.
8746 return handleIntegerConversion<doIntegralCast, doIntegralCast>
8747 (S, LHS, RHS, LHSType, RHSType, /*IsCompAssign = */ false);
8748}
8749
8750/// Convert scalar operands to a vector that matches the
8751/// condition in length.
8752///
8753/// Used when handling the OpenCL conditional operator where the
8754/// condition is a vector while the other operands are scalar.
8755///
8756/// We first compute the "result type" for the scalar operands
8757/// according to OpenCL v1.1 s6.3.i. Both operands are then converted
8758/// into a vector of that type where the length matches the condition
8759/// vector type. s6.11.6 requires that the element types of the result
8760/// and the condition must have the same number of bits.
8761static QualType
8762OpenCLConvertScalarsToVectors(Sema &S, ExprResult &LHS, ExprResult &RHS,
8763 QualType CondTy, SourceLocation QuestionLoc) {
8764 QualType ResTy = OpenCLArithmeticConversions(S, LHS, RHS, QuestionLoc);
8765 if (ResTy.isNull()) return QualType();
8766
8767 const VectorType *CV = CondTy->getAs<VectorType>();
8768 assert(CV)(static_cast <bool> (CV) ? void (0) : __assert_fail ("CV"
, "clang/lib/Sema/SemaExpr.cpp", 8768, __extension__ __PRETTY_FUNCTION__
))
;
8769
8770 // Determine the vector result type
8771 unsigned NumElements = CV->getNumElements();
8772 QualType VectorTy = S.Context.getExtVectorType(ResTy, NumElements);
8773
8774 // Ensure that all types have the same number of bits
8775 if (S.Context.getTypeSize(CV->getElementType())
8776 != S.Context.getTypeSize(ResTy)) {
8777 // Since VectorTy is created internally, it does not pretty print
8778 // with an OpenCL name. Instead, we just print a description.
8779 std::string EleTyName = ResTy.getUnqualifiedType().getAsString();
8780 SmallString<64> Str;
8781 llvm::raw_svector_ostream OS(Str);
8782 OS << "(vector of " << NumElements << " '" << EleTyName << "' values)";
8783 S.Diag(QuestionLoc, diag::err_conditional_vector_element_size)
8784 << CondTy << OS.str();
8785 return QualType();
8786 }
8787
8788 // Convert operands to the vector result type
8789 LHS = S.ImpCastExprToType(LHS.get(), VectorTy, CK_VectorSplat);
8790 RHS = S.ImpCastExprToType(RHS.get(), VectorTy, CK_VectorSplat);
8791
8792 return VectorTy;
8793}
8794
8795/// Return false if this is a valid OpenCL condition vector
8796static bool checkOpenCLConditionVector(Sema &S, Expr *Cond,
8797 SourceLocation QuestionLoc) {
8798 // OpenCL v1.1 s6.11.6 says the elements of the vector must be of
8799 // integral type.
8800 const VectorType *CondTy = Cond->getType()->getAs<VectorType>();
8801 assert(CondTy)(static_cast <bool> (CondTy) ? void (0) : __assert_fail
("CondTy", "clang/lib/Sema/SemaExpr.cpp", 8801, __extension__
__PRETTY_FUNCTION__))
;
8802 QualType EleTy = CondTy->getElementType();
8803 if (EleTy->isIntegerType()) return false;
8804
8805 S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_nonfloat)
8806 << Cond->getType() << Cond->getSourceRange();
8807 return true;
8808}
8809
8810/// Return false if the vector condition type and the vector
8811/// result type are compatible.
8812///
8813/// OpenCL v1.1 s6.11.6 requires that both vector types have the same
8814/// number of elements, and their element types have the same number
8815/// of bits.
8816static bool checkVectorResult(Sema &S, QualType CondTy, QualType VecResTy,
8817 SourceLocation QuestionLoc) {
8818 const VectorType *CV = CondTy->getAs<VectorType>();
8819 const VectorType *RV = VecResTy->getAs<VectorType>();
8820 assert(CV && RV)(static_cast <bool> (CV && RV) ? void (0) : __assert_fail
("CV && RV", "clang/lib/Sema/SemaExpr.cpp", 8820, __extension__
__PRETTY_FUNCTION__))
;
8821
8822 if (CV->getNumElements() != RV->getNumElements()) {
8823 S.Diag(QuestionLoc, diag::err_conditional_vector_size)
8824 << CondTy << VecResTy;
8825 return true;
8826 }
8827
8828 QualType CVE = CV->getElementType();
8829 QualType RVE = RV->getElementType();
8830
8831 if (S.Context.getTypeSize(CVE) != S.Context.getTypeSize(RVE)) {
8832 S.Diag(QuestionLoc, diag::err_conditional_vector_element_size)
8833 << CondTy << VecResTy;
8834 return true;
8835 }
8836
8837 return false;
8838}
8839
8840/// Return the resulting type for the conditional operator in
8841/// OpenCL (aka "ternary selection operator", OpenCL v1.1
8842/// s6.3.i) when the condition is a vector type.
8843static QualType
8844OpenCLCheckVectorConditional(Sema &S, ExprResult &Cond,
8845 ExprResult &LHS, ExprResult &RHS,
8846 SourceLocation QuestionLoc) {
8847 Cond = S.DefaultFunctionArrayLvalueConversion(Cond.get());
8848 if (Cond.isInvalid())
8849 return QualType();
8850 QualType CondTy = Cond.get()->getType();
8851
8852 if (checkOpenCLConditionVector(S, Cond.get(), QuestionLoc))
8853 return QualType();
8854
8855 // If either operand is a vector then find the vector type of the
8856 // result as specified in OpenCL v1.1 s6.3.i.
8857 if (LHS.get()->getType()->isVectorType() ||
8858 RHS.get()->getType()->isVectorType()) {
8859 bool IsBoolVecLang =
8860 !S.getLangOpts().OpenCL && !S.getLangOpts().OpenCLCPlusPlus;
8861 QualType VecResTy =
8862 S.CheckVectorOperands(LHS, RHS, QuestionLoc,
8863 /*isCompAssign*/ false,
8864 /*AllowBothBool*/ true,
8865 /*AllowBoolConversions*/ false,
8866 /*AllowBooleanOperation*/ IsBoolVecLang,
8867 /*ReportInvalid*/ true);
8868 if (VecResTy.isNull())
8869 return QualType();
8870 // The result type must match the condition type as specified in
8871 // OpenCL v1.1 s6.11.6.
8872 if (checkVectorResult(S, CondTy, VecResTy, QuestionLoc))
8873 return QualType();
8874 return VecResTy;
8875 }
8876
8877 // Both operands are scalar.
8878 return OpenCLConvertScalarsToVectors(S, LHS, RHS, CondTy, QuestionLoc);
8879}
8880
8881/// Return true if the Expr is block type
8882static bool checkBlockType(Sema &S, const Expr *E) {
8883 if (const CallExpr *CE = dyn_cast<CallExpr>(E)) {
8884 QualType Ty = CE->getCallee()->getType();
8885 if (Ty->isBlockPointerType()) {
8886 S.Diag(E->getExprLoc(), diag::err_opencl_ternary_with_block);
8887 return true;
8888 }
8889 }
8890 return false;
8891}
8892
8893/// Note that LHS is not null here, even if this is the gnu "x ?: y" extension.
8894/// In that case, LHS = cond.
8895/// C99 6.5.15
8896QualType Sema::CheckConditionalOperands(ExprResult &Cond, ExprResult &LHS,
8897 ExprResult &RHS, ExprValueKind &VK,
8898 ExprObjectKind &OK,
8899 SourceLocation QuestionLoc) {
8900
8901 ExprResult LHSResult = CheckPlaceholderExpr(LHS.get());
8902 if (!LHSResult.isUsable()) return QualType();
8903 LHS = LHSResult;
8904
8905 ExprResult RHSResult = CheckPlaceholderExpr(RHS.get());
8906 if (!RHSResult.isUsable()) return QualType();
8907 RHS = RHSResult;
8908
8909 // C++ is sufficiently different to merit its own checker.
8910 if (getLangOpts().CPlusPlus)
8911 return CXXCheckConditionalOperands(Cond, LHS, RHS, VK, OK, QuestionLoc);
8912
8913 VK = VK_PRValue;
8914 OK = OK_Ordinary;
8915
8916 if (Context.isDependenceAllowed() &&
8917 (Cond.get()->isTypeDependent() || LHS.get()->isTypeDependent() ||
8918 RHS.get()->isTypeDependent())) {
8919 assert(!getLangOpts().CPlusPlus)(static_cast <bool> (!getLangOpts().CPlusPlus) ? void (
0) : __assert_fail ("!getLangOpts().CPlusPlus", "clang/lib/Sema/SemaExpr.cpp"
, 8919, __extension__ __PRETTY_FUNCTION__))
;
8920 assert((Cond.get()->containsErrors() || LHS.get()->containsErrors() ||(static_cast <bool> ((Cond.get()->containsErrors() ||
LHS.get()->containsErrors() || RHS.get()->containsErrors
()) && "should only occur in error-recovery path.") ?
void (0) : __assert_fail ("(Cond.get()->containsErrors() || LHS.get()->containsErrors() || RHS.get()->containsErrors()) && \"should only occur in error-recovery path.\""
, "clang/lib/Sema/SemaExpr.cpp", 8922, __extension__ __PRETTY_FUNCTION__
))
8921 RHS.get()->containsErrors()) &&(static_cast <bool> ((Cond.get()->containsErrors() ||
LHS.get()->containsErrors() || RHS.get()->containsErrors
()) && "should only occur in error-recovery path.") ?
void (0) : __assert_fail ("(Cond.get()->containsErrors() || LHS.get()->containsErrors() || RHS.get()->containsErrors()) && \"should only occur in error-recovery path.\""
, "clang/lib/Sema/SemaExpr.cpp", 8922, __extension__ __PRETTY_FUNCTION__
))
8922 "should only occur in error-recovery path.")(static_cast <bool> ((Cond.get()->containsErrors() ||
LHS.get()->containsErrors() || RHS.get()->containsErrors
()) && "should only occur in error-recovery path.") ?
void (0) : __assert_fail ("(Cond.get()->containsErrors() || LHS.get()->containsErrors() || RHS.get()->containsErrors()) && \"should only occur in error-recovery path.\""
, "clang/lib/Sema/SemaExpr.cpp", 8922, __extension__ __PRETTY_FUNCTION__
))
;
8923 return Context.DependentTy;
8924 }
8925
8926 // The OpenCL operator with a vector condition is sufficiently
8927 // different to merit its own checker.
8928 if ((getLangOpts().OpenCL && Cond.get()->getType()->isVectorType()) ||
8929 Cond.get()->getType()->isExtVectorType())
8930 return OpenCLCheckVectorConditional(*this, Cond, LHS, RHS, QuestionLoc);
8931
8932 // First, check the condition.
8933 Cond = UsualUnaryConversions(Cond.get());
8934 if (Cond.isInvalid())
8935 return QualType();
8936 if (checkCondition(*this, Cond.get(), QuestionLoc))
8937 return QualType();
8938
8939 // Now check the two expressions.
8940 if (LHS.get()->getType()->isVectorType() ||
8941 RHS.get()->getType()->isVectorType())
8942 return CheckVectorOperands(LHS, RHS, QuestionLoc, /*isCompAssign*/ false,
8943 /*AllowBothBool*/ true,
8944 /*AllowBoolConversions*/ false,
8945 /*AllowBooleanOperation*/ false,
8946 /*ReportInvalid*/ true);
8947
8948 QualType ResTy =
8949 UsualArithmeticConversions(LHS, RHS, QuestionLoc, ACK_Conditional);
8950 if (LHS.isInvalid() || RHS.isInvalid())
8951 return QualType();
8952
8953 QualType LHSTy = LHS.get()->getType();
8954 QualType RHSTy = RHS.get()->getType();
8955
8956 // Diagnose attempts to convert between __ibm128, __float128 and long double
8957 // where such conversions currently can't be handled.
8958 if (unsupportedTypeConversion(*this, LHSTy, RHSTy)) {
8959 Diag(QuestionLoc,
8960 diag::err_typecheck_cond_incompatible_operands) << LHSTy << RHSTy
8961 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
8962 return QualType();
8963 }
8964
8965 // OpenCL v2.0 s6.12.5 - Blocks cannot be used as expressions of the ternary
8966 // selection operator (?:).
8967 if (getLangOpts().OpenCL &&
8968 ((int)checkBlockType(*this, LHS.get()) | (int)checkBlockType(*this, RHS.get()))) {
8969 return QualType();
8970 }
8971
8972 // If both operands have arithmetic type, do the usual arithmetic conversions
8973 // to find a common type: C99 6.5.15p3,5.
8974 if (LHSTy->isArithmeticType() && RHSTy->isArithmeticType()) {
8975 // Disallow invalid arithmetic conversions, such as those between bit-
8976 // precise integers types of different sizes, or between a bit-precise
8977 // integer and another type.
8978 if (ResTy.isNull() && (LHSTy->isBitIntType() || RHSTy->isBitIntType())) {
8979 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands)
8980 << LHSTy << RHSTy << LHS.get()->getSourceRange()
8981 << RHS.get()->getSourceRange();
8982 return QualType();
8983 }
8984
8985 LHS = ImpCastExprToType(LHS.get(), ResTy, PrepareScalarCast(LHS, ResTy));
8986 RHS = ImpCastExprToType(RHS.get(), ResTy, PrepareScalarCast(RHS, ResTy));
8987
8988 return ResTy;
8989 }
8990
8991 // And if they're both bfloat (which isn't arithmetic), that's fine too.
8992 if (LHSTy->isBFloat16Type() && RHSTy->isBFloat16Type()) {
8993 return Context.getCommonSugaredType(LHSTy, RHSTy);
8994 }
8995
8996 // If both operands are the same structure or union type, the result is that
8997 // type.
8998 if (const RecordType *LHSRT = LHSTy->getAs<RecordType>()) { // C99 6.5.15p3
8999 if (const RecordType *RHSRT = RHSTy->getAs<RecordType>())
9000 if (LHSRT->getDecl() == RHSRT->getDecl())
9001 // "If both the operands have structure or union type, the result has
9002 // that type." This implies that CV qualifiers are dropped.
9003 return Context.getCommonSugaredType(LHSTy.getUnqualifiedType(),
9004 RHSTy.getUnqualifiedType());
9005 // FIXME: Type of conditional expression must be complete in C mode.
9006 }
9007
9008 // C99 6.5.15p5: "If both operands have void type, the result has void type."
9009 // The following || allows only one side to be void (a GCC-ism).
9010 if (LHSTy->isVoidType() || RHSTy->isVoidType()) {
9011 QualType ResTy;
9012 if (LHSTy->isVoidType() && RHSTy->isVoidType()) {
9013 ResTy = Context.getCommonSugaredType(LHSTy, RHSTy);
9014 } else if (RHSTy->isVoidType()) {
9015 ResTy = RHSTy;
9016 Diag(RHS.get()->getBeginLoc(), diag::ext_typecheck_cond_one_void)
9017 << RHS.get()->getSourceRange();
9018 } else {
9019 ResTy = LHSTy;
9020 Diag(LHS.get()->getBeginLoc(), diag::ext_typecheck_cond_one_void)
9021 << LHS.get()->getSourceRange();
9022 }
9023 LHS = ImpCastExprToType(LHS.get(), ResTy, CK_ToVoid);
9024 RHS = ImpCastExprToType(RHS.get(), ResTy, CK_ToVoid);
9025 return ResTy;
9026 }
9027
9028 // C2x 6.5.15p7:
9029 // ... if both the second and third operands have nullptr_t type, the
9030 // result also has that type.
9031 if (LHSTy->isNullPtrType() && Context.hasSameType(LHSTy, RHSTy))
9032 return ResTy;
9033
9034 // C99 6.5.15p6 - "if one operand is a null pointer constant, the result has
9035 // the type of the other operand."
9036 if (!checkConditionalNullPointer(*this, RHS, LHSTy)) return LHSTy;
9037 if (!checkConditionalNullPointer(*this, LHS, RHSTy)) return RHSTy;
9038
9039 // All objective-c pointer type analysis is done here.
9040 QualType compositeType = FindCompositeObjCPointerType(LHS, RHS,
9041 QuestionLoc);
9042 if (LHS.isInvalid() || RHS.isInvalid())
9043 return QualType();
9044 if (!compositeType.isNull())
9045 return compositeType;
9046
9047
9048 // Handle block pointer types.
9049 if (LHSTy->isBlockPointerType() || RHSTy->isBlockPointerType())
9050 return checkConditionalBlockPointerCompatibility(*this, LHS, RHS,
9051 QuestionLoc);
9052
9053 // Check constraints for C object pointers types (C99 6.5.15p3,6).
9054 if (LHSTy->isPointerType() && RHSTy->isPointerType())
9055 return checkConditionalObjectPointersCompatibility(*this, LHS, RHS,
9056 QuestionLoc);
9057
9058 // GCC compatibility: soften pointer/integer mismatch. Note that
9059 // null pointers have been filtered out by this point.
9060 if (checkPointerIntegerMismatch(*this, LHS, RHS.get(), QuestionLoc,
9061 /*IsIntFirstExpr=*/true))
9062 return RHSTy;
9063 if (checkPointerIntegerMismatch(*this, RHS, LHS.get(), QuestionLoc,
9064 /*IsIntFirstExpr=*/false))
9065 return LHSTy;
9066
9067 // Allow ?: operations in which both operands have the same
9068 // built-in sizeless type.
9069 if (LHSTy->isSizelessBuiltinType() && Context.hasSameType(LHSTy, RHSTy))
9070 return Context.getCommonSugaredType(LHSTy, RHSTy);
9071
9072 // Emit a better diagnostic if one of the expressions is a null pointer
9073 // constant and the other is not a pointer type. In this case, the user most
9074 // likely forgot to take the address of the other expression.
9075 if (DiagnoseConditionalForNull(LHS.get(), RHS.get(), QuestionLoc))
9076 return QualType();
9077
9078 // Otherwise, the operands are not compatible.
9079 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands)
9080 << LHSTy << RHSTy << LHS.get()->getSourceRange()
9081 << RHS.get()->getSourceRange();
9082 return QualType();
9083}
9084
9085/// FindCompositeObjCPointerType - Helper method to find composite type of
9086/// two objective-c pointer types of the two input expressions.
9087QualType Sema::FindCompositeObjCPointerType(ExprResult &LHS, ExprResult &RHS,
9088 SourceLocation QuestionLoc) {
9089 QualType LHSTy = LHS.get()->getType();
9090 QualType RHSTy = RHS.get()->getType();
9091
9092 // Handle things like Class and struct objc_class*. Here we case the result
9093 // to the pseudo-builtin, because that will be implicitly cast back to the
9094 // redefinition type if an attempt is made to access its fields.
9095 if (LHSTy->isObjCClassType() &&
9096 (Context.hasSameType(RHSTy, Context.getObjCClassRedefinitionType()))) {
9097 RHS = ImpCastExprToType(RHS.get(), LHSTy, CK_CPointerToObjCPointerCast);
9098 return LHSTy;
9099 }
9100 if (RHSTy->isObjCClassType() &&
9101 (Context.hasSameType(LHSTy, Context.getObjCClassRedefinitionType()))) {
9102 LHS = ImpCastExprToType(LHS.get(), RHSTy, CK_CPointerToObjCPointerCast);
9103 return RHSTy;
9104 }
9105 // And the same for struct objc_object* / id
9106 if (LHSTy->isObjCIdType() &&
9107 (Context.hasSameType(RHSTy, Context.getObjCIdRedefinitionType()))) {
9108 RHS = ImpCastExprToType(RHS.get(), LHSTy, CK_CPointerToObjCPointerCast);
9109 return LHSTy;
9110 }
9111 if (RHSTy->isObjCIdType() &&
9112 (Context.hasSameType(LHSTy, Context.getObjCIdRedefinitionType()))) {
9113 LHS = ImpCastExprToType(LHS.get(), RHSTy, CK_CPointerToObjCPointerCast);
9114 return RHSTy;
9115 }
9116 // And the same for struct objc_selector* / SEL
9117 if (Context.isObjCSelType(LHSTy) &&
9118 (Context.hasSameType(RHSTy, Context.getObjCSelRedefinitionType()))) {
9119 RHS = ImpCastExprToType(RHS.get(), LHSTy, CK_BitCast);
9120 return LHSTy;
9121 }
9122 if (Context.isObjCSelType(RHSTy) &&
9123 (Context.hasSameType(LHSTy, Context.getObjCSelRedefinitionType()))) {
9124 LHS = ImpCastExprToType(LHS.get(), RHSTy, CK_BitCast);
9125 return RHSTy;
9126 }
9127 // Check constraints for Objective-C object pointers types.
9128 if (LHSTy->isObjCObjectPointerType() && RHSTy->isObjCObjectPointerType()) {
9129
9130 if (Context.getCanonicalType(LHSTy) == Context.getCanonicalType(RHSTy)) {
9131 // Two identical object pointer types are always compatible.
9132 return LHSTy;
9133 }
9134 const ObjCObjectPointerType *LHSOPT = LHSTy->castAs<ObjCObjectPointerType>();
9135 const ObjCObjectPointerType *RHSOPT = RHSTy->castAs<ObjCObjectPointerType>();
9136 QualType compositeType = LHSTy;
9137
9138 // If both operands are interfaces and either operand can be
9139 // assigned to the other, use that type as the composite
9140 // type. This allows
9141 // xxx ? (A*) a : (B*) b
9142 // where B is a subclass of A.
9143 //
9144 // Additionally, as for assignment, if either type is 'id'
9145 // allow silent coercion. Finally, if the types are
9146 // incompatible then make sure to use 'id' as the composite
9147 // type so the result is acceptable for sending messages to.
9148
9149 // FIXME: Consider unifying with 'areComparableObjCPointerTypes'.
9150 // It could return the composite type.
9151 if (!(compositeType =
9152 Context.areCommonBaseCompatible(LHSOPT, RHSOPT)).isNull()) {
9153 // Nothing more to do.
9154 } else if (Context.canAssignObjCInterfaces(LHSOPT, RHSOPT)) {
9155 compositeType = RHSOPT->isObjCBuiltinType() ? RHSTy : LHSTy;
9156 } else if (Context.canAssignObjCInterfaces(RHSOPT, LHSOPT)) {
9157 compositeType = LHSOPT->isObjCBuiltinType() ? LHSTy : RHSTy;
9158 } else if ((LHSOPT->isObjCQualifiedIdType() ||
9159 RHSOPT->isObjCQualifiedIdType()) &&
9160 Context.ObjCQualifiedIdTypesAreCompatible(LHSOPT, RHSOPT,
9161 true)) {
9162 // Need to handle "id<xx>" explicitly.
9163 // GCC allows qualified id and any Objective-C type to devolve to
9164 // id. Currently localizing to here until clear this should be
9165 // part of ObjCQualifiedIdTypesAreCompatible.
9166 compositeType = Context.getObjCIdType();
9167 } else if (LHSTy->isObjCIdType() || RHSTy->isObjCIdType()) {
9168 compositeType = Context.getObjCIdType();
9169 } else {
9170 Diag(QuestionLoc, diag::ext_typecheck_cond_incompatible_operands)
9171 << LHSTy << RHSTy
9172 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
9173 QualType incompatTy = Context.getObjCIdType();
9174 LHS = ImpCastExprToType(LHS.get(), incompatTy, CK_BitCast);
9175 RHS = ImpCastExprToType(RHS.get(), incompatTy, CK_BitCast);
9176 return incompatTy;
9177 }
9178 // The object pointer types are compatible.
9179 LHS = ImpCastExprToType(LHS.get(), compositeType, CK_BitCast);
9180 RHS = ImpCastExprToType(RHS.get(), compositeType, CK_BitCast);
9181 return compositeType;
9182 }
9183 // Check Objective-C object pointer types and 'void *'
9184 if (LHSTy->isVoidPointerType() && RHSTy->isObjCObjectPointerType()) {
9185 if (getLangOpts().ObjCAutoRefCount) {
9186 // ARC forbids the implicit conversion of object pointers to 'void *',
9187 // so these types are not compatible.
9188 Diag(QuestionLoc, diag::err_cond_voidptr_arc) << LHSTy << RHSTy
9189 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
9190 LHS = RHS = true;
9191 return QualType();
9192 }
9193 QualType lhptee = LHSTy->castAs<PointerType>()->getPointeeType();
9194 QualType rhptee = RHSTy->castAs<ObjCObjectPointerType>()->getPointeeType();
9195 QualType destPointee
9196 = Context.getQualifiedType(lhptee, rhptee.getQualifiers());
9197 QualType destType = Context.getPointerType(destPointee);
9198 // Add qualifiers if necessary.
9199 LHS = ImpCastExprToType(LHS.get(), destType, CK_NoOp);
9200 // Promote to void*.
9201 RHS = ImpCastExprToType(RHS.get(), destType, CK_BitCast);
9202 return destType;
9203 }
9204 if (LHSTy->isObjCObjectPointerType() && RHSTy->isVoidPointerType()) {
9205 if (getLangOpts().ObjCAutoRefCount) {
9206 // ARC forbids the implicit conversion of object pointers to 'void *',
9207 // so these types are not compatible.
9208 Diag(QuestionLoc, diag::err_cond_voidptr_arc) << LHSTy << RHSTy
9209 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
9210 LHS = RHS = true;
9211 return QualType();
9212 }
9213 QualType lhptee = LHSTy->castAs<ObjCObjectPointerType>()->getPointeeType();
9214 QualType rhptee = RHSTy->castAs<PointerType>()->getPointeeType();
9215 QualType destPointee
9216 = Context.getQualifiedType(rhptee, lhptee.getQualifiers());
9217 QualType destType = Context.getPointerType(destPointee);
9218 // Add qualifiers if necessary.
9219 RHS = ImpCastExprToType(RHS.get(), destType, CK_NoOp);
9220 // Promote to void*.
9221 LHS = ImpCastExprToType(LHS.get(), destType, CK_BitCast);
9222 return destType;
9223 }
9224 return QualType();
9225}
9226
9227/// SuggestParentheses - Emit a note with a fixit hint that wraps
9228/// ParenRange in parentheses.
9229static void SuggestParentheses(Sema &Self, SourceLocation Loc,
9230 const PartialDiagnostic &Note,
9231 SourceRange ParenRange) {
9232 SourceLocation EndLoc = Self.getLocForEndOfToken(ParenRange.getEnd());
9233 if (ParenRange.getBegin().isFileID() && ParenRange.getEnd().isFileID() &&
9234 EndLoc.isValid()) {
9235 Self.Diag(Loc, Note)
9236 << FixItHint::CreateInsertion(ParenRange.getBegin(), "(")
9237 << FixItHint::CreateInsertion(EndLoc, ")");
9238 } else {
9239 // We can't display the parentheses, so just show the bare note.
9240 Self.Diag(Loc, Note) << ParenRange;
9241 }
9242}
9243
9244static bool IsArithmeticOp(BinaryOperatorKind Opc) {
9245 return BinaryOperator::isAdditiveOp(Opc) ||
9246 BinaryOperator::isMultiplicativeOp(Opc) ||
9247 BinaryOperator::isShiftOp(Opc) || Opc == BO_And || Opc == BO_Or;
9248 // This only checks for bitwise-or and bitwise-and, but not bitwise-xor and
9249 // not any of the logical operators. Bitwise-xor is commonly used as a
9250 // logical-xor because there is no logical-xor operator. The logical
9251 // operators, including uses of xor, have a high false positive rate for
9252 // precedence warnings.
9253}
9254
9255/// IsArithmeticBinaryExpr - Returns true if E is an arithmetic binary
9256/// expression, either using a built-in or overloaded operator,
9257/// and sets *OpCode to the opcode and *RHSExprs to the right-hand side
9258/// expression.
9259static bool IsArithmeticBinaryExpr(Expr *E, BinaryOperatorKind *Opcode,
9260 Expr **RHSExprs) {
9261 // Don't strip parenthesis: we should not warn if E is in parenthesis.
9262 E = E->IgnoreImpCasts();
9263 E = E->IgnoreConversionOperatorSingleStep();
9264 E = E->IgnoreImpCasts();
9265 if (auto *MTE = dyn_cast<MaterializeTemporaryExpr>(E)) {
9266 E = MTE->getSubExpr();
9267 E = E->IgnoreImpCasts();
9268 }
9269
9270 // Built-in binary operator.
9271 if (BinaryOperator *OP = dyn_cast<BinaryOperator>(E)) {
9272 if (IsArithmeticOp(OP->getOpcode())) {
9273 *Opcode = OP->getOpcode();
9274 *RHSExprs = OP->getRHS();
9275 return true;
9276 }
9277 }
9278
9279 // Overloaded operator.
9280 if (CXXOperatorCallExpr *Call = dyn_cast<CXXOperatorCallExpr>(E)) {
9281 if (Call->getNumArgs() != 2)
9282 return false;
9283
9284 // Make sure this is really a binary operator that is safe to pass into
9285 // BinaryOperator::getOverloadedOpcode(), e.g. it's not a subscript op.
9286 OverloadedOperatorKind OO = Call->getOperator();
9287 if (OO < OO_Plus || OO > OO_Arrow ||
9288 OO == OO_PlusPlus || OO == OO_MinusMinus)
9289 return false;
9290
9291 BinaryOperatorKind OpKind = BinaryOperator::getOverloadedOpcode(OO);
9292 if (IsArithmeticOp(OpKind)) {
9293 *Opcode = OpKind;
9294 *RHSExprs = Call->getArg(1);
9295 return true;
9296 }
9297 }
9298
9299 return false;
9300}
9301
9302/// ExprLooksBoolean - Returns true if E looks boolean, i.e. it has boolean type
9303/// or is a logical expression such as (x==y) which has int type, but is
9304/// commonly interpreted as boolean.
9305static bool ExprLooksBoolean(Expr *E) {
9306 E = E->IgnoreParenImpCasts();
9307
9308 if (E->getType()->isBooleanType())
9309 return true;
9310 if (BinaryOperator *OP = dyn_cast<BinaryOperator>(E))
9311 return OP->isComparisonOp() || OP->isLogicalOp();
9312 if (UnaryOperator *OP = dyn_cast<UnaryOperator>(E))
9313 return OP->getOpcode() == UO_LNot;
9314 if (E->getType()->isPointerType())
9315 return true;
9316 // FIXME: What about overloaded operator calls returning "unspecified boolean
9317 // type"s (commonly pointer-to-members)?
9318
9319 return false;
9320}
9321
9322/// DiagnoseConditionalPrecedence - Emit a warning when a conditional operator
9323/// and binary operator are mixed in a way that suggests the programmer assumed
9324/// the conditional operator has higher precedence, for example:
9325/// "int x = a + someBinaryCondition ? 1 : 2".
9326static void DiagnoseConditionalPrecedence(Sema &Self,
9327 SourceLocation OpLoc,
9328 Expr *Condition,
9329 Expr *LHSExpr,
9330 Expr *RHSExpr) {
9331 BinaryOperatorKind CondOpcode;
9332 Expr *CondRHS;
9333
9334 if (!IsArithmeticBinaryExpr(Condition, &CondOpcode, &CondRHS))
9335 return;
9336 if (!ExprLooksBoolean(CondRHS))
9337 return;
9338
9339 // The condition is an arithmetic binary expression, with a right-
9340 // hand side that looks boolean, so warn.
9341
9342 unsigned DiagID = BinaryOperator::isBitwiseOp(CondOpcode)
9343 ? diag::warn_precedence_bitwise_conditional
9344 : diag::warn_precedence_conditional;
9345
9346 Self.Diag(OpLoc, DiagID)
9347 << Condition->getSourceRange()
9348 << BinaryOperator::getOpcodeStr(CondOpcode);
9349
9350 SuggestParentheses(
9351 Self, OpLoc,
9352 Self.PDiag(diag::note_precedence_silence)
9353 << BinaryOperator::getOpcodeStr(CondOpcode),
9354 SourceRange(Condition->getBeginLoc(), Condition->getEndLoc()));
9355
9356 SuggestParentheses(Self, OpLoc,
9357 Self.PDiag(diag::note_precedence_conditional_first),
9358 SourceRange(CondRHS->getBeginLoc(), RHSExpr->getEndLoc()));
9359}
9360
9361/// Compute the nullability of a conditional expression.
9362static QualType computeConditionalNullability(QualType ResTy, bool IsBin,
9363 QualType LHSTy, QualType RHSTy,
9364 ASTContext &Ctx) {
9365 if (!ResTy->isAnyPointerType())
9366 return ResTy;
9367
9368 auto GetNullability = [](QualType Ty) {
9369 std::optional<NullabilityKind> Kind = Ty->getNullability();
9370 if (Kind) {
9371 // For our purposes, treat _Nullable_result as _Nullable.
9372 if (*Kind == NullabilityKind::NullableResult)
9373 return NullabilityKind::Nullable;
9374 return *Kind;
9375 }
9376 return NullabilityKind::Unspecified;
9377 };
9378
9379 auto LHSKind = GetNullability(LHSTy), RHSKind = GetNullability(RHSTy);
9380 NullabilityKind MergedKind;
9381
9382 // Compute nullability of a binary conditional expression.
9383 if (IsBin) {
9384 if (LHSKind == NullabilityKind::NonNull)
9385 MergedKind = NullabilityKind::NonNull;
9386 else
9387 MergedKind = RHSKind;
9388 // Compute nullability of a normal conditional expression.
9389 } else {
9390 if (LHSKind == NullabilityKind::Nullable ||
9391 RHSKind == NullabilityKind::Nullable)
9392 MergedKind = NullabilityKind::Nullable;
9393 else if (LHSKind == NullabilityKind::NonNull)
9394 MergedKind = RHSKind;
9395 else if (RHSKind == NullabilityKind::NonNull)
9396 MergedKind = LHSKind;
9397 else
9398 MergedKind = NullabilityKind::Unspecified;
9399 }
9400
9401 // Return if ResTy already has the correct nullability.
9402 if (GetNullability(ResTy) == MergedKind)
9403 return ResTy;
9404
9405 // Strip all nullability from ResTy.
9406 while (ResTy->getNullability())
9407 ResTy = ResTy.getSingleStepDesugaredType(Ctx);
9408
9409 // Create a new AttributedType with the new nullability kind.
9410 auto NewAttr = AttributedType::getNullabilityAttrKind(MergedKind);
9411 return Ctx.getAttributedType(NewAttr, ResTy, ResTy);
9412}
9413
9414/// ActOnConditionalOp - Parse a ?: operation. Note that 'LHS' may be null
9415/// in the case of a the GNU conditional expr extension.
9416ExprResult Sema::ActOnConditionalOp(SourceLocation QuestionLoc,
9417 SourceLocation ColonLoc,
9418 Expr *CondExpr, Expr *LHSExpr,
9419 Expr *RHSExpr) {
9420 if (!Context.isDependenceAllowed()) {
9421 // C cannot handle TypoExpr nodes in the condition because it
9422 // doesn't handle dependent types properly, so make sure any TypoExprs have
9423 // been dealt with before checking the operands.
9424 ExprResult CondResult = CorrectDelayedTyposInExpr(CondExpr);
9425 ExprResult LHSResult = CorrectDelayedTyposInExpr(LHSExpr);
9426 ExprResult RHSResult = CorrectDelayedTyposInExpr(RHSExpr);
9427
9428 if (!CondResult.isUsable())
9429 return ExprError();
9430
9431 if (LHSExpr) {
9432 if (!LHSResult.isUsable())
9433 return ExprError();
9434 }
9435
9436 if (!RHSResult.isUsable())
9437 return ExprError();
9438
9439 CondExpr = CondResult.get();
9440 LHSExpr = LHSResult.get();
9441 RHSExpr = RHSResult.get();
9442 }
9443
9444 // If this is the gnu "x ?: y" extension, analyze the types as though the LHS
9445 // was the condition.
9446 OpaqueValueExpr *opaqueValue = nullptr;
9447 Expr *commonExpr = nullptr;
9448 if (!LHSExpr) {
9449 commonExpr = CondExpr;
9450 // Lower out placeholder types first. This is important so that we don't
9451 // try to capture a placeholder. This happens in few cases in C++; such
9452 // as Objective-C++'s dictionary subscripting syntax.
9453 if (commonExpr->hasPlaceholderType()) {
9454 ExprResult result = CheckPlaceholderExpr(commonExpr);
9455 if (!result.isUsable()) return ExprError();
9456 commonExpr = result.get();
9457 }
9458 // We usually want to apply unary conversions *before* saving, except
9459 // in the special case of a C++ l-value conditional.
9460 if (!(getLangOpts().CPlusPlus
9461 && !commonExpr->isTypeDependent()
9462 && commonExpr->getValueKind() == RHSExpr->getValueKind()
9463 && commonExpr->isGLValue()
9464 && commonExpr->isOrdinaryOrBitFieldObject()
9465 && RHSExpr->isOrdinaryOrBitFieldObject()
9466 && Context.hasSameType(commonExpr->getType(), RHSExpr->getType()))) {
9467 ExprResult commonRes = UsualUnaryConversions(commonExpr);
9468 if (commonRes.isInvalid())
9469 return ExprError();
9470 commonExpr = commonRes.get();
9471 }
9472
9473 // If the common expression is a class or array prvalue, materialize it
9474 // so that we can safely refer to it multiple times.
9475 if (commonExpr->isPRValue() && (commonExpr->getType()->isRecordType() ||
9476 commonExpr->getType()->isArrayType())) {
9477 ExprResult MatExpr = TemporaryMaterializationConversion(commonExpr);
9478 if (MatExpr.isInvalid())
9479 return ExprError();
9480 commonExpr = MatExpr.get();
9481 }
9482
9483 opaqueValue = new (Context) OpaqueValueExpr(commonExpr->getExprLoc(),
9484 commonExpr->getType(),
9485 commonExpr->getValueKind(),
9486 commonExpr->getObjectKind(),
9487 commonExpr);
9488 LHSExpr = CondExpr = opaqueValue;
9489 }
9490
9491 QualType LHSTy = LHSExpr->getType(), RHSTy = RHSExpr->getType();
9492 ExprValueKind VK = VK_PRValue;
9493 ExprObjectKind OK = OK_Ordinary;
9494 ExprResult Cond = CondExpr, LHS = LHSExpr, RHS = RHSExpr;
9495 QualType result = CheckConditionalOperands(Cond, LHS, RHS,
9496 VK, OK, QuestionLoc);
9497 if (result.isNull() || Cond.isInvalid() || LHS.isInvalid() ||
9498 RHS.isInvalid())
9499 return ExprError();
9500
9501 DiagnoseConditionalPrecedence(*this, QuestionLoc, Cond.get(), LHS.get(),
9502 RHS.get());
9503
9504 CheckBoolLikeConversion(Cond.get(), QuestionLoc);
9505
9506 result = computeConditionalNullability(result, commonExpr, LHSTy, RHSTy,
9507 Context);
9508
9509 if (!commonExpr)
9510 return new (Context)
9511 ConditionalOperator(Cond.get(), QuestionLoc, LHS.get(), ColonLoc,
9512 RHS.get(), result, VK, OK);
9513
9514 return new (Context) BinaryConditionalOperator(
9515 commonExpr, opaqueValue, Cond.get(), LHS.get(), RHS.get(), QuestionLoc,
9516 ColonLoc, result, VK, OK);
9517}
9518
9519// Check if we have a conversion between incompatible cmse function pointer
9520// types, that is, a conversion between a function pointer with the
9521// cmse_nonsecure_call attribute and one without.
9522static bool IsInvalidCmseNSCallConversion(Sema &S, QualType FromType,
9523 QualType ToType) {
9524 if (const auto *ToFn =
9525 dyn_cast<FunctionType>(S.Context.getCanonicalType(ToType))) {
9526 if (const auto *FromFn =
9527 dyn_cast<FunctionType>(S.Context.getCanonicalType(FromType))) {
9528 FunctionType::ExtInfo ToEInfo = ToFn->getExtInfo();
9529 FunctionType::ExtInfo FromEInfo = FromFn->getExtInfo();
9530
9531 return ToEInfo.getCmseNSCall() != FromEInfo.getCmseNSCall();
9532 }
9533 }
9534 return false;
9535}
9536
9537// checkPointerTypesForAssignment - This is a very tricky routine (despite
9538// being closely modeled after the C99 spec:-). The odd characteristic of this
9539// routine is it effectively iqnores the qualifiers on the top level pointee.
9540// This circumvents the usual type rules specified in 6.2.7p1 & 6.7.5.[1-3].
9541// FIXME: add a couple examples in this comment.
9542static Sema::AssignConvertType
9543checkPointerTypesForAssignment(Sema &S, QualType LHSType, QualType RHSType,
9544 SourceLocation Loc) {
9545 assert(LHSType.isCanonical() && "LHS not canonicalized!")(static_cast <bool> (LHSType.isCanonical() && "LHS not canonicalized!"
) ? void (0) : __assert_fail ("LHSType.isCanonical() && \"LHS not canonicalized!\""
, "clang/lib/Sema/SemaExpr.cpp", 9545, __extension__ __PRETTY_FUNCTION__
))
;
9546 assert(RHSType.isCanonical() && "RHS not canonicalized!")(static_cast <bool> (RHSType.isCanonical() && "RHS not canonicalized!"
) ? void (0) : __assert_fail ("RHSType.isCanonical() && \"RHS not canonicalized!\""
, "clang/lib/Sema/SemaExpr.cpp", 9546, __extension__ __PRETTY_FUNCTION__
))
;
9547
9548 // get the "pointed to" type (ignoring qualifiers at the top level)
9549 const Type *lhptee, *rhptee;
9550 Qualifiers lhq, rhq;
9551 std::tie(lhptee, lhq) =
9552 cast<PointerType>(LHSType)->getPointeeType().split().asPair();
9553 std::tie(rhptee, rhq) =
9554 cast<PointerType>(RHSType)->getPointeeType().split().asPair();
9555
9556 Sema::AssignConvertType ConvTy = Sema::Compatible;
9557
9558 // C99 6.5.16.1p1: This following citation is common to constraints
9559 // 3 & 4 (below). ...and the type *pointed to* by the left has all the
9560 // qualifiers of the type *pointed to* by the right;
9561
9562 // As a special case, 'non-__weak A *' -> 'non-__weak const *' is okay.
9563 if (lhq.getObjCLifetime() != rhq.getObjCLifetime() &&
9564 lhq.compatiblyIncludesObjCLifetime(rhq)) {
9565 // Ignore lifetime for further calculation.
9566 lhq.removeObjCLifetime();
9567 rhq.removeObjCLifetime();
9568 }
9569
9570 if (!lhq.compatiblyIncludes(rhq)) {
9571 // Treat address-space mismatches as fatal.
9572 if (!lhq.isAddressSpaceSupersetOf(rhq))
9573 return Sema::IncompatiblePointerDiscardsQualifiers;
9574
9575 // It's okay to add or remove GC or lifetime qualifiers when converting to
9576 // and from void*.
9577 else if (lhq.withoutObjCGCAttr().withoutObjCLifetime()
9578 .compatiblyIncludes(
9579 rhq.withoutObjCGCAttr().withoutObjCLifetime())
9580 && (lhptee->isVoidType() || rhptee->isVoidType()))
9581 ; // keep old
9582
9583 // Treat lifetime mismatches as fatal.
9584 else if (lhq.getObjCLifetime() != rhq.getObjCLifetime())
9585 ConvTy = Sema::IncompatiblePointerDiscardsQualifiers;
9586
9587 // For GCC/MS compatibility, other qualifier mismatches are treated
9588 // as still compatible in C.
9589 else ConvTy = Sema::CompatiblePointerDiscardsQualifiers;
9590 }
9591
9592 // C99 6.5.16.1p1 (constraint 4): If one operand is a pointer to an object or
9593 // incomplete type and the other is a pointer to a qualified or unqualified
9594 // version of void...
9595 if (lhptee->isVoidType()) {
9596 if (rhptee->isIncompleteOrObjectType())
9597 return ConvTy;
9598
9599 // As an extension, we allow cast to/from void* to function pointer.
9600 assert(rhptee->isFunctionType())(static_cast <bool> (rhptee->isFunctionType()) ? void
(0) : __assert_fail ("rhptee->isFunctionType()", "clang/lib/Sema/SemaExpr.cpp"
, 9600, __extension__ __PRETTY_FUNCTION__))
;
9601 return Sema::FunctionVoidPointer;
9602 }
9603
9604 if (rhptee->isVoidType()) {
9605 if (lhptee->isIncompleteOrObjectType())
9606 return ConvTy;
9607
9608 // As an extension, we allow cast to/from void* to function pointer.
9609 assert(lhptee->isFunctionType())(static_cast <bool> (lhptee->isFunctionType()) ? void
(0) : __assert_fail ("lhptee->isFunctionType()", "clang/lib/Sema/SemaExpr.cpp"
, 9609, __extension__ __PRETTY_FUNCTION__))
;
9610 return Sema::FunctionVoidPointer;
9611 }
9612
9613 if (!S.Diags.isIgnored(
9614 diag::warn_typecheck_convert_incompatible_function_pointer_strict,
9615 Loc) &&
9616 RHSType->isFunctionPointerType() && LHSType->isFunctionPointerType() &&
9617 !S.IsFunctionConversion(RHSType, LHSType, RHSType))
9618 return Sema::IncompatibleFunctionPointerStrict;
9619
9620 // C99 6.5.16.1p1 (constraint 3): both operands are pointers to qualified or
9621 // unqualified versions of compatible types, ...
9622 QualType ltrans = QualType(lhptee, 0), rtrans = QualType(rhptee, 0);
9623 if (!S.Context.typesAreCompatible(ltrans, rtrans)) {
9624 // Check if the pointee types are compatible ignoring the sign.
9625 // We explicitly check for char so that we catch "char" vs
9626 // "unsigned char" on systems where "char" is unsigned.
9627 if (lhptee->isCharType())
9628 ltrans = S.Context.UnsignedCharTy;
9629 else if (lhptee->hasSignedIntegerRepresentation())
9630 ltrans = S.Context.getCorrespondingUnsignedType(ltrans);
9631
9632 if (rhptee->isCharType())
9633 rtrans = S.Context.UnsignedCharTy;
9634 else if (rhptee->hasSignedIntegerRepresentation())
9635 rtrans = S.Context.getCorrespondingUnsignedType(rtrans);
9636
9637 if (ltrans == rtrans) {
9638 // Types are compatible ignoring the sign. Qualifier incompatibility
9639 // takes priority over sign incompatibility because the sign
9640 // warning can be disabled.
9641 if (ConvTy != Sema::Compatible)
9642 return ConvTy;
9643
9644 return Sema::IncompatiblePointerSign;
9645 }
9646
9647 // If we are a multi-level pointer, it's possible that our issue is simply
9648 // one of qualification - e.g. char ** -> const char ** is not allowed. If
9649 // the eventual target type is the same and the pointers have the same
9650 // level of indirection, this must be the issue.
9651 if (isa<PointerType>(lhptee) && isa<PointerType>(rhptee)) {
9652 do {
9653 std::tie(lhptee, lhq) =
9654 cast<PointerType>(lhptee)->getPointeeType().split().asPair();
9655 std::tie(rhptee, rhq) =
9656 cast<PointerType>(rhptee)->getPointeeType().split().asPair();
9657
9658 // Inconsistent address spaces at this point is invalid, even if the
9659 // address spaces would be compatible.
9660 // FIXME: This doesn't catch address space mismatches for pointers of
9661 // different nesting levels, like:
9662 // __local int *** a;
9663 // int ** b = a;
9664 // It's not clear how to actually determine when such pointers are
9665 // invalidly incompatible.
9666 if (lhq.getAddressSpace() != rhq.getAddressSpace())
9667 return Sema::IncompatibleNestedPointerAddressSpaceMismatch;
9668
9669 } while (isa<PointerType>(lhptee) && isa<PointerType>(rhptee));
9670
9671 if (lhptee == rhptee)
9672 return Sema::IncompatibleNestedPointerQualifiers;
9673 }
9674
9675 // General pointer incompatibility takes priority over qualifiers.
9676 if (RHSType->isFunctionPointerType() && LHSType->isFunctionPointerType())
9677 return Sema::IncompatibleFunctionPointer;
9678 return Sema::IncompatiblePointer;
9679 }
9680 if (!S.getLangOpts().CPlusPlus &&
9681 S.IsFunctionConversion(ltrans, rtrans, ltrans))
9682 return Sema::IncompatibleFunctionPointer;
9683 if (IsInvalidCmseNSCallConversion(S, ltrans, rtrans))
9684 return Sema::IncompatibleFunctionPointer;
9685 return ConvTy;
9686}
9687
9688/// checkBlockPointerTypesForAssignment - This routine determines whether two
9689/// block pointer types are compatible or whether a block and normal pointer
9690/// are compatible. It is more restrict than comparing two function pointer
9691// types.
9692static Sema::AssignConvertType
9693checkBlockPointerTypesForAssignment(Sema &S, QualType LHSType,
9694 QualType RHSType) {
9695 assert(LHSType.isCanonical() && "LHS not canonicalized!")(static_cast <bool> (LHSType.isCanonical() && "LHS not canonicalized!"
) ? void (0) : __assert_fail ("LHSType.isCanonical() && \"LHS not canonicalized!\""
, "clang/lib/Sema/SemaExpr.cpp", 9695, __extension__ __PRETTY_FUNCTION__
))
;
9696 assert(RHSType.isCanonical() && "RHS not canonicalized!")(static_cast <bool> (RHSType.isCanonical() && "RHS not canonicalized!"
) ? void (0) : __assert_fail ("RHSType.isCanonical() && \"RHS not canonicalized!\""
, "clang/lib/Sema/SemaExpr.cpp", 9696, __extension__ __PRETTY_FUNCTION__
))
;
9697
9698 QualType lhptee, rhptee;
9699
9700 // get the "pointed to" type (ignoring qualifiers at the top level)
9701 lhptee = cast<BlockPointerType>(LHSType)->getPointeeType();
9702 rhptee = cast<BlockPointerType>(RHSType)->getPointeeType();
9703
9704 // In C++, the types have to match exactly.
9705 if (S.getLangOpts().CPlusPlus)
9706 return Sema::IncompatibleBlockPointer;
9707
9708 Sema::AssignConvertType ConvTy = Sema::Compatible;
9709
9710 // For blocks we enforce that qualifiers are identical.
9711 Qualifiers LQuals = lhptee.getLocalQualifiers();
9712 Qualifiers RQuals = rhptee.getLocalQualifiers();
9713 if (S.getLangOpts().OpenCL) {
9714 LQuals.removeAddressSpace();
9715 RQuals.removeAddressSpace();
9716 }
9717 if (LQuals != RQuals)
9718 ConvTy = Sema::CompatiblePointerDiscardsQualifiers;
9719
9720 // FIXME: OpenCL doesn't define the exact compile time semantics for a block
9721 // assignment.
9722 // The current behavior is similar to C++ lambdas. A block might be
9723 // assigned to a variable iff its return type and parameters are compatible
9724 // (C99 6.2.7) with the corresponding return type and parameters of the LHS of
9725 // an assignment. Presumably it should behave in way that a function pointer
9726 // assignment does in C, so for each parameter and return type:
9727 // * CVR and address space of LHS should be a superset of CVR and address
9728 // space of RHS.
9729 // * unqualified types should be compatible.
9730 if (S.getLangOpts().OpenCL) {
9731 if (!S.Context.typesAreBlockPointerCompatible(
9732 S.Context.getQualifiedType(LHSType.getUnqualifiedType(), LQuals),
9733 S.Context.getQualifiedType(RHSType.getUnqualifiedType(), RQuals)))
9734 return Sema::IncompatibleBlockPointer;
9735 } else if (!S.Context.typesAreBlockPointerCompatible(LHSType, RHSType))
9736 return Sema::IncompatibleBlockPointer;
9737
9738 return ConvTy;
9739}
9740
9741/// checkObjCPointerTypesForAssignment - Compares two objective-c pointer types
9742/// for assignment compatibility.
9743static Sema::AssignConvertType
9744checkObjCPointerTypesForAssignment(Sema &S, QualType LHSType,
9745 QualType RHSType) {
9746 assert(LHSType.isCanonical() && "LHS was not canonicalized!")(static_cast <bool> (LHSType.isCanonical() && "LHS was not canonicalized!"
) ? void (0) : __assert_fail ("LHSType.isCanonical() && \"LHS was not canonicalized!\""
, "clang/lib/Sema/SemaExpr.cpp", 9746, __extension__ __PRETTY_FUNCTION__
))
;
9747 assert(RHSType.isCanonical() && "RHS was not canonicalized!")(static_cast <bool> (RHSType.isCanonical() && "RHS was not canonicalized!"
) ? void (0) : __assert_fail ("RHSType.isCanonical() && \"RHS was not canonicalized!\""
, "clang/lib/Sema/SemaExpr.cpp", 9747, __extension__ __PRETTY_FUNCTION__
))
;
9748
9749 if (LHSType->isObjCBuiltinType()) {
9750 // Class is not compatible with ObjC object pointers.
9751 if (LHSType->isObjCClassType() && !RHSType->isObjCBuiltinType() &&
9752 !RHSType->isObjCQualifiedClassType())
9753 return Sema::IncompatiblePointer;
9754 return Sema::Compatible;
9755 }
9756 if (RHSType->isObjCBuiltinType()) {
9757 if (RHSType->isObjCClassType() && !LHSType->isObjCBuiltinType() &&
9758 !LHSType->isObjCQualifiedClassType())
9759 return Sema::IncompatiblePointer;
9760 return Sema::Compatible;
9761 }
9762 QualType lhptee = LHSType->castAs<ObjCObjectPointerType>()->getPointeeType();
9763 QualType rhptee = RHSType->castAs<ObjCObjectPointerType>()->getPointeeType();
9764
9765 if (!lhptee.isAtLeastAsQualifiedAs(rhptee) &&
9766 // make an exception for id<P>
9767 !LHSType->isObjCQualifiedIdType())
9768 return Sema::CompatiblePointerDiscardsQualifiers;
9769
9770 if (S.Context.typesAreCompatible(LHSType, RHSType))
9771 return Sema::Compatible;
9772 if (LHSType->isObjCQualifiedIdType() || RHSType->isObjCQualifiedIdType())
9773 return Sema::IncompatibleObjCQualifiedId;
9774 return Sema::IncompatiblePointer;
9775}
9776
9777Sema::AssignConvertType
9778Sema::CheckAssignmentConstraints(SourceLocation Loc,
9779 QualType LHSType, QualType RHSType) {
9780 // Fake up an opaque expression. We don't actually care about what
9781 // cast operations are required, so if CheckAssignmentConstraints
9782 // adds casts to this they'll be wasted, but fortunately that doesn't
9783 // usually happen on valid code.
9784 OpaqueValueExpr RHSExpr(Loc, RHSType, VK_PRValue);
9785 ExprResult RHSPtr = &RHSExpr;
9786 CastKind K;
9787
9788 return CheckAssignmentConstraints(LHSType, RHSPtr, K, /*ConvertRHS=*/false);
9789}
9790
9791/// This helper function returns true if QT is a vector type that has element
9792/// type ElementType.
9793static bool isVector(QualType QT, QualType ElementType) {
9794 if (const VectorType *VT = QT->getAs<VectorType>())
9795 return VT->getElementType().getCanonicalType() == ElementType;
9796 return false;
9797}
9798
9799/// CheckAssignmentConstraints (C99 6.5.16) - This routine currently
9800/// has code to accommodate several GCC extensions when type checking
9801/// pointers. Here are some objectionable examples that GCC considers warnings:
9802///
9803/// int a, *pint;
9804/// short *pshort;
9805/// struct foo *pfoo;
9806///
9807/// pint = pshort; // warning: assignment from incompatible pointer type
9808/// a = pint; // warning: assignment makes integer from pointer without a cast
9809/// pint = a; // warning: assignment makes pointer from integer without a cast
9810/// pint = pfoo; // warning: assignment from incompatible pointer type
9811///
9812/// As a result, the code for dealing with pointers is more complex than the
9813/// C99 spec dictates.
9814///
9815/// Sets 'Kind' for any result kind except Incompatible.
9816Sema::AssignConvertType
9817Sema::CheckAssignmentConstraints(QualType LHSType, ExprResult &RHS,
9818 CastKind &Kind, bool ConvertRHS) {
9819 QualType RHSType = RHS.get()->getType();
9820 QualType OrigLHSType = LHSType;
9821
9822 // Get canonical types. We're not formatting these types, just comparing
9823 // them.
9824 LHSType = Context.getCanonicalType(LHSType).getUnqualifiedType();
9825 RHSType = Context.getCanonicalType(RHSType).getUnqualifiedType();
9826
9827 // Common case: no conversion required.
9828 if (LHSType == RHSType) {
9829 Kind = CK_NoOp;
9830 return Compatible;
9831 }
9832
9833 // If the LHS has an __auto_type, there are no additional type constraints
9834 // to be worried about.
9835 if (const auto *AT = dyn_cast<AutoType>(LHSType)) {
9836 if (AT->isGNUAutoType()) {
9837 Kind = CK_NoOp;
9838 return Compatible;
9839 }
9840 }
9841
9842 // If we have an atomic type, try a non-atomic assignment, then just add an
9843 // atomic qualification step.
9844 if (const AtomicType *AtomicTy = dyn_cast<AtomicType>(LHSType)) {
9845 Sema::AssignConvertType result =
9846 CheckAssignmentConstraints(AtomicTy->getValueType(), RHS, Kind);
9847 if (result != Compatible)
9848 return result;
9849 if (Kind != CK_NoOp && ConvertRHS)
9850 RHS = ImpCastExprToType(RHS.get(), AtomicTy->getValueType(), Kind);
9851 Kind = CK_NonAtomicToAtomic;
9852 return Compatible;
9853 }
9854
9855 // If the left-hand side is a reference type, then we are in a
9856 // (rare!) case where we've allowed the use of references in C,
9857 // e.g., as a parameter type in a built-in function. In this case,
9858 // just make sure that the type referenced is compatible with the
9859 // right-hand side type. The caller is responsible for adjusting
9860 // LHSType so that the resulting expression does not have reference
9861 // type.
9862 if (const ReferenceType *LHSTypeRef = LHSType->getAs<ReferenceType>()) {
9863 if (Context.typesAreCompatible(LHSTypeRef->getPointeeType(), RHSType)) {
9864 Kind = CK_LValueBitCast;
9865 return Compatible;
9866 }
9867 return Incompatible;
9868 }
9869
9870 // Allow scalar to ExtVector assignments, and assignments of an ExtVector type
9871 // to the same ExtVector type.
9872 if (LHSType->isExtVectorType()) {
9873 if (RHSType->isExtVectorType())
9874 return Incompatible;
9875 if (RHSType->isArithmeticType()) {
9876 // CK_VectorSplat does T -> vector T, so first cast to the element type.
9877 if (ConvertRHS)
9878 RHS = prepareVectorSplat(LHSType, RHS.get());
9879 Kind = CK_VectorSplat;
9880 return Compatible;
9881 }
9882 }
9883
9884 // Conversions to or from vector type.
9885 if (LHSType->isVectorType() || RHSType->isVectorType()) {
9886 if (LHSType->isVectorType() && RHSType->isVectorType()) {
9887 // Allow assignments of an AltiVec vector type to an equivalent GCC
9888 // vector type and vice versa
9889 if (Context.areCompatibleVectorTypes(LHSType, RHSType)) {
9890 Kind = CK_BitCast;
9891 return Compatible;
9892 }
9893
9894 // If we are allowing lax vector conversions, and LHS and RHS are both
9895 // vectors, the total size only needs to be the same. This is a bitcast;
9896 // no bits are changed but the result type is different.
9897 if (isLaxVectorConversion(RHSType, LHSType)) {
9898 // The default for lax vector conversions with Altivec vectors will
9899 // change, so if we are converting between vector types where
9900 // at least one is an Altivec vector, emit a warning.
9901 if (Context.getTargetInfo().getTriple().isPPC() &&
9902 anyAltivecTypes(RHSType, LHSType) &&
9903 !Context.areCompatibleVectorTypes(RHSType, LHSType))
9904 Diag(RHS.get()->getExprLoc(), diag::warn_deprecated_lax_vec_conv_all)
9905 << RHSType << LHSType;
9906 Kind = CK_BitCast;
9907 return IncompatibleVectors;
9908 }
9909 }
9910
9911 // When the RHS comes from another lax conversion (e.g. binops between
9912 // scalars and vectors) the result is canonicalized as a vector. When the
9913 // LHS is also a vector, the lax is allowed by the condition above. Handle
9914 // the case where LHS is a scalar.
9915 if (LHSType->isScalarType()) {
9916 const VectorType *VecType = RHSType->getAs<VectorType>();
9917 if (VecType && VecType->getNumElements() == 1 &&
9918 isLaxVectorConversion(RHSType, LHSType)) {
9919 if (Context.getTargetInfo().getTriple().isPPC() &&
9920 (VecType->getVectorKind() == VectorType::AltiVecVector ||
9921 VecType->getVectorKind() == VectorType::AltiVecBool ||
9922 VecType->getVectorKind() == VectorType::AltiVecPixel))
9923 Diag(RHS.get()->getExprLoc(), diag::warn_deprecated_lax_vec_conv_all)
9924 << RHSType << LHSType;
9925 ExprResult *VecExpr = &RHS;
9926 *VecExpr = ImpCastExprToType(VecExpr->get(), LHSType, CK_BitCast);
9927 Kind = CK_BitCast;
9928 return Compatible;
9929 }
9930 }
9931
9932 // Allow assignments between fixed-length and sizeless SVE vectors.
9933 if ((LHSType->isSVESizelessBuiltinType() && RHSType->isVectorType()) ||
9934 (LHSType->isVectorType() && RHSType->isSVESizelessBuiltinType()))
9935 if (Context.areCompatibleSveTypes(LHSType, RHSType) ||
9936 Context.areLaxCompatibleSveTypes(LHSType, RHSType)) {
9937 Kind = CK_BitCast;
9938 return Compatible;
9939 }
9940
9941 // Allow assignments between fixed-length and sizeless RVV vectors.
9942 if ((LHSType->isRVVSizelessBuiltinType() && RHSType->isVectorType()) ||
9943 (LHSType->isVectorType() && RHSType->isRVVSizelessBuiltinType())) {
9944 if (Context.areCompatibleRVVTypes(LHSType, RHSType) ||
9945 Context.areLaxCompatibleRVVTypes(LHSType, RHSType)) {
9946 Kind = CK_BitCast;
9947 return Compatible;
9948 }
9949 }
9950
9951 return Incompatible;
9952 }
9953
9954 // Diagnose attempts to convert between __ibm128, __float128 and long double
9955 // where such conversions currently can't be handled.
9956 if (unsupportedTypeConversion(*this, LHSType, RHSType))
9957 return Incompatible;
9958
9959 // Disallow assigning a _Complex to a real type in C++ mode since it simply
9960 // discards the imaginary part.
9961 if (getLangOpts().CPlusPlus && RHSType->getAs<ComplexType>() &&
9962 !LHSType->getAs<ComplexType>())
9963 return Incompatible;
9964
9965 // Arithmetic conversions.
9966 if (LHSType->isArithmeticType() && RHSType->isArithmeticType() &&
9967 !(getLangOpts().CPlusPlus && LHSType->isEnumeralType())) {
9968 if (ConvertRHS)
9969 Kind = PrepareScalarCast(RHS, LHSType);
9970 return Compatible;
9971 }
9972
9973 // Conversions to normal pointers.
9974 if (const PointerType *LHSPointer = dyn_cast<PointerType>(LHSType)) {
9975 // U* -> T*
9976 if (isa<PointerType>(RHSType)) {
9977 LangAS AddrSpaceL = LHSPointer->getPointeeType().getAddressSpace();
9978 LangAS AddrSpaceR = RHSType->getPointeeType().getAddressSpace();
9979 if (AddrSpaceL != AddrSpaceR)
9980 Kind = CK_AddressSpaceConversion;
9981 else if (Context.hasCvrSimilarType(RHSType, LHSType))
9982 Kind = CK_NoOp;
9983 else
9984 Kind = CK_BitCast;
9985 return checkPointerTypesForAssignment(*this, LHSType, RHSType,
9986 RHS.get()->getBeginLoc());
9987 }
9988
9989 // int -> T*
9990 if (RHSType->isIntegerType()) {
9991 Kind = CK_IntegralToPointer; // FIXME: null?
9992 return IntToPointer;
9993 }
9994
9995 // C pointers are not compatible with ObjC object pointers,
9996 // with two exceptions:
9997 if (isa<ObjCObjectPointerType>(RHSType)) {
9998 // - conversions to void*
9999 if (LHSPointer->getPointeeType()->isVoidType()) {
10000 Kind = CK_BitCast;
10001 return Compatible;
10002 }
10003
10004 // - conversions from 'Class' to the redefinition type
10005 if (RHSType->isObjCClassType() &&
10006 Context.hasSameType(LHSType,
10007 Context.getObjCClassRedefinitionType())) {
10008 Kind = CK_BitCast;
10009 return Compatible;
10010 }
10011
10012 Kind = CK_BitCast;
10013 return IncompatiblePointer;
10014 }
10015
10016 // U^ -> void*
10017 if (RHSType->getAs<BlockPointerType>()) {
10018 if (LHSPointer->getPointeeType()->isVoidType()) {
10019 LangAS AddrSpaceL = LHSPointer->getPointeeType().getAddressSpace();
10020 LangAS AddrSpaceR = RHSType->getAs<BlockPointerType>()
10021 ->getPointeeType()
10022 .getAddressSpace();
10023 Kind =
10024 AddrSpaceL != AddrSpaceR ? CK_AddressSpaceConversion : CK_BitCast;
10025 return Compatible;
10026 }
10027 }
10028
10029 return Incompatible;
10030 }
10031
10032 // Conversions to block pointers.
10033 if (isa<BlockPointerType>(LHSType)) {
10034 // U^ -> T^
10035 if (RHSType->isBlockPointerType()) {
10036 LangAS AddrSpaceL = LHSType->getAs<BlockPointerType>()
10037 ->getPointeeType()
10038 .getAddressSpace();
10039 LangAS AddrSpaceR = RHSType->getAs<BlockPointerType>()
10040 ->getPointeeType()
10041 .getAddressSpace();
10042 Kind = AddrSpaceL != AddrSpaceR ? CK_AddressSpaceConversion : CK_BitCast;
10043 return checkBlockPointerTypesForAssignment(*this, LHSType, RHSType);
10044 }
10045
10046 // int or null -> T^
10047 if (RHSType->isIntegerType()) {
10048 Kind = CK_IntegralToPointer; // FIXME: null
10049 return IntToBlockPointer;
10050 }
10051
10052 // id -> T^
10053 if (getLangOpts().ObjC && RHSType->isObjCIdType()) {
10054 Kind = CK_AnyPointerToBlockPointerCast;
10055 return Compatible;
10056 }
10057
10058 // void* -> T^
10059 if (const PointerType *RHSPT = RHSType->getAs<PointerType>())
10060 if (RHSPT->getPointeeType()->isVoidType()) {
10061 Kind = CK_AnyPointerToBlockPointerCast;
10062 return Compatible;
10063 }
10064
10065 return Incompatible;
10066 }
10067
10068 // Conversions to Objective-C pointers.
10069 if (isa<ObjCObjectPointerType>(LHSType)) {
10070 // A* -> B*
10071 if (RHSType->isObjCObjectPointerType()) {
10072 Kind = CK_BitCast;
10073 Sema::AssignConvertType result =
10074 checkObjCPointerTypesForAssignment(*this, LHSType, RHSType);
10075 if (getLangOpts().allowsNonTrivialObjCLifetimeQualifiers() &&
10076 result == Compatible &&
10077 !CheckObjCARCUnavailableWeakConversion(OrigLHSType, RHSType))
10078 result = IncompatibleObjCWeakRef;
10079 return result;
10080 }
10081
10082 // int or null -> A*
10083 if (RHSType->isIntegerType()) {
10084 Kind = CK_IntegralToPointer; // FIXME: null
10085 return IntToPointer;
10086 }
10087
10088 // In general, C pointers are not compatible with ObjC object pointers,
10089 // with two exceptions:
10090 if (isa<PointerType>(RHSType)) {
10091 Kind = CK_CPointerToObjCPointerCast;
10092
10093 // - conversions from 'void*'
10094 if (RHSType->isVoidPointerType()) {
10095 return Compatible;
10096 }
10097
10098 // - conversions to 'Class' from its redefinition type
10099 if (LHSType->isObjCClassType() &&
10100 Context.hasSameType(RHSType,
10101 Context.getObjCClassRedefinitionType())) {
10102 return Compatible;
10103 }
10104
10105 return IncompatiblePointer;
10106 }
10107
10108 // Only under strict condition T^ is compatible with an Objective-C pointer.
10109 if (RHSType->isBlockPointerType() &&
10110 LHSType->isBlockCompatibleObjCPointerType(Context)) {
10111 if (ConvertRHS)
10112 maybeExtendBlockObject(RHS);
10113 Kind = CK_BlockPointerToObjCPointerCast;
10114 return Compatible;
10115 }
10116
10117 return Incompatible;
10118 }
10119
10120 // Conversion to nullptr_t (C2x only)
10121 if (getLangOpts().C2x && LHSType->isNullPtrType() &&
10122 RHS.get()->isNullPointerConstant(Context,
10123 Expr::NPC_ValueDependentIsNull)) {
10124 // null -> nullptr_t
10125 Kind = CK_NullToPointer;
10126 return Compatible;
10127 }
10128
10129 // Conversions from pointers that are not covered by the above.
10130 if (isa<PointerType>(RHSType)) {
10131 // T* -> _Bool
10132 if (LHSType == Context.BoolTy) {
10133 Kind = CK_PointerToBoolean;
10134 return Compatible;
10135 }
10136
10137 // T* -> int
10138 if (LHSType->isIntegerType()) {
10139 Kind = CK_PointerToIntegral;
10140 return PointerToInt;
10141 }
10142
10143 return Incompatible;
10144 }
10145
10146 // Conversions from Objective-C pointers that are not covered by the above.
10147 if (isa<ObjCObjectPointerType>(RHSType)) {
10148 // T* -> _Bool
10149 if (LHSType == Context.BoolTy) {
10150 Kind = CK_PointerToBoolean;
10151 return Compatible;
10152 }
10153
10154 // T* -> int
10155 if (LHSType->isIntegerType()) {
10156 Kind = CK_PointerToIntegral;
10157 return PointerToInt;
10158 }
10159
10160 return Incompatible;
10161 }
10162
10163 // struct A -> struct B
10164 if (isa<TagType>(LHSType) && isa<TagType>(RHSType)) {
10165 if (Context.typesAreCompatible(LHSType, RHSType)) {
10166 Kind = CK_NoOp;
10167 return Compatible;
10168 }
10169 }
10170
10171 if (LHSType->isSamplerT() && RHSType->isIntegerType()) {
10172 Kind = CK_IntToOCLSampler;
10173 return Compatible;
10174 }
10175
10176 return Incompatible;
10177}
10178
10179/// Constructs a transparent union from an expression that is
10180/// used to initialize the transparent union.
10181static void ConstructTransparentUnion(Sema &S, ASTContext &C,
10182 ExprResult &EResult, QualType UnionType,
10183 FieldDecl *Field) {
10184 // Build an initializer list that designates the appropriate member
10185 // of the transparent union.
10186 Expr *E = EResult.get();
10187 InitListExpr *Initializer = new (C) InitListExpr(C, SourceLocation(),
10188 E, SourceLocation());
10189 Initializer->setType(UnionType);
10190 Initializer->setInitializedFieldInUnion(Field);
10191
10192 // Build a compound literal constructing a value of the transparent
10193 // union type from this initializer list.
10194 TypeSourceInfo *unionTInfo = C.getTrivialTypeSourceInfo(UnionType);
10195 EResult = new (C) CompoundLiteralExpr(SourceLocation(), unionTInfo, UnionType,
10196 VK_PRValue, Initializer, false);
10197}
10198
10199Sema::AssignConvertType
10200Sema::CheckTransparentUnionArgumentConstraints(QualType ArgType,
10201 ExprResult &RHS) {
10202 QualType RHSType = RHS.get()->getType();
10203
10204 // If the ArgType is a Union type, we want to handle a potential
10205 // transparent_union GCC extension.
10206 const RecordType *UT = ArgType->getAsUnionType();
10207 if (!UT || !UT->getDecl()->hasAttr<TransparentUnionAttr>())
10208 return Incompatible;
10209
10210 // The field to initialize within the transparent union.
10211 RecordDecl *UD = UT->getDecl();
10212 FieldDecl *InitField = nullptr;
10213 // It's compatible if the expression matches any of the fields.
10214 for (auto *it : UD->fields()) {
10215 if (it->getType()->isPointerType()) {
10216 // If the transparent union contains a pointer type, we allow:
10217 // 1) void pointer
10218 // 2) null pointer constant
10219 if (RHSType->isPointerType())
10220 if (RHSType->castAs<PointerType>()->getPointeeType()->isVoidType()) {
10221 RHS = ImpCastExprToType(RHS.get(), it->getType(), CK_BitCast);
10222 InitField = it;
10223 break;
10224 }
10225
10226 if (RHS.get()->isNullPointerConstant(Context,
10227 Expr::NPC_ValueDependentIsNull)) {
10228 RHS = ImpCastExprToType(RHS.get(), it->getType(),
10229 CK_NullToPointer);
10230 InitField = it;
10231 break;
10232 }
10233 }
10234
10235 CastKind Kind;
10236 if (CheckAssignmentConstraints(it->getType(), RHS, Kind)
10237 == Compatible) {
10238 RHS = ImpCastExprToType(RHS.get(), it->getType(), Kind);
10239 InitField = it;
10240 break;
10241 }
10242 }
10243
10244 if (!InitField)
10245 return Incompatible;
10246
10247 ConstructTransparentUnion(*this, Context, RHS, ArgType, InitField);
10248 return Compatible;
10249}
10250
10251Sema::AssignConvertType
10252Sema::CheckSingleAssignmentConstraints(QualType LHSType, ExprResult &CallerRHS,
10253 bool Diagnose,
10254 bool DiagnoseCFAudited,
10255 bool ConvertRHS) {
10256 // We need to be able to tell the caller whether we diagnosed a problem, if
10257 // they ask us to issue diagnostics.
10258 assert((ConvertRHS || !Diagnose) && "can't indicate whether we diagnosed")(static_cast <bool> ((ConvertRHS || !Diagnose) &&
"can't indicate whether we diagnosed") ? void (0) : __assert_fail
("(ConvertRHS || !Diagnose) && \"can't indicate whether we diagnosed\""
, "clang/lib/Sema/SemaExpr.cpp", 10258, __extension__ __PRETTY_FUNCTION__
))
;
10259
10260 // If ConvertRHS is false, we want to leave the caller's RHS untouched. Sadly,
10261 // we can't avoid *all* modifications at the moment, so we need some somewhere
10262 // to put the updated value.
10263 ExprResult LocalRHS = CallerRHS;
10264 ExprResult &RHS = ConvertRHS ? CallerRHS : LocalRHS;
10265
10266 if (const auto *LHSPtrType = LHSType->getAs<PointerType>()) {
10267 if (const auto *RHSPtrType = RHS.get()->getType()->getAs<PointerType>()) {
10268 if (RHSPtrType->getPointeeType()->hasAttr(attr::NoDeref) &&
10269 !LHSPtrType->getPointeeType()->hasAttr(attr::NoDeref)) {
10270 Diag(RHS.get()->getExprLoc(),
10271 diag::warn_noderef_to_dereferenceable_pointer)
10272 << RHS.get()->getSourceRange();
10273 }
10274 }
10275 }
10276
10277 if (getLangOpts().CPlusPlus) {
10278 if (!LHSType->isRecordType() && !LHSType->isAtomicType()) {
10279 // C++ 5.17p3: If the left operand is not of class type, the
10280 // expression is implicitly converted (C++ 4) to the
10281 // cv-unqualified type of the left operand.
10282 QualType RHSType = RHS.get()->getType();
10283 if (Diagnose) {
10284 RHS = PerformImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(),
10285 AA_Assigning);
10286 } else {
10287 ImplicitConversionSequence ICS =
10288 TryImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(),
10289 /*SuppressUserConversions=*/false,
10290 AllowedExplicit::None,
10291 /*InOverloadResolution=*/false,
10292 /*CStyle=*/false,
10293 /*AllowObjCWritebackConversion=*/false);
10294 if (ICS.isFailure())
10295 return Incompatible;
10296 RHS = PerformImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(),
10297 ICS, AA_Assigning);
10298 }
10299 if (RHS.isInvalid())
10300 return Incompatible;
10301 Sema::AssignConvertType result = Compatible;
10302 if (getLangOpts().allowsNonTrivialObjCLifetimeQualifiers() &&
10303 !CheckObjCARCUnavailableWeakConversion(LHSType, RHSType))
10304 result = IncompatibleObjCWeakRef;
10305 return result;
10306 }
10307
10308 // FIXME: Currently, we fall through and treat C++ classes like C
10309 // structures.
10310 // FIXME: We also fall through for atomics; not sure what should
10311 // happen there, though.
10312 } else if (RHS.get()->getType() == Context.OverloadTy) {
10313 // As a set of extensions to C, we support overloading on functions. These
10314 // functions need to be resolved here.
10315 DeclAccessPair DAP;
10316 if (FunctionDecl *FD = ResolveAddressOfOverloadedFunction(
10317 RHS.get(), LHSType, /*Complain=*/false, DAP))
10318 RHS = FixOverloadedFunctionReference(RHS.get(), DAP, FD);
10319 else
10320 return Incompatible;
10321 }
10322
10323 // This check seems unnatural, however it is necessary to ensure the proper
10324 // conversion of functions/arrays. If the conversion were done for all
10325 // DeclExpr's (created by ActOnIdExpression), it would mess up the unary
10326 // expressions that suppress this implicit conversion (&, sizeof). This needs
10327 // to happen before we check for null pointer conversions because C does not
10328 // undergo the same implicit conversions as C++ does above (by the calls to
10329 // TryImplicitConversion() and PerformImplicitConversion()) which insert the
10330 // lvalue to rvalue cast before checking for null pointer constraints. This
10331 // addresses code like: nullptr_t val; int *ptr; ptr = val;
10332 //
10333 // Suppress this for references: C++ 8.5.3p5.
10334 if (!LHSType->isReferenceType()) {
10335 // FIXME: We potentially allocate here even if ConvertRHS is false.
10336 RHS = DefaultFunctionArrayLvalueConversion(RHS.get(), Diagnose);
10337 if (RHS.isInvalid())
10338 return Incompatible;
10339 }
10340
10341 // The constraints are expressed in terms of the atomic, qualified, or
10342 // unqualified type of the LHS.
10343 QualType LHSTypeAfterConversion = LHSType.getAtomicUnqualifiedType();
10344
10345 // C99 6.5.16.1p1: the left operand is a pointer and the right is
10346 // a null pointer constant <C2x>or its type is nullptr_t;</C2x>.
10347 if ((LHSTypeAfterConversion->isPointerType() ||
10348 LHSTypeAfterConversion->isObjCObjectPointerType() ||
10349 LHSTypeAfterConversion->isBlockPointerType()) &&
10350 ((getLangOpts().C2x && RHS.get()->getType()->isNullPtrType()) ||
10351 RHS.get()->isNullPointerConstant(Context,
10352 Expr::NPC_ValueDependentIsNull))) {
10353 if (Diagnose || ConvertRHS) {
10354 CastKind Kind;
10355 CXXCastPath Path;
10356 CheckPointerConversion(RHS.get(), LHSType, Kind, Path,
10357 /*IgnoreBaseAccess=*/false, Diagnose);
10358 if (ConvertRHS)
10359 RHS = ImpCastExprToType(RHS.get(), LHSType, Kind, VK_PRValue, &Path);
10360 }
10361 return Compatible;
10362 }
10363 // C2x 6.5.16.1p1: the left operand has type atomic, qualified, or
10364 // unqualified bool, and the right operand is a pointer or its type is
10365 // nullptr_t.
10366 if (getLangOpts().C2x && LHSType->isBooleanType() &&
10367 RHS.get()->getType()->isNullPtrType()) {
10368 // NB: T* -> _Bool is handled in CheckAssignmentConstraints, this only
10369 // only handles nullptr -> _Bool due to needing an extra conversion
10370 // step.
10371 // We model this by converting from nullptr -> void * and then let the
10372 // conversion from void * -> _Bool happen naturally.
10373 if (Diagnose || ConvertRHS) {
10374 CastKind Kind;
10375 CXXCastPath Path;
10376 CheckPointerConversion(RHS.get(), Context.VoidPtrTy, Kind, Path,
10377 /*IgnoreBaseAccess=*/false, Diagnose);
10378 if (ConvertRHS)
10379 RHS = ImpCastExprToType(RHS.get(), Context.VoidPtrTy, Kind, VK_PRValue,
10380 &Path);
10381 }
10382 }
10383
10384 // OpenCL queue_t type assignment.
10385 if (LHSType->isQueueT() && RHS.get()->isNullPointerConstant(
10386 Context, Expr::NPC_ValueDependentIsNull)) {
10387 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer);
10388 return Compatible;
10389 }
10390
10391 CastKind Kind;
10392 Sema::AssignConvertType result =
10393 CheckAssignmentConstraints(LHSType, RHS, Kind, ConvertRHS);
10394
10395 // C99 6.5.16.1p2: The value of the right operand is converted to the
10396 // type of the assignment expression.
10397 // CheckAssignmentConstraints allows the left-hand side to be a reference,
10398 // so that we can use references in built-in functions even in C.
10399 // The getNonReferenceType() call makes sure that the resulting expression
10400 // does not have reference type.
10401 if (result != Incompatible && RHS.get()->getType() != LHSType) {
10402 QualType Ty = LHSType.getNonLValueExprType(Context);
10403 Expr *E = RHS.get();
10404
10405 // Check for various Objective-C errors. If we are not reporting
10406 // diagnostics and just checking for errors, e.g., during overload
10407 // resolution, return Incompatible to indicate the failure.
10408 if (getLangOpts().allowsNonTrivialObjCLifetimeQualifiers() &&
10409 CheckObjCConversion(SourceRange(), Ty, E, CCK_ImplicitConversion,
10410 Diagnose, DiagnoseCFAudited) != ACR_okay) {
10411 if (!Diagnose)
10412 return Incompatible;
10413 }
10414 if (getLangOpts().ObjC &&
10415 (CheckObjCBridgeRelatedConversions(E->getBeginLoc(), LHSType,
10416 E->getType(), E, Diagnose) ||
10417 CheckConversionToObjCLiteral(LHSType, E, Diagnose))) {
10418 if (!Diagnose)
10419 return Incompatible;
10420 // Replace the expression with a corrected version and continue so we
10421 // can find further errors.
10422 RHS = E;
10423 return Compatible;
10424 }
10425
10426 if (ConvertRHS)
10427 RHS = ImpCastExprToType(E, Ty, Kind);
10428 }
10429
10430 return result;
10431}
10432
10433namespace {
10434/// The original operand to an operator, prior to the application of the usual
10435/// arithmetic conversions and converting the arguments of a builtin operator
10436/// candidate.
10437struct OriginalOperand {
10438 explicit OriginalOperand(Expr *Op) : Orig(Op), Conversion(nullptr) {
10439 if (auto *MTE = dyn_cast<MaterializeTemporaryExpr>(Op))
10440 Op = MTE->getSubExpr();
10441 if (auto *BTE = dyn_cast<CXXBindTemporaryExpr>(Op))
10442 Op = BTE->getSubExpr();
10443 if (auto *ICE = dyn_cast<ImplicitCastExpr>(Op)) {
10444 Orig = ICE->getSubExprAsWritten();
10445 Conversion = ICE->getConversionFunction();
10446 }
10447 }
10448
10449 QualType getType() const { return Orig->getType(); }
10450
10451 Expr *Orig;
10452 NamedDecl *Conversion;
10453};
10454}
10455
10456QualType Sema::InvalidOperands(SourceLocation Loc, ExprResult &LHS,
10457 ExprResult &RHS) {
10458 OriginalOperand OrigLHS(LHS.get()), OrigRHS(RHS.get());
10459
10460 Diag(Loc, diag::err_typecheck_invalid_operands)
10461 << OrigLHS.getType() << OrigRHS.getType()
10462 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
10463
10464 // If a user-defined conversion was applied to either of the operands prior
10465 // to applying the built-in operator rules, tell the user about it.
10466 if (OrigLHS.Conversion) {
10467 Diag(OrigLHS.Conversion->getLocation(),
10468 diag::note_typecheck_invalid_operands_converted)
10469 << 0 << LHS.get()->getType();
10470 }
10471 if (OrigRHS.Conversion) {
10472 Diag(OrigRHS.Conversion->getLocation(),
10473 diag::note_typecheck_invalid_operands_converted)
10474 << 1 << RHS.get()->getType();
10475 }
10476
10477 return QualType();
10478}
10479
10480// Diagnose cases where a scalar was implicitly converted to a vector and
10481// diagnose the underlying types. Otherwise, diagnose the error
10482// as invalid vector logical operands for non-C++ cases.
10483QualType Sema::InvalidLogicalVectorOperands(SourceLocation Loc, ExprResult &LHS,
10484 ExprResult &RHS) {
10485 QualType LHSType = LHS.get()->IgnoreImpCasts()->getType();
10486 QualType RHSType = RHS.get()->IgnoreImpCasts()->getType();
10487
10488 bool LHSNatVec = LHSType->isVectorType();
10489 bool RHSNatVec = RHSType->isVectorType();
10490
10491 if (!(LHSNatVec && RHSNatVec)) {
10492 Expr *Vector = LHSNatVec ? LHS.get() : RHS.get();
10493 Expr *NonVector = !LHSNatVec ? LHS.get() : RHS.get();
10494 Diag(Loc, diag::err_typecheck_logical_vector_expr_gnu_cpp_restrict)
10495 << 0 << Vector->getType() << NonVector->IgnoreImpCasts()->getType()
10496 << Vector->getSourceRange();
10497 return QualType();
10498 }
10499
10500 Diag(Loc, diag::err_typecheck_logical_vector_expr_gnu_cpp_restrict)
10501 << 1 << LHSType << RHSType << LHS.get()->getSourceRange()
10502 << RHS.get()->getSourceRange();
10503
10504 return QualType();
10505}
10506
10507/// Try to convert a value of non-vector type to a vector type by converting
10508/// the type to the element type of the vector and then performing a splat.
10509/// If the language is OpenCL, we only use conversions that promote scalar
10510/// rank; for C, Obj-C, and C++ we allow any real scalar conversion except
10511/// for float->int.
10512///
10513/// OpenCL V2.0 6.2.6.p2:
10514/// An error shall occur if any scalar operand type has greater rank
10515/// than the type of the vector element.
10516///
10517/// \param scalar - if non-null, actually perform the conversions
10518/// \return true if the operation fails (but without diagnosing the failure)
10519static bool tryVectorConvertAndSplat(Sema &S, ExprResult *scalar,
10520 QualType scalarTy,
10521 QualType vectorEltTy,
10522 QualType vectorTy,
10523 unsigned &DiagID) {
10524 // The conversion to apply to the scalar before splatting it,
10525 // if necessary.
10526 CastKind scalarCast = CK_NoOp;
10527
10528 if (vectorEltTy->isIntegralType(S.Context)) {
10529 if (S.getLangOpts().OpenCL && (scalarTy->isRealFloatingType() ||
10530 (scalarTy->isIntegerType() &&
10531 S.Context.getIntegerTypeOrder(vectorEltTy, scalarTy) < 0))) {
10532 DiagID = diag::err_opencl_scalar_type_rank_greater_than_vector_type;
10533 return true;
10534 }
10535 if (!scalarTy->isIntegralType(S.Context))
10536 return true;
10537 scalarCast = CK_IntegralCast;
10538 } else if (vectorEltTy->isRealFloatingType()) {
10539 if (scalarTy->isRealFloatingType()) {
10540 if (S.getLangOpts().OpenCL &&
10541 S.Context.getFloatingTypeOrder(vectorEltTy, scalarTy) < 0) {
10542 DiagID = diag::err_opencl_scalar_type_rank_greater_than_vector_type;
10543 return true;
10544 }
10545 scalarCast = CK_FloatingCast;
10546 }
10547 else if (scalarTy->isIntegralType(S.Context))
10548 scalarCast = CK_IntegralToFloating;
10549 else
10550 return true;
10551 } else {
10552 return true;
10553 }
10554
10555 // Adjust scalar if desired.
10556 if (scalar) {
10557 if (scalarCast != CK_NoOp)
10558 *scalar = S.ImpCastExprToType(scalar->get(), vectorEltTy, scalarCast);
10559 *scalar = S.ImpCastExprToType(scalar->get(), vectorTy, CK_VectorSplat);
10560 }
10561 return false;
10562}
10563
10564/// Convert vector E to a vector with the same number of elements but different
10565/// element type.
10566static ExprResult convertVector(Expr *E, QualType ElementType, Sema &S) {
10567 const auto *VecTy = E->getType()->getAs<VectorType>();
10568 assert(VecTy && "Expression E must be a vector")(static_cast <bool> (VecTy && "Expression E must be a vector"
) ? void (0) : __assert_fail ("VecTy && \"Expression E must be a vector\""
, "clang/lib/Sema/SemaExpr.cpp", 10568, __extension__ __PRETTY_FUNCTION__
))
;
10569 QualType NewVecTy =
10570 VecTy->isExtVectorType()
10571 ? S.Context.getExtVectorType(ElementType, VecTy->getNumElements())
10572 : S.Context.getVectorType(ElementType, VecTy->getNumElements(),
10573 VecTy->getVectorKind());
10574
10575 // Look through the implicit cast. Return the subexpression if its type is
10576 // NewVecTy.
10577 if (auto *ICE = dyn_cast<ImplicitCastExpr>(E))
10578 if (ICE->getSubExpr()->getType() == NewVecTy)
10579 return ICE->getSubExpr();
10580
10581 auto Cast = ElementType->isIntegerType() ? CK_IntegralCast : CK_FloatingCast;
10582 return S.ImpCastExprToType(E, NewVecTy, Cast);
10583}
10584
10585/// Test if a (constant) integer Int can be casted to another integer type
10586/// IntTy without losing precision.
10587static bool canConvertIntToOtherIntTy(Sema &S, ExprResult *Int,
10588 QualType OtherIntTy) {
10589 QualType IntTy = Int->get()->getType().getUnqualifiedType();
10590
10591 // Reject cases where the value of the Int is unknown as that would
10592 // possibly cause truncation, but accept cases where the scalar can be
10593 // demoted without loss of precision.
10594 Expr::EvalResult EVResult;
10595 bool CstInt = Int->get()->EvaluateAsInt(EVResult, S.Context);
10596 int Order = S.Context.getIntegerTypeOrder(OtherIntTy, IntTy);
10597 bool IntSigned = IntTy->hasSignedIntegerRepresentation();
10598 bool OtherIntSigned = OtherIntTy->hasSignedIntegerRepresentation();
10599
10600 if (CstInt) {
10601 // If the scalar is constant and is of a higher order and has more active
10602 // bits that the vector element type, reject it.
10603 llvm::APSInt Result = EVResult.Val.getInt();
10604 unsigned NumBits = IntSigned
10605 ? (Result.isNegative() ? Result.getSignificantBits()
10606 : Result.getActiveBits())
10607 : Result.getActiveBits();
10608 if (Order < 0 && S.Context.getIntWidth(OtherIntTy) < NumBits)
10609 return true;
10610
10611 // If the signedness of the scalar type and the vector element type
10612 // differs and the number of bits is greater than that of the vector
10613 // element reject it.
10614 return (IntSigned != OtherIntSigned &&
10615 NumBits > S.Context.getIntWidth(OtherIntTy));
10616 }
10617
10618 // Reject cases where the value of the scalar is not constant and it's
10619 // order is greater than that of the vector element type.
10620 return (Order < 0);
10621}
10622
10623/// Test if a (constant) integer Int can be casted to floating point type
10624/// FloatTy without losing precision.
10625static bool canConvertIntTyToFloatTy(Sema &S, ExprResult *Int,
10626 QualType FloatTy) {
10627 QualType IntTy = Int->get()->getType().getUnqualifiedType();
10628
10629 // Determine if the integer constant can be expressed as a floating point
10630 // number of the appropriate type.
10631 Expr::EvalResult EVResult;
10632 bool CstInt = Int->get()->EvaluateAsInt(EVResult, S.Context);
10633
10634 uint64_t Bits = 0;
10635 if (CstInt) {
10636 // Reject constants that would be truncated if they were converted to
10637 // the floating point type. Test by simple to/from conversion.
10638 // FIXME: Ideally the conversion to an APFloat and from an APFloat
10639 // could be avoided if there was a convertFromAPInt method
10640 // which could signal back if implicit truncation occurred.
10641 llvm::APSInt Result = EVResult.Val.getInt();
10642 llvm::APFloat Float(S.Context.getFloatTypeSemantics(FloatTy));
10643 Float.convertFromAPInt(Result, IntTy->hasSignedIntegerRepresentation(),
10644 llvm::APFloat::rmTowardZero);
10645 llvm::APSInt ConvertBack(S.Context.getIntWidth(IntTy),
10646 !IntTy->hasSignedIntegerRepresentation());
10647 bool Ignored = false;
10648 Float.convertToInteger(ConvertBack, llvm::APFloat::rmNearestTiesToEven,
10649 &Ignored);
10650 if (Result != ConvertBack)
10651 return true;
10652 } else {
10653 // Reject types that cannot be fully encoded into the mantissa of
10654 // the float.
10655 Bits = S.Context.getTypeSize(IntTy);
10656 unsigned FloatPrec = llvm::APFloat::semanticsPrecision(
10657 S.Context.getFloatTypeSemantics(FloatTy));
10658 if (Bits > FloatPrec)
10659 return true;
10660 }
10661
10662 return false;
10663}
10664
10665/// Attempt to convert and splat Scalar into a vector whose types matches
10666/// Vector following GCC conversion rules. The rule is that implicit
10667/// conversion can occur when Scalar can be casted to match Vector's element
10668/// type without causing truncation of Scalar.
10669static bool tryGCCVectorConvertAndSplat(Sema &S, ExprResult *Scalar,
10670 ExprResult *Vector) {
10671 QualType ScalarTy = Scalar->get()->getType().getUnqualifiedType();
10672 QualType VectorTy = Vector->get()->getType().getUnqualifiedType();
10673 QualType VectorEltTy;
10674
10675 if (const auto *VT = VectorTy->getAs<VectorType>()) {
10676 assert(!isa<ExtVectorType>(VT) &&(static_cast <bool> (!isa<ExtVectorType>(VT) &&
"ExtVectorTypes should not be handled here!") ? void (0) : __assert_fail
("!isa<ExtVectorType>(VT) && \"ExtVectorTypes should not be handled here!\""
, "clang/lib/Sema/SemaExpr.cpp", 10677, __extension__ __PRETTY_FUNCTION__
))
10677 "ExtVectorTypes should not be handled here!")(static_cast <bool> (!isa<ExtVectorType>(VT) &&
"ExtVectorTypes should not be handled here!") ? void (0) : __assert_fail
("!isa<ExtVectorType>(VT) && \"ExtVectorTypes should not be handled here!\""
, "clang/lib/Sema/SemaExpr.cpp", 10677, __extension__ __PRETTY_FUNCTION__
))
;
10678 VectorEltTy = VT->getElementType();
10679 } else if (VectorTy->isVLSTBuiltinType()) {
10680 VectorEltTy =
10681 VectorTy->castAs<BuiltinType>()->getSveEltType(S.getASTContext());
10682 } else {
10683 llvm_unreachable("Only Fixed-Length and SVE Vector types are handled here")::llvm::llvm_unreachable_internal("Only Fixed-Length and SVE Vector types are handled here"
, "clang/lib/Sema/SemaExpr.cpp", 10683)
;
10684 }
10685
10686 // Reject cases where the vector element type or the scalar element type are
10687 // not integral or floating point types.
10688 if (!VectorEltTy->isArithmeticType() || !ScalarTy->isArithmeticType())
10689 return true;
10690
10691 // The conversion to apply to the scalar before splatting it,
10692 // if necessary.
10693 CastKind ScalarCast = CK_NoOp;
10694
10695 // Accept cases where the vector elements are integers and the scalar is
10696 // an integer.
10697 // FIXME: Notionally if the scalar was a floating point value with a precise
10698 // integral representation, we could cast it to an appropriate integer
10699 // type and then perform the rest of the checks here. GCC will perform
10700 // this conversion in some cases as determined by the input language.
10701 // We should accept it on a language independent basis.
10702 if (VectorEltTy->isIntegralType(S.Context) &&
10703 ScalarTy->isIntegralType(S.Context) &&
10704 S.Context.getIntegerTypeOrder(VectorEltTy, ScalarTy)) {
10705
10706 if (canConvertIntToOtherIntTy(S, Scalar, VectorEltTy))
10707 return true;
10708
10709 ScalarCast = CK_IntegralCast;
10710 } else if (VectorEltTy->isIntegralType(S.Context) &&
10711 ScalarTy->isRealFloatingType()) {
10712 if (S.Context.getTypeSize(VectorEltTy) == S.Context.getTypeSize(ScalarTy))
10713 ScalarCast = CK_FloatingToIntegral;
10714 else
10715 return true;
10716 } else if (VectorEltTy->isRealFloatingType()) {
10717 if (ScalarTy->isRealFloatingType()) {
10718
10719 // Reject cases where the scalar type is not a constant and has a higher
10720 // Order than the vector element type.
10721 llvm::APFloat Result(0.0);
10722
10723 // Determine whether this is a constant scalar. In the event that the
10724 // value is dependent (and thus cannot be evaluated by the constant
10725 // evaluator), skip the evaluation. This will then diagnose once the
10726 // expression is instantiated.
10727 bool CstScalar = Scalar->get()->isValueDependent() ||
10728 Scalar->get()->EvaluateAsFloat(Result, S.Context);
10729 int Order = S.Context.getFloatingTypeOrder(VectorEltTy, ScalarTy);
10730 if (!CstScalar && Order < 0)
10731 return true;
10732
10733 // If the scalar cannot be safely casted to the vector element type,
10734 // reject it.
10735 if (CstScalar) {
10736 bool Truncated = false;
10737 Result.convert(S.Context.getFloatTypeSemantics(VectorEltTy),
10738 llvm::APFloat::rmNearestTiesToEven, &Truncated);
10739 if (Truncated)
10740 return true;
10741 }
10742
10743 ScalarCast = CK_FloatingCast;
10744 } else if (ScalarTy->isIntegralType(S.Context)) {
10745 if (canConvertIntTyToFloatTy(S, Scalar, VectorEltTy))
10746 return true;
10747
10748 ScalarCast = CK_IntegralToFloating;
10749 } else
10750 return true;
10751 } else if (ScalarTy->isEnumeralType())
10752 return true;
10753
10754 // Adjust scalar if desired.
10755 if (Scalar) {
10756 if (ScalarCast != CK_NoOp)
10757 *Scalar = S.ImpCastExprToType(Scalar->get(), VectorEltTy, ScalarCast);
10758 *Scalar = S.ImpCastExprToType(Scalar->get(), VectorTy, CK_VectorSplat);
10759 }
10760 return false;
10761}
10762
10763QualType Sema::CheckVectorOperands(ExprResult &LHS, ExprResult &RHS,
10764 SourceLocation Loc, bool IsCompAssign,
10765 bool AllowBothBool,
10766 bool AllowBoolConversions,
10767 bool AllowBoolOperation,
10768 bool ReportInvalid) {
10769 if (!IsCompAssign) {
10770 LHS = DefaultFunctionArrayLvalueConversion(LHS.get());
10771 if (LHS.isInvalid())
10772 return QualType();
10773 }
10774 RHS = DefaultFunctionArrayLvalueConversion(RHS.get());
10775 if (RHS.isInvalid())
10776 return QualType();
10777
10778 // For conversion purposes, we ignore any qualifiers.
10779 // For example, "const float" and "float" are equivalent.
10780 QualType LHSType = LHS.get()->getType().getUnqualifiedType();
10781 QualType RHSType = RHS.get()->getType().getUnqualifiedType();
10782
10783 const VectorType *LHSVecType = LHSType->getAs<VectorType>();
10784 const VectorType *RHSVecType = RHSType->getAs<VectorType>();
10785 assert(LHSVecType || RHSVecType)(static_cast <bool> (LHSVecType || RHSVecType) ? void (
0) : __assert_fail ("LHSVecType || RHSVecType", "clang/lib/Sema/SemaExpr.cpp"
, 10785, __extension__ __PRETTY_FUNCTION__))
;
10786
10787 if ((LHSVecType && LHSVecType->getElementType()->isBFloat16Type()) ||
10788 (RHSVecType && RHSVecType->getElementType()->isBFloat16Type()))
10789 return ReportInvalid ? InvalidOperands(Loc, LHS, RHS) : QualType();
10790
10791 // AltiVec-style "vector bool op vector bool" combinations are allowed
10792 // for some operators but not others.
10793 if (!AllowBothBool &&
10794 LHSVecType && LHSVecType->getVectorKind() == VectorType::AltiVecBool &&
10795 RHSVecType && RHSVecType->getVectorKind() == VectorType::AltiVecBool)
10796 return ReportInvalid ? InvalidOperands(Loc, LHS, RHS) : QualType();
10797
10798 // This operation may not be performed on boolean vectors.
10799 if (!AllowBoolOperation &&
10800 (LHSType->isExtVectorBoolType() || RHSType->isExtVectorBoolType()))
10801 return ReportInvalid ? InvalidOperands(Loc, LHS, RHS) : QualType();
10802
10803 // If the vector types are identical, return.
10804 if (Context.hasSameType(LHSType, RHSType))
10805 return Context.getCommonSugaredType(LHSType, RHSType);
10806
10807 // If we have compatible AltiVec and GCC vector types, use the AltiVec type.
10808 if (LHSVecType && RHSVecType &&
10809 Context.areCompatibleVectorTypes(LHSType, RHSType)) {
10810 if (isa<ExtVectorType>(LHSVecType)) {
10811 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast);
10812 return LHSType;
10813 }
10814
10815 if (!IsCompAssign)
10816 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_BitCast);
10817 return RHSType;
10818 }
10819
10820 // AllowBoolConversions says that bool and non-bool AltiVec vectors
10821 // can be mixed, with the result being the non-bool type. The non-bool
10822 // operand must have integer element type.
10823 if (AllowBoolConversions && LHSVecType && RHSVecType &&
10824 LHSVecType->getNumElements() == RHSVecType->getNumElements() &&
10825 (Context.getTypeSize(LHSVecType->getElementType()) ==
10826 Context.getTypeSize(RHSVecType->getElementType()))) {
10827 if (LHSVecType->getVectorKind() == VectorType::AltiVecVector &&
10828 LHSVecType->getElementType()->isIntegerType() &&
10829 RHSVecType->getVectorKind() == VectorType::AltiVecBool) {
10830 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast);
10831 return LHSType;
10832 }
10833 if (!IsCompAssign &&
10834 LHSVecType->getVectorKind() == VectorType::AltiVecBool &&
10835 RHSVecType->getVectorKind() == VectorType::AltiVecVector &&
10836 RHSVecType->getElementType()->isIntegerType()) {
10837 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_BitCast);
10838 return RHSType;
10839 }
10840 }
10841
10842 // Expressions containing fixed-length and sizeless SVE/RVV vectors are
10843 // invalid since the ambiguity can affect the ABI.
10844 auto IsSveRVVConversion = [](QualType FirstType, QualType SecondType,
10845 unsigned &SVEorRVV) {
10846 const VectorType *VecType = SecondType->getAs<VectorType>();
10847 SVEorRVV = 0;
10848 if (FirstType->isSizelessBuiltinType() && VecType) {
10849 if (VecType->getVectorKind() == VectorType::SveFixedLengthDataVector ||
10850 VecType->getVectorKind() == VectorType::SveFixedLengthPredicateVector)
10851 return true;
10852 if (VecType->getVectorKind() == VectorType::RVVFixedLengthDataVector) {
10853 SVEorRVV = 1;
10854 return true;
10855 }
10856 }
10857
10858 return false;
10859 };
10860
10861 unsigned SVEorRVV;
10862 if (IsSveRVVConversion(LHSType, RHSType, SVEorRVV) ||
10863 IsSveRVVConversion(RHSType, LHSType, SVEorRVV)) {
10864 Diag(Loc, diag::err_typecheck_sve_rvv_ambiguous)
10865 << SVEorRVV << LHSType << RHSType;
10866 return QualType();
10867 }
10868
10869 // Expressions containing GNU and SVE or RVV (fixed or sizeless) vectors are
10870 // invalid since the ambiguity can affect the ABI.
10871 auto IsSveRVVGnuConversion = [](QualType FirstType, QualType SecondType,
10872 unsigned &SVEorRVV) {
10873 const VectorType *FirstVecType = FirstType->getAs<VectorType>();
10874 const VectorType *SecondVecType = SecondType->getAs<VectorType>();
10875
10876 SVEorRVV = 0;
10877 if (FirstVecType && SecondVecType) {
10878 if (FirstVecType->getVectorKind() == VectorType::GenericVector) {
10879 if (SecondVecType->getVectorKind() ==
10880 VectorType::SveFixedLengthDataVector ||
10881 SecondVecType->getVectorKind() ==
10882 VectorType::SveFixedLengthPredicateVector)
10883 return true;
10884 if (SecondVecType->getVectorKind() ==
10885 VectorType::RVVFixedLengthDataVector) {
10886 SVEorRVV = 1;
10887 return true;
10888 }
10889 }
10890 return false;
10891 }
10892
10893 if (SecondVecType &&
10894 SecondVecType->getVectorKind() == VectorType::GenericVector) {
10895 if (FirstType->isSVESizelessBuiltinType())
10896 return true;
10897 if (FirstType->isRVVSizelessBuiltinType()) {
10898 SVEorRVV = 1;
10899 return true;
10900 }
10901 }
10902
10903 return false;
10904 };
10905
10906 if (IsSveRVVGnuConversion(LHSType, RHSType, SVEorRVV) ||
10907 IsSveRVVGnuConversion(RHSType, LHSType, SVEorRVV)) {
10908 Diag(Loc, diag::err_typecheck_sve_rvv_gnu_ambiguous)
10909 << SVEorRVV << LHSType << RHSType;
10910 return QualType();
10911 }
10912
10913 // If there's a vector type and a scalar, try to convert the scalar to
10914 // the vector element type and splat.
10915 unsigned DiagID = diag::err_typecheck_vector_not_convertable;
10916 if (!RHSVecType) {
10917 if (isa<ExtVectorType>(LHSVecType)) {
10918 if (!tryVectorConvertAndSplat(*this, &RHS, RHSType,
10919 LHSVecType->getElementType(), LHSType,
10920 DiagID))
10921 return LHSType;
10922 } else {
10923 if (!tryGCCVectorConvertAndSplat(*this, &RHS, &LHS))
10924 return LHSType;
10925 }
10926 }
10927 if (!LHSVecType) {
10928 if (isa<ExtVectorType>(RHSVecType)) {
10929 if (!tryVectorConvertAndSplat(*this, (IsCompAssign ? nullptr : &LHS),
10930 LHSType, RHSVecType->getElementType(),
10931 RHSType, DiagID))
10932 return RHSType;
10933 } else {
10934 if (LHS.get()->isLValue() ||
10935 !tryGCCVectorConvertAndSplat(*this, &LHS, &RHS))
10936 return RHSType;
10937 }
10938 }
10939
10940 // FIXME: The code below also handles conversion between vectors and
10941 // non-scalars, we should break this down into fine grained specific checks
10942 // and emit proper diagnostics.
10943 QualType VecType = LHSVecType ? LHSType : RHSType;
10944 const VectorType *VT = LHSVecType ? LHSVecType : RHSVecType;
10945 QualType OtherType = LHSVecType ? RHSType : LHSType;
10946 ExprResult *OtherExpr = LHSVecType ? &RHS : &LHS;
10947 if (isLaxVectorConversion(OtherType, VecType)) {
10948 if (Context.getTargetInfo().getTriple().isPPC() &&
10949 anyAltivecTypes(RHSType, LHSType) &&
10950 !Context.areCompatibleVectorTypes(RHSType, LHSType))
10951 Diag(Loc, diag::warn_deprecated_lax_vec_conv_all) << RHSType << LHSType;
10952 // If we're allowing lax vector conversions, only the total (data) size
10953 // needs to be the same. For non compound assignment, if one of the types is
10954 // scalar, the result is always the vector type.
10955 if (!IsCompAssign) {
10956 *OtherExpr = ImpCastExprToType(OtherExpr->get(), VecType, CK_BitCast);
10957 return VecType;
10958 // In a compound assignment, lhs += rhs, 'lhs' is a lvalue src, forbidding
10959 // any implicit cast. Here, the 'rhs' should be implicit casted to 'lhs'
10960 // type. Note that this is already done by non-compound assignments in
10961 // CheckAssignmentConstraints. If it's a scalar type, only bitcast for
10962 // <1 x T> -> T. The result is also a vector type.
10963 } else if (OtherType->isExtVectorType() || OtherType->isVectorType() ||
10964 (OtherType->isScalarType() && VT->getNumElements() == 1)) {
10965 ExprResult *RHSExpr = &RHS;
10966 *RHSExpr = ImpCastExprToType(RHSExpr->get(), LHSType, CK_BitCast);
10967 return VecType;
10968 }
10969 }
10970
10971 // Okay, the expression is invalid.
10972
10973 // If there's a non-vector, non-real operand, diagnose that.
10974 if ((!RHSVecType && !RHSType->isRealType()) ||
10975 (!LHSVecType && !LHSType->isRealType())) {
10976 Diag(Loc, diag::err_typecheck_vector_not_convertable_non_scalar)
10977 << LHSType << RHSType
10978 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
10979 return QualType();
10980 }
10981
10982 // OpenCL V1.1 6.2.6.p1:
10983 // If the operands are of more than one vector type, then an error shall
10984 // occur. Implicit conversions between vector types are not permitted, per
10985 // section 6.2.1.
10986 if (getLangOpts().OpenCL &&
10987 RHSVecType && isa<ExtVectorType>(RHSVecType) &&
10988 LHSVecType && isa<ExtVectorType>(LHSVecType)) {
10989 Diag(Loc, diag::err_opencl_implicit_vector_conversion) << LHSType
10990 << RHSType;
10991 return QualType();
10992 }
10993
10994
10995 // If there is a vector type that is not a ExtVector and a scalar, we reach
10996 // this point if scalar could not be converted to the vector's element type
10997 // without truncation.
10998 if ((RHSVecType && !isa<ExtVectorType>(RHSVecType)) ||
10999 (LHSVecType && !isa<ExtVectorType>(LHSVecType))) {
11000 QualType Scalar = LHSVecType ? RHSType : LHSType;
11001 QualType Vector = LHSVecType ? LHSType : RHSType;
11002 unsigned ScalarOrVector = LHSVecType && RHSVecType ? 1 : 0;
11003 Diag(Loc,
11004 diag::err_typecheck_vector_not_convertable_implict_truncation)
11005 << ScalarOrVector << Scalar << Vector;
11006
11007 return QualType();
11008 }
11009
11010 // Otherwise, use the generic diagnostic.
11011 Diag(Loc, DiagID)
11012 << LHSType << RHSType
11013 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
11014 return QualType();
11015}
11016
11017QualType Sema::CheckSizelessVectorOperands(ExprResult &LHS, ExprResult &RHS,
11018 SourceLocation Loc,
11019 bool IsCompAssign,
11020 ArithConvKind OperationKind) {
11021 if (!IsCompAssign) {
11022 LHS = DefaultFunctionArrayLvalueConversion(LHS.get());
11023 if (LHS.isInvalid())
11024 return QualType();
11025 }
11026 RHS = DefaultFunctionArrayLvalueConversion(RHS.get());
11027 if (RHS.isInvalid())
11028 return QualType();
11029
11030 QualType LHSType = LHS.get()->getType().getUnqualifiedType();
11031 QualType RHSType = RHS.get()->getType().getUnqualifiedType();
11032
11033 const BuiltinType *LHSBuiltinTy = LHSType->getAs<BuiltinType>();
11034 const BuiltinType *RHSBuiltinTy = RHSType->getAs<BuiltinType>();
11035
11036 unsigned DiagID = diag::err_typecheck_invalid_operands;
11037 if ((OperationKind == ACK_Arithmetic) &&
11038 ((LHSBuiltinTy && LHSBuiltinTy->isSVEBool()) ||
11039 (RHSBuiltinTy && RHSBuiltinTy->isSVEBool()))) {
11040 Diag(Loc, DiagID) << LHSType << RHSType << LHS.get()->getSourceRange()
11041 << RHS.get()->getSourceRange();
11042 return QualType();
11043 }
11044
11045 if (Context.hasSameType(LHSType, RHSType))
11046 return LHSType;
11047
11048 if (LHSType->isVLSTBuiltinType() && !RHSType->isVLSTBuiltinType()) {
11049 if (!tryGCCVectorConvertAndSplat(*this, &RHS, &LHS))
11050 return LHSType;
11051 }
11052 if (RHSType->isVLSTBuiltinType() && !LHSType->isVLSTBuiltinType()) {
11053 if (LHS.get()->isLValue() ||
11054 !tryGCCVectorConvertAndSplat(*this, &LHS, &RHS))
11055 return RHSType;
11056 }
11057
11058 if ((!LHSType->isVLSTBuiltinType() && !LHSType->isRealType()) ||
11059 (!RHSType->isVLSTBuiltinType() && !RHSType->isRealType())) {
11060 Diag(Loc, diag::err_typecheck_vector_not_convertable_non_scalar)
11061 << LHSType << RHSType << LHS.get()->getSourceRange()
11062 << RHS.get()->getSourceRange();
11063 return QualType();
11064 }
11065
11066 if (LHSType->isVLSTBuiltinType() && RHSType->isVLSTBuiltinType() &&
11067 Context.getBuiltinVectorTypeInfo(LHSBuiltinTy).EC !=
11068 Context.getBuiltinVectorTypeInfo(RHSBuiltinTy).EC) {
11069 Diag(Loc, diag::err_typecheck_vector_lengths_not_equal)
11070 << LHSType << RHSType << LHS.get()->getSourceRange()
11071 << RHS.get()->getSourceRange();
11072 return QualType();
11073 }
11074
11075 if (LHSType->isVLSTBuiltinType() || RHSType->isVLSTBuiltinType()) {
11076 QualType Scalar = LHSType->isVLSTBuiltinType() ? RHSType : LHSType;
11077 QualType Vector = LHSType->isVLSTBuiltinType() ? LHSType : RHSType;
11078 bool ScalarOrVector =
11079 LHSType->isVLSTBuiltinType() && RHSType->isVLSTBuiltinType();
11080
11081 Diag(Loc, diag::err_typecheck_vector_not_convertable_implict_truncation)
11082 << ScalarOrVector << Scalar << Vector;
11083
11084 return QualType();
11085 }
11086
11087 Diag(Loc, DiagID) << LHSType << RHSType << LHS.get()->getSourceRange()
11088 << RHS.get()->getSourceRange();
11089 return QualType();
11090}
11091
11092// checkArithmeticNull - Detect when a NULL constant is used improperly in an
11093// expression. These are mainly cases where the null pointer is used as an
11094// integer instead of a pointer.
11095static void checkArithmeticNull(Sema &S, ExprResult &LHS, ExprResult &RHS,
11096 SourceLocation Loc, bool IsCompare) {
11097 // The canonical way to check for a GNU null is with isNullPointerConstant,
11098 // but we use a bit of a hack here for speed; this is a relatively
11099 // hot path, and isNullPointerConstant is slow.
11100 bool LHSNull = isa<GNUNullExpr>(LHS.get()->IgnoreParenImpCasts());
11101 bool RHSNull = isa<GNUNullExpr>(RHS.get()->IgnoreParenImpCasts());
11102
11103 QualType NonNullType = LHSNull ? RHS.get()->getType() : LHS.get()->getType();
11104
11105 // Avoid analyzing cases where the result will either be invalid (and
11106 // diagnosed as such) or entirely valid and not something to warn about.
11107 if ((!LHSNull && !RHSNull) || NonNullType->isBlockPointerType() ||
11108 NonNullType->isMemberPointerType() || NonNullType->isFunctionType())
11109 return;
11110
11111 // Comparison operations would not make sense with a null pointer no matter
11112 // what the other expression is.
11113 if (!IsCompare) {
11114 S.Diag(Loc, diag::warn_null_in_arithmetic_operation)
11115 << (LHSNull ? LHS.get()->getSourceRange() : SourceRange())
11116 << (RHSNull ? RHS.get()->getSourceRange() : SourceRange());
11117 return;
11118 }
11119
11120 // The rest of the operations only make sense with a null pointer
11121 // if the other expression is a pointer.
11122 if (LHSNull == RHSNull || NonNullType->isAnyPointerType() ||
11123 NonNullType->canDecayToPointerType())
11124 return;
11125
11126 S.Diag(Loc, diag::warn_null_in_comparison_operation)
11127 << LHSNull /* LHS is NULL */ << NonNullType
11128 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
11129}
11130
11131static void DiagnoseDivisionSizeofPointerOrArray(Sema &S, Expr *LHS, Expr *RHS,
11132 SourceLocation Loc) {
11133 const auto *LUE = dyn_cast<UnaryExprOrTypeTraitExpr>(LHS);
11134 const auto *RUE = dyn_cast<UnaryExprOrTypeTraitExpr>(RHS);
11135 if (!LUE || !RUE)
11136 return;
11137 if (LUE->getKind() != UETT_SizeOf || LUE->isArgumentType() ||
11138 RUE->getKind() != UETT_SizeOf)
11139 return;
11140
11141 const Expr *LHSArg = LUE->getArgumentExpr()->IgnoreParens();
11142 QualType LHSTy = LHSArg->getType();
11143 QualType RHSTy;
11144
11145 if (RUE->isArgumentType())
11146 RHSTy = RUE->getArgumentType().getNonReferenceType();
11147 else
11148 RHSTy = RUE->getArgumentExpr()->IgnoreParens()->getType();
11149
11150 if (LHSTy->isPointerType() && !RHSTy->isPointerType()) {
11151 if (!S.Context.hasSameUnqualifiedType(LHSTy->getPointeeType(), RHSTy))
11152 return;
11153
11154 S.Diag(Loc, diag::warn_division_sizeof_ptr) << LHS << LHS->getSourceRange();
11155 if (const auto *DRE = dyn_cast<DeclRefExpr>(LHSArg)) {
11156 if (const ValueDecl *LHSArgDecl = DRE->getDecl())
11157 S.Diag(LHSArgDecl->getLocation(), diag::note_pointer_declared_here)
11158 << LHSArgDecl;
11159 }
11160 } else if (const auto *ArrayTy = S.Context.getAsArrayType(LHSTy)) {
11161 QualType ArrayElemTy = ArrayTy->getElementType();
11162 if (ArrayElemTy != S.Context.getBaseElementType(ArrayTy) ||
11163 ArrayElemTy->isDependentType() || RHSTy->isDependentType() ||
11164 RHSTy->isReferenceType() || ArrayElemTy->isCharType() ||
11165 S.Context.getTypeSize(ArrayElemTy) == S.Context.getTypeSize(RHSTy))
11166 return;
11167 S.Diag(Loc, diag::warn_division_sizeof_array)
11168 << LHSArg->getSourceRange() << ArrayElemTy << RHSTy;
11169 if (const auto *DRE = dyn_cast<DeclRefExpr>(LHSArg)) {
11170 if (const ValueDecl *LHSArgDecl = DRE->getDecl())
11171 S.Diag(LHSArgDecl->getLocation(), diag::note_array_declared_here)
11172 << LHSArgDecl;
11173 }
11174
11175 S.Diag(Loc, diag::note_precedence_silence) << RHS;
11176 }
11177}
11178
11179static void DiagnoseBadDivideOrRemainderValues(Sema& S, ExprResult &LHS,
11180 ExprResult &RHS,
11181 SourceLocation Loc, bool IsDiv) {
11182 // Check for division/remainder by zero.
11183 Expr::EvalResult RHSValue;
11184 if (!RHS.get()->isValueDependent() &&
11185 RHS.get()->EvaluateAsInt(RHSValue, S.Context) &&
11186 RHSValue.Val.getInt() == 0)
11187 S.DiagRuntimeBehavior(Loc, RHS.get(),
11188 S.PDiag(diag::warn_remainder_division_by_zero)
11189 << IsDiv << RHS.get()->getSourceRange());
11190}
11191
11192QualType Sema::CheckMultiplyDivideOperands(ExprResult &LHS, ExprResult &RHS,
11193 SourceLocation Loc,
11194 bool IsCompAssign, bool IsDiv) {
11195 checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/false);
11196
11197 QualType LHSTy = LHS.get()->getType();
11198 QualType RHSTy = RHS.get()->getType();
11199 if (LHSTy->isVectorType() || RHSTy->isVectorType())
11200 return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign,
11201 /*AllowBothBool*/ getLangOpts().AltiVec,
11202 /*AllowBoolConversions*/ false,
11203 /*AllowBooleanOperation*/ false,
11204 /*ReportInvalid*/ true);
11205 if (LHSTy->isVLSTBuiltinType() || RHSTy->isVLSTBuiltinType())
11206 return CheckSizelessVectorOperands(LHS, RHS, Loc, IsCompAssign,
11207 ACK_Arithmetic);
11208 if (!IsDiv &&
11209 (LHSTy->isConstantMatrixType() || RHSTy->isConstantMatrixType()))
11210 return CheckMatrixMultiplyOperands(LHS, RHS, Loc, IsCompAssign);
11211 // For division, only matrix-by-scalar is supported. Other combinations with
11212 // matrix types are invalid.
11213 if (IsDiv && LHSTy->isConstantMatrixType() && RHSTy->isArithmeticType())
11214 return CheckMatrixElementwiseOperands(LHS, RHS, Loc, IsCompAssign);
11215
11216 QualType compType = UsualArithmeticConversions(
11217 LHS, RHS, Loc, IsCompAssign ? ACK_CompAssign : ACK_Arithmetic);
11218 if (LHS.isInvalid() || RHS.isInvalid())
11219 return QualType();
11220
11221
11222 if (compType.isNull() || !compType->isArithmeticType())
11223 return InvalidOperands(Loc, LHS, RHS);
11224 if (IsDiv) {
11225 DiagnoseBadDivideOrRemainderValues(*this, LHS, RHS, Loc, IsDiv);
11226 DiagnoseDivisionSizeofPointerOrArray(*this, LHS.get(), RHS.get(), Loc);
11227 }
11228 return compType;
11229}
11230
11231QualType Sema::CheckRemainderOperands(
11232 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, bool IsCompAssign) {
11233 checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/false);
11234
11235 if (LHS.get()->getType()->isVectorType() ||
11236 RHS.get()->getType()->isVectorType()) {
11237 if (LHS.get()->getType()->hasIntegerRepresentation() &&
11238 RHS.get()->getType()->hasIntegerRepresentation())
11239 return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign,
11240 /*AllowBothBool*/ getLangOpts().AltiVec,
11241 /*AllowBoolConversions*/ false,
11242 /*AllowBooleanOperation*/ false,
11243 /*ReportInvalid*/ true);
11244 return InvalidOperands(Loc, LHS, RHS);
11245 }
11246
11247 if (LHS.get()->getType()->isVLSTBuiltinType() ||
11248 RHS.get()->getType()->isVLSTBuiltinType()) {
11249 if (LHS.get()->getType()->hasIntegerRepresentation() &&
11250 RHS.get()->getType()->hasIntegerRepresentation())
11251 return CheckSizelessVectorOperands(LHS, RHS, Loc, IsCompAssign,
11252 ACK_Arithmetic);
11253
11254 return InvalidOperands(Loc, LHS, RHS);
11255 }
11256
11257 QualType compType = UsualArithmeticConversions(
11258 LHS, RHS, Loc, IsCompAssign ? ACK_CompAssign : ACK_Arithmetic);
11259 if (LHS.isInvalid() || RHS.isInvalid())
11260 return QualType();
11261
11262 if (compType.isNull() || !compType->isIntegerType())
11263 return InvalidOperands(Loc, LHS, RHS);
11264 DiagnoseBadDivideOrRemainderValues(*this, LHS, RHS, Loc, false /* IsDiv */);
11265 return compType;
11266}
11267
11268/// Diagnose invalid arithmetic on two void pointers.
11269static void diagnoseArithmeticOnTwoVoidPointers(Sema &S, SourceLocation Loc,
11270 Expr *LHSExpr, Expr *RHSExpr) {
11271 S.Diag(Loc, S.getLangOpts().CPlusPlus
11272 ? diag::err_typecheck_pointer_arith_void_type
11273 : diag::ext_gnu_void_ptr)
11274 << 1 /* two pointers */ << LHSExpr->getSourceRange()
11275 << RHSExpr->getSourceRange();
11276}
11277
11278/// Diagnose invalid arithmetic on a void pointer.
11279static void diagnoseArithmeticOnVoidPointer(Sema &S, SourceLocation Loc,
11280 Expr *Pointer) {
11281 S.Diag(Loc, S.getLangOpts().CPlusPlus
11282 ? diag::err_typecheck_pointer_arith_void_type
11283 : diag::ext_gnu_void_ptr)
11284 << 0 /* one pointer */ << Pointer->getSourceRange();
11285}
11286
11287/// Diagnose invalid arithmetic on a null pointer.
11288///
11289/// If \p IsGNUIdiom is true, the operation is using the 'p = (i8*)nullptr + n'
11290/// idiom, which we recognize as a GNU extension.
11291///
11292static void diagnoseArithmeticOnNullPointer(Sema &S, SourceLocation Loc,
11293 Expr *Pointer, bool IsGNUIdiom) {
11294 if (IsGNUIdiom)
11295 S.Diag(Loc, diag::warn_gnu_null_ptr_arith)
11296 << Pointer->getSourceRange();
11297 else
11298 S.Diag(Loc, diag::warn_pointer_arith_null_ptr)
11299 << S.getLangOpts().CPlusPlus << Pointer->getSourceRange();
11300}
11301
11302/// Diagnose invalid subraction on a null pointer.
11303///
11304static void diagnoseSubtractionOnNullPointer(Sema &S, SourceLocation Loc,
11305 Expr *Pointer, bool BothNull) {
11306 // Null - null is valid in C++ [expr.add]p7
11307 if (BothNull && S.getLangOpts().CPlusPlus)
11308 return;
11309
11310 // Is this s a macro from a system header?
11311 if (S.Diags.getSuppressSystemWarnings() && S.SourceMgr.isInSystemMacro(Loc))
11312 return;
11313
11314 S.DiagRuntimeBehavior(Loc, Pointer,
11315 S.PDiag(diag::warn_pointer_sub_null_ptr)
11316 << S.getLangOpts().CPlusPlus
11317 << Pointer->getSourceRange());
11318}
11319
11320/// Diagnose invalid arithmetic on two function pointers.
11321static void diagnoseArithmeticOnTwoFunctionPointers(Sema &S, SourceLocation Loc,
11322 Expr *LHS, Expr *RHS) {
11323 assert(LHS->getType()->isAnyPointerType())(static_cast <bool> (LHS->getType()->isAnyPointerType
()) ? void (0) : __assert_fail ("LHS->getType()->isAnyPointerType()"
, "clang/lib/Sema/SemaExpr.cpp", 11323, __extension__ __PRETTY_FUNCTION__
))
;
11324 assert(RHS->getType()->isAnyPointerType())(static_cast <bool> (RHS->getType()->isAnyPointerType
()) ? void (0) : __assert_fail ("RHS->getType()->isAnyPointerType()"
, "clang/lib/Sema/SemaExpr.cpp", 11324, __extension__ __PRETTY_FUNCTION__
))
;
11325 S.Diag(Loc, S.getLangOpts().CPlusPlus
11326 ? diag::err_typecheck_pointer_arith_function_type
11327 : diag::ext_gnu_ptr_func_arith)
11328 << 1 /* two pointers */ << LHS->getType()->getPointeeType()
11329 // We only show the second type if it differs from the first.
11330 << (unsigned)!S.Context.hasSameUnqualifiedType(LHS->getType(),
11331 RHS->getType())
11332 << RHS->getType()->getPointeeType()
11333 << LHS->getSourceRange() << RHS->getSourceRange();
11334}
11335
11336/// Diagnose invalid arithmetic on a function pointer.
11337static void diagnoseArithmeticOnFunctionPointer(Sema &S, SourceLocation Loc,
11338 Expr *Pointer) {
11339 assert(Pointer->getType()->isAnyPointerType())(static_cast <bool> (Pointer->getType()->isAnyPointerType
()) ? void (0) : __assert_fail ("Pointer->getType()->isAnyPointerType()"
, "clang/lib/Sema/SemaExpr.cpp", 11339, __extension__ __PRETTY_FUNCTION__
))
;
11340 S.Diag(Loc, S.getLangOpts().CPlusPlus
11341 ? diag::err_typecheck_pointer_arith_function_type
11342 : diag::ext_gnu_ptr_func_arith)
11343 << 0 /* one pointer */ << Pointer->getType()->getPointeeType()
11344 << 0 /* one pointer, so only one type */
11345 << Pointer->getSourceRange();
11346}
11347
11348/// Emit error if Operand is incomplete pointer type
11349///
11350/// \returns True if pointer has incomplete type
11351static bool checkArithmeticIncompletePointerType(Sema &S, SourceLocation Loc,
11352 Expr *Operand) {
11353 QualType ResType = Operand->getType();
11354 if (const AtomicType *ResAtomicType = ResType->getAs<AtomicType>())
11355 ResType = ResAtomicType->getValueType();
11356
11357 assert(ResType->isAnyPointerType() && !ResType->isDependentType())(static_cast <bool> (ResType->isAnyPointerType() &&
!ResType->isDependentType()) ? void (0) : __assert_fail (
"ResType->isAnyPointerType() && !ResType->isDependentType()"
, "clang/lib/Sema/SemaExpr.cpp", 11357, __extension__ __PRETTY_FUNCTION__
))
;
11358 QualType PointeeTy = ResType->getPointeeType();
11359 return S.RequireCompleteSizedType(
11360 Loc, PointeeTy,
11361 diag::err_typecheck_arithmetic_incomplete_or_sizeless_type,
11362 Operand->getSourceRange());
11363}
11364
11365/// Check the validity of an arithmetic pointer operand.
11366///
11367/// If the operand has pointer type, this code will check for pointer types
11368/// which are invalid in arithmetic operations. These will be diagnosed
11369/// appropriately, including whether or not the use is supported as an
11370/// extension.
11371///
11372/// \returns True when the operand is valid to use (even if as an extension).
11373static bool checkArithmeticOpPointerOperand(Sema &S, SourceLocation Loc,
11374 Expr *Operand) {
11375 QualType ResType = Operand->getType();
11376 if (const AtomicType *ResAtomicType = ResType->getAs<AtomicType>())
11377 ResType = ResAtomicType->getValueType();
11378
11379 if (!ResType->isAnyPointerType()) return true;
11380
11381 QualType PointeeTy = ResType->getPointeeType();
11382 if (PointeeTy->isVoidType()) {
11383 diagnoseArithmeticOnVoidPointer(S, Loc, Operand);
11384 return !S.getLangOpts().CPlusPlus;
11385 }
11386 if (PointeeTy->isFunctionType()) {
11387 diagnoseArithmeticOnFunctionPointer(S, Loc, Operand);
11388 return !S.getLangOpts().CPlusPlus;
11389 }
11390
11391 if (checkArithmeticIncompletePointerType(S, Loc, Operand)) return false;
11392
11393 return true;
11394}
11395
11396/// Check the validity of a binary arithmetic operation w.r.t. pointer
11397/// operands.
11398///
11399/// This routine will diagnose any invalid arithmetic on pointer operands much
11400/// like \see checkArithmeticOpPointerOperand. However, it has special logic
11401/// for emitting a single diagnostic even for operations where both LHS and RHS
11402/// are (potentially problematic) pointers.
11403///
11404/// \returns True when the operand is valid to use (even if as an extension).
11405static bool checkArithmeticBinOpPointerOperands(Sema &S, SourceLocation Loc,
11406 Expr *LHSExpr, Expr *RHSExpr) {
11407 bool isLHSPointer = LHSExpr->getType()->isAnyPointerType();
11408 bool isRHSPointer = RHSExpr->getType()->isAnyPointerType();
11409 if (!isLHSPointer && !isRHSPointer) return true;
11410
11411 QualType LHSPointeeTy, RHSPointeeTy;
11412 if (isLHSPointer) LHSPointeeTy = LHSExpr->getType()->getPointeeType();
11413 if (isRHSPointer) RHSPointeeTy = RHSExpr->getType()->getPointeeType();
11414
11415 // if both are pointers check if operation is valid wrt address spaces
11416 if (isLHSPointer && isRHSPointer) {
11417 if (!LHSPointeeTy.isAddressSpaceOverlapping(RHSPointeeTy)) {
11418 S.Diag(Loc,
11419 diag::err_typecheck_op_on_nonoverlapping_address_space_pointers)
11420 << LHSExpr->getType() << RHSExpr->getType() << 1 /*arithmetic op*/
11421 << LHSExpr->getSourceRange() << RHSExpr->getSourceRange();
11422 return false;
11423 }
11424 }
11425
11426 // Check for arithmetic on pointers to incomplete types.
11427 bool isLHSVoidPtr = isLHSPointer && LHSPointeeTy->isVoidType();
11428 bool isRHSVoidPtr = isRHSPointer && RHSPointeeTy->isVoidType();
11429 if (isLHSVoidPtr || isRHSVoidPtr) {
11430 if (!isRHSVoidPtr) diagnoseArithmeticOnVoidPointer(S, Loc, LHSExpr);
11431 else if (!isLHSVoidPtr) diagnoseArithmeticOnVoidPointer(S, Loc, RHSExpr);
11432 else diagnoseArithmeticOnTwoVoidPointers(S, Loc, LHSExpr, RHSExpr);
11433
11434 return !S.getLangOpts().CPlusPlus;
11435 }
11436
11437 bool isLHSFuncPtr = isLHSPointer && LHSPointeeTy->isFunctionType();
11438 bool isRHSFuncPtr = isRHSPointer && RHSPointeeTy->isFunctionType();
11439 if (isLHSFuncPtr || isRHSFuncPtr) {
11440 if (!isRHSFuncPtr) diagnoseArithmeticOnFunctionPointer(S, Loc, LHSExpr);
11441 else if (!isLHSFuncPtr) diagnoseArithmeticOnFunctionPointer(S, Loc,
11442 RHSExpr);
11443 else diagnoseArithmeticOnTwoFunctionPointers(S, Loc, LHSExpr, RHSExpr);
11444
11445 return !S.getLangOpts().CPlusPlus;
11446 }
11447
11448 if (isLHSPointer && checkArithmeticIncompletePointerType(S, Loc, LHSExpr))
11449 return false;
11450 if (isRHSPointer && checkArithmeticIncompletePointerType(S, Loc, RHSExpr))
11451 return false;
11452
11453 return true;
11454}
11455
11456/// diagnoseStringPlusInt - Emit a warning when adding an integer to a string
11457/// literal.
11458static void diagnoseStringPlusInt(Sema &Self, SourceLocation OpLoc,
11459 Expr *LHSExpr, Expr *RHSExpr) {
11460 StringLiteral* StrExpr = dyn_cast<StringLiteral>(LHSExpr->IgnoreImpCasts());
11461 Expr* IndexExpr = RHSExpr;
11462 if (!StrExpr) {
11463 StrExpr = dyn_cast<StringLiteral>(RHSExpr->IgnoreImpCasts());
11464 IndexExpr = LHSExpr;
11465 }
11466
11467 bool IsStringPlusInt = StrExpr &&
11468 IndexExpr->getType()->isIntegralOrUnscopedEnumerationType();
11469 if (!IsStringPlusInt || IndexExpr->isValueDependent())
11470 return;
11471
11472 SourceRange DiagRange(LHSExpr->getBeginLoc(), RHSExpr->getEndLoc());
11473 Self.Diag(OpLoc, diag::warn_string_plus_int)
11474 << DiagRange << IndexExpr->IgnoreImpCasts()->getType();
11475
11476 // Only print a fixit for "str" + int, not for int + "str".
11477 if (IndexExpr == RHSExpr) {
11478 SourceLocation EndLoc = Self.getLocForEndOfToken(RHSExpr->getEndLoc());
11479 Self.Diag(OpLoc, diag::note_string_plus_scalar_silence)
11480 << FixItHint::CreateInsertion(LHSExpr->getBeginLoc(), "&")
11481 << FixItHint::CreateReplacement(SourceRange(OpLoc), "[")
11482 << FixItHint::CreateInsertion(EndLoc, "]");
11483 } else
11484 Self.Diag(OpLoc, diag::note_string_plus_scalar_silence);
11485}
11486
11487/// Emit a warning when adding a char literal to a string.
11488static void diagnoseStringPlusChar(Sema &Self, SourceLocation OpLoc,
11489 Expr *LHSExpr, Expr *RHSExpr) {
11490 const Expr *StringRefExpr = LHSExpr;
11491 const CharacterLiteral *CharExpr =
11492 dyn_cast<CharacterLiteral>(RHSExpr->IgnoreImpCasts());
11493
11494 if (!CharExpr) {
11495 CharExpr = dyn_cast<CharacterLiteral>(LHSExpr->IgnoreImpCasts());
11496 StringRefExpr = RHSExpr;
11497 }
11498
11499 if (!CharExpr || !StringRefExpr)
11500 return;
11501
11502 const QualType StringType = StringRefExpr->getType();
11503
11504 // Return if not a PointerType.
11505 if (!StringType->isAnyPointerType())
11506 return;
11507
11508 // Return if not a CharacterType.
11509 if (!StringType->getPointeeType()->isAnyCharacterType())
11510 return;
11511
11512 ASTContext &Ctx = Self.getASTContext();
11513 SourceRange DiagRange(LHSExpr->getBeginLoc(), RHSExpr->getEndLoc());
11514
11515 const QualType CharType = CharExpr->getType();
11516 if (!CharType->isAnyCharacterType() &&
11517 CharType->isIntegerType() &&
11518 llvm::isUIntN(Ctx.getCharWidth(), CharExpr->getValue())) {
11519 Self.Diag(OpLoc, diag::warn_string_plus_char)
11520 << DiagRange << Ctx.CharTy;
11521 } else {
11522 Self.Diag(OpLoc, diag::warn_string_plus_char)
11523 << DiagRange << CharExpr->getType();
11524 }
11525
11526 // Only print a fixit for str + char, not for char + str.
11527 if (isa<CharacterLiteral>(RHSExpr->IgnoreImpCasts())) {
11528 SourceLocation EndLoc = Self.getLocForEndOfToken(RHSExpr->getEndLoc());
11529 Self.Diag(OpLoc, diag::note_string_plus_scalar_silence)
11530 << FixItHint::CreateInsertion(LHSExpr->getBeginLoc(), "&")
11531 << FixItHint::CreateReplacement(SourceRange(OpLoc), "[")
11532 << FixItHint::CreateInsertion(EndLoc, "]");
11533 } else {
11534 Self.Diag(OpLoc, diag::note_string_plus_scalar_silence);
11535 }
11536}
11537
11538/// Emit error when two pointers are incompatible.
11539static void diagnosePointerIncompatibility(Sema &S, SourceLocation Loc,
11540 Expr *LHSExpr, Expr *RHSExpr) {
11541 assert(LHSExpr->getType()->isAnyPointerType())(static_cast <bool> (LHSExpr->getType()->isAnyPointerType
()) ? void (0) : __assert_fail ("LHSExpr->getType()->isAnyPointerType()"
, "clang/lib/Sema/SemaExpr.cpp", 11541, __extension__ __PRETTY_FUNCTION__
))
;
11542 assert(RHSExpr->getType()->isAnyPointerType())(static_cast <bool> (RHSExpr->getType()->isAnyPointerType
()) ? void (0) : __assert_fail ("RHSExpr->getType()->isAnyPointerType()"
, "clang/lib/Sema/SemaExpr.cpp", 11542, __extension__ __PRETTY_FUNCTION__
))
;
11543 S.Diag(Loc, diag::err_typecheck_sub_ptr_compatible)
11544 << LHSExpr->getType() << RHSExpr->getType() << LHSExpr->getSourceRange()
11545 << RHSExpr->getSourceRange();
11546}
11547
11548// C99 6.5.6
11549QualType Sema::CheckAdditionOperands(ExprResult &LHS, ExprResult &RHS,
11550 SourceLocation Loc, BinaryOperatorKind Opc,
11551 QualType* CompLHSTy) {
11552 checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/false);
11553
11554 if (LHS.get()->getType()->isVectorType() ||
11555 RHS.get()->getType()->isVectorType()) {
11556 QualType compType =
11557 CheckVectorOperands(LHS, RHS, Loc, CompLHSTy,
11558 /*AllowBothBool*/ getLangOpts().AltiVec,
11559 /*AllowBoolConversions*/ getLangOpts().ZVector,
11560 /*AllowBooleanOperation*/ false,
11561 /*ReportInvalid*/ true);
11562 if (CompLHSTy) *CompLHSTy = compType;
11563 return compType;
11564 }
11565
11566 if (LHS.get()->getType()->isVLSTBuiltinType() ||
11567 RHS.get()->getType()->isVLSTBuiltinType()) {
11568 QualType compType =
11569 CheckSizelessVectorOperands(LHS, RHS, Loc, CompLHSTy, ACK_Arithmetic);
11570 if (CompLHSTy)
11571 *CompLHSTy = compType;
11572 return compType;
11573 }
11574
11575 if (LHS.get()->getType()->isConstantMatrixType() ||
11576 RHS.get()->getType()->isConstantMatrixType()) {
11577 QualType compType =
11578 CheckMatrixElementwiseOperands(LHS, RHS, Loc, CompLHSTy);
11579 if (CompLHSTy)
11580 *CompLHSTy = compType;
11581 return compType;
11582 }
11583
11584 QualType compType = UsualArithmeticConversions(
11585 LHS, RHS, Loc, CompLHSTy ? ACK_CompAssign : ACK_Arithmetic);
11586 if (LHS.isInvalid() || RHS.isInvalid())
11587 return QualType();
11588
11589 // Diagnose "string literal" '+' int and string '+' "char literal".
11590 if (Opc == BO_Add) {
11591 diagnoseStringPlusInt(*this, Loc, LHS.get(), RHS.get());
11592 diagnoseStringPlusChar(*this, Loc, LHS.get(), RHS.get());
11593 }
11594
11595 // handle the common case first (both operands are arithmetic).
11596 if (!compType.isNull() && compType->isArithmeticType()) {
11597 if (CompLHSTy) *CompLHSTy = compType;
11598 return compType;
11599 }
11600
11601 // Type-checking. Ultimately the pointer's going to be in PExp;
11602 // note that we bias towards the LHS being the pointer.
11603 Expr *PExp = LHS.get(), *IExp = RHS.get();
11604
11605 bool isObjCPointer;
11606 if (PExp->getType()->isPointerType()) {
11607 isObjCPointer = false;
11608 } else if (PExp->getType()->isObjCObjectPointerType()) {
11609 isObjCPointer = true;
11610 } else {
11611 std::swap(PExp, IExp);
11612 if (PExp->getType()->isPointerType()) {
11613 isObjCPointer = false;
11614 } else if (PExp->getType()->isObjCObjectPointerType()) {
11615 isObjCPointer = true;
11616 } else {
11617 return InvalidOperands(Loc, LHS, RHS);
11618 }
11619 }
11620 assert(PExp->getType()->isAnyPointerType())(static_cast <bool> (PExp->getType()->isAnyPointerType
()) ? void (0) : __assert_fail ("PExp->getType()->isAnyPointerType()"
, "clang/lib/Sema/SemaExpr.cpp", 11620, __extension__ __PRETTY_FUNCTION__
))
;
11621
11622 if (!IExp->getType()->isIntegerType())
11623 return InvalidOperands(Loc, LHS, RHS);
11624
11625 // Adding to a null pointer results in undefined behavior.
11626 if (PExp->IgnoreParenCasts()->isNullPointerConstant(
11627 Context, Expr::NPC_ValueDependentIsNotNull)) {
11628 // In C++ adding zero to a null pointer is defined.
11629 Expr::EvalResult KnownVal;
11630 if (!getLangOpts().CPlusPlus ||
11631 (!IExp->isValueDependent() &&
11632 (!IExp->EvaluateAsInt(KnownVal, Context) ||
11633 KnownVal.Val.getInt() != 0))) {
11634 // Check the conditions to see if this is the 'p = nullptr + n' idiom.
11635 bool IsGNUIdiom = BinaryOperator::isNullPointerArithmeticExtension(
11636 Context, BO_Add, PExp, IExp);
11637 diagnoseArithmeticOnNullPointer(*this, Loc, PExp, IsGNUIdiom);
11638 }
11639 }
11640
11641 if (!checkArithmeticOpPointerOperand(*this, Loc, PExp))
11642 return QualType();
11643
11644 if (isObjCPointer && checkArithmeticOnObjCPointer(*this, Loc, PExp))
11645 return QualType();
11646
11647 // Check array bounds for pointer arithemtic
11648 CheckArrayAccess(PExp, IExp);
11649
11650 if (CompLHSTy) {
11651 QualType LHSTy = Context.isPromotableBitField(LHS.get());
11652 if (LHSTy.isNull()) {
11653 LHSTy = LHS.get()->getType();
11654 if (Context.isPromotableIntegerType(LHSTy))
11655 LHSTy = Context.getPromotedIntegerType(LHSTy);
11656 }
11657 *CompLHSTy = LHSTy;
11658 }
11659
11660 return PExp->getType();
11661}
11662
11663// C99 6.5.6
11664QualType Sema::CheckSubtractionOperands(ExprResult &LHS, ExprResult &RHS,
11665 SourceLocation Loc,
11666 QualType* CompLHSTy) {
11667 checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/false);
11668
11669 if (LHS.get()->getType()->isVectorType() ||
11670 RHS.get()->getType()->isVectorType()) {
11671 QualType compType =
11672 CheckVectorOperands(LHS, RHS, Loc, CompLHSTy,
11673 /*AllowBothBool*/ getLangOpts().AltiVec,
11674 /*AllowBoolConversions*/ getLangOpts().ZVector,
11675 /*AllowBooleanOperation*/ false,
11676 /*ReportInvalid*/ true);
11677 if (CompLHSTy) *CompLHSTy = compType;
11678 return compType;
11679 }
11680
11681 if (LHS.get()->getType()->isVLSTBuiltinType() ||
11682 RHS.get()->getType()->isVLSTBuiltinType()) {
11683 QualType compType =
11684 CheckSizelessVectorOperands(LHS, RHS, Loc, CompLHSTy, ACK_Arithmetic);
11685 if (CompLHSTy)
11686 *CompLHSTy = compType;
11687 return compType;
11688 }
11689
11690 if (LHS.get()->getType()->isConstantMatrixType() ||
11691 RHS.get()->getType()->isConstantMatrixType()) {
11692 QualType compType =
11693 CheckMatrixElementwiseOperands(LHS, RHS, Loc, CompLHSTy);
11694 if (CompLHSTy)
11695 *CompLHSTy = compType;
11696 return compType;
11697 }
11698
11699 QualType compType = UsualArithmeticConversions(
11700 LHS, RHS, Loc, CompLHSTy ? ACK_CompAssign : ACK_Arithmetic);
11701 if (LHS.isInvalid() || RHS.isInvalid())
11702 return QualType();
11703
11704 // Enforce type constraints: C99 6.5.6p3.
11705
11706 // Handle the common case first (both operands are arithmetic).
11707 if (!compType.isNull() && compType->isArithmeticType()) {
11708 if (CompLHSTy) *CompLHSTy = compType;
11709 return compType;
11710 }
11711
11712 // Either ptr - int or ptr - ptr.
11713 if (LHS.get()->getType()->isAnyPointerType()) {
11714 QualType lpointee = LHS.get()->getType()->getPointeeType();
11715
11716 // Diagnose bad cases where we step over interface counts.
11717 if (LHS.get()->getType()->isObjCObjectPointerType() &&
11718 checkArithmeticOnObjCPointer(*this, Loc, LHS.get()))
11719 return QualType();
11720
11721 // The result type of a pointer-int computation is the pointer type.
11722 if (RHS.get()->getType()->isIntegerType()) {
11723 // Subtracting from a null pointer should produce a warning.
11724 // The last argument to the diagnose call says this doesn't match the
11725 // GNU int-to-pointer idiom.
11726 if (LHS.get()->IgnoreParenCasts()->isNullPointerConstant(Context,
11727 Expr::NPC_ValueDependentIsNotNull)) {
11728 // In C++ adding zero to a null pointer is defined.
11729 Expr::EvalResult KnownVal;
11730 if (!getLangOpts().CPlusPlus ||
11731 (!RHS.get()->isValueDependent() &&
11732 (!RHS.get()->EvaluateAsInt(KnownVal, Context) ||
11733 KnownVal.Val.getInt() != 0))) {
11734 diagnoseArithmeticOnNullPointer(*this, Loc, LHS.get(), false);
11735 }
11736 }
11737
11738 if (!checkArithmeticOpPointerOperand(*this, Loc, LHS.get()))
11739 return QualType();
11740
11741 // Check array bounds for pointer arithemtic
11742 CheckArrayAccess(LHS.get(), RHS.get(), /*ArraySubscriptExpr*/nullptr,
11743 /*AllowOnePastEnd*/true, /*IndexNegated*/true);
11744
11745 if (CompLHSTy) *CompLHSTy = LHS.get()->getType();
11746 return LHS.get()->getType();
11747 }
11748
11749 // Handle pointer-pointer subtractions.
11750 if (const PointerType *RHSPTy
11751 = RHS.get()->getType()->getAs<PointerType>()) {
11752 QualType rpointee = RHSPTy->getPointeeType();
11753
11754 if (getLangOpts().CPlusPlus) {
11755 // Pointee types must be the same: C++ [expr.add]
11756 if (!Context.hasSameUnqualifiedType(lpointee, rpointee)) {
11757 diagnosePointerIncompatibility(*this, Loc, LHS.get(), RHS.get());
11758 }
11759 } else {
11760 // Pointee types must be compatible C99 6.5.6p3
11761 if (!Context.typesAreCompatible(
11762 Context.getCanonicalType(lpointee).getUnqualifiedType(),
11763 Context.getCanonicalType(rpointee).getUnqualifiedType())) {
11764 diagnosePointerIncompatibility(*this, Loc, LHS.get(), RHS.get());
11765 return QualType();
11766 }
11767 }
11768
11769 if (!checkArithmeticBinOpPointerOperands(*this, Loc,
11770 LHS.get(), RHS.get()))
11771 return QualType();
11772
11773 bool LHSIsNullPtr = LHS.get()->IgnoreParenCasts()->isNullPointerConstant(
11774 Context, Expr::NPC_ValueDependentIsNotNull);
11775 bool RHSIsNullPtr = RHS.get()->IgnoreParenCasts()->isNullPointerConstant(
11776 Context, Expr::NPC_ValueDependentIsNotNull);
11777
11778 // Subtracting nullptr or from nullptr is suspect
11779 if (LHSIsNullPtr)
11780 diagnoseSubtractionOnNullPointer(*this, Loc, LHS.get(), RHSIsNullPtr);
11781 if (RHSIsNullPtr)
11782 diagnoseSubtractionOnNullPointer(*this, Loc, RHS.get(), LHSIsNullPtr);
11783
11784 // The pointee type may have zero size. As an extension, a structure or
11785 // union may have zero size or an array may have zero length. In this
11786 // case subtraction does not make sense.
11787 if (!rpointee->isVoidType() && !rpointee->isFunctionType()) {
11788 CharUnits ElementSize = Context.getTypeSizeInChars(rpointee);
11789 if (ElementSize.isZero()) {
11790 Diag(Loc,diag::warn_sub_ptr_zero_size_types)
11791 << rpointee.getUnqualifiedType()
11792 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
11793 }
11794 }
11795
11796 if (CompLHSTy) *CompLHSTy = LHS.get()->getType();
11797 return Context.getPointerDiffType();
11798 }
11799 }
11800
11801 return InvalidOperands(Loc, LHS, RHS);
11802}
11803
11804static bool isScopedEnumerationType(QualType T) {
11805 if (const EnumType *ET = T->getAs<EnumType>())
11806 return ET->getDecl()->isScoped();
11807 return false;
11808}
11809
11810static void DiagnoseBadShiftValues(Sema& S, ExprResult &LHS, ExprResult &RHS,
11811 SourceLocation Loc, BinaryOperatorKind Opc,
11812 QualType LHSType) {
11813 // OpenCL 6.3j: shift values are effectively % word size of LHS (more defined),
11814 // so skip remaining warnings as we don't want to modify values within Sema.
11815 if (S.getLangOpts().OpenCL)
11816 return;
11817
11818 // Check right/shifter operand
11819 Expr::EvalResult RHSResult;
11820 if (RHS.get()->isValueDependent() ||
11821 !RHS.get()->EvaluateAsInt(RHSResult, S.Context))
11822 return;
11823 llvm::APSInt Right = RHSResult.Val.getInt();
11824
11825 if (Right.isNegative()) {
11826 S.DiagRuntimeBehavior(Loc, RHS.get(),
11827 S.PDiag(diag::warn_shift_negative)
11828 << RHS.get()->getSourceRange());
11829 return;
11830 }
11831
11832 QualType LHSExprType = LHS.get()->getType();
11833 uint64_t LeftSize = S.Context.getTypeSize(LHSExprType);
11834 if (LHSExprType->isBitIntType())
11835 LeftSize = S.Context.getIntWidth(LHSExprType);
11836 else if (LHSExprType->isFixedPointType()) {
11837 auto FXSema = S.Context.getFixedPointSemantics(LHSExprType);
11838 LeftSize = FXSema.getWidth() - (unsigned)FXSema.hasUnsignedPadding();
11839 }
11840 llvm::APInt LeftBits(Right.getBitWidth(), LeftSize);
11841 if (Right.uge(LeftBits)) {
11842 S.DiagRuntimeBehavior(Loc, RHS.get(),
11843 S.PDiag(diag::warn_shift_gt_typewidth)
11844 << RHS.get()->getSourceRange());
11845 return;
11846 }
11847
11848 // FIXME: We probably need to handle fixed point types specially here.
11849 if (Opc != BO_Shl || LHSExprType->isFixedPointType())
11850 return;
11851
11852 // When left shifting an ICE which is signed, we can check for overflow which
11853 // according to C++ standards prior to C++2a has undefined behavior
11854 // ([expr.shift] 5.8/2). Unsigned integers have defined behavior modulo one
11855 // more than the maximum value representable in the result type, so never
11856 // warn for those. (FIXME: Unsigned left-shift overflow in a constant
11857 // expression is still probably a bug.)
11858 Expr::EvalResult LHSResult;
11859 if (LHS.get()->isValueDependent() ||
11860 LHSType->hasUnsignedIntegerRepresentation() ||
11861 !LHS.get()->EvaluateAsInt(LHSResult, S.Context))
11862 return;
11863 llvm::APSInt Left = LHSResult.Val.getInt();
11864
11865 // Don't warn if signed overflow is defined, then all the rest of the
11866 // diagnostics will not be triggered because the behavior is defined.
11867 // Also don't warn in C++20 mode (and newer), as signed left shifts
11868 // always wrap and never overflow.
11869 if (S.getLangOpts().isSignedOverflowDefined() || S.getLangOpts().CPlusPlus20)
11870 return;
11871
11872 // If LHS does not have a non-negative value then, the
11873 // behavior is undefined before C++2a. Warn about it.
11874 if (Left.isNegative()) {
11875 S.DiagRuntimeBehavior(Loc, LHS.get(),
11876 S.PDiag(diag::warn_shift_lhs_negative)
11877 << LHS.get()->getSourceRange());
11878 return;
11879 }
11880
11881 llvm::APInt ResultBits =
11882 static_cast<llvm::APInt &>(Right) + Left.getSignificantBits();
11883 if (LeftBits.uge(ResultBits))
11884 return;
11885 llvm::APSInt Result = Left.extend(ResultBits.getLimitedValue());
11886 Result = Result.shl(Right);
11887
11888 // Print the bit representation of the signed integer as an unsigned
11889 // hexadecimal number.
11890 SmallString<40> HexResult;
11891 Result.toString(HexResult, 16, /*Signed =*/false, /*Literal =*/true);
11892
11893 // If we are only missing a sign bit, this is less likely to result in actual
11894 // bugs -- if the result is cast back to an unsigned type, it will have the
11895 // expected value. Thus we place this behind a different warning that can be
11896 // turned off separately if needed.
11897 if (LeftBits == ResultBits - 1) {
11898 S.Diag(Loc, diag::warn_shift_result_sets_sign_bit)
11899 << HexResult << LHSType
11900 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
11901 return;
11902 }
11903
11904 S.Diag(Loc, diag::warn_shift_result_gt_typewidth)
11905 << HexResult.str() << Result.getSignificantBits() << LHSType
11906 << Left.getBitWidth() << LHS.get()->getSourceRange()
11907 << RHS.get()->getSourceRange();
11908}
11909
11910/// Return the resulting type when a vector is shifted
11911/// by a scalar or vector shift amount.
11912static QualType checkVectorShift(Sema &S, ExprResult &LHS, ExprResult &RHS,
11913 SourceLocation Loc, bool IsCompAssign) {
11914 // OpenCL v1.1 s6.3.j says RHS can be a vector only if LHS is a vector.
11915 if ((S.LangOpts.OpenCL || S.LangOpts.ZVector) &&
11916 !LHS.get()->getType()->isVectorType()) {
11917 S.Diag(Loc, diag::err_shift_rhs_only_vector)
11918 << RHS.get()->getType() << LHS.get()->getType()
11919 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
11920 return QualType();
11921 }
11922
11923 if (!IsCompAssign) {
11924 LHS = S.UsualUnaryConversions(LHS.get());
11925 if (LHS.isInvalid()) return QualType();
11926 }
11927
11928 RHS = S.UsualUnaryConversions(RHS.get());
11929 if (RHS.isInvalid()) return QualType();
11930
11931 QualType LHSType = LHS.get()->getType();
11932 // Note that LHS might be a scalar because the routine calls not only in
11933 // OpenCL case.
11934 const VectorType *LHSVecTy = LHSType->getAs<VectorType>();
11935 QualType LHSEleType = LHSVecTy ? LHSVecTy->getElementType() : LHSType;
11936
11937 // Note that RHS might not be a vector.
11938 QualType RHSType = RHS.get()->getType();
11939 const VectorType *RHSVecTy = RHSType->getAs<VectorType>();
11940 QualType RHSEleType = RHSVecTy ? RHSVecTy->getElementType() : RHSType;
11941
11942 // Do not allow shifts for boolean vectors.
11943 if ((LHSVecTy && LHSVecTy->isExtVectorBoolType()) ||
11944 (RHSVecTy && RHSVecTy->isExtVectorBoolType())) {
11945 S.Diag(Loc, diag::err_typecheck_invalid_operands)
11946 << LHS.get()->getType() << RHS.get()->getType()
11947 << LHS.get()->getSourceRange();
11948 return QualType();
11949 }
11950
11951 // The operands need to be integers.
11952 if (!LHSEleType->isIntegerType()) {
11953 S.Diag(Loc, diag::err_typecheck_expect_int)
11954 << LHS.get()->getType() << LHS.get()->getSourceRange();
11955 return QualType();
11956 }
11957
11958 if (!RHSEleType->isIntegerType()) {
11959 S.Diag(Loc, diag::err_typecheck_expect_int)
11960 << RHS.get()->getType() << RHS.get()->getSourceRange();
11961 return QualType();
11962 }
11963
11964 if (!LHSVecTy) {
11965 assert(RHSVecTy)(static_cast <bool> (RHSVecTy) ? void (0) : __assert_fail
("RHSVecTy", "clang/lib/Sema/SemaExpr.cpp", 11965, __extension__
__PRETTY_FUNCTION__))
;
11966 if (IsCompAssign)
11967 return RHSType;
11968 if (LHSEleType != RHSEleType) {
11969 LHS = S.ImpCastExprToType(LHS.get(),RHSEleType, CK_IntegralCast);
11970 LHSEleType = RHSEleType;
11971 }
11972 QualType VecTy =
11973 S.Context.getExtVectorType(LHSEleType, RHSVecTy->getNumElements());
11974 LHS = S.ImpCastExprToType(LHS.get(), VecTy, CK_VectorSplat);
11975 LHSType = VecTy;
11976 } else if (RHSVecTy) {
11977 // OpenCL v1.1 s6.3.j says that for vector types, the operators
11978 // are applied component-wise. So if RHS is a vector, then ensure
11979 // that the number of elements is the same as LHS...
11980 if (RHSVecTy->getNumElements() != LHSVecTy->getNumElements()) {
11981 S.Diag(Loc, diag::err_typecheck_vector_lengths_not_equal)
11982 << LHS.get()->getType() << RHS.get()->getType()
11983 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
11984 return QualType();
11985 }
11986 if (!S.LangOpts.OpenCL && !S.LangOpts.ZVector) {
11987 const BuiltinType *LHSBT = LHSEleType->getAs<clang::BuiltinType>();
11988 const BuiltinType *RHSBT = RHSEleType->getAs<clang::BuiltinType>();
11989 if (LHSBT != RHSBT &&
11990 S.Context.getTypeSize(LHSBT) != S.Context.getTypeSize(RHSBT)) {
11991 S.Diag(Loc, diag::warn_typecheck_vector_element_sizes_not_equal)
11992 << LHS.get()->getType() << RHS.get()->getType()
11993 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
11994 }
11995 }
11996 } else {
11997 // ...else expand RHS to match the number of elements in LHS.
11998 QualType VecTy =
11999 S.Context.getExtVectorType(RHSEleType, LHSVecTy->getNumElements());
12000 RHS = S.ImpCastExprToType(RHS.get(), VecTy, CK_VectorSplat);
12001 }
12002
12003 return LHSType;
12004}
12005
12006static QualType checkSizelessVectorShift(Sema &S, ExprResult &LHS,
12007 ExprResult &RHS, SourceLocation Loc,
12008 bool IsCompAssign) {
12009 if (!IsCompAssign) {
12010 LHS = S.UsualUnaryConversions(LHS.get());
12011 if (LHS.isInvalid())
12012 return QualType();
12013 }
12014
12015 RHS = S.UsualUnaryConversions(RHS.get());
12016 if (RHS.isInvalid())
12017 return QualType();
12018
12019 QualType LHSType = LHS.get()->getType();
12020 const BuiltinType *LHSBuiltinTy = LHSType->getAs<BuiltinType>();
12021 QualType LHSEleType = LHSType->isVLSTBuiltinType()
12022 ? LHSBuiltinTy->getSveEltType(S.getASTContext())
12023 : LHSType;
12024
12025 // Note that RHS might not be a vector
12026 QualType RHSType = RHS.get()->getType();
12027 const BuiltinType *RHSBuiltinTy = RHSType->getAs<BuiltinType>();
12028 QualType RHSEleType = RHSType->isVLSTBuiltinType()
12029 ? RHSBuiltinTy->getSveEltType(S.getASTContext())
12030 : RHSType;
12031
12032 if ((LHSBuiltinTy && LHSBuiltinTy->isSVEBool()) ||
12033 (RHSBuiltinTy && RHSBuiltinTy->isSVEBool())) {
12034 S.Diag(Loc, diag::err_typecheck_invalid_operands)
12035 << LHSType << RHSType << LHS.get()->getSourceRange();
12036 return QualType();
12037 }
12038
12039 if (!LHSEleType->isIntegerType()) {
12040 S.Diag(Loc, diag::err_typecheck_expect_int)
12041 << LHS.get()->getType() << LHS.get()->getSourceRange();
12042 return QualType();
12043 }
12044
12045 if (!RHSEleType->isIntegerType()) {
12046 S.Diag(Loc, diag::err_typecheck_expect_int)
12047 << RHS.get()->getType() << RHS.get()->getSourceRange();
12048 return QualType();
12049 }
12050
12051 if (LHSType->isVLSTBuiltinType() && RHSType->isVLSTBuiltinType() &&
12052 (S.Context.getBuiltinVectorTypeInfo(LHSBuiltinTy).EC !=
12053 S.Context.getBuiltinVectorTypeInfo(RHSBuiltinTy).EC)) {
12054 S.Diag(Loc, diag::err_typecheck_invalid_operands)
12055 << LHSType << RHSType << LHS.get()->getSourceRange()
12056 << RHS.get()->getSourceRange();
12057 return QualType();
12058 }
12059
12060 if (!LHSType->isVLSTBuiltinType()) {
12061 assert(RHSType->isVLSTBuiltinType())(static_cast <bool> (RHSType->isVLSTBuiltinType()) ?
void (0) : __assert_fail ("RHSType->isVLSTBuiltinType()",
"clang/lib/Sema/SemaExpr.cpp", 12061, __extension__ __PRETTY_FUNCTION__
))
;
12062 if (IsCompAssign)
12063 return RHSType;
12064 if (LHSEleType != RHSEleType) {
12065 LHS = S.ImpCastExprToType(LHS.get(), RHSEleType, clang::CK_IntegralCast);
12066 LHSEleType = RHSEleType;
12067 }
12068 const llvm::ElementCount VecSize =
12069 S.Context.getBuiltinVectorTypeInfo(RHSBuiltinTy).EC;
12070 QualType VecTy =
12071 S.Context.getScalableVectorType(LHSEleType, VecSize.getKnownMinValue());
12072 LHS = S.ImpCastExprToType(LHS.get(), VecTy, clang::CK_VectorSplat);
12073 LHSType = VecTy;
12074 } else if (RHSBuiltinTy && RHSBuiltinTy->isVLSTBuiltinType()) {
12075 if (S.Context.getTypeSize(RHSBuiltinTy) !=
12076 S.Context.getTypeSize(LHSBuiltinTy)) {
12077 S.Diag(Loc, diag::err_typecheck_vector_lengths_not_equal)
12078 << LHSType << RHSType << LHS.get()->getSourceRange()
12079 << RHS.get()->getSourceRange();
12080 return QualType();
12081 }
12082 } else {
12083 const llvm::ElementCount VecSize =
12084 S.Context.getBuiltinVectorTypeInfo(LHSBuiltinTy).EC;
12085 if (LHSEleType != RHSEleType) {
12086 RHS = S.ImpCastExprToType(RHS.get(), LHSEleType, clang::CK_IntegralCast);
12087 RHSEleType = LHSEleType;
12088 }
12089 QualType VecTy =
12090 S.Context.getScalableVectorType(RHSEleType, VecSize.getKnownMinValue());
12091 RHS = S.ImpCastExprToType(RHS.get(), VecTy, CK_VectorSplat);
12092 }
12093
12094 return LHSType;
12095}
12096
12097// C99 6.5.7
12098QualType Sema::CheckShiftOperands(ExprResult &LHS, ExprResult &RHS,
12099 SourceLocation Loc, BinaryOperatorKind Opc,
12100 bool IsCompAssign) {
12101 checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/false);
12102
12103 // Vector shifts promote their scalar inputs to vector type.
12104 if (LHS.get()->getType()->isVectorType() ||
12105 RHS.get()->getType()->isVectorType()) {
12106 if (LangOpts.ZVector) {
12107 // The shift operators for the z vector extensions work basically
12108 // like general shifts, except that neither the LHS nor the RHS is
12109 // allowed to be a "vector bool".
12110 if (auto LHSVecType = LHS.get()->getType()->getAs<VectorType>())
12111 if (LHSVecType->getVectorKind() == VectorType::AltiVecBool)
12112 return InvalidOperands(Loc, LHS, RHS);
12113 if (auto RHSVecType = RHS.get()->getType()->getAs<VectorType>())
12114 if (RHSVecType->getVectorKind() == VectorType::AltiVecBool)
12115 return InvalidOperands(Loc, LHS, RHS);
12116 }
12117 return checkVectorShift(*this, LHS, RHS, Loc, IsCompAssign);
12118 }
12119
12120 if (LHS.get()->getType()->isVLSTBuiltinType() ||
12121 RHS.get()->getType()->isVLSTBuiltinType())
12122 return checkSizelessVectorShift(*this, LHS, RHS, Loc, IsCompAssign);
12123
12124 // Shifts don't perform usual arithmetic conversions, they just do integer
12125 // promotions on each operand. C99 6.5.7p3
12126
12127 // For the LHS, do usual unary conversions, but then reset them away
12128 // if this is a compound assignment.
12129 ExprResult OldLHS = LHS;
12130 LHS = UsualUnaryConversions(LHS.get());
12131 if (LHS.isInvalid())
12132 return QualType();
12133 QualType LHSType = LHS.get()->getType();
12134 if (IsCompAssign) LHS = OldLHS;
12135
12136 // The RHS is simpler.
12137 RHS = UsualUnaryConversions(RHS.get());
12138 if (RHS.isInvalid())
12139 return QualType();
12140 QualType RHSType = RHS.get()->getType();
12141
12142 // C99 6.5.7p2: Each of the operands shall have integer type.
12143 // Embedded-C 4.1.6.2.2: The LHS may also be fixed-point.
12144 if ((!LHSType->isFixedPointOrIntegerType() &&
12145 !LHSType->hasIntegerRepresentation()) ||
12146 !RHSType->hasIntegerRepresentation())
12147 return InvalidOperands(Loc, LHS, RHS);
12148
12149 // C++0x: Don't allow scoped enums. FIXME: Use something better than
12150 // hasIntegerRepresentation() above instead of this.
12151 if (isScopedEnumerationType(LHSType) ||
12152 isScopedEnumerationType(RHSType)) {
12153 return InvalidOperands(Loc, LHS, RHS);
12154 }
12155 DiagnoseBadShiftValues(*this, LHS, RHS, Loc, Opc, LHSType);
12156
12157 // "The type of the result is that of the promoted left operand."
12158 return LHSType;
12159}
12160
12161/// Diagnose bad pointer comparisons.
12162static void diagnoseDistinctPointerComparison(Sema &S, SourceLocation Loc,
12163 ExprResult &LHS, ExprResult &RHS,
12164 bool IsError) {
12165 S.Diag(Loc, IsError ? diag::err_typecheck_comparison_of_distinct_pointers
12166 : diag::ext_typecheck_comparison_of_distinct_pointers)
12167 << LHS.get()->getType() << RHS.get()->getType()
12168 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
12169}
12170
12171/// Returns false if the pointers are converted to a composite type,
12172/// true otherwise.
12173static bool convertPointersToCompositeType(Sema &S, SourceLocation Loc,
12174 ExprResult &LHS, ExprResult &RHS) {
12175 // C++ [expr.rel]p2:
12176 // [...] Pointer conversions (4.10) and qualification
12177 // conversions (4.4) are performed on pointer operands (or on
12178 // a pointer operand and a null pointer constant) to bring
12179 // them to their composite pointer type. [...]
12180 //
12181 // C++ [expr.eq]p1 uses the same notion for (in)equality
12182 // comparisons of pointers.
12183
12184 QualType LHSType = LHS.get()->getType();
12185 QualType RHSType = RHS.get()->getType();
12186 assert(LHSType->isPointerType() || RHSType->isPointerType() ||(static_cast <bool> (LHSType->isPointerType() || RHSType
->isPointerType() || LHSType->isMemberPointerType() || RHSType
->isMemberPointerType()) ? void (0) : __assert_fail ("LHSType->isPointerType() || RHSType->isPointerType() || LHSType->isMemberPointerType() || RHSType->isMemberPointerType()"
, "clang/lib/Sema/SemaExpr.cpp", 12187, __extension__ __PRETTY_FUNCTION__
))
12187 LHSType->isMemberPointerType() || RHSType->isMemberPointerType())(static_cast <bool> (LHSType->isPointerType() || RHSType
->isPointerType() || LHSType->isMemberPointerType() || RHSType
->isMemberPointerType()) ? void (0) : __assert_fail ("LHSType->isPointerType() || RHSType->isPointerType() || LHSType->isMemberPointerType() || RHSType->isMemberPointerType()"
, "clang/lib/Sema/SemaExpr.cpp", 12187, __extension__ __PRETTY_FUNCTION__
))
;
12188
12189 QualType T = S.FindCompositePointerType(Loc, LHS, RHS);
12190 if (T.isNull()) {
12191 if ((LHSType->isAnyPointerType() || LHSType->isMemberPointerType()) &&
12192 (RHSType->isAnyPointerType() || RHSType->isMemberPointerType()))
12193 diagnoseDistinctPointerComparison(S, Loc, LHS, RHS, /*isError*/true);
12194 else
12195 S.InvalidOperands(Loc, LHS, RHS);
12196 return true;
12197 }
12198
12199 return false;
12200}
12201
12202static void diagnoseFunctionPointerToVoidComparison(Sema &S, SourceLocation Loc,
12203 ExprResult &LHS,
12204 ExprResult &RHS,
12205 bool IsError) {
12206 S.Diag(Loc, IsError ? diag::err_typecheck_comparison_of_fptr_to_void
12207 : diag::ext_typecheck_comparison_of_fptr_to_void)
12208 << LHS.get()->getType() << RHS.get()->getType()
12209 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
12210}
12211
12212static bool isObjCObjectLiteral(ExprResult &E) {
12213 switch (E.get()->IgnoreParenImpCasts()->getStmtClass()) {
12214 case Stmt::ObjCArrayLiteralClass:
12215 case Stmt::ObjCDictionaryLiteralClass:
12216 case Stmt::ObjCStringLiteralClass:
12217 case Stmt::ObjCBoxedExprClass:
12218 return true;
12219 default:
12220 // Note that ObjCBoolLiteral is NOT an object literal!
12221 return false;
12222 }
12223}
12224
12225static bool hasIsEqualMethod(Sema &S, const Expr *LHS, const Expr *RHS) {
12226 const ObjCObjectPointerType *Type =
12227 LHS->getType()->getAs<ObjCObjectPointerType>();
12228
12229 // If this is not actually an Objective-C object, bail out.
12230 if (!Type)
12231 return false;
12232
12233 // Get the LHS object's interface type.
12234 QualType InterfaceType = Type->getPointeeType();
12235
12236 // If the RHS isn't an Objective-C object, bail out.
12237 if (!RHS->getType()->isObjCObjectPointerType())
12238 return false;
12239
12240 // Try to find the -isEqual: method.
12241 Selector IsEqualSel = S.NSAPIObj->getIsEqualSelector();
12242 ObjCMethodDecl *Method = S.LookupMethodInObjectType(IsEqualSel,
12243 InterfaceType,
12244 /*IsInstance=*/true);
12245 if (!Method) {
12246 if (Type->isObjCIdType()) {
12247 // For 'id', just check the global pool.
12248 Method = S.LookupInstanceMethodInGlobalPool(IsEqualSel, SourceRange(),
12249 /*receiverId=*/true);
12250 } else {
12251 // Check protocols.
12252 Method = S.LookupMethodInQualifiedType(IsEqualSel, Type,
12253 /*IsInstance=*/true);
12254 }
12255 }
12256
12257 if (!Method)
12258 return false;
12259
12260 QualType T = Method->parameters()[0]->getType();
12261 if (!T->isObjCObjectPointerType())
12262 return false;
12263
12264 QualType R = Method->getReturnType();
12265 if (!R->isScalarType())
12266 return false;
12267
12268 return true;
12269}
12270
12271Sema::ObjCLiteralKind Sema::CheckLiteralKind(Expr *FromE) {
12272 FromE = FromE->IgnoreParenImpCasts();
12273 switch (FromE->getStmtClass()) {
12274 default:
12275 break;
12276 case Stmt::ObjCStringLiteralClass:
12277 // "string literal"
12278 return LK_String;
12279 case Stmt::ObjCArrayLiteralClass:
12280 // "array literal"
12281 return LK_Array;
12282 case Stmt::ObjCDictionaryLiteralClass:
12283 // "dictionary literal"
12284 return LK_Dictionary;
12285 case Stmt::BlockExprClass:
12286 return LK_Block;
12287 case Stmt::ObjCBoxedExprClass: {
12288 Expr *Inner = cast<ObjCBoxedExpr>(FromE)->getSubExpr()->IgnoreParens();
12289 switch (Inner->getStmtClass()) {
12290 case Stmt::IntegerLiteralClass:
12291 case Stmt::FloatingLiteralClass:
12292 case Stmt::CharacterLiteralClass:
12293 case Stmt::ObjCBoolLiteralExprClass:
12294 case Stmt::CXXBoolLiteralExprClass:
12295 // "numeric literal"
12296 return LK_Numeric;
12297 case Stmt::ImplicitCastExprClass: {
12298 CastKind CK = cast<CastExpr>(Inner)->getCastKind();
12299 // Boolean literals can be represented by implicit casts.
12300 if (CK == CK_IntegralToBoolean || CK == CK_IntegralCast)
12301 return LK_Numeric;
12302 break;
12303 }
12304 default:
12305 break;
12306 }
12307 return LK_Boxed;
12308 }
12309 }
12310 return LK_None;
12311}
12312
12313static void diagnoseObjCLiteralComparison(Sema &S, SourceLocation Loc,
12314 ExprResult &LHS, ExprResult &RHS,
12315 BinaryOperator::Opcode Opc){
12316 Expr *Literal;
12317 Expr *Other;
12318 if (isObjCObjectLiteral(LHS)) {
12319 Literal = LHS.get();
12320 Other = RHS.get();
12321 } else {
12322 Literal = RHS.get();
12323 Other = LHS.get();
12324 }
12325
12326 // Don't warn on comparisons against nil.
12327 Other = Other->IgnoreParenCasts();
12328 if (Other->isNullPointerConstant(S.getASTContext(),
12329 Expr::NPC_ValueDependentIsNotNull))
12330 return;
12331
12332 // This should be kept in sync with warn_objc_literal_comparison.
12333 // LK_String should always be after the other literals, since it has its own
12334 // warning flag.
12335 Sema::ObjCLiteralKind LiteralKind = S.CheckLiteralKind(Literal);
12336 assert(LiteralKind != Sema::LK_Block)(static_cast <bool> (LiteralKind != Sema::LK_Block) ? void
(0) : __assert_fail ("LiteralKind != Sema::LK_Block", "clang/lib/Sema/SemaExpr.cpp"
, 12336, __extension__ __PRETTY_FUNCTION__))
;
12337 if (LiteralKind == Sema::LK_None) {
12338 llvm_unreachable("Unknown Objective-C object literal kind")::llvm::llvm_unreachable_internal("Unknown Objective-C object literal kind"
, "clang/lib/Sema/SemaExpr.cpp", 12338)
;
12339 }
12340
12341 if (LiteralKind == Sema::LK_String)
12342 S.Diag(Loc, diag::warn_objc_string_literal_comparison)
12343 << Literal->getSourceRange();
12344 else
12345 S.Diag(Loc, diag::warn_objc_literal_comparison)
12346 << LiteralKind << Literal->getSourceRange();
12347
12348 if (BinaryOperator::isEqualityOp(Opc) &&
12349 hasIsEqualMethod(S, LHS.get(), RHS.get())) {
12350 SourceLocation Start = LHS.get()->getBeginLoc();
12351 SourceLocation End = S.getLocForEndOfToken(RHS.get()->getEndLoc());
12352 CharSourceRange OpRange =
12353 CharSourceRange::getCharRange(Loc, S.getLocForEndOfToken(Loc));
12354
12355 S.Diag(Loc, diag::note_objc_literal_comparison_isequal)
12356 << FixItHint::CreateInsertion(Start, Opc == BO_EQ ? "[" : "![")
12357 << FixItHint::CreateReplacement(OpRange, " isEqual:")
12358 << FixItHint::CreateInsertion(End, "]");
12359 }
12360}
12361
12362/// Warns on !x < y, !x & y where !(x < y), !(x & y) was probably intended.
12363static void diagnoseLogicalNotOnLHSofCheck(Sema &S, ExprResult &LHS,
12364 ExprResult &RHS, SourceLocation Loc,
12365 BinaryOperatorKind Opc) {
12366 // Check that left hand side is !something.
12367 UnaryOperator *UO = dyn_cast<UnaryOperator>(LHS.get()->IgnoreImpCasts());
12368 if (!UO || UO->getOpcode() != UO_LNot) return;
12369
12370 // Only check if the right hand side is non-bool arithmetic type.
12371 if (RHS.get()->isKnownToHaveBooleanValue()) return;
12372
12373 // Make sure that the something in !something is not bool.
12374 Expr *SubExpr = UO->getSubExpr()->IgnoreImpCasts();
12375 if (SubExpr->isKnownToHaveBooleanValue()) return;
12376
12377 // Emit warning.
12378 bool IsBitwiseOp = Opc == BO_And || Opc == BO_Or || Opc == BO_Xor;
12379 S.Diag(UO->getOperatorLoc(), diag::warn_logical_not_on_lhs_of_check)
12380 << Loc << IsBitwiseOp;
12381
12382 // First note suggest !(x < y)
12383 SourceLocation FirstOpen = SubExpr->getBeginLoc();
12384 SourceLocation FirstClose = RHS.get()->getEndLoc();
12385 FirstClose = S.getLocForEndOfToken(FirstClose);
12386 if (FirstClose.isInvalid())
12387 FirstOpen = SourceLocation();
12388 S.Diag(UO->getOperatorLoc(), diag::note_logical_not_fix)
12389 << IsBitwiseOp
12390 << FixItHint::CreateInsertion(FirstOpen, "(")
12391 << FixItHint::CreateInsertion(FirstClose, ")");
12392
12393 // Second note suggests (!x) < y
12394 SourceLocation SecondOpen = LHS.get()->getBeginLoc();
12395 SourceLocation SecondClose = LHS.get()->getEndLoc();
12396 SecondClose = S.getLocForEndOfToken(SecondClose);
12397 if (SecondClose.isInvalid())
12398 SecondOpen = SourceLocation();
12399 S.Diag(UO->getOperatorLoc(), diag::note_logical_not_silence_with_parens)
12400 << FixItHint::CreateInsertion(SecondOpen, "(")
12401 << FixItHint::CreateInsertion(SecondClose, ")");
12402}
12403
12404// Returns true if E refers to a non-weak array.
12405static bool checkForArray(const Expr *E) {
12406 const ValueDecl *D = nullptr;
12407 if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(E)) {
12408 D = DR->getDecl();
12409 } else if (const MemberExpr *Mem = dyn_cast<MemberExpr>(E)) {
12410 if (Mem->isImplicitAccess())
12411 D = Mem->getMemberDecl();
12412 }
12413 if (!D)
12414 return false;
12415 return D->getType()->isArrayType() && !D->isWeak();
12416}
12417
12418/// Diagnose some forms of syntactically-obvious tautological comparison.
12419static void diagnoseTautologicalComparison(Sema &S, SourceLocation Loc,
12420 Expr *LHS, Expr *RHS,
12421 BinaryOperatorKind Opc) {
12422 Expr *LHSStripped = LHS->IgnoreParenImpCasts();
12423 Expr *RHSStripped = RHS->IgnoreParenImpCasts();
12424
12425 QualType LHSType = LHS->getType();
12426 QualType RHSType = RHS->getType();
12427 if (LHSType->hasFloatingRepresentation() ||
12428 (LHSType->isBlockPointerType() && !BinaryOperator::isEqualityOp(Opc)) ||
12429 S.inTemplateInstantiation())
12430 return;
12431
12432 // Comparisons between two array types are ill-formed for operator<=>, so
12433 // we shouldn't emit any additional warnings about it.
12434 if (Opc == BO_Cmp && LHSType->isArrayType() && RHSType->isArrayType())
12435 return;
12436
12437 // For non-floating point types, check for self-comparisons of the form
12438 // x == x, x != x, x < x, etc. These always evaluate to a constant, and
12439 // often indicate logic errors in the program.
12440 //
12441 // NOTE: Don't warn about comparison expressions resulting from macro
12442 // expansion. Also don't warn about comparisons which are only self
12443 // comparisons within a template instantiation. The warnings should catch
12444 // obvious cases in the definition of the template anyways. The idea is to
12445 // warn when the typed comparison operator will always evaluate to the same
12446 // result.
12447
12448 // Used for indexing into %select in warn_comparison_always
12449 enum {
12450 AlwaysConstant,
12451 AlwaysTrue,
12452 AlwaysFalse,
12453 AlwaysEqual, // std::strong_ordering::equal from operator<=>
12454 };
12455
12456 // C++2a [depr.array.comp]:
12457 // Equality and relational comparisons ([expr.eq], [expr.rel]) between two
12458 // operands of array type are deprecated.
12459 if (S.getLangOpts().CPlusPlus20 && LHSStripped->getType()->isArrayType() &&
12460 RHSStripped->getType()->isArrayType()) {
12461 S.Diag(Loc, diag::warn_depr_array_comparison)
12462 << LHS->getSourceRange() << RHS->getSourceRange()
12463 << LHSStripped->getType() << RHSStripped->getType();
12464 // Carry on to produce the tautological comparison warning, if this
12465 // expression is potentially-evaluated, we can resolve the array to a
12466 // non-weak declaration, and so on.
12467 }
12468
12469 if (!LHS->getBeginLoc().isMacroID() && !RHS->getBeginLoc().isMacroID()) {
12470 if (Expr::isSameComparisonOperand(LHS, RHS)) {
12471 unsigned Result;
12472 switch (Opc) {
12473 case BO_EQ:
12474 case BO_LE:
12475 case BO_GE:
12476 Result = AlwaysTrue;
12477 break;
12478 case BO_NE:
12479 case BO_LT:
12480 case BO_GT:
12481 Result = AlwaysFalse;
12482 break;
12483 case BO_Cmp:
12484 Result = AlwaysEqual;
12485 break;
12486 default:
12487 Result = AlwaysConstant;
12488 break;
12489 }
12490 S.DiagRuntimeBehavior(Loc, nullptr,
12491 S.PDiag(diag::warn_comparison_always)
12492 << 0 /*self-comparison*/
12493 << Result);
12494 } else if (checkForArray(LHSStripped) && checkForArray(RHSStripped)) {
12495 // What is it always going to evaluate to?
12496 unsigned Result;
12497 switch (Opc) {
12498 case BO_EQ: // e.g. array1 == array2
12499 Result = AlwaysFalse;
12500 break;
12501 case BO_NE: // e.g. array1 != array2
12502 Result = AlwaysTrue;
12503 break;
12504 default: // e.g. array1 <= array2
12505 // The best we can say is 'a constant'
12506 Result = AlwaysConstant;
12507 break;
12508 }
12509 S.DiagRuntimeBehavior(Loc, nullptr,
12510 S.PDiag(diag::warn_comparison_always)
12511 << 1 /*array comparison*/
12512 << Result);
12513 }
12514 }
12515
12516 if (isa<CastExpr>(LHSStripped))
12517 LHSStripped = LHSStripped->IgnoreParenCasts();
12518 if (isa<CastExpr>(RHSStripped))
12519 RHSStripped = RHSStripped->IgnoreParenCasts();
12520
12521 // Warn about comparisons against a string constant (unless the other
12522 // operand is null); the user probably wants string comparison function.
12523 Expr *LiteralString = nullptr;
12524 Expr *LiteralStringStripped = nullptr;
12525 if ((isa<StringLiteral>(LHSStripped) || isa<ObjCEncodeExpr>(LHSStripped)) &&
12526 !RHSStripped->isNullPointerConstant(S.Context,
12527 Expr::NPC_ValueDependentIsNull)) {
12528 LiteralString = LHS;
12529 LiteralStringStripped = LHSStripped;
12530 } else if ((isa<StringLiteral>(RHSStripped) ||
12531 isa<ObjCEncodeExpr>(RHSStripped)) &&
12532 !LHSStripped->isNullPointerConstant(S.Context,
12533 Expr::NPC_ValueDependentIsNull)) {
12534 LiteralString = RHS;
12535 LiteralStringStripped = RHSStripped;
12536 }
12537
12538 if (LiteralString) {
12539 S.DiagRuntimeBehavior(Loc, nullptr,
12540 S.PDiag(diag::warn_stringcompare)
12541 << isa<ObjCEncodeExpr>(LiteralStringStripped)
12542 << LiteralString->getSourceRange());
12543 }
12544}
12545
12546static ImplicitConversionKind castKindToImplicitConversionKind(CastKind CK) {
12547 switch (CK) {
12548 default: {
12549#ifndef NDEBUG
12550 llvm::errs() << "unhandled cast kind: " << CastExpr::getCastKindName(CK)
12551 << "\n";
12552#endif
12553 llvm_unreachable("unhandled cast kind")::llvm::llvm_unreachable_internal("unhandled cast kind", "clang/lib/Sema/SemaExpr.cpp"
, 12553)
;
12554 }
12555 case CK_UserDefinedConversion:
12556 return ICK_Identity;
12557 case CK_LValueToRValue:
12558 return ICK_Lvalue_To_Rvalue;
12559 case CK_ArrayToPointerDecay:
12560 return ICK_Array_To_Pointer;
12561 case CK_FunctionToPointerDecay:
12562 return ICK_Function_To_Pointer;
12563 case CK_IntegralCast:
12564 return ICK_Integral_Conversion;
12565 case CK_FloatingCast:
12566 return ICK_Floating_Conversion;
12567 case CK_IntegralToFloating:
12568 case CK_FloatingToIntegral:
12569 return ICK_Floating_Integral;
12570 case CK_IntegralComplexCast:
12571 case CK_FloatingComplexCast:
12572 case CK_FloatingComplexToIntegralComplex:
12573 case CK_IntegralComplexToFloatingComplex:
12574 return ICK_Complex_Conversion;
12575 case CK_FloatingComplexToReal:
12576 case CK_FloatingRealToComplex:
12577 case CK_IntegralComplexToReal:
12578 case CK_IntegralRealToComplex:
12579 return ICK_Complex_Real;
12580 }
12581}
12582
12583static bool checkThreeWayNarrowingConversion(Sema &S, QualType ToType, Expr *E,
12584 QualType FromType,
12585 SourceLocation Loc) {
12586 // Check for a narrowing implicit conversion.
12587 StandardConversionSequence SCS;
12588 SCS.setAsIdentityConversion();
12589 SCS.setToType(0, FromType);
12590 SCS.setToType(1, ToType);
12591 if (const auto *ICE = dyn_cast<ImplicitCastExpr>(E))
12592 SCS.Second = castKindToImplicitConversionKind(ICE->getCastKind());
12593
12594 APValue PreNarrowingValue;
12595 QualType PreNarrowingType;
12596 switch (SCS.getNarrowingKind(S.Context, E, PreNarrowingValue,
12597 PreNarrowingType,
12598 /*IgnoreFloatToIntegralConversion*/ true)) {
12599 case NK_Dependent_Narrowing:
12600 // Implicit conversion to a narrower type, but the expression is
12601 // value-dependent so we can't tell whether it's actually narrowing.
12602 case NK_Not_Narrowing:
12603 return false;
12604
12605 case NK_Constant_Narrowing:
12606 // Implicit conversion to a narrower type, and the value is not a constant
12607 // expression.
12608 S.Diag(E->getBeginLoc(), diag::err_spaceship_argument_narrowing)
12609 << /*Constant*/ 1
12610 << PreNarrowingValue.getAsString(S.Context, PreNarrowingType) << ToType;
12611 return true;
12612
12613 case NK_Variable_Narrowing:
12614 // Implicit conversion to a narrower type, and the value is not a constant
12615 // expression.
12616 case NK_Type_Narrowing:
12617 S.Diag(E->getBeginLoc(), diag::err_spaceship_argument_narrowing)
12618 << /*Constant*/ 0 << FromType << ToType;
12619 // TODO: It's not a constant expression, but what if the user intended it
12620 // to be? Can we produce notes to help them figure out why it isn't?
12621 return true;
12622 }
12623 llvm_unreachable("unhandled case in switch")::llvm::llvm_unreachable_internal("unhandled case in switch",
"clang/lib/Sema/SemaExpr.cpp", 12623)
;
12624}
12625
12626static QualType checkArithmeticOrEnumeralThreeWayCompare(Sema &S,
12627 ExprResult &LHS,
12628 ExprResult &RHS,
12629 SourceLocation Loc) {
12630 QualType LHSType = LHS.get()->getType();
12631 QualType RHSType = RHS.get()->getType();
12632 // Dig out the original argument type and expression before implicit casts
12633 // were applied. These are the types/expressions we need to check the
12634 // [expr.spaceship] requirements against.
12635 ExprResult LHSStripped = LHS.get()->IgnoreParenImpCasts();
12636 ExprResult RHSStripped = RHS.get()->IgnoreParenImpCasts();
12637 QualType LHSStrippedType = LHSStripped.get()->getType();
12638 QualType RHSStrippedType = RHSStripped.get()->getType();
12639
12640 // C++2a [expr.spaceship]p3: If one of the operands is of type bool and the
12641 // other is not, the program is ill-formed.
12642 if (LHSStrippedType->isBooleanType() != RHSStrippedType->isBooleanType()) {
12643 S.InvalidOperands(Loc, LHSStripped, RHSStripped);
12644 return QualType();
12645 }
12646
12647 // FIXME: Consider combining this with checkEnumArithmeticConversions.
12648 int NumEnumArgs = (int)LHSStrippedType->isEnumeralType() +
12649 RHSStrippedType->isEnumeralType();
12650 if (NumEnumArgs == 1) {
12651 bool LHSIsEnum = LHSStrippedType->isEnumeralType();
12652 QualType OtherTy = LHSIsEnum ? RHSStrippedType : LHSStrippedType;
12653 if (OtherTy->hasFloatingRepresentation()) {
12654 S.InvalidOperands(Loc, LHSStripped, RHSStripped);
12655 return QualType();
12656 }
12657 }
12658 if (NumEnumArgs == 2) {
12659 // C++2a [expr.spaceship]p5: If both operands have the same enumeration
12660 // type E, the operator yields the result of converting the operands
12661 // to the underlying type of E and applying <=> to the converted operands.
12662 if (!S.Context.hasSameUnqualifiedType(LHSStrippedType, RHSStrippedType)) {
12663 S.InvalidOperands(Loc, LHS, RHS);
12664 return QualType();
12665 }
12666 QualType IntType =
12667 LHSStrippedType->castAs<EnumType>()->getDecl()->getIntegerType();
12668 assert(IntType->isArithmeticType())(static_cast <bool> (IntType->isArithmeticType()) ? void
(0) : __assert_fail ("IntType->isArithmeticType()", "clang/lib/Sema/SemaExpr.cpp"
, 12668, __extension__ __PRETTY_FUNCTION__))
;
12669
12670 // We can't use `CK_IntegralCast` when the underlying type is 'bool', so we
12671 // promote the boolean type, and all other promotable integer types, to
12672 // avoid this.
12673 if (S.Context.isPromotableIntegerType(IntType))
12674 IntType = S.Context.getPromotedIntegerType(IntType);
12675
12676 LHS = S.ImpCastExprToType(LHS.get(), IntType, CK_IntegralCast);
12677 RHS = S.ImpCastExprToType(RHS.get(), IntType, CK_IntegralCast);
12678 LHSType = RHSType = IntType;
12679 }
12680
12681 // C++2a [expr.spaceship]p4: If both operands have arithmetic types, the
12682 // usual arithmetic conversions are applied to the operands.
12683 QualType Type =
12684 S.UsualArithmeticConversions(LHS, RHS, Loc, Sema::ACK_Comparison);
12685 if (LHS.isInvalid() || RHS.isInvalid())
12686 return QualType();
12687 if (Type.isNull())
12688 return S.InvalidOperands(Loc, LHS, RHS);
12689
12690 std::optional<ComparisonCategoryType> CCT =
12691 getComparisonCategoryForBuiltinCmp(Type);
12692 if (!CCT)
12693 return S.InvalidOperands(Loc, LHS, RHS);
12694
12695 bool HasNarrowing = checkThreeWayNarrowingConversion(
12696 S, Type, LHS.get(), LHSType, LHS.get()->getBeginLoc());
12697 HasNarrowing |= checkThreeWayNarrowingConversion(S, Type, RHS.get(), RHSType,
12698 RHS.get()->getBeginLoc());
12699 if (HasNarrowing)
12700 return QualType();
12701
12702 assert(!Type.isNull() && "composite type for <=> has not been set")(static_cast <bool> (!Type.isNull() && "composite type for <=> has not been set"
) ? void (0) : __assert_fail ("!Type.isNull() && \"composite type for <=> has not been set\""
, "clang/lib/Sema/SemaExpr.cpp", 12702, __extension__ __PRETTY_FUNCTION__
))
;
12703
12704 return S.CheckComparisonCategoryType(
12705 *CCT, Loc, Sema::ComparisonCategoryUsage::OperatorInExpression);
12706}
12707
12708static QualType checkArithmeticOrEnumeralCompare(Sema &S, ExprResult &LHS,
12709 ExprResult &RHS,
12710 SourceLocation Loc,
12711 BinaryOperatorKind Opc) {
12712 if (Opc == BO_Cmp)
12713 return checkArithmeticOrEnumeralThreeWayCompare(S, LHS, RHS, Loc);
12714
12715 // C99 6.5.8p3 / C99 6.5.9p4
12716 QualType Type =
12717 S.UsualArithmeticConversions(LHS, RHS, Loc, Sema::ACK_Comparison);
12718 if (LHS.isInvalid() || RHS.isInvalid())
12719 return QualType();
12720 if (Type.isNull())
12721 return S.InvalidOperands(Loc, LHS, RHS);
12722 assert(Type->isArithmeticType() || Type->isEnumeralType())(static_cast <bool> (Type->isArithmeticType() || Type
->isEnumeralType()) ? void (0) : __assert_fail ("Type->isArithmeticType() || Type->isEnumeralType()"
, "clang/lib/Sema/SemaExpr.cpp", 12722, __extension__ __PRETTY_FUNCTION__
))
;
12723
12724 if (Type->isAnyComplexType() && BinaryOperator::isRelationalOp(Opc))
12725 return S.InvalidOperands(Loc, LHS, RHS);
12726
12727 // Check for comparisons of floating point operands using != and ==.
12728 if (Type->hasFloatingRepresentation())
12729 S.CheckFloatComparison(Loc, LHS.get(), RHS.get(), Opc);
12730
12731 // The result of comparisons is 'bool' in C++, 'int' in C.
12732 return S.Context.getLogicalOperationType();
12733}
12734
12735void Sema::CheckPtrComparisonWithNullChar(ExprResult &E, ExprResult &NullE) {
12736 if (!NullE.get()->getType()->isAnyPointerType())
12737 return;
12738 int NullValue = PP.isMacroDefined("NULL") ? 0 : 1;
12739 if (!E.get()->getType()->isAnyPointerType() &&
12740 E.get()->isNullPointerConstant(Context,
12741 Expr::NPC_ValueDependentIsNotNull) ==
12742 Expr::NPCK_ZeroExpression) {
12743 if (const auto *CL = dyn_cast<CharacterLiteral>(E.get())) {
12744 if (CL->getValue() == 0)
12745 Diag(E.get()->getExprLoc(), diag::warn_pointer_compare)
12746 << NullValue
12747 << FixItHint::CreateReplacement(E.get()->getExprLoc(),
12748 NullValue ? "NULL" : "(void *)0");
12749 } else if (const auto *CE = dyn_cast<CStyleCastExpr>(E.get())) {
12750 TypeSourceInfo *TI = CE->getTypeInfoAsWritten();
12751 QualType T = Context.getCanonicalType(TI->getType()).getUnqualifiedType();
12752 if (T == Context.CharTy)
12753 Diag(E.get()->getExprLoc(), diag::warn_pointer_compare)
12754 << NullValue
12755 << FixItHint::CreateReplacement(E.get()->getExprLoc(),
12756 NullValue ? "NULL" : "(void *)0");
12757 }
12758 }
12759}
12760
12761// C99 6.5.8, C++ [expr.rel]
12762QualType Sema::CheckCompareOperands(ExprResult &LHS, ExprResult &RHS,
12763 SourceLocation Loc,
12764 BinaryOperatorKind Opc) {
12765 bool IsRelational = BinaryOperator::isRelationalOp(Opc);
12766 bool IsThreeWay = Opc == BO_Cmp;
12767 bool IsOrdered = IsRelational || IsThreeWay;
12768 auto IsAnyPointerType = [](ExprResult E) {
12769 QualType Ty = E.get()->getType();
12770 return Ty->isPointerType() || Ty->isMemberPointerType();
12771 };
12772
12773 // C++2a [expr.spaceship]p6: If at least one of the operands is of pointer
12774 // type, array-to-pointer, ..., conversions are performed on both operands to
12775 // bring them to their composite type.
12776 // Otherwise, all comparisons expect an rvalue, so convert to rvalue before
12777 // any type-related checks.
12778 if (!IsThreeWay || IsAnyPointerType(LHS) || IsAnyPointerType(RHS)) {
12779 LHS = DefaultFunctionArrayLvalueConversion(LHS.get());
12780 if (LHS.isInvalid())
12781 return QualType();
12782 RHS = DefaultFunctionArrayLvalueConversion(RHS.get());
12783 if (RHS.isInvalid())
12784 return QualType();
12785 } else {
12786 LHS = DefaultLvalueConversion(LHS.get());
12787 if (LHS.isInvalid())
12788 return QualType();
12789 RHS = DefaultLvalueConversion(RHS.get());
12790 if (RHS.isInvalid())
12791 return QualType();
12792 }
12793
12794 checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/true);
12795 if (!getLangOpts().CPlusPlus && BinaryOperator::isEqualityOp(Opc)) {
12796 CheckPtrComparisonWithNullChar(LHS, RHS);
12797 CheckPtrComparisonWithNullChar(RHS, LHS);
12798 }
12799
12800 // Handle vector comparisons separately.
12801 if (LHS.get()->getType()->isVectorType() ||
12802 RHS.get()->getType()->isVectorType())
12803 return CheckVectorCompareOperands(LHS, RHS, Loc, Opc);
12804
12805 if (LHS.get()->getType()->isVLSTBuiltinType() ||
12806 RHS.get()->getType()->isVLSTBuiltinType())
12807 return CheckSizelessVectorCompareOperands(LHS, RHS, Loc, Opc);
12808
12809 diagnoseLogicalNotOnLHSofCheck(*this, LHS, RHS, Loc, Opc);
12810 diagnoseTautologicalComparison(*this, Loc, LHS.get(), RHS.get(), Opc);
12811
12812 QualType LHSType = LHS.get()->getType();
12813 QualType RHSType = RHS.get()->getType();
12814 if ((LHSType->isArithmeticType() || LHSType->isEnumeralType()) &&
12815 (RHSType->isArithmeticType() || RHSType->isEnumeralType()))
12816 return checkArithmeticOrEnumeralCompare(*this, LHS, RHS, Loc, Opc);
12817
12818 const Expr::NullPointerConstantKind LHSNullKind =
12819 LHS.get()->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull);
12820 const Expr::NullPointerConstantKind RHSNullKind =
12821 RHS.get()->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull);
12822 bool LHSIsNull = LHSNullKind != Expr::NPCK_NotNull;
12823 bool RHSIsNull = RHSNullKind != Expr::NPCK_NotNull;
12824
12825 auto computeResultTy = [&]() {
12826 if (Opc != BO_Cmp)
12827 return Context.getLogicalOperationType();
12828 assert(getLangOpts().CPlusPlus)(static_cast <bool> (getLangOpts().CPlusPlus) ? void (0
) : __assert_fail ("getLangOpts().CPlusPlus", "clang/lib/Sema/SemaExpr.cpp"
, 12828, __extension__ __PRETTY_FUNCTION__))
;
12829 assert(Context.hasSameType(LHS.get()->getType(), RHS.get()->getType()))(static_cast <bool> (Context.hasSameType(LHS.get()->
getType(), RHS.get()->getType())) ? void (0) : __assert_fail
("Context.hasSameType(LHS.get()->getType(), RHS.get()->getType())"
, "clang/lib/Sema/SemaExpr.cpp", 12829, __extension__ __PRETTY_FUNCTION__
))
;
12830
12831 QualType CompositeTy = LHS.get()->getType();
12832 assert(!CompositeTy->isReferenceType())(static_cast <bool> (!CompositeTy->isReferenceType()
) ? void (0) : __assert_fail ("!CompositeTy->isReferenceType()"
, "clang/lib/Sema/SemaExpr.cpp", 12832, __extension__ __PRETTY_FUNCTION__
))
;
12833
12834 std::optional<ComparisonCategoryType> CCT =
12835 getComparisonCategoryForBuiltinCmp(CompositeTy);
12836 if (!CCT)
12837 return InvalidOperands(Loc, LHS, RHS);
12838
12839 if (CompositeTy->isPointerType() && LHSIsNull != RHSIsNull) {
12840 // P0946R0: Comparisons between a null pointer constant and an object
12841 // pointer result in std::strong_equality, which is ill-formed under
12842 // P1959R0.
12843 Diag(Loc, diag::err_typecheck_three_way_comparison_of_pointer_and_zero)
12844 << (LHSIsNull ? LHS.get()->getSourceRange()
12845 : RHS.get()->getSourceRange());
12846 return QualType();
12847 }
12848
12849 return CheckComparisonCategoryType(
12850 *CCT, Loc, ComparisonCategoryUsage::OperatorInExpression);
12851 };
12852
12853 if (!IsOrdered && LHSIsNull != RHSIsNull) {
12854 bool IsEquality = Opc == BO_EQ;
12855 if (RHSIsNull)
12856 DiagnoseAlwaysNonNullPointer(LHS.get(), RHSNullKind, IsEquality,
12857 RHS.get()->getSourceRange());
12858 else
12859 DiagnoseAlwaysNonNullPointer(RHS.get(), LHSNullKind, IsEquality,
12860 LHS.get()->getSourceRange());
12861 }
12862
12863 if (IsOrdered && LHSType->isFunctionPointerType() &&
12864 RHSType->isFunctionPointerType()) {
12865 // Valid unless a relational comparison of function pointers
12866 bool IsError = Opc == BO_Cmp;
12867 auto DiagID =
12868 IsError ? diag::err_typecheck_ordered_comparison_of_function_pointers
12869 : getLangOpts().CPlusPlus
12870 ? diag::warn_typecheck_ordered_comparison_of_function_pointers
12871 : diag::ext_typecheck_ordered_comparison_of_function_pointers;
12872 Diag(Loc, DiagID) << LHSType << RHSType << LHS.get()->getSourceRange()
12873 << RHS.get()->getSourceRange();
12874 if (IsError)
12875 return QualType();
12876 }
12877
12878 if ((LHSType->isIntegerType() && !LHSIsNull) ||
12879 (RHSType->isIntegerType() && !RHSIsNull)) {
12880 // Skip normal pointer conversion checks in this case; we have better
12881 // diagnostics for this below.
12882 } else if (getLangOpts().CPlusPlus) {
12883 // Equality comparison of a function pointer to a void pointer is invalid,
12884 // but we allow it as an extension.
12885 // FIXME: If we really want to allow this, should it be part of composite
12886 // pointer type computation so it works in conditionals too?
12887 if (!IsOrdered &&
12888 ((LHSType->isFunctionPointerType() && RHSType->isVoidPointerType()) ||
12889 (RHSType->isFunctionPointerType() && LHSType->isVoidPointerType()))) {
12890 // This is a gcc extension compatibility comparison.
12891 // In a SFINAE context, we treat this as a hard error to maintain
12892 // conformance with the C++ standard.
12893 diagnoseFunctionPointerToVoidComparison(
12894 *this, Loc, LHS, RHS, /*isError*/ (bool)isSFINAEContext());
12895
12896 if (isSFINAEContext())
12897 return QualType();
12898
12899 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast);
12900 return computeResultTy();
12901 }
12902
12903 // C++ [expr.eq]p2:
12904 // If at least one operand is a pointer [...] bring them to their
12905 // composite pointer type.
12906 // C++ [expr.spaceship]p6
12907 // If at least one of the operands is of pointer type, [...] bring them
12908 // to their composite pointer type.
12909 // C++ [expr.rel]p2:
12910 // If both operands are pointers, [...] bring them to their composite
12911 // pointer type.
12912 // For <=>, the only valid non-pointer types are arrays and functions, and
12913 // we already decayed those, so this is really the same as the relational
12914 // comparison rule.
12915 if ((int)LHSType->isPointerType() + (int)RHSType->isPointerType() >=
12916 (IsOrdered ? 2 : 1) &&
12917 (!LangOpts.ObjCAutoRefCount || !(LHSType->isObjCObjectPointerType() ||
12918 RHSType->isObjCObjectPointerType()))) {
12919 if (convertPointersToCompositeType(*this, Loc, LHS, RHS))
12920 return QualType();
12921 return computeResultTy();
12922 }
12923 } else if (LHSType->isPointerType() &&
12924 RHSType->isPointerType()) { // C99 6.5.8p2
12925 // All of the following pointer-related warnings are GCC extensions, except
12926 // when handling null pointer constants.
12927 QualType LCanPointeeTy =
12928 LHSType->castAs<PointerType>()->getPointeeType().getCanonicalType();
12929 QualType RCanPointeeTy =
12930 RHSType->castAs<PointerType>()->getPointeeType().getCanonicalType();
12931
12932 // C99 6.5.9p2 and C99 6.5.8p2
12933 if (Context.typesAreCompatible(LCanPointeeTy.getUnqualifiedType(),
12934 RCanPointeeTy.getUnqualifiedType())) {
12935 if (IsRelational) {
12936 // Pointers both need to point to complete or incomplete types
12937 if ((LCanPointeeTy->isIncompleteType() !=
12938 RCanPointeeTy->isIncompleteType()) &&
12939 !getLangOpts().C11) {
12940 Diag(Loc, diag::ext_typecheck_compare_complete_incomplete_pointers)
12941 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange()
12942 << LHSType << RHSType << LCanPointeeTy->isIncompleteType()
12943 << RCanPointeeTy->isIncompleteType();
12944 }
12945 }
12946 } else if (!IsRelational &&
12947 (LCanPointeeTy->isVoidType() || RCanPointeeTy->isVoidType())) {
12948 // Valid unless comparison between non-null pointer and function pointer
12949 if ((LCanPointeeTy->isFunctionType() || RCanPointeeTy->isFunctionType())
12950 && !LHSIsNull && !RHSIsNull)
12951 diagnoseFunctionPointerToVoidComparison(*this, Loc, LHS, RHS,
12952 /*isError*/false);
12953 } else {
12954 // Invalid
12955 diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS, /*isError*/false);
12956 }
12957 if (LCanPointeeTy != RCanPointeeTy) {
12958 // Treat NULL constant as a special case in OpenCL.
12959 if (getLangOpts().OpenCL && !LHSIsNull && !RHSIsNull) {
12960 if (!LCanPointeeTy.isAddressSpaceOverlapping(RCanPointeeTy)) {
12961 Diag(Loc,
12962 diag::err_typecheck_op_on_nonoverlapping_address_space_pointers)
12963 << LHSType << RHSType << 0 /* comparison */
12964 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
12965 }
12966 }
12967 LangAS AddrSpaceL = LCanPointeeTy.getAddressSpace();
12968 LangAS AddrSpaceR = RCanPointeeTy.getAddressSpace();
12969 CastKind Kind = AddrSpaceL != AddrSpaceR ? CK_AddressSpaceConversion
12970 : CK_BitCast;
12971 if (LHSIsNull && !RHSIsNull)
12972 LHS = ImpCastExprToType(LHS.get(), RHSType, Kind);
12973 else
12974 RHS = ImpCastExprToType(RHS.get(), LHSType, Kind);
12975 }
12976 return computeResultTy();
12977 }
12978
12979
12980 // C++ [expr.eq]p4:
12981 // Two operands of type std::nullptr_t or one operand of type
12982 // std::nullptr_t and the other a null pointer constant compare
12983 // equal.
12984 // C2x 6.5.9p5:
12985 // If both operands have type nullptr_t or one operand has type nullptr_t
12986 // and the other is a null pointer constant, they compare equal.
12987 if (!IsOrdered && LHSIsNull && RHSIsNull) {
12988 if (LHSType->isNullPtrType()) {
12989 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer);
12990 return computeResultTy();
12991 }
12992 if (RHSType->isNullPtrType()) {
12993 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer);
12994 return computeResultTy();
12995 }
12996 }
12997
12998 if (!getLangOpts().CPlusPlus && !IsOrdered && (LHSIsNull || RHSIsNull)) {
12999 // C2x 6.5.9p6:
13000 // Otherwise, at least one operand is a pointer. If one is a pointer and
13001 // the other is a null pointer constant, the null pointer constant is
13002 // converted to the type of the pointer.
13003 if (LHSIsNull && RHSType->isPointerType()) {
13004 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer);
13005 return computeResultTy();
13006 }
13007 if (RHSIsNull && LHSType->isPointerType()) {
13008 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer);
13009 return computeResultTy();
13010 }
13011 }
13012
13013 // Comparison of Objective-C pointers and block pointers against nullptr_t.
13014 // These aren't covered by the composite pointer type rules.
13015 if (!IsOrdered && RHSType->isNullPtrType() &&
13016 (LHSType->isObjCObjectPointerType() || LHSType->isBlockPointerType())) {
13017 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer);
13018 return computeResultTy();
13019 }
13020 if (!IsOrdered && LHSType->isNullPtrType() &&
13021 (RHSType->isObjCObjectPointerType() || RHSType->isBlockPointerType())) {
13022 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer);
13023 return computeResultTy();
13024 }
13025
13026 if (getLangOpts().CPlusPlus) {
13027 if (IsRelational &&
13028 ((LHSType->isNullPtrType() && RHSType->isPointerType()) ||
13029 (RHSType->isNullPtrType() && LHSType->isPointerType()))) {
13030 // HACK: Relational comparison of nullptr_t against a pointer type is
13031 // invalid per DR583, but we allow it within std::less<> and friends,
13032 // since otherwise common uses of it break.
13033 // FIXME: Consider removing this hack once LWG fixes std::less<> and
13034 // friends to have std::nullptr_t overload candidates.
13035 DeclContext *DC = CurContext;
13036 if (isa<FunctionDecl>(DC))
13037 DC = DC->getParent();
13038 if (auto *CTSD = dyn_cast<ClassTemplateSpecializationDecl>(DC)) {
13039 if (CTSD->isInStdNamespace() &&
13040 llvm::StringSwitch<bool>(CTSD->getName())
13041 .Cases("less", "less_equal", "greater", "greater_equal", true)
13042 .Default(false)) {
13043 if (RHSType->isNullPtrType())
13044 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer);
13045 else
13046 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer);
13047 return computeResultTy();
13048 }
13049 }
13050 }
13051
13052 // C++ [expr.eq]p2:
13053 // If at least one operand is a pointer to member, [...] bring them to
13054 // their composite pointer type.
13055 if (!IsOrdered &&
13056 (LHSType->isMemberPointerType() || RHSType->isMemberPointerType())) {
13057 if (convertPointersToCompositeType(*this, Loc, LHS, RHS))
13058 return QualType();
13059 else
13060 return computeResultTy();
13061 }
13062 }
13063
13064 // Handle block pointer types.
13065 if (!IsOrdered && LHSType->isBlockPointerType() &&
13066 RHSType->isBlockPointerType()) {
13067 QualType lpointee = LHSType->castAs<BlockPointerType>()->getPointeeType();
13068 QualType rpointee = RHSType->castAs<BlockPointerType>()->getPointeeType();
13069
13070 if (!LHSIsNull && !RHSIsNull &&
13071 !Context.typesAreCompatible(lpointee, rpointee)) {
13072 Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks)
13073 << LHSType << RHSType << LHS.get()->getSourceRange()
13074 << RHS.get()->getSourceRange();
13075 }
13076 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast);
13077 return computeResultTy();
13078 }
13079
13080 // Allow block pointers to be compared with null pointer constants.
13081 if (!IsOrdered
13082 && ((LHSType->isBlockPointerType() && RHSType->isPointerType())
13083 || (LHSType->isPointerType() && RHSType->isBlockPointerType()))) {
13084 if (!LHSIsNull && !RHSIsNull) {
13085 if (!((RHSType->isPointerType() && RHSType->castAs<PointerType>()
13086 ->getPointeeType()->isVoidType())
13087 || (LHSType->isPointerType() && LHSType->castAs<PointerType>()
13088 ->getPointeeType()->isVoidType())))
13089 Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks)
13090 << LHSType << RHSType << LHS.get()->getSourceRange()
13091 << RHS.get()->getSourceRange();
13092 }
13093 if (LHSIsNull && !RHSIsNull)
13094 LHS = ImpCastExprToType(LHS.get(), RHSType,
13095 RHSType->isPointerType() ? CK_BitCast
13096 : CK_AnyPointerToBlockPointerCast);
13097 else
13098 RHS = ImpCastExprToType(RHS.get(), LHSType,
13099 LHSType->isPointerType() ? CK_BitCast
13100 : CK_AnyPointerToBlockPointerCast);
13101 return computeResultTy();
13102 }
13103
13104 if (LHSType->isObjCObjectPointerType() ||
13105 RHSType->isObjCObjectPointerType()) {
13106 const PointerType *LPT = LHSType->getAs<PointerType>();
13107 const PointerType *RPT = RHSType->getAs<PointerType>();
13108 if (LPT || RPT) {
13109 bool LPtrToVoid = LPT ? LPT->getPointeeType()->isVoidType() : false;
13110 bool RPtrToVoid = RPT ? RPT->getPointeeType()->isVoidType() : false;
13111
13112 if (!LPtrToVoid && !RPtrToVoid &&
13113 !Context.typesAreCompatible(LHSType, RHSType)) {
13114 diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS,
13115 /*isError*/false);
13116 }
13117 // FIXME: If LPtrToVoid, we should presumably convert the LHS rather than
13118 // the RHS, but we have test coverage for this behavior.
13119 // FIXME: Consider using convertPointersToCompositeType in C++.
13120 if (LHSIsNull && !RHSIsNull) {
13121 Expr *E = LHS.get();
13122 if (getLangOpts().ObjCAutoRefCount)
13123 CheckObjCConversion(SourceRange(), RHSType, E,
13124 CCK_ImplicitConversion);
13125 LHS = ImpCastExprToType(E, RHSType,
13126 RPT ? CK_BitCast :CK_CPointerToObjCPointerCast);
13127 }
13128 else {
13129 Expr *E = RHS.get();
13130 if (getLangOpts().ObjCAutoRefCount)
13131 CheckObjCConversion(SourceRange(), LHSType, E, CCK_ImplicitConversion,
13132 /*Diagnose=*/true,
13133 /*DiagnoseCFAudited=*/false, Opc);
13134 RHS = ImpCastExprToType(E, LHSType,
13135 LPT ? CK_BitCast :CK_CPointerToObjCPointerCast);
13136 }
13137 return computeResultTy();
13138 }
13139 if (LHSType->isObjCObjectPointerType() &&
13140 RHSType->isObjCObjectPointerType()) {
13141 if (!Context.areComparableObjCPointerTypes(LHSType, RHSType))
13142 diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS,
13143 /*isError*/false);
13144 if (isObjCObjectLiteral(LHS) || isObjCObjectLiteral(RHS))
13145 diagnoseObjCLiteralComparison(*this, Loc, LHS, RHS, Opc);
13146
13147 if (LHSIsNull && !RHSIsNull)
13148 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_BitCast);
13149 else
13150 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast);
13151 return computeResultTy();
13152 }
13153
13154 if (!IsOrdered && LHSType->isBlockPointerType() &&
13155 RHSType->isBlockCompatibleObjCPointerType(Context)) {
13156 LHS = ImpCastExprToType(LHS.get(), RHSType,
13157 CK_BlockPointerToObjCPointerCast);
13158 return computeResultTy();
13159 } else if (!IsOrdered &&
13160 LHSType->isBlockCompatibleObjCPointerType(Context) &&
13161 RHSType->isBlockPointerType()) {
13162 RHS = ImpCastExprToType(RHS.get(), LHSType,
13163 CK_BlockPointerToObjCPointerCast);
13164 return computeResultTy();
13165 }
13166 }
13167 if ((LHSType->isAnyPointerType() && RHSType->isIntegerType()) ||
13168 (LHSType->isIntegerType() && RHSType->isAnyPointerType())) {
13169 unsigned DiagID = 0;
13170 bool isError = false;
13171 if (LangOpts.DebuggerSupport) {
13172 // Under a debugger, allow the comparison of pointers to integers,
13173 // since users tend to want to compare addresses.
13174 } else if ((LHSIsNull && LHSType->isIntegerType()) ||
13175 (RHSIsNull && RHSType->isIntegerType())) {
13176 if (IsOrdered) {
13177 isError = getLangOpts().CPlusPlus;
13178 DiagID =
13179 isError ? diag::err_typecheck_ordered_comparison_of_pointer_and_zero
13180 : diag::ext_typecheck_ordered_comparison_of_pointer_and_zero;
13181 }
13182 } else if (getLangOpts().CPlusPlus) {
13183 DiagID = diag::err_typecheck_comparison_of_pointer_integer;
13184 isError = true;
13185 } else if (IsOrdered)
13186 DiagID = diag::ext_typecheck_ordered_comparison_of_pointer_integer;
13187 else
13188 DiagID = diag::ext_typecheck_comparison_of_pointer_integer;
13189
13190 if (DiagID) {
13191 Diag(Loc, DiagID)
13192 << LHSType << RHSType << LHS.get()->getSourceRange()
13193 << RHS.get()->getSourceRange();
13194 if (isError)
13195 return QualType();
13196 }
13197
13198 if (LHSType->isIntegerType())
13199 LHS = ImpCastExprToType(LHS.get(), RHSType,
13200 LHSIsNull ? CK_NullToPointer : CK_IntegralToPointer);
13201 else
13202 RHS = ImpCastExprToType(RHS.get(), LHSType,
13203 RHSIsNull ? CK_NullToPointer : CK_IntegralToPointer);
13204 return computeResultTy();
13205 }
13206
13207 // Handle block pointers.
13208 if (!IsOrdered && RHSIsNull
13209 && LHSType->isBlockPointerType() && RHSType->isIntegerType()) {
13210 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer);
13211 return computeResultTy();
13212 }
13213 if (!IsOrdered && LHSIsNull
13214 && LHSType->isIntegerType() && RHSType->isBlockPointerType()) {
13215 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer);
13216 return computeResultTy();
13217 }
13218
13219 if (getLangOpts().getOpenCLCompatibleVersion() >= 200) {
13220 if (LHSType->isClkEventT() && RHSType->isClkEventT()) {
13221 return computeResultTy();
13222 }
13223
13224 if (LHSType->isQueueT() && RHSType->isQueueT()) {
13225 return computeResultTy();
13226 }
13227
13228 if (LHSIsNull && RHSType->isQueueT()) {
13229 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer);
13230 return computeResultTy();
13231 }
13232
13233 if (LHSType->isQueueT() && RHSIsNull) {
13234 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer);
13235 return computeResultTy();
13236 }
13237 }
13238
13239 return InvalidOperands(Loc, LHS, RHS);
13240}
13241
13242// Return a signed ext_vector_type that is of identical size and number of
13243// elements. For floating point vectors, return an integer type of identical
13244// size and number of elements. In the non ext_vector_type case, search from
13245// the largest type to the smallest type to avoid cases where long long == long,
13246// where long gets picked over long long.
13247QualType Sema::GetSignedVectorType(QualType V) {
13248 const VectorType *VTy = V->castAs<VectorType>();
13249 unsigned TypeSize = Context.getTypeSize(VTy->getElementType());
13250
13251 if (isa<ExtVectorType>(VTy)) {
13252 if (VTy->isExtVectorBoolType())
13253 return Context.getExtVectorType(Context.BoolTy, VTy->getNumElements());
13254 if (TypeSize == Context.getTypeSize(Context.CharTy))
13255 return Context.getExtVectorType(Context.CharTy, VTy->getNumElements());
13256 if (TypeSize == Context.getTypeSize(Context.ShortTy))
13257 return Context.getExtVectorType(Context.ShortTy, VTy->getNumElements());
13258 if (TypeSize == Context.getTypeSize(Context.IntTy))
13259 return Context.getExtVectorType(Context.IntTy, VTy->getNumElements());
13260 if (TypeSize == Context.getTypeSize(Context.Int128Ty))
13261 return Context.getExtVectorType(Context.Int128Ty, VTy->getNumElements());
13262 if (TypeSize == Context.getTypeSize(Context.LongTy))
13263 return Context.getExtVectorType(Context.LongTy, VTy->getNumElements());
13264 assert(TypeSize == Context.getTypeSize(Context.LongLongTy) &&(static_cast <bool> (TypeSize == Context.getTypeSize(Context
.LongLongTy) && "Unhandled vector element size in vector compare"
) ? void (0) : __assert_fail ("TypeSize == Context.getTypeSize(Context.LongLongTy) && \"Unhandled vector element size in vector compare\""
, "clang/lib/Sema/SemaExpr.cpp", 13265, __extension__ __PRETTY_FUNCTION__
))
13265 "Unhandled vector element size in vector compare")(static_cast <bool> (TypeSize == Context.getTypeSize(Context
.LongLongTy) && "Unhandled vector element size in vector compare"
) ? void (0) : __assert_fail ("TypeSize == Context.getTypeSize(Context.LongLongTy) && \"Unhandled vector element size in vector compare\""
, "clang/lib/Sema/SemaExpr.cpp", 13265, __extension__ __PRETTY_FUNCTION__
))
;
13266 return Context.getExtVectorType(Context.LongLongTy, VTy->getNumElements());
13267 }
13268
13269 if (TypeSize == Context.getTypeSize(Context.Int128Ty))
13270 return Context.getVectorType(Context.Int128Ty, VTy->getNumElements(),
13271 VectorType::GenericVector);
13272 if (TypeSize == Context.getTypeSize(Context.LongLongTy))
13273 return Context.getVectorType(Context.LongLongTy, VTy->getNumElements(),
13274 VectorType::GenericVector);
13275 if (TypeSize == Context.getTypeSize(Context.LongTy))
13276 return Context.getVectorType(Context.LongTy, VTy->getNumElements(),
13277 VectorType::GenericVector);
13278 if (TypeSize == Context.getTypeSize(Context.IntTy))
13279 return Context.getVectorType(Context.IntTy, VTy->getNumElements(),
13280 VectorType::GenericVector);
13281 if (TypeSize == Context.getTypeSize(Context.ShortTy))
13282 return Context.getVectorType(Context.ShortTy, VTy->getNumElements(),
13283 VectorType::GenericVector);
13284 assert(TypeSize == Context.getTypeSize(Context.CharTy) &&(static_cast <bool> (TypeSize == Context.getTypeSize(Context
.CharTy) && "Unhandled vector element size in vector compare"
) ? void (0) : __assert_fail ("TypeSize == Context.getTypeSize(Context.CharTy) && \"Unhandled vector element size in vector compare\""
, "clang/lib/Sema/SemaExpr.cpp", 13285, __extension__ __PRETTY_FUNCTION__
))
13285 "Unhandled vector element size in vector compare")(static_cast <bool> (TypeSize == Context.getTypeSize(Context
.CharTy) && "Unhandled vector element size in vector compare"
) ? void (0) : __assert_fail ("TypeSize == Context.getTypeSize(Context.CharTy) && \"Unhandled vector element size in vector compare\""
, "clang/lib/Sema/SemaExpr.cpp", 13285, __extension__ __PRETTY_FUNCTION__
))
;
13286 return Context.getVectorType(Context.CharTy, VTy->getNumElements(),
13287 VectorType::GenericVector);
13288}
13289
13290QualType Sema::GetSignedSizelessVectorType(QualType V) {
13291 const BuiltinType *VTy = V->castAs<BuiltinType>();
13292 assert(VTy->isSizelessBuiltinType() && "expected sizeless type")(static_cast <bool> (VTy->isSizelessBuiltinType() &&
"expected sizeless type") ? void (0) : __assert_fail ("VTy->isSizelessBuiltinType() && \"expected sizeless type\""
, "clang/lib/Sema/SemaExpr.cpp", 13292, __extension__ __PRETTY_FUNCTION__
))
;
13293
13294 const QualType ETy = V->getSveEltType(Context);
13295 const auto TypeSize = Context.getTypeSize(ETy);
13296
13297 const QualType IntTy = Context.getIntTypeForBitwidth(TypeSize, true);
13298 const llvm::ElementCount VecSize = Context.getBuiltinVectorTypeInfo(VTy).EC;
13299 return Context.getScalableVectorType(IntTy, VecSize.getKnownMinValue());
13300}
13301
13302/// CheckVectorCompareOperands - vector comparisons are a clang extension that
13303/// operates on extended vector types. Instead of producing an IntTy result,
13304/// like a scalar comparison, a vector comparison produces a vector of integer
13305/// types.
13306QualType Sema::CheckVectorCompareOperands(ExprResult &LHS, ExprResult &RHS,
13307 SourceLocation Loc,
13308 BinaryOperatorKind Opc) {
13309 if (Opc == BO_Cmp) {
13310 Diag(Loc, diag::err_three_way_vector_comparison);
13311 return QualType();
13312 }
13313
13314 // Check to make sure we're operating on vectors of the same type and width,
13315 // Allowing one side to be a scalar of element type.
13316 QualType vType =
13317 CheckVectorOperands(LHS, RHS, Loc, /*isCompAssign*/ false,
13318 /*AllowBothBool*/ true,
13319 /*AllowBoolConversions*/ getLangOpts().ZVector,
13320 /*AllowBooleanOperation*/ true,
13321 /*ReportInvalid*/ true);
13322 if (vType.isNull())
13323 return vType;
13324
13325 QualType LHSType = LHS.get()->getType();
13326
13327 // Determine the return type of a vector compare. By default clang will return
13328 // a scalar for all vector compares except vector bool and vector pixel.
13329 // With the gcc compiler we will always return a vector type and with the xl
13330 // compiler we will always return a scalar type. This switch allows choosing
13331 // which behavior is prefered.
13332 if (getLangOpts().AltiVec) {
13333 switch (getLangOpts().getAltivecSrcCompat()) {
13334 case LangOptions::AltivecSrcCompatKind::Mixed:
13335 // If AltiVec, the comparison results in a numeric type, i.e.
13336 // bool for C++, int for C
13337 if (vType->castAs<VectorType>()->getVectorKind() ==
13338 VectorType::AltiVecVector)
13339 return Context.getLogicalOperationType();
13340 else
13341 Diag(Loc, diag::warn_deprecated_altivec_src_compat);
13342 break;
13343 case LangOptions::AltivecSrcCompatKind::GCC:
13344 // For GCC we always return the vector type.
13345 break;
13346 case LangOptions::AltivecSrcCompatKind::XL:
13347 return Context.getLogicalOperationType();
13348 break;
13349 }
13350 }
13351
13352 // For non-floating point types, check for self-comparisons of the form
13353 // x == x, x != x, x < x, etc. These always evaluate to a constant, and
13354 // often indicate logic errors in the program.
13355 diagnoseTautologicalComparison(*this, Loc, LHS.get(), RHS.get(), Opc);
13356
13357 // Check for comparisons of floating point operands using != and ==.
13358 if (LHSType->hasFloatingRepresentation()) {
13359 assert(RHS.get()->getType()->hasFloatingRepresentation())(static_cast <bool> (RHS.get()->getType()->hasFloatingRepresentation
()) ? void (0) : __assert_fail ("RHS.get()->getType()->hasFloatingRepresentation()"
, "clang/lib/Sema/SemaExpr.cpp", 13359, __extension__ __PRETTY_FUNCTION__
))
;
13360 CheckFloatComparison(Loc, LHS.get(), RHS.get(), Opc);
13361 }
13362
13363 // Return a signed type for the vector.
13364 return GetSignedVectorType(vType);
13365}
13366
13367QualType Sema::CheckSizelessVectorCompareOperands(ExprResult &LHS,
13368 ExprResult &RHS,
13369 SourceLocation Loc,
13370 BinaryOperatorKind Opc) {
13371 if (Opc == BO_Cmp) {
13372 Diag(Loc, diag::err_three_way_vector_comparison);
13373 return QualType();
13374 }
13375
13376 // Check to make sure we're operating on vectors of the same type and width,
13377 // Allowing one side to be a scalar of element type.
13378 QualType vType = CheckSizelessVectorOperands(
13379 LHS, RHS, Loc, /*isCompAssign*/ false, ACK_Comparison);
13380
13381 if (vType.isNull())
13382 return vType;
13383
13384 QualType LHSType = LHS.get()->getType();
13385
13386 // For non-floating point types, check for self-comparisons of the form
13387 // x == x, x != x, x < x, etc. These always evaluate to a constant, and
13388 // often indicate logic errors in the program.
13389 diagnoseTautologicalComparison(*this, Loc, LHS.get(), RHS.get(), Opc);
13390
13391 // Check for comparisons of floating point operands using != and ==.
13392 if (LHSType->hasFloatingRepresentation()) {
13393 assert(RHS.get()->getType()->hasFloatingRepresentation())(static_cast <bool> (RHS.get()->getType()->hasFloatingRepresentation
()) ? void (0) : __assert_fail ("RHS.get()->getType()->hasFloatingRepresentation()"
, "clang/lib/Sema/SemaExpr.cpp", 13393, __extension__ __PRETTY_FUNCTION__
))
;
13394 CheckFloatComparison(Loc, LHS.get(), RHS.get(), Opc);
13395 }
13396
13397 const BuiltinType *LHSBuiltinTy = LHSType->getAs<BuiltinType>();
13398 const BuiltinType *RHSBuiltinTy = RHS.get()->getType()->getAs<BuiltinType>();
13399
13400 if (LHSBuiltinTy && RHSBuiltinTy && LHSBuiltinTy->isSVEBool() &&
13401 RHSBuiltinTy->isSVEBool())
13402 return LHSType;
13403
13404 // Return a signed type for the vector.
13405 return GetSignedSizelessVectorType(vType);
13406}
13407
13408static void diagnoseXorMisusedAsPow(Sema &S, const ExprResult &XorLHS,
13409 const ExprResult &XorRHS,
13410 const SourceLocation Loc) {
13411 // Do not diagnose macros.
13412 if (Loc.isMacroID())
13413 return;
13414
13415 // Do not diagnose if both LHS and RHS are macros.
13416 if (XorLHS.get()->getExprLoc().isMacroID() &&
13417 XorRHS.get()->getExprLoc().isMacroID())
13418 return;
13419
13420 bool Negative = false;
13421 bool ExplicitPlus = false;
13422 const auto *LHSInt = dyn_cast<IntegerLiteral>(XorLHS.get());
13423 const auto *RHSInt = dyn_cast<IntegerLiteral>(XorRHS.get());
13424
13425 if (!LHSInt)
13426 return;
13427 if (!RHSInt) {
13428 // Check negative literals.
13429 if (const auto *UO = dyn_cast<UnaryOperator>(XorRHS.get())) {
13430 UnaryOperatorKind Opc = UO->getOpcode();
13431 if (Opc != UO_Minus && Opc != UO_Plus)
13432 return;
13433 RHSInt = dyn_cast<IntegerLiteral>(UO->getSubExpr());
13434 if (!RHSInt)
13435 return;
13436 Negative = (Opc == UO_Minus);
13437 ExplicitPlus = !Negative;
13438 } else {
13439 return;
13440 }
13441 }
13442
13443 const llvm::APInt &LeftSideValue = LHSInt->getValue();
13444 llvm::APInt RightSideValue = RHSInt->getValue();
13445 if (LeftSideValue != 2 && LeftSideValue != 10)
13446 return;
13447
13448 if (LeftSideValue.getBitWidth() != RightSideValue.getBitWidth())
13449 return;
13450
13451 CharSourceRange ExprRange = CharSourceRange::getCharRange(
13452 LHSInt->getBeginLoc(), S.getLocForEndOfToken(RHSInt->getLocation()));
13453 llvm::StringRef ExprStr =
13454 Lexer::getSourceText(ExprRange, S.getSourceManager(), S.getLangOpts());
13455
13456 CharSourceRange XorRange =
13457 CharSourceRange::getCharRange(Loc, S.getLocForEndOfToken(Loc));
13458 llvm::StringRef XorStr =
13459 Lexer::getSourceText(XorRange, S.getSourceManager(), S.getLangOpts());
13460 // Do not diagnose if xor keyword/macro is used.
13461 if (XorStr == "xor")
13462 return;
13463
13464 std::string LHSStr = std::string(Lexer::getSourceText(
13465 CharSourceRange::getTokenRange(LHSInt->getSourceRange()),
13466 S.getSourceManager(), S.getLangOpts()));
13467 std::string RHSStr = std::string(Lexer::getSourceText(
13468 CharSourceRange::getTokenRange(RHSInt->getSourceRange()),
13469 S.getSourceManager(), S.getLangOpts()));
13470
13471 if (Negative) {
13472 RightSideValue = -RightSideValue;
13473 RHSStr = "-" + RHSStr;
13474 } else if (ExplicitPlus) {
13475 RHSStr = "+" + RHSStr;
13476 }
13477
13478 StringRef LHSStrRef = LHSStr;
13479 StringRef RHSStrRef = RHSStr;
13480 // Do not diagnose literals with digit separators, binary, hexadecimal, octal
13481 // literals.
13482 if (LHSStrRef.startswith("0b") || LHSStrRef.startswith("0B") ||
13483 RHSStrRef.startswith("0b") || RHSStrRef.startswith("0B") ||
13484 LHSStrRef.startswith("0x") || LHSStrRef.startswith("0X") ||
13485 RHSStrRef.startswith("0x") || RHSStrRef.startswith("0X") ||
13486 (LHSStrRef.size() > 1 && LHSStrRef.startswith("0")) ||
13487 (RHSStrRef.size() > 1 && RHSStrRef.startswith("0")) ||
13488 LHSStrRef.contains('\'') || RHSStrRef.contains('\''))
13489 return;
13490
13491 bool SuggestXor =
13492 S.getLangOpts().CPlusPlus || S.getPreprocessor().isMacroDefined("xor");
13493 const llvm::APInt XorValue = LeftSideValue ^ RightSideValue;
13494 int64_t RightSideIntValue = RightSideValue.getSExtValue();
13495 if (LeftSideValue == 2 && RightSideIntValue >= 0) {
13496 std::string SuggestedExpr = "1 << " + RHSStr;
13497 bool Overflow = false;
13498 llvm::APInt One = (LeftSideValue - 1);
13499 llvm::APInt PowValue = One.sshl_ov(RightSideValue, Overflow);
13500 if (Overflow) {
13501 if (RightSideIntValue < 64)
13502 S.Diag(Loc, diag::warn_xor_used_as_pow_base)
13503 << ExprStr << toString(XorValue, 10, true) << ("1LL << " + RHSStr)
13504 << FixItHint::CreateReplacement(ExprRange, "1LL << " + RHSStr);
13505 else if (RightSideIntValue == 64)
13506 S.Diag(Loc, diag::warn_xor_used_as_pow)
13507 << ExprStr << toString(XorValue, 10, true);
13508 else
13509 return;
13510 } else {
13511 S.Diag(Loc, diag::warn_xor_used_as_pow_base_extra)
13512 << ExprStr << toString(XorValue, 10, true) << SuggestedExpr
13513 << toString(PowValue, 10, true)
13514 << FixItHint::CreateReplacement(
13515 ExprRange, (RightSideIntValue == 0) ? "1" : SuggestedExpr);
13516 }
13517
13518 S.Diag(Loc, diag::note_xor_used_as_pow_silence)
13519 << ("0x2 ^ " + RHSStr) << SuggestXor;
13520 } else if (LeftSideValue == 10) {
13521 std::string SuggestedValue = "1e" + std::to_string(RightSideIntValue);
13522 S.Diag(Loc, diag::warn_xor_used_as_pow_base)
13523 << ExprStr << toString(XorValue, 10, true) << SuggestedValue
13524 << FixItHint::CreateReplacement(ExprRange, SuggestedValue);
13525 S.Diag(Loc, diag::note_xor_used_as_pow_silence)
13526 << ("0xA ^ " + RHSStr) << SuggestXor;
13527 }
13528}
13529
13530QualType Sema::CheckVectorLogicalOperands(ExprResult &LHS, ExprResult &RHS,
13531 SourceLocation Loc) {
13532 // Ensure that either both operands are of the same vector type, or
13533 // one operand is of a vector type and the other is of its element type.
13534 QualType vType = CheckVectorOperands(LHS, RHS, Loc, false,
13535 /*AllowBothBool*/ true,
13536 /*AllowBoolConversions*/ false,
13537 /*AllowBooleanOperation*/ false,
13538 /*ReportInvalid*/ false);
13539 if (vType.isNull())
13540 return InvalidOperands(Loc, LHS, RHS);
13541 if (getLangOpts().OpenCL &&
13542 getLangOpts().getOpenCLCompatibleVersion() < 120 &&
13543 vType->hasFloatingRepresentation())
13544 return InvalidOperands(Loc, LHS, RHS);
13545 // FIXME: The check for C++ here is for GCC compatibility. GCC rejects the
13546 // usage of the logical operators && and || with vectors in C. This
13547 // check could be notionally dropped.
13548 if (!getLangOpts().CPlusPlus &&
13549 !(isa<ExtVectorType>(vType->getAs<VectorType>())))
13550 return InvalidLogicalVectorOperands(Loc, LHS, RHS);
13551
13552 return GetSignedVectorType(LHS.get()->getType());
13553}
13554
13555QualType Sema::CheckMatrixElementwiseOperands(ExprResult &LHS, ExprResult &RHS,
13556 SourceLocation Loc,
13557 bool IsCompAssign) {
13558 if (!IsCompAssign) {
13559 LHS = DefaultFunctionArrayLvalueConversion(LHS.get());
13560 if (LHS.isInvalid())
13561 return QualType();
13562 }
13563 RHS = DefaultFunctionArrayLvalueConversion(RHS.get());
13564 if (RHS.isInvalid())
13565 return QualType();
13566
13567 // For conversion purposes, we ignore any qualifiers.
13568 // For example, "const float" and "float" are equivalent.
13569 QualType LHSType = LHS.get()->getType().getUnqualifiedType();
13570 QualType RHSType = RHS.get()->getType().getUnqualifiedType();
13571
13572 const MatrixType *LHSMatType = LHSType->getAs<MatrixType>();
13573 const MatrixType *RHSMatType = RHSType->getAs<MatrixType>();
13574 assert((LHSMatType || RHSMatType) && "At least one operand must be a matrix")(static_cast <bool> ((LHSMatType || RHSMatType) &&
"At least one operand must be a matrix") ? void (0) : __assert_fail
("(LHSMatType || RHSMatType) && \"At least one operand must be a matrix\""
, "clang/lib/Sema/SemaExpr.cpp", 13574, __extension__ __PRETTY_FUNCTION__
))
;
13575
13576 if (Context.hasSameType(LHSType, RHSType))
13577 return Context.getCommonSugaredType(LHSType, RHSType);
13578
13579 // Type conversion may change LHS/RHS. Keep copies to the original results, in
13580 // case we have to return InvalidOperands.
13581 ExprResult OriginalLHS = LHS;
13582 ExprResult OriginalRHS = RHS;
13583 if (LHSMatType && !RHSMatType) {
13584 RHS = tryConvertExprToType(RHS.get(), LHSMatType->getElementType());
13585 if (!RHS.isInvalid())
13586 return LHSType;
13587
13588 return InvalidOperands(Loc, OriginalLHS, OriginalRHS);
13589 }
13590
13591 if (!LHSMatType && RHSMatType) {
13592 LHS = tryConvertExprToType(LHS.get(), RHSMatType->getElementType());
13593 if (!LHS.isInvalid())
13594 return RHSType;
13595 return InvalidOperands(Loc, OriginalLHS, OriginalRHS);
13596 }
13597
13598 return InvalidOperands(Loc, LHS, RHS);
13599}
13600
13601QualType Sema::CheckMatrixMultiplyOperands(ExprResult &LHS, ExprResult &RHS,
13602 SourceLocation Loc,
13603 bool IsCompAssign) {
13604 if (!IsCompAssign) {
13605 LHS = DefaultFunctionArrayLvalueConversion(LHS.get());
13606 if (LHS.isInvalid())
13607 return QualType();
13608 }
13609 RHS = DefaultFunctionArrayLvalueConversion(RHS.get());
13610 if (RHS.isInvalid())
13611 return QualType();
13612
13613 auto *LHSMatType = LHS.get()->getType()->getAs<ConstantMatrixType>();
13614 auto *RHSMatType = RHS.get()->getType()->getAs<ConstantMatrixType>();
13615 assert((LHSMatType || RHSMatType) && "At least one operand must be a matrix")(static_cast <bool> ((LHSMatType || RHSMatType) &&
"At least one operand must be a matrix") ? void (0) : __assert_fail
("(LHSMatType || RHSMatType) && \"At least one operand must be a matrix\""
, "clang/lib/Sema/SemaExpr.cpp", 13615, __extension__ __PRETTY_FUNCTION__
))
;
13616
13617 if (LHSMatType && RHSMatType) {
13618 if (LHSMatType->getNumColumns() != RHSMatType->getNumRows())
13619 return InvalidOperands(Loc, LHS, RHS);
13620
13621 if (Context.hasSameType(LHSMatType, RHSMatType))
13622 return Context.getCommonSugaredType(
13623 LHS.get()->getType().getUnqualifiedType(),
13624 RHS.get()->getType().getUnqualifiedType());
13625
13626 QualType LHSELTy = LHSMatType->getElementType(),
13627 RHSELTy = RHSMatType->getElementType();
13628 if (!Context.hasSameType(LHSELTy, RHSELTy))
13629 return InvalidOperands(Loc, LHS, RHS);
13630
13631 return Context.getConstantMatrixType(
13632 Context.getCommonSugaredType(LHSELTy, RHSELTy),
13633 LHSMatType->getNumRows(), RHSMatType->getNumColumns());
13634 }
13635 return CheckMatrixElementwiseOperands(LHS, RHS, Loc, IsCompAssign);
13636}
13637
13638static bool isLegalBoolVectorBinaryOp(BinaryOperatorKind Opc) {
13639 switch (Opc) {
13640 default:
13641 return false;
13642 case BO_And:
13643 case BO_AndAssign:
13644 case BO_Or:
13645 case BO_OrAssign:
13646 case BO_Xor:
13647 case BO_XorAssign:
13648 return true;
13649 }
13650}
13651
13652inline QualType Sema::CheckBitwiseOperands(ExprResult &LHS, ExprResult &RHS,
13653 SourceLocation Loc,
13654 BinaryOperatorKind Opc) {
13655 checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/false);
13656
13657 bool IsCompAssign =
13658 Opc == BO_AndAssign || Opc == BO_OrAssign || Opc == BO_XorAssign;
13659
13660 bool LegalBoolVecOperator = isLegalBoolVectorBinaryOp(Opc);
13661
13662 if (LHS.get()->getType()->isVectorType() ||
13663 RHS.get()->getType()->isVectorType()) {
13664 if (LHS.get()->getType()->hasIntegerRepresentation() &&
13665 RHS.get()->getType()->hasIntegerRepresentation())
13666 return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign,
13667 /*AllowBothBool*/ true,
13668 /*AllowBoolConversions*/ getLangOpts().ZVector,
13669 /*AllowBooleanOperation*/ LegalBoolVecOperator,
13670 /*ReportInvalid*/ true);
13671 return InvalidOperands(Loc, LHS, RHS);
13672 }
13673
13674 if (LHS.get()->getType()->isVLSTBuiltinType() ||
13675 RHS.get()->getType()->isVLSTBuiltinType()) {
13676 if (LHS.get()->getType()->hasIntegerRepresentation() &&
13677 RHS.get()->getType()->hasIntegerRepresentation())
13678 return CheckSizelessVectorOperands(LHS, RHS, Loc, IsCompAssign,
13679 ACK_BitwiseOp);
13680 return InvalidOperands(Loc, LHS, RHS);
13681 }
13682
13683 if (LHS.get()->getType()->isVLSTBuiltinType() ||
13684 RHS.get()->getType()->isVLSTBuiltinType()) {
13685 if (LHS.get()->getType()->hasIntegerRepresentation() &&
13686 RHS.get()->getType()->hasIntegerRepresentation())
13687 return CheckSizelessVectorOperands(LHS, RHS, Loc, IsCompAssign,
13688 ACK_BitwiseOp);
13689 return InvalidOperands(Loc, LHS, RHS);
13690 }
13691
13692 if (Opc == BO_And)
13693 diagnoseLogicalNotOnLHSofCheck(*this, LHS, RHS, Loc, Opc);
13694
13695 if (LHS.get()->getType()->hasFloatingRepresentation() ||
13696 RHS.get()->getType()->hasFloatingRepresentation())
13697 return InvalidOperands(Loc, LHS, RHS);
13698
13699 ExprResult LHSResult = LHS, RHSResult = RHS;
13700 QualType compType = UsualArithmeticConversions(
13701 LHSResult, RHSResult, Loc, IsCompAssign ? ACK_CompAssign : ACK_BitwiseOp);
13702 if (LHSResult.isInvalid() || RHSResult.isInvalid())
13703 return QualType();
13704 LHS = LHSResult.get();
13705 RHS = RHSResult.get();
13706
13707 if (Opc == BO_Xor)
13708 diagnoseXorMisusedAsPow(*this, LHS, RHS, Loc);
13709
13710 if (!compType.isNull() && compType->isIntegralOrUnscopedEnumerationType())
13711 return compType;
13712 return InvalidOperands(Loc, LHS, RHS);
13713}
13714
13715// C99 6.5.[13,14]
13716inline QualType Sema::CheckLogicalOperands(ExprResult &LHS, ExprResult &RHS,
13717 SourceLocation Loc,
13718 BinaryOperatorKind Opc) {
13719 // Check vector operands differently.
13720 if (LHS.get()->getType()->isVectorType() ||
13721 RHS.get()->getType()->isVectorType())
13722 return CheckVectorLogicalOperands(LHS, RHS, Loc);
13723
13724 bool EnumConstantInBoolContext = false;
13725 for (const ExprResult &HS : {LHS, RHS}) {
13726 if (const auto *DREHS = dyn_cast<DeclRefExpr>(HS.get())) {
13727 const auto *ECDHS = dyn_cast<EnumConstantDecl>(DREHS->getDecl());
13728 if (ECDHS && ECDHS->getInitVal() != 0 && ECDHS->getInitVal() != 1)
13729 EnumConstantInBoolContext = true;
13730 }
13731 }
13732
13733 if (EnumConstantInBoolContext)
13734 Diag(Loc, diag::warn_enum_constant_in_bool_context);
13735
13736 // Diagnose cases where the user write a logical and/or but probably meant a
13737 // bitwise one. We do this when the LHS is a non-bool integer and the RHS
13738 // is a constant.
13739 if (!EnumConstantInBoolContext && LHS.get()->getType()->isIntegerType() &&
13740 !LHS.get()->getType()->isBooleanType() &&
13741 RHS.get()->getType()->isIntegerType() && !RHS.get()->isValueDependent() &&
13742 // Don't warn in macros or template instantiations.
13743 !Loc.isMacroID() && !inTemplateInstantiation()) {
13744 // If the RHS can be constant folded, and if it constant folds to something
13745 // that isn't 0 or 1 (which indicate a potential logical operation that
13746 // happened to fold to true/false) then warn.
13747 // Parens on the RHS are ignored.
13748 Expr::EvalResult EVResult;
13749 if (RHS.get()->EvaluateAsInt(EVResult, Context)) {
13750 llvm::APSInt Result = EVResult.Val.getInt();
13751 if ((getLangOpts().Bool && !RHS.get()->getType()->isBooleanType() &&
13752 !RHS.get()->getExprLoc().isMacroID()) ||
13753 (Result != 0 && Result != 1)) {
13754 Diag(Loc, diag::warn_logical_instead_of_bitwise)
13755 << RHS.get()->getSourceRange() << (Opc == BO_LAnd ? "&&" : "||");
13756 // Suggest replacing the logical operator with the bitwise version
13757 Diag(Loc, diag::note_logical_instead_of_bitwise_change_operator)
13758 << (Opc == BO_LAnd ? "&" : "|")
13759 << FixItHint::CreateReplacement(
13760 SourceRange(Loc, getLocForEndOfToken(Loc)),
13761 Opc == BO_LAnd ? "&" : "|");
13762 if (Opc == BO_LAnd)
13763 // Suggest replacing "Foo() && kNonZero" with "Foo()"
13764 Diag(Loc, diag::note_logical_instead_of_bitwise_remove_constant)
13765 << FixItHint::CreateRemoval(
13766 SourceRange(getLocForEndOfToken(LHS.get()->getEndLoc()),
13767 RHS.get()->getEndLoc()));
13768 }
13769 }
13770 }
13771
13772 if (!Context.getLangOpts().CPlusPlus) {
13773 // OpenCL v1.1 s6.3.g: The logical operators and (&&), or (||) do
13774 // not operate on the built-in scalar and vector float types.
13775 if (Context.getLangOpts().OpenCL &&
13776 Context.getLangOpts().OpenCLVersion < 120) {
13777 if (LHS.get()->getType()->isFloatingType() ||
13778 RHS.get()->getType()->isFloatingType())
13779 return InvalidOperands(Loc, LHS, RHS);
13780 }
13781
13782 LHS = UsualUnaryConversions(LHS.get());
13783 if (LHS.isInvalid())
13784 return QualType();
13785
13786 RHS = UsualUnaryConversions(RHS.get());
13787 if (RHS.isInvalid())
13788 return QualType();
13789
13790 if (!LHS.get()->getType()->isScalarType() ||
13791 !RHS.get()->getType()->isScalarType())
13792 return InvalidOperands(Loc, LHS, RHS);
13793
13794 return Context.IntTy;
13795 }
13796
13797 // The following is safe because we only use this method for
13798 // non-overloadable operands.
13799
13800 // C++ [expr.log.and]p1
13801 // C++ [expr.log.or]p1
13802 // The operands are both contextually converted to type bool.
13803 ExprResult LHSRes = PerformContextuallyConvertToBool(LHS.get());
13804 if (LHSRes.isInvalid())
13805 return InvalidOperands(Loc, LHS, RHS);
13806 LHS = LHSRes;
13807
13808 ExprResult RHSRes = PerformContextuallyConvertToBool(RHS.get());
13809 if (RHSRes.isInvalid())
13810 return InvalidOperands(Loc, LHS, RHS);
13811 RHS = RHSRes;
13812
13813 // C++ [expr.log.and]p2
13814 // C++ [expr.log.or]p2
13815 // The result is a bool.
13816 return Context.BoolTy;
13817}
13818
13819static bool IsReadonlyMessage(Expr *E, Sema &S) {
13820 const MemberExpr *ME = dyn_cast<MemberExpr>(E);
13821 if (!ME) return false;
13822 if (!isa<FieldDecl>(ME->getMemberDecl())) return false;
13823 ObjCMessageExpr *Base = dyn_cast<ObjCMessageExpr>(
13824 ME->getBase()->IgnoreImplicit()->IgnoreParenImpCasts());
13825 if (!Base) return false;
13826 return Base->getMethodDecl() != nullptr;
13827}
13828
13829/// Is the given expression (which must be 'const') a reference to a
13830/// variable which was originally non-const, but which has become
13831/// 'const' due to being captured within a block?
13832enum NonConstCaptureKind { NCCK_None, NCCK_Block, NCCK_Lambda };
13833static NonConstCaptureKind isReferenceToNonConstCapture(Sema &S, Expr *E) {
13834 assert(E->isLValue() && E->getType().isConstQualified())(static_cast <bool> (E->isLValue() && E->
getType().isConstQualified()) ? void (0) : __assert_fail ("E->isLValue() && E->getType().isConstQualified()"
, "clang/lib/Sema/SemaExpr.cpp", 13834, __extension__ __PRETTY_FUNCTION__
))
;
13835 E = E->IgnoreParens();
13836
13837 // Must be a reference to a declaration from an enclosing scope.
13838 DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E);
13839 if (!DRE) return NCCK_None;
13840 if (!DRE->refersToEnclosingVariableOrCapture()) return NCCK_None;
13841
13842 // The declaration must be a variable which is not declared 'const'.
13843 VarDecl *var = dyn_cast<VarDecl>(DRE->getDecl());
13844 if (!var) return NCCK_None;
13845 if (var->getType().isConstQualified()) return NCCK_None;
13846 assert(var->hasLocalStorage() && "capture added 'const' to non-local?")(static_cast <bool> (var->hasLocalStorage() &&
"capture added 'const' to non-local?") ? void (0) : __assert_fail
("var->hasLocalStorage() && \"capture added 'const' to non-local?\""
, "clang/lib/Sema/SemaExpr.cpp", 13846, __extension__ __PRETTY_FUNCTION__
))
;
13847
13848 // Decide whether the first capture was for a block or a lambda.
13849 DeclContext *DC = S.CurContext, *Prev = nullptr;
13850 // Decide whether the first capture was for a block or a lambda.
13851 while (DC) {
13852 // For init-capture, it is possible that the variable belongs to the
13853 // template pattern of the current context.
13854 if (auto *FD = dyn_cast<FunctionDecl>(DC))
13855 if (var->isInitCapture() &&
13856 FD->getTemplateInstantiationPattern() == var->getDeclContext())
13857 break;
13858 if (DC == var->getDeclContext())
13859 break;
13860 Prev = DC;
13861 DC = DC->getParent();
13862 }
13863 // Unless we have an init-capture, we've gone one step too far.
13864 if (!var->isInitCapture())
13865 DC = Prev;
13866 return (isa<BlockDecl>(DC) ? NCCK_Block : NCCK_Lambda);
13867}
13868
13869static bool IsTypeModifiable(QualType Ty, bool IsDereference) {
13870 Ty = Ty.getNonReferenceType();
13871 if (IsDereference && Ty->isPointerType())
13872 Ty = Ty->getPointeeType();
13873 return !Ty.isConstQualified();
13874}
13875
13876// Update err_typecheck_assign_const and note_typecheck_assign_const
13877// when this enum is changed.
13878enum {
13879 ConstFunction,
13880 ConstVariable,
13881 ConstMember,
13882 ConstMethod,
13883 NestedConstMember,
13884 ConstUnknown, // Keep as last element
13885};
13886
13887/// Emit the "read-only variable not assignable" error and print notes to give
13888/// more information about why the variable is not assignable, such as pointing
13889/// to the declaration of a const variable, showing that a method is const, or
13890/// that the function is returning a const reference.
13891static void DiagnoseConstAssignment(Sema &S, const Expr *E,
13892 SourceLocation Loc) {
13893 SourceRange ExprRange = E->getSourceRange();
13894
13895 // Only emit one error on the first const found. All other consts will emit
13896 // a note to the error.
13897 bool DiagnosticEmitted = false;
13898
13899 // Track if the current expression is the result of a dereference, and if the
13900 // next checked expression is the result of a dereference.
13901 bool IsDereference = false;
13902 bool NextIsDereference = false;
13903
13904 // Loop to process MemberExpr chains.
13905 while (true) {
13906 IsDereference = NextIsDereference;
13907
13908 E = E->IgnoreImplicit()->IgnoreParenImpCasts();
13909 if (const MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
13910 NextIsDereference = ME->isArrow();
13911 const ValueDecl *VD = ME->getMemberDecl();
13912 if (const FieldDecl *Field = dyn_cast<FieldDecl>(VD)) {
13913 // Mutable fields can be modified even if the class is const.
13914 if (Field->isMutable()) {
13915 assert(DiagnosticEmitted && "Expected diagnostic not emitted.")(static_cast <bool> (DiagnosticEmitted && "Expected diagnostic not emitted."
) ? void (0) : __assert_fail ("DiagnosticEmitted && \"Expected diagnostic not emitted.\""
, "clang/lib/Sema/SemaExpr.cpp", 13915, __extension__ __PRETTY_FUNCTION__
))
;
13916 break;
13917 }
13918
13919 if (!IsTypeModifiable(Field->getType(), IsDereference)) {
13920 if (!DiagnosticEmitted) {
13921 S.Diag(Loc, diag::err_typecheck_assign_const)
13922 << ExprRange << ConstMember << false /*static*/ << Field
13923 << Field->getType();
13924 DiagnosticEmitted = true;
13925 }
13926 S.Diag(VD->getLocation(), diag::note_typecheck_assign_const)
13927 << ConstMember << false /*static*/ << Field << Field->getType()
13928 << Field->getSourceRange();
13929 }
13930 E = ME->getBase();
13931 continue;
13932 } else if (const VarDecl *VDecl = dyn_cast<VarDecl>(VD)) {
13933 if (VDecl->getType().isConstQualified()) {
13934 if (!DiagnosticEmitted) {
13935 S.Diag(Loc, diag::err_typecheck_assign_const)
13936 << ExprRange << ConstMember << true /*static*/ << VDecl
13937 << VDecl->getType();
13938 DiagnosticEmitted = true;
13939 }
13940 S.Diag(VD->getLocation(), diag::note_typecheck_assign_const)
13941 << ConstMember << true /*static*/ << VDecl << VDecl->getType()
13942 << VDecl->getSourceRange();
13943 }
13944 // Static fields do not inherit constness from parents.
13945 break;
13946 }
13947 break; // End MemberExpr
13948 } else if (const ArraySubscriptExpr *ASE =
13949 dyn_cast<ArraySubscriptExpr>(E)) {
13950 E = ASE->getBase()->IgnoreParenImpCasts();
13951 continue;
13952 } else if (const ExtVectorElementExpr *EVE =
13953 dyn_cast<ExtVectorElementExpr>(E)) {
13954 E = EVE->getBase()->IgnoreParenImpCasts();
13955 continue;
13956 }
13957 break;
13958 }
13959
13960 if (const CallExpr *CE = dyn_cast<CallExpr>(E)) {
13961 // Function calls
13962 const FunctionDecl *FD = CE->getDirectCallee();
13963 if (FD && !IsTypeModifiable(FD->getReturnType(), IsDereference)) {
13964 if (!DiagnosticEmitted) {
13965 S.Diag(Loc, diag::err_typecheck_assign_const) << ExprRange
13966 << ConstFunction << FD;
13967 DiagnosticEmitted = true;
13968 }
13969 S.Diag(FD->getReturnTypeSourceRange().getBegin(),
13970 diag::note_typecheck_assign_const)
13971 << ConstFunction << FD << FD->getReturnType()
13972 << FD->getReturnTypeSourceRange();
13973 }
13974 } else if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
13975 // Point to variable declaration.
13976 if (const ValueDecl *VD = DRE->getDecl()) {
13977 if (!IsTypeModifiable(VD->getType(), IsDereference)) {
13978 if (!DiagnosticEmitted) {
13979 S.Diag(Loc, diag::err_typecheck_assign_const)
13980 << ExprRange << ConstVariable << VD << VD->getType();
13981 DiagnosticEmitted = true;
13982 }
13983 S.Diag(VD->getLocation(), diag::note_typecheck_assign_const)
13984 << ConstVariable << VD << VD->getType() << VD->getSourceRange();
13985 }
13986 }
13987 } else if (isa<CXXThisExpr>(E)) {
13988 if (const DeclContext *DC = S.getFunctionLevelDeclContext()) {
13989 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(DC)) {
13990 if (MD->isConst()) {
13991 if (!DiagnosticEmitted) {
13992 S.Diag(Loc, diag::err_typecheck_assign_const) << ExprRange
13993 << ConstMethod << MD;
13994 DiagnosticEmitted = true;
13995 }
13996 S.Diag(MD->getLocation(), diag::note_typecheck_assign_const)
13997 << ConstMethod << MD << MD->getSourceRange();
13998 }
13999 }
14000 }
14001 }
14002
14003 if (DiagnosticEmitted)
14004 return;
14005
14006 // Can't determine a more specific message, so display the generic error.
14007 S.Diag(Loc, diag::err_typecheck_assign_const) << ExprRange << ConstUnknown;
14008}
14009
14010enum OriginalExprKind {
14011 OEK_Variable,
14012 OEK_Member,
14013 OEK_LValue
14014};
14015
14016static void DiagnoseRecursiveConstFields(Sema &S, const ValueDecl *VD,
14017 const RecordType *Ty,
14018 SourceLocation Loc, SourceRange Range,
14019 OriginalExprKind OEK,
14020 bool &DiagnosticEmitted) {
14021 std::vector<const RecordType *> RecordTypeList;
14022 RecordTypeList.push_back(Ty);
14023 unsigned NextToCheckIndex = 0;
14024 // We walk the record hierarchy breadth-first to ensure that we print
14025 // diagnostics in field nesting order.
14026 while (RecordTypeList.size() > NextToCheckIndex) {
14027 bool IsNested = NextToCheckIndex > 0;
14028 for (const FieldDecl *Field :
14029 RecordTypeList[NextToCheckIndex]->getDecl()->fields()) {
14030 // First, check every field for constness.
14031 QualType FieldTy = Field->getType();
14032 if (FieldTy.isConstQualified()) {
14033 if (!DiagnosticEmitted) {
14034 S.Diag(Loc, diag::err_typecheck_assign_const)
14035 << Range << NestedConstMember << OEK << VD
14036 << IsNested << Field;
14037 DiagnosticEmitted = true;
14038 }
14039 S.Diag(Field->getLocation(), diag::note_typecheck_assign_const)
14040 << NestedConstMember << IsNested << Field
14041 << FieldTy << Field->getSourceRange();
14042 }
14043
14044 // Then we append it to the list to check next in order.
14045 FieldTy = FieldTy.getCanonicalType();
14046 if (const auto *FieldRecTy = FieldTy->getAs<RecordType>()) {
14047 if (!llvm::is_contained(RecordTypeList, FieldRecTy))
14048 RecordTypeList.push_back(FieldRecTy);
14049 }
14050 }
14051 ++NextToCheckIndex;
14052 }
14053}
14054
14055/// Emit an error for the case where a record we are trying to assign to has a
14056/// const-qualified field somewhere in its hierarchy.
14057static void DiagnoseRecursiveConstFields(Sema &S, const Expr *E,
14058 SourceLocation Loc) {
14059 QualType Ty = E->getType();
14060 assert(Ty->isRecordType() && "lvalue was not record?")(static_cast <bool> (Ty->isRecordType() && "lvalue was not record?"
) ? void (0) : __assert_fail ("Ty->isRecordType() && \"lvalue was not record?\""
, "clang/lib/Sema/SemaExpr.cpp", 14060, __extension__ __PRETTY_FUNCTION__
))
;
14061 SourceRange Range = E->getSourceRange();
14062 const RecordType *RTy = Ty.getCanonicalType()->getAs<RecordType>();
14063 bool DiagEmitted = false;
14064
14065 if (const MemberExpr *ME = dyn_cast<MemberExpr>(E))
14066 DiagnoseRecursiveConstFields(S, ME->getMemberDecl(), RTy, Loc,
14067 Range, OEK_Member, DiagEmitted);
14068 else if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
14069 DiagnoseRecursiveConstFields(S, DRE->getDecl(), RTy, Loc,
14070 Range, OEK_Variable, DiagEmitted);
14071 else
14072 DiagnoseRecursiveConstFields(S, nullptr, RTy, Loc,
14073 Range, OEK_LValue, DiagEmitted);
14074 if (!DiagEmitted)
14075 DiagnoseConstAssignment(S, E, Loc);
14076}
14077
14078/// CheckForModifiableLvalue - Verify that E is a modifiable lvalue. If not,
14079/// emit an error and return true. If so, return false.
14080static bool CheckForModifiableLvalue(Expr *E, SourceLocation Loc, Sema &S) {
14081 assert(!E->hasPlaceholderType(BuiltinType::PseudoObject))(static_cast <bool> (!E->hasPlaceholderType(BuiltinType
::PseudoObject)) ? void (0) : __assert_fail ("!E->hasPlaceholderType(BuiltinType::PseudoObject)"
, "clang/lib/Sema/SemaExpr.cpp", 14081, __extension__ __PRETTY_FUNCTION__
))
;
14082
14083 S.CheckShadowingDeclModification(E, Loc);
14084
14085 SourceLocation OrigLoc = Loc;
14086 Expr::isModifiableLvalueResult IsLV = E->isModifiableLvalue(S.Context,
14087 &Loc);
14088 if (IsLV == Expr::MLV_ClassTemporary && IsReadonlyMessage(E, S))
14089 IsLV = Expr::MLV_InvalidMessageExpression;
14090 if (IsLV == Expr::MLV_Valid)
14091 return false;
14092
14093 unsigned DiagID = 0;
14094 bool NeedType = false;
14095 switch (IsLV) { // C99 6.5.16p2
14096 case Expr::MLV_ConstQualified:
14097 // Use a specialized diagnostic when we're assigning to an object
14098 // from an enclosing function or block.
14099 if (NonConstCaptureKind NCCK = isReferenceToNonConstCapture(S, E)) {
14100 if (NCCK == NCCK_Block)
14101 DiagID = diag::err_block_decl_ref_not_modifiable_lvalue;
14102 else
14103 DiagID = diag::err_lambda_decl_ref_not_modifiable_lvalue;
14104 break;
14105 }
14106
14107 // In ARC, use some specialized diagnostics for occasions where we
14108 // infer 'const'. These are always pseudo-strong variables.
14109 if (S.getLangOpts().ObjCAutoRefCount) {
14110 DeclRefExpr *declRef = dyn_cast<DeclRefExpr>(E->IgnoreParenCasts());
14111 if (declRef && isa<VarDecl>(declRef->getDecl())) {
14112 VarDecl *var = cast<VarDecl>(declRef->getDecl());
14113
14114 // Use the normal diagnostic if it's pseudo-__strong but the
14115 // user actually wrote 'const'.
14116 if (var->isARCPseudoStrong() &&
14117 (!var->getTypeSourceInfo() ||
14118 !var->getTypeSourceInfo()->getType().isConstQualified())) {
14119 // There are three pseudo-strong cases:
14120 // - self
14121 ObjCMethodDecl *method = S.getCurMethodDecl();
14122 if (method && var == method->getSelfDecl()) {
14123 DiagID = method->isClassMethod()
14124 ? diag::err_typecheck_arc_assign_self_class_method
14125 : diag::err_typecheck_arc_assign_self;
14126
14127 // - Objective-C externally_retained attribute.
14128 } else if (var->hasAttr<ObjCExternallyRetainedAttr>() ||
14129 isa<ParmVarDecl>(var)) {
14130 DiagID = diag::err_typecheck_arc_assign_externally_retained;
14131
14132 // - fast enumeration variables
14133 } else {
14134 DiagID = diag::err_typecheck_arr_assign_enumeration;
14135 }
14136
14137 SourceRange Assign;
14138 if (Loc != OrigLoc)
14139 Assign = SourceRange(OrigLoc, OrigLoc);
14140 S.Diag(Loc, DiagID) << E->getSourceRange() << Assign;
14141 // We need to preserve the AST regardless, so migration tool
14142 // can do its job.
14143 return false;
14144 }
14145 }
14146 }
14147
14148 // If none of the special cases above are triggered, then this is a
14149 // simple const assignment.
14150 if (DiagID == 0) {
14151 DiagnoseConstAssignment(S, E, Loc);
14152 return true;
14153 }
14154
14155 break;
14156 case Expr::MLV_ConstAddrSpace:
14157 DiagnoseConstAssignment(S, E, Loc);
14158 return true;
14159 case Expr::MLV_ConstQualifiedField:
14160 DiagnoseRecursiveConstFields(S, E, Loc);
14161 return true;
14162 case Expr::MLV_ArrayType:
14163 case Expr::MLV_ArrayTemporary:
14164 DiagID = diag::err_typecheck_array_not_modifiable_lvalue;
14165 NeedType = true;
14166 break;
14167 case Expr::MLV_NotObjectType:
14168 DiagID = diag::err_typecheck_non_object_not_modifiable_lvalue;
14169 NeedType = true;
14170 break;
14171 case Expr::MLV_LValueCast:
14172 DiagID = diag::err_typecheck_lvalue_casts_not_supported;
14173 break;
14174 case Expr::MLV_Valid:
14175 llvm_unreachable("did not take early return for MLV_Valid")::llvm::llvm_unreachable_internal("did not take early return for MLV_Valid"
, "clang/lib/Sema/SemaExpr.cpp", 14175)
;
14176 case Expr::MLV_InvalidExpression:
14177 case Expr::MLV_MemberFunction:
14178 case Expr::MLV_ClassTemporary:
14179 DiagID = diag::err_typecheck_expression_not_modifiable_lvalue;
14180 break;
14181 case Expr::MLV_IncompleteType:
14182 case Expr::MLV_IncompleteVoidType:
14183 return S.RequireCompleteType(Loc, E->getType(),
14184 diag::err_typecheck_incomplete_type_not_modifiable_lvalue, E);
14185 case Expr::MLV_DuplicateVectorComponents:
14186 DiagID = diag::err_typecheck_duplicate_vector_components_not_mlvalue;
14187 break;
14188 case Expr::MLV_NoSetterProperty:
14189 llvm_unreachable("readonly properties should be processed differently")::llvm::llvm_unreachable_internal("readonly properties should be processed differently"
, "clang/lib/Sema/SemaExpr.cpp", 14189)
;
14190 case Expr::MLV_InvalidMessageExpression:
14191 DiagID = diag::err_readonly_message_assignment;
14192 break;
14193 case Expr::MLV_SubObjCPropertySetting:
14194 DiagID = diag::err_no_subobject_property_setting;
14195 break;
14196 }
14197
14198 SourceRange Assign;
14199 if (Loc != OrigLoc)
14200 Assign = SourceRange(OrigLoc, OrigLoc);
14201 if (NeedType)
14202 S.Diag(Loc, DiagID) << E->getType() << E->getSourceRange() << Assign;
14203 else
14204 S.Diag(Loc, DiagID) << E->getSourceRange() << Assign;
14205 return true;
14206}
14207
14208static void CheckIdentityFieldAssignment(Expr *LHSExpr, Expr *RHSExpr,
14209 SourceLocation Loc,
14210 Sema &Sema) {
14211 if (Sema.inTemplateInstantiation())
14212 return;
14213 if (Sema.isUnevaluatedContext())
14214 return;
14215 if (Loc.isInvalid() || Loc.isMacroID())
14216 return;
14217 if (LHSExpr->getExprLoc().isMacroID() || RHSExpr->getExprLoc().isMacroID())
14218 return;
14219
14220 // C / C++ fields
14221 MemberExpr *ML = dyn_cast<MemberExpr>(LHSExpr);
14222 MemberExpr *MR = dyn_cast<MemberExpr>(RHSExpr);
14223 if (ML && MR) {
14224 if (!(isa<CXXThisExpr>(ML->getBase()) && isa<CXXThisExpr>(MR->getBase())))
14225 return;
14226 const ValueDecl *LHSDecl =
14227 cast<ValueDecl>(ML->getMemberDecl()->getCanonicalDecl());
14228 const ValueDecl *RHSDecl =
14229 cast<ValueDecl>(MR->getMemberDecl()->getCanonicalDecl());
14230 if (LHSDecl != RHSDecl)
14231 return;
14232 if (LHSDecl->getType().isVolatileQualified())
14233 return;
14234 if (const ReferenceType *RefTy = LHSDecl->getType()->getAs<ReferenceType>())
14235 if (RefTy->getPointeeType().isVolatileQualified())
14236 return;
14237
14238 Sema.Diag(Loc, diag::warn_identity_field_assign) << 0;
14239 }
14240
14241 // Objective-C instance variables
14242 ObjCIvarRefExpr *OL = dyn_cast<ObjCIvarRefExpr>(LHSExpr);
14243 ObjCIvarRefExpr *OR = dyn_cast<ObjCIvarRefExpr>(RHSExpr);
14244 if (OL && OR && OL->getDecl() == OR->getDecl()) {
14245 DeclRefExpr *RL = dyn_cast<DeclRefExpr>(OL->getBase()->IgnoreImpCasts());
14246 DeclRefExpr *RR = dyn_cast<DeclRefExpr>(OR->getBase()->IgnoreImpCasts());
14247 if (RL && RR && RL->getDecl() == RR->getDecl())
14248 Sema.Diag(Loc, diag::warn_identity_field_assign) << 1;
14249 }
14250}
14251
14252// C99 6.5.16.1
14253QualType Sema::CheckAssignmentOperands(Expr *LHSExpr, ExprResult &RHS,
14254 SourceLocation Loc,
14255 QualType CompoundType,
14256 BinaryOperatorKind Opc) {
14257 assert(!LHSExpr->hasPlaceholderType(BuiltinType::PseudoObject))(static_cast <bool> (!LHSExpr->hasPlaceholderType(BuiltinType
::PseudoObject)) ? void (0) : __assert_fail ("!LHSExpr->hasPlaceholderType(BuiltinType::PseudoObject)"
, "clang/lib/Sema/SemaExpr.cpp", 14257, __extension__ __PRETTY_FUNCTION__
))
;
14258
14259 // Verify that LHS is a modifiable lvalue, and emit error if not.
14260 if (CheckForModifiableLvalue(LHSExpr, Loc, *this))
14261 return QualType();
14262
14263 QualType LHSType = LHSExpr->getType();
14264 QualType RHSType = CompoundType.isNull() ? RHS.get()->getType() :
14265 CompoundType;
14266 // OpenCL v1.2 s6.1.1.1 p2:
14267 // The half data type can only be used to declare a pointer to a buffer that
14268 // contains half values
14269 if (getLangOpts().OpenCL &&
14270 !getOpenCLOptions().isAvailableOption("cl_khr_fp16", getLangOpts()) &&
14271 LHSType->isHalfType()) {
14272 Diag(Loc, diag::err_opencl_half_load_store) << 1
14273 << LHSType.getUnqualifiedType();
14274 return QualType();
14275 }
14276
14277 AssignConvertType ConvTy;
14278 if (CompoundType.isNull()) {
14279 Expr *RHSCheck = RHS.get();
14280
14281 CheckIdentityFieldAssignment(LHSExpr, RHSCheck, Loc, *this);
14282
14283 QualType LHSTy(LHSType);
14284 ConvTy = CheckSingleAssignmentConstraints(LHSTy, RHS);
14285 if (RHS.isInvalid())
14286 return QualType();
14287 // Special case of NSObject attributes on c-style pointer types.
14288 if (ConvTy == IncompatiblePointer &&
14289 ((Context.isObjCNSObjectType(LHSType) &&
14290 RHSType->isObjCObjectPointerType()) ||
14291 (Context.isObjCNSObjectType(RHSType) &&
14292 LHSType->isObjCObjectPointerType())))
14293 ConvTy = Compatible;
14294
14295 if (ConvTy == Compatible &&
14296 LHSType->isObjCObjectType())
14297 Diag(Loc, diag::err_objc_object_assignment)
14298 << LHSType;
14299
14300 // If the RHS is a unary plus or minus, check to see if they = and + are
14301 // right next to each other. If so, the user may have typo'd "x =+ 4"
14302 // instead of "x += 4".
14303 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(RHSCheck))
14304 RHSCheck = ICE->getSubExpr();
14305 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(RHSCheck)) {
14306 if ((UO->getOpcode() == UO_Plus || UO->getOpcode() == UO_Minus) &&
14307 Loc.isFileID() && UO->getOperatorLoc().isFileID() &&
14308 // Only if the two operators are exactly adjacent.
14309 Loc.getLocWithOffset(1) == UO->getOperatorLoc() &&
14310 // And there is a space or other character before the subexpr of the
14311 // unary +/-. We don't want to warn on "x=-1".
14312 Loc.getLocWithOffset(2) != UO->getSubExpr()->getBeginLoc() &&
14313 UO->getSubExpr()->getBeginLoc().isFileID()) {
14314 Diag(Loc, diag::warn_not_compound_assign)
14315 << (UO->getOpcode() == UO_Plus ? "+" : "-")
14316 << SourceRange(UO->getOperatorLoc(), UO->getOperatorLoc());
14317 }
14318 }
14319
14320 if (ConvTy == Compatible) {
14321 if (LHSType.getObjCLifetime() == Qualifiers::OCL_Strong) {
14322 // Warn about retain cycles where a block captures the LHS, but
14323 // not if the LHS is a simple variable into which the block is
14324 // being stored...unless that variable can be captured by reference!
14325 const Expr *InnerLHS = LHSExpr->IgnoreParenCasts();
14326 const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(InnerLHS);
14327 if (!DRE || DRE->getDecl()->hasAttr<BlocksAttr>())
14328 checkRetainCycles(LHSExpr, RHS.get());
14329 }
14330
14331 if (LHSType.getObjCLifetime() == Qualifiers::OCL_Strong ||
14332 LHSType.isNonWeakInMRRWithObjCWeak(Context)) {
14333 // It is safe to assign a weak reference into a strong variable.
14334 // Although this code can still have problems:
14335 // id x = self.weakProp;
14336 // id y = self.weakProp;
14337 // we do not warn to warn spuriously when 'x' and 'y' are on separate
14338 // paths through the function. This should be revisited if
14339 // -Wrepeated-use-of-weak is made flow-sensitive.
14340 // For ObjCWeak only, we do not warn if the assign is to a non-weak
14341 // variable, which will be valid for the current autorelease scope.
14342 if (!Diags.isIgnored(diag::warn_arc_repeated_use_of_weak,
14343 RHS.get()->getBeginLoc()))
14344 getCurFunction()->markSafeWeakUse(RHS.get());
14345
14346 } else if (getLangOpts().ObjCAutoRefCount || getLangOpts().ObjCWeak) {
14347 checkUnsafeExprAssigns(Loc, LHSExpr, RHS.get());
14348 }
14349 }
14350 } else {
14351 // Compound assignment "x += y"
14352 ConvTy = CheckAssignmentConstraints(Loc, LHSType, RHSType);
14353 }
14354
14355 if (DiagnoseAssignmentResult(ConvTy, Loc, LHSType, RHSType,
14356 RHS.get(), AA_Assigning))
14357 return QualType();
14358
14359 CheckForNullPointerDereference(*this, LHSExpr);
14360
14361 if (getLangOpts().CPlusPlus20 && LHSType.isVolatileQualified()) {
14362 if (CompoundType.isNull()) {
14363 // C++2a [expr.ass]p5:
14364 // A simple-assignment whose left operand is of a volatile-qualified
14365 // type is deprecated unless the assignment is either a discarded-value
14366 // expression or an unevaluated operand
14367 ExprEvalContexts.back().VolatileAssignmentLHSs.push_back(LHSExpr);
14368 }
14369 }
14370
14371 // C11 6.5.16p3: The type of an assignment expression is the type of the
14372 // left operand would have after lvalue conversion.
14373 // C11 6.3.2.1p2: ...this is called lvalue conversion. If the lvalue has
14374 // qualified type, the value has the unqualified version of the type of the
14375 // lvalue; additionally, if the lvalue has atomic type, the value has the
14376 // non-atomic version of the type of the lvalue.
14377 // C++ 5.17p1: the type of the assignment expression is that of its left
14378 // operand.
14379 return getLangOpts().CPlusPlus ? LHSType : LHSType.getAtomicUnqualifiedType();
14380}
14381
14382// Scenarios to ignore if expression E is:
14383// 1. an explicit cast expression into void
14384// 2. a function call expression that returns void
14385static bool IgnoreCommaOperand(const Expr *E, const ASTContext &Context) {
14386 E = E->IgnoreParens();
14387
14388 if (const CastExpr *CE = dyn_cast<CastExpr>(E)) {
14389 if (CE->getCastKind() == CK_ToVoid) {
14390 return true;
14391 }
14392
14393 // static_cast<void> on a dependent type will not show up as CK_ToVoid.
14394 if (CE->getCastKind() == CK_Dependent && E->getType()->isVoidType() &&
14395 CE->getSubExpr()->getType()->isDependentType()) {
14396 return true;
14397 }
14398 }
14399
14400 if (const auto *CE = dyn_cast<CallExpr>(E))
14401 return CE->getCallReturnType(Context)->isVoidType();
14402 return false;
14403}
14404
14405// Look for instances where it is likely the comma operator is confused with
14406// another operator. There is an explicit list of acceptable expressions for
14407// the left hand side of the comma operator, otherwise emit a warning.
14408void Sema::DiagnoseCommaOperator(const Expr *LHS, SourceLocation Loc) {
14409 // No warnings in macros
14410 if (Loc.isMacroID())
14411 return;
14412
14413 // Don't warn in template instantiations.
14414 if (inTemplateInstantiation())
14415 return;
14416
14417 // Scope isn't fine-grained enough to explicitly list the specific cases, so
14418 // instead, skip more than needed, then call back into here with the
14419 // CommaVisitor in SemaStmt.cpp.
14420 // The listed locations are the initialization and increment portions
14421 // of a for loop. The additional checks are on the condition of
14422 // if statements, do/while loops, and for loops.
14423 // Differences in scope flags for C89 mode requires the extra logic.
14424 const unsigned ForIncrementFlags =
14425 getLangOpts().C99 || getLangOpts().CPlusPlus
14426 ? Scope::ControlScope | Scope::ContinueScope | Scope::BreakScope
14427 : Scope::ContinueScope | Scope::BreakScope;
14428 const unsigned ForInitFlags = Scope::ControlScope | Scope::DeclScope;
14429 const unsigned ScopeFlags = getCurScope()->getFlags();
14430 if ((ScopeFlags & ForIncrementFlags) == ForIncrementFlags ||
14431 (ScopeFlags & ForInitFlags) == ForInitFlags)
14432 return;
14433
14434 // If there are multiple comma operators used together, get the RHS of the
14435 // of the comma operator as the LHS.
14436 while (const BinaryOperator *BO = dyn_cast<BinaryOperator>(LHS)) {
14437 if (BO->getOpcode() != BO_Comma)
14438 break;
14439 LHS = BO->getRHS();
14440 }
14441
14442 // Only allow some expressions on LHS to not warn.
14443 if (IgnoreCommaOperand(LHS, Context))
14444 return;
14445
14446 Diag(Loc, diag::warn_comma_operator);
14447 Diag(LHS->getBeginLoc(), diag::note_cast_to_void)
14448 << LHS->getSourceRange()
14449 << FixItHint::CreateInsertion(LHS->getBeginLoc(),
14450 LangOpts.CPlusPlus ? "static_cast<void>("
14451 : "(void)(")
14452 << FixItHint::CreateInsertion(PP.getLocForEndOfToken(LHS->getEndLoc()),
14453 ")");
14454}
14455
14456// C99 6.5.17
14457static QualType CheckCommaOperands(Sema &S, ExprResult &LHS, ExprResult &RHS,
14458 SourceLocation Loc) {
14459 LHS = S.CheckPlaceholderExpr(LHS.get());
14460 RHS = S.CheckPlaceholderExpr(RHS.get());
14461 if (LHS.isInvalid() || RHS.isInvalid())
14462 return QualType();
14463
14464 // C's comma performs lvalue conversion (C99 6.3.2.1) on both its
14465 // operands, but not unary promotions.
14466 // C++'s comma does not do any conversions at all (C++ [expr.comma]p1).
14467
14468 // So we treat the LHS as a ignored value, and in C++ we allow the
14469 // containing site to determine what should be done with the RHS.
14470 LHS = S.IgnoredValueConversions(LHS.get());
14471 if (LHS.isInvalid())
14472 return QualType();
14473
14474 S.DiagnoseUnusedExprResult(LHS.get(), diag::warn_unused_comma_left_operand);
14475
14476 if (!S.getLangOpts().CPlusPlus) {
14477 RHS = S.DefaultFunctionArrayLvalueConversion(RHS.get());
14478 if (RHS.isInvalid())
14479 return QualType();
14480 if (!RHS.get()->getType()->isVoidType())
14481 S.RequireCompleteType(Loc, RHS.get()->getType(),
14482 diag::err_incomplete_type);
14483 }
14484
14485 if (!S.getDiagnostics().isIgnored(diag::warn_comma_operator, Loc))
14486 S.DiagnoseCommaOperator(LHS.get(), Loc);
14487
14488 return RHS.get()->getType();
14489}
14490
14491/// CheckIncrementDecrementOperand - unlike most "Check" methods, this routine
14492/// doesn't need to call UsualUnaryConversions or UsualArithmeticConversions.
14493static QualType CheckIncrementDecrementOperand(Sema &S, Expr *Op,
14494 ExprValueKind &VK,
14495 ExprObjectKind &OK,
14496 SourceLocation OpLoc,
14497 bool IsInc, bool IsPrefix) {
14498 if (Op->isTypeDependent())
14499 return S.Context.DependentTy;
14500
14501 QualType ResType = Op->getType();
14502 // Atomic types can be used for increment / decrement where the non-atomic
14503 // versions can, so ignore the _Atomic() specifier for the purpose of
14504 // checking.
14505 if (const AtomicType *ResAtomicType = ResType->getAs<AtomicType>())
14506 ResType = ResAtomicType->getValueType();
14507
14508 assert(!ResType.isNull() && "no type for increment/decrement expression")(static_cast <bool> (!ResType.isNull() && "no type for increment/decrement expression"
) ? void (0) : __assert_fail ("!ResType.isNull() && \"no type for increment/decrement expression\""
, "clang/lib/Sema/SemaExpr.cpp", 14508, __extension__ __PRETTY_FUNCTION__
))
;
14509
14510 if (S.getLangOpts().CPlusPlus && ResType->isBooleanType()) {
14511 // Decrement of bool is not allowed.
14512 if (!IsInc) {
14513 S.Diag(OpLoc, diag::err_decrement_bool) << Op->getSourceRange();
14514 return QualType();
14515 }
14516 // Increment of bool sets it to true, but is deprecated.
14517 S.Diag(OpLoc, S.getLangOpts().CPlusPlus17 ? diag::ext_increment_bool
14518 : diag::warn_increment_bool)
14519 << Op->getSourceRange();
14520 } else if (S.getLangOpts().CPlusPlus && ResType->isEnumeralType()) {
14521 // Error on enum increments and decrements in C++ mode
14522 S.Diag(OpLoc, diag::err_increment_decrement_enum) << IsInc << ResType;
14523 return QualType();
14524 } else if (ResType->isRealType()) {
14525 // OK!
14526 } else if (ResType->isPointerType()) {
14527 // C99 6.5.2.4p2, 6.5.6p2
14528 if (!checkArithmeticOpPointerOperand(S, OpLoc, Op))
14529 return QualType();
14530 } else if (ResType->isObjCObjectPointerType()) {
14531 // On modern runtimes, ObjC pointer arithmetic is forbidden.
14532 // Otherwise, we just need a complete type.
14533 if (checkArithmeticIncompletePointerType(S, OpLoc, Op) ||
14534 checkArithmeticOnObjCPointer(S, OpLoc, Op))
14535 return QualType();
14536 } else if (ResType->isAnyComplexType()) {
14537 // C99 does not support ++/-- on complex types, we allow as an extension.
14538 S.Diag(OpLoc, diag::ext_integer_increment_complex)
14539 << ResType << Op->getSourceRange();
14540 } else if (ResType->isPlaceholderType()) {
14541 ExprResult PR = S.CheckPlaceholderExpr(Op);
14542 if (PR.isInvalid()) return QualType();
14543 return CheckIncrementDecrementOperand(S, PR.get(), VK, OK, OpLoc,
14544 IsInc, IsPrefix);
14545 } else if (S.getLangOpts().AltiVec && ResType->isVectorType()) {
14546 // OK! ( C/C++ Language Extensions for CBEA(Version 2.6) 10.3 )
14547 } else if (S.getLangOpts().ZVector && ResType->isVectorType() &&
14548 (ResType->castAs<VectorType>()->getVectorKind() !=
14549 VectorType::AltiVecBool)) {
14550 // The z vector extensions allow ++ and -- for non-bool vectors.
14551 } else if(S.getLangOpts().OpenCL && ResType->isVectorType() &&
14552 ResType->castAs<VectorType>()->getElementType()->isIntegerType()) {
14553 // OpenCL V1.2 6.3 says dec/inc ops operate on integer vector types.
14554 } else {
14555 S.Diag(OpLoc, diag::err_typecheck_illegal_increment_decrement)
14556 << ResType << int(IsInc) << Op->getSourceRange();
14557 return QualType();
14558 }
14559 // At this point, we know we have a real, complex or pointer type.
14560 // Now make sure the operand is a modifiable lvalue.
14561 if (CheckForModifiableLvalue(Op, OpLoc, S))
14562 return QualType();
14563 if (S.getLangOpts().CPlusPlus20 && ResType.isVolatileQualified()) {
14564 // C++2a [expr.pre.inc]p1, [expr.post.inc]p1:
14565 // An operand with volatile-qualified type is deprecated
14566 S.Diag(OpLoc, diag::warn_deprecated_increment_decrement_volatile)
14567 << IsInc << ResType;
14568 }
14569 // In C++, a prefix increment is the same type as the operand. Otherwise
14570 // (in C or with postfix), the increment is the unqualified type of the
14571 // operand.
14572 if (IsPrefix && S.getLangOpts().CPlusPlus) {
14573 VK = VK_LValue;
14574 OK = Op->getObjectKind();
14575 return ResType;
14576 } else {
14577 VK = VK_PRValue;
14578 return ResType.getUnqualifiedType();
14579 }
14580}
14581
14582
14583/// getPrimaryDecl - Helper function for CheckAddressOfOperand().
14584/// This routine allows us to typecheck complex/recursive expressions
14585/// where the declaration is needed for type checking. We only need to
14586/// handle cases when the expression references a function designator
14587/// or is an lvalue. Here are some examples:
14588/// - &(x) => x
14589/// - &*****f => f for f a function designator.
14590/// - &s.xx => s
14591/// - &s.zz[1].yy -> s, if zz is an array
14592/// - *(x + 1) -> x, if x is an array
14593/// - &"123"[2] -> 0
14594/// - & __real__ x -> x
14595///
14596/// FIXME: We don't recurse to the RHS of a comma, nor handle pointers to
14597/// members.
14598static ValueDecl *getPrimaryDecl(Expr *E) {
14599 switch (E->getStmtClass()) {
14600 case Stmt::DeclRefExprClass:
14601 return cast<DeclRefExpr>(E)->getDecl();
14602 case Stmt::MemberExprClass:
14603 // If this is an arrow operator, the address is an offset from
14604 // the base's value, so the object the base refers to is
14605 // irrelevant.
14606 if (cast<MemberExpr>(E)->isArrow())
14607 return nullptr;
14608 // Otherwise, the expression refers to a part of the base
14609 return getPrimaryDecl(cast<MemberExpr>(E)->getBase());
14610 case Stmt::ArraySubscriptExprClass: {
14611 // FIXME: This code shouldn't be necessary! We should catch the implicit
14612 // promotion of register arrays earlier.
14613 Expr* Base = cast<ArraySubscriptExpr>(E)->getBase();
14614 if (ImplicitCastExpr* ICE = dyn_cast<ImplicitCastExpr>(Base)) {
14615 if (ICE->getSubExpr()->getType()->isArrayType())
14616 return getPrimaryDecl(ICE->getSubExpr());
14617 }
14618 return nullptr;
14619 }
14620 case Stmt::UnaryOperatorClass: {
14621 UnaryOperator *UO = cast<UnaryOperator>(E);
14622
14623 switch(UO->getOpcode()) {
14624 case UO_Real:
14625 case UO_Imag:
14626 case UO_Extension:
14627 return getPrimaryDecl(UO->getSubExpr());
14628 default:
14629 return nullptr;
14630 }
14631 }
14632 case Stmt::ParenExprClass:
14633 return getPrimaryDecl(cast<ParenExpr>(E)->getSubExpr());
14634 case Stmt::ImplicitCastExprClass:
14635 // If the result of an implicit cast is an l-value, we care about
14636 // the sub-expression; otherwise, the result here doesn't matter.
14637 return getPrimaryDecl(cast<ImplicitCastExpr>(E)->getSubExpr());
14638 case Stmt::CXXUuidofExprClass:
14639 return cast<CXXUuidofExpr>(E)->getGuidDecl();
14640 default:
14641 return nullptr;
14642 }
14643}
14644
14645namespace {
14646enum {
14647 AO_Bit_Field = 0,
14648 AO_Vector_Element = 1,
14649 AO_Property_Expansion = 2,
14650 AO_Register_Variable = 3,
14651 AO_Matrix_Element = 4,
14652 AO_No_Error = 5
14653};
14654}
14655/// Diagnose invalid operand for address of operations.
14656///
14657/// \param Type The type of operand which cannot have its address taken.
14658static void diagnoseAddressOfInvalidType(Sema &S, SourceLocation Loc,
14659 Expr *E, unsigned Type) {
14660 S.Diag(Loc, diag::err_typecheck_address_of) << Type << E->getSourceRange();
14661}
14662
14663/// CheckAddressOfOperand - The operand of & must be either a function
14664/// designator or an lvalue designating an object. If it is an lvalue, the
14665/// object cannot be declared with storage class register or be a bit field.
14666/// Note: The usual conversions are *not* applied to the operand of the &
14667/// operator (C99 6.3.2.1p[2-4]), and its result is never an lvalue.
14668/// In C++, the operand might be an overloaded function name, in which case
14669/// we allow the '&' but retain the overloaded-function type.
14670QualType Sema::CheckAddressOfOperand(ExprResult &OrigOp, SourceLocation OpLoc) {
14671 if (const BuiltinType *PTy = OrigOp.get()->getType()->getAsPlaceholderType()){
14672 if (PTy->getKind() == BuiltinType::Overload) {
14673 Expr *E = OrigOp.get()->IgnoreParens();
14674 if (!isa<OverloadExpr>(E)) {
14675 assert(cast<UnaryOperator>(E)->getOpcode() == UO_AddrOf)(static_cast <bool> (cast<UnaryOperator>(E)->getOpcode
() == UO_AddrOf) ? void (0) : __assert_fail ("cast<UnaryOperator>(E)->getOpcode() == UO_AddrOf"
, "clang/lib/Sema/SemaExpr.cpp", 14675, __extension__ __PRETTY_FUNCTION__
))
;
14676 Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof_addrof_function)
14677 << OrigOp.get()->getSourceRange();
14678 return QualType();
14679 }
14680
14681 OverloadExpr *Ovl = cast<OverloadExpr>(E);
14682 if (isa<UnresolvedMemberExpr>(Ovl))
14683 if (!ResolveSingleFunctionTemplateSpecialization(Ovl)) {
14684 Diag(OpLoc, diag::err_invalid_form_pointer_member_function)
14685 << OrigOp.get()->getSourceRange();
14686 return QualType();
14687 }
14688
14689 return Context.OverloadTy;
14690 }
14691
14692 if (PTy->getKind() == BuiltinType::UnknownAny)
14693 return Context.UnknownAnyTy;
14694
14695 if (PTy->getKind() == BuiltinType::BoundMember) {
14696 Diag(OpLoc, diag::err_invalid_form_pointer_member_function)
14697 << OrigOp.get()->getSourceRange();
14698 return QualType();
14699 }
14700
14701 OrigOp = CheckPlaceholderExpr(OrigOp.get());
14702 if (OrigOp.isInvalid()) return QualType();
14703 }
14704
14705 if (OrigOp.get()->isTypeDependent())
14706 return Context.DependentTy;
14707
14708 assert(!OrigOp.get()->hasPlaceholderType())(static_cast <bool> (!OrigOp.get()->hasPlaceholderType
()) ? void (0) : __assert_fail ("!OrigOp.get()->hasPlaceholderType()"
, "clang/lib/Sema/SemaExpr.cpp", 14708, __extension__ __PRETTY_FUNCTION__
))
;
14709
14710 // Make sure to ignore parentheses in subsequent checks
14711 Expr *op = OrigOp.get()->IgnoreParens();
14712
14713 // In OpenCL captures for blocks called as lambda functions
14714 // are located in the private address space. Blocks used in
14715 // enqueue_kernel can be located in a different address space
14716 // depending on a vendor implementation. Thus preventing
14717 // taking an address of the capture to avoid invalid AS casts.
14718 if (LangOpts.OpenCL) {
14719 auto* VarRef = dyn_cast<DeclRefExpr>(op);
14720 if (VarRef && VarRef->refersToEnclosingVariableOrCapture()) {
14721 Diag(op->getExprLoc(), diag::err_opencl_taking_address_capture);
14722 return QualType();
14723 }
14724 }
14725
14726 if (getLangOpts().C99) {
14727 // Implement C99-only parts of addressof rules.
14728 if (UnaryOperator* uOp = dyn_cast<UnaryOperator>(op)) {
14729 if (uOp->getOpcode() == UO_Deref)
14730 // Per C99 6.5.3.2, the address of a deref always returns a valid result
14731 // (assuming the deref expression is valid).
14732 return uOp->getSubExpr()->getType();
14733 }
14734 // Technically, there should be a check for array subscript
14735 // expressions here, but the result of one is always an lvalue anyway.
14736 }
14737 ValueDecl *dcl = getPrimaryDecl(op);
14738
14739 if (auto *FD = dyn_cast_or_null<FunctionDecl>(dcl))
14740 if (!checkAddressOfFunctionIsAvailable(FD, /*Complain=*/true,
14741 op->getBeginLoc()))
14742 return QualType();
14743
14744 Expr::LValueClassification lval = op->ClassifyLValue(Context);
14745 unsigned AddressOfError = AO_No_Error;
14746
14747 if (lval == Expr::LV_ClassTemporary || lval == Expr::LV_ArrayTemporary) {
14748 bool sfinae = (bool)isSFINAEContext();
14749 Diag(OpLoc, isSFINAEContext() ? diag::err_typecheck_addrof_temporary
14750 : diag::ext_typecheck_addrof_temporary)
14751 << op->getType() << op->getSourceRange();
14752 if (sfinae)
14753 return QualType();
14754 // Materialize the temporary as an lvalue so that we can take its address.
14755 OrigOp = op =
14756 CreateMaterializeTemporaryExpr(op->getType(), OrigOp.get(), true);
14757 } else if (isa<ObjCSelectorExpr>(op)) {
14758 return Context.getPointerType(op->getType());
14759 } else if (lval == Expr::LV_MemberFunction) {
14760 // If it's an instance method, make a member pointer.
14761 // The expression must have exactly the form &A::foo.
14762
14763 // If the underlying expression isn't a decl ref, give up.
14764 if (!isa<DeclRefExpr>(op)) {
14765 Diag(OpLoc, diag::err_invalid_form_pointer_member_function)
14766 << OrigOp.get()->getSourceRange();
14767 return QualType();
14768 }
14769 DeclRefExpr *DRE = cast<DeclRefExpr>(op);
14770 CXXMethodDecl *MD = cast<CXXMethodDecl>(DRE->getDecl());
14771
14772 // The id-expression was parenthesized.
14773 if (OrigOp.get() != DRE) {
14774 Diag(OpLoc, diag::err_parens_pointer_member_function)
14775 << OrigOp.get()->getSourceRange();
14776
14777 // The method was named without a qualifier.
14778 } else if (!DRE->getQualifier()) {
14779 if (MD->getParent()->getName().empty())
14780 Diag(OpLoc, diag::err_unqualified_pointer_member_function)
14781 << op->getSourceRange();
14782 else {
14783 SmallString<32> Str;
14784 StringRef Qual = (MD->getParent()->getName() + "::").toStringRef(Str);
14785 Diag(OpLoc, diag::err_unqualified_pointer_member_function)
14786 << op->getSourceRange()
14787 << FixItHint::CreateInsertion(op->getSourceRange().getBegin(), Qual);
14788 }
14789 }
14790
14791 // Taking the address of a dtor is illegal per C++ [class.dtor]p2.
14792 if (isa<CXXDestructorDecl>(MD))
14793 Diag(OpLoc, diag::err_typecheck_addrof_dtor) << op->getSourceRange();
14794
14795 QualType MPTy = Context.getMemberPointerType(
14796 op->getType(), Context.getTypeDeclType(MD->getParent()).getTypePtr());
14797 // Under the MS ABI, lock down the inheritance model now.
14798 if (Context.getTargetInfo().getCXXABI().isMicrosoft())
14799 (void)isCompleteType(OpLoc, MPTy);
14800 return MPTy;
14801 } else if (lval != Expr::LV_Valid && lval != Expr::LV_IncompleteVoidType) {
14802 // C99 6.5.3.2p1
14803 // The operand must be either an l-value or a function designator
14804 if (!op->getType()->isFunctionType()) {
14805 // Use a special diagnostic for loads from property references.
14806 if (isa<PseudoObjectExpr>(op)) {
14807 AddressOfError = AO_Property_Expansion;
14808 } else {
14809 Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof)
14810 << op->getType() << op->getSourceRange();
14811 return QualType();
14812 }
14813 }
14814 } else if (op->getObjectKind() == OK_BitField) { // C99 6.5.3.2p1
14815 // The operand cannot be a bit-field
14816 AddressOfError = AO_Bit_Field;
14817 } else if (op->getObjectKind() == OK_VectorComponent) {
14818 // The operand cannot be an element of a vector
14819 AddressOfError = AO_Vector_Element;
14820 } else if (op->getObjectKind() == OK_MatrixComponent) {
14821 // The operand cannot be an element of a matrix.
14822 AddressOfError = AO_Matrix_Element;
14823 } else if (dcl) { // C99 6.5.3.2p1
14824 // We have an lvalue with a decl. Make sure the decl is not declared
14825 // with the register storage-class specifier.
14826 if (const VarDecl *vd = dyn_cast<VarDecl>(dcl)) {
14827 // in C++ it is not error to take address of a register
14828 // variable (c++03 7.1.1P3)
14829 if (vd->getStorageClass() == SC_Register &&
14830 !getLangOpts().CPlusPlus) {
14831 AddressOfError = AO_Register_Variable;
14832 }
14833 } else if (isa<MSPropertyDecl>(dcl)) {
14834 AddressOfError = AO_Property_Expansion;
14835 } else if (isa<FunctionTemplateDecl>(dcl)) {
14836 return Context.OverloadTy;
14837 } else if (isa<FieldDecl>(dcl) || isa<IndirectFieldDecl>(dcl)) {
14838 // Okay: we can take the address of a field.
14839 // Could be a pointer to member, though, if there is an explicit
14840 // scope qualifier for the class.
14841 if (isa<DeclRefExpr>(op) && cast<DeclRefExpr>(op)->getQualifier()) {
14842 DeclContext *Ctx = dcl->getDeclContext();
14843 if (Ctx && Ctx->isRecord()) {
14844 if (dcl->getType()->isReferenceType()) {
14845 Diag(OpLoc,
14846 diag::err_cannot_form_pointer_to_member_of_reference_type)
14847 << dcl->getDeclName() << dcl->getType();
14848 return QualType();
14849 }
14850
14851 while (cast<RecordDecl>(Ctx)->isAnonymousStructOrUnion())
14852 Ctx = Ctx->getParent();
14853
14854 QualType MPTy = Context.getMemberPointerType(
14855 op->getType(),
14856 Context.getTypeDeclType(cast<RecordDecl>(Ctx)).getTypePtr());
14857 // Under the MS ABI, lock down the inheritance model now.
14858 if (Context.getTargetInfo().getCXXABI().isMicrosoft())
14859 (void)isCompleteType(OpLoc, MPTy);
14860 return MPTy;
14861 }
14862 }
14863 } else if (!isa<FunctionDecl, NonTypeTemplateParmDecl, BindingDecl,
14864 MSGuidDecl, UnnamedGlobalConstantDecl>(dcl))
14865 llvm_unreachable("Unknown/unexpected decl type")::llvm::llvm_unreachable_internal("Unknown/unexpected decl type"
, "clang/lib/Sema/SemaExpr.cpp", 14865)
;
14866 }
14867
14868 if (AddressOfError != AO_No_Error) {
14869 diagnoseAddressOfInvalidType(*this, OpLoc, op, AddressOfError);
14870 return QualType();
14871 }
14872
14873 if (lval == Expr::LV_IncompleteVoidType) {
14874 // Taking the address of a void variable is technically illegal, but we
14875 // allow it in cases which are otherwise valid.
14876 // Example: "extern void x; void* y = &x;".
14877 Diag(OpLoc, diag::ext_typecheck_addrof_void) << op->getSourceRange();
14878 }
14879
14880 // If the operand has type "type", the result has type "pointer to type".
14881 if (op->getType()->isObjCObjectType())
14882 return Context.getObjCObjectPointerType(op->getType());
14883
14884 if (Context.getTargetInfo().getTriple().isWasm() &&
14885 op->getType()->isWebAssemblyReferenceType()) {
14886 Diag(OpLoc, diag::err_wasm_ca_reference)
14887 << 1 << OrigOp.get()->getSourceRange();
14888 return QualType();
14889 }
14890
14891 CheckAddressOfPackedMember(op);
14892
14893 return Context.getPointerType(op->getType());
14894}
14895
14896static void RecordModifiableNonNullParam(Sema &S, const Expr *Exp) {
14897 const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Exp);
14898 if (!DRE)
14899 return;
14900 const Decl *D = DRE->getDecl();
14901 if (!D)
14902 return;
14903 const ParmVarDecl *Param = dyn_cast<ParmVarDecl>(D);
14904 if (!Param)
14905 return;
14906 if (const FunctionDecl* FD = dyn_cast<FunctionDecl>(Param->getDeclContext()))
14907 if (!FD->hasAttr<NonNullAttr>() && !Param->hasAttr<NonNullAttr>())
14908 return;
14909 if (FunctionScopeInfo *FD = S.getCurFunction())
14910 FD->ModifiedNonNullParams.insert(Param);
14911}
14912
14913/// CheckIndirectionOperand - Type check unary indirection (prefix '*').
14914static QualType CheckIndirectionOperand(Sema &S, Expr *Op, ExprValueKind &VK,
14915 SourceLocation OpLoc,
14916 bool IsAfterAmp = false) {
14917 if (Op->isTypeDependent())
14918 return S.Context.DependentTy;
14919
14920 ExprResult ConvResult = S.UsualUnaryConversions(Op);
14921 if (ConvResult.isInvalid())
14922 return QualType();
14923 Op = ConvResult.get();
14924 QualType OpTy = Op->getType();
14925 QualType Result;
14926
14927 if (isa<CXXReinterpretCastExpr>(Op)) {
14928 QualType OpOrigType = Op->IgnoreParenCasts()->getType();
14929 S.CheckCompatibleReinterpretCast(OpOrigType, OpTy, /*IsDereference*/true,
14930 Op->getSourceRange());
14931 }
14932
14933 if (const PointerType *PT = OpTy->getAs<PointerType>())
14934 {
14935 Result = PT->getPointeeType();
14936 }
14937 else if (const ObjCObjectPointerType *OPT =
14938 OpTy->getAs<ObjCObjectPointerType>())
14939 Result = OPT->getPointeeType();
14940 else {
14941 ExprResult PR = S.CheckPlaceholderExpr(Op);
14942 if (PR.isInvalid()) return QualType();
14943 if (PR.get() != Op)
14944 return CheckIndirectionOperand(S, PR.get(), VK, OpLoc);
14945 }
14946
14947 if (Result.isNull()) {
14948 S.Diag(OpLoc, diag::err_typecheck_indirection_requires_pointer)
14949 << OpTy << Op->getSourceRange();
14950 return QualType();
14951 }
14952
14953 if (Result->isVoidType()) {
14954 // C++ [expr.unary.op]p1:
14955 // [...] the expression to which [the unary * operator] is applied shall
14956 // be a pointer to an object type, or a pointer to a function type
14957 LangOptions LO = S.getLangOpts();
14958 if (LO.CPlusPlus)
14959 S.Diag(OpLoc, diag::ext_typecheck_indirection_through_void_pointer_cpp)
14960 << OpTy << Op->getSourceRange();
14961 else if (!(LO.C99 && IsAfterAmp) && !S.isUnevaluatedContext())
14962 S.Diag(OpLoc, diag::ext_typecheck_indirection_through_void_pointer)
14963 << OpTy << Op->getSourceRange();
14964 }
14965
14966 // Dereferences are usually l-values...
14967 VK = VK_LValue;
14968
14969 // ...except that certain expressions are never l-values in C.
14970 if (!S.getLangOpts().CPlusPlus && Result.isCForbiddenLValueType())
14971 VK = VK_PRValue;
14972
14973 return Result;
14974}
14975
14976BinaryOperatorKind Sema::ConvertTokenKindToBinaryOpcode(tok::TokenKind Kind) {
14977 BinaryOperatorKind Opc;
14978 switch (Kind) {
14979 default: llvm_unreachable("Unknown binop!")::llvm::llvm_unreachable_internal("Unknown binop!", "clang/lib/Sema/SemaExpr.cpp"
, 14979)
;
14980 case tok::periodstar: Opc = BO_PtrMemD; break;
14981 case tok::arrowstar: Opc = BO_PtrMemI; break;
14982 case tok::star: Opc = BO_Mul; break;
14983 case tok::slash: Opc = BO_Div; break;
14984 case tok::percent: Opc = BO_Rem; break;
14985 case tok::plus: Opc = BO_Add; break;
14986 case tok::minus: Opc = BO_Sub; break;
14987 case tok::lessless: Opc = BO_Shl; break;
14988 case tok::greatergreater: Opc = BO_Shr; break;
14989 case tok::lessequal: Opc = BO_LE; break;
14990 case tok::less: Opc = BO_LT; break;
14991 case tok::greaterequal: Opc = BO_GE; break;
14992 case tok::greater: Opc = BO_GT; break;
14993 case tok::exclaimequal: Opc = BO_NE; break;
14994 case tok::equalequal: Opc = BO_EQ; break;
14995 case tok::spaceship: Opc = BO_Cmp; break;
14996 case tok::amp: Opc = BO_And; break;
14997 case tok::caret: Opc = BO_Xor; break;
14998 case tok::pipe: Opc = BO_Or; break;
14999 case tok::ampamp: Opc = BO_LAnd; break;
15000 case tok::pipepipe: Opc = BO_LOr; break;
15001 case tok::equal: Opc = BO_Assign; break;
15002 case tok::starequal: Opc = BO_MulAssign; break;
15003 case tok::slashequal: Opc = BO_DivAssign; break;
15004 case tok::percentequal: Opc = BO_RemAssign; break;
15005 case tok::plusequal: Opc = BO_AddAssign; break;
15006 case tok::minusequal: Opc = BO_SubAssign; break;
15007 case tok::lesslessequal: Opc = BO_ShlAssign; break;
15008 case tok::greatergreaterequal: Opc = BO_ShrAssign; break;
15009 case tok::ampequal: Opc = BO_AndAssign; break;
15010 case tok::caretequal: Opc = BO_XorAssign; break;
15011 case tok::pipeequal: Opc = BO_OrAssign; break;
15012 case tok::comma: Opc = BO_Comma; break;
15013 }
15014 return Opc;
15015}
15016
15017static inline UnaryOperatorKind ConvertTokenKindToUnaryOpcode(
15018 tok::TokenKind Kind) {
15019 UnaryOperatorKind Opc;
15020 switch (Kind) {
15021 default: llvm_unreachable("Unknown unary op!")::llvm::llvm_unreachable_internal("Unknown unary op!", "clang/lib/Sema/SemaExpr.cpp"
, 15021)
;
15022 case tok::plusplus: Opc = UO_PreInc; break;
15023 case tok::minusminus: Opc = UO_PreDec; break;
15024 case tok::amp: Opc = UO_AddrOf; break;
15025 case tok::star: Opc = UO_Deref; break;
15026 case tok::plus: Opc = UO_Plus; break;
15027 case tok::minus: Opc = UO_Minus; break;
15028 case tok::tilde: Opc = UO_Not; break;
15029 case tok::exclaim: Opc = UO_LNot; break;
15030 case tok::kw___real: Opc = UO_Real; break;
15031 case tok::kw___imag: Opc = UO_Imag; break;
15032 case tok::kw___extension__: Opc = UO_Extension; break;
15033 }
15034 return Opc;
15035}
15036
15037const FieldDecl *
15038Sema::getSelfAssignmentClassMemberCandidate(const ValueDecl *SelfAssigned) {
15039 // Explore the case for adding 'this->' to the LHS of a self assignment, very
15040 // common for setters.
15041 // struct A {
15042 // int X;
15043 // -void setX(int X) { X = X; }
15044 // +void setX(int X) { this->X = X; }
15045 // };
15046
15047 // Only consider parameters for self assignment fixes.
15048 if (!isa<ParmVarDecl>(SelfAssigned))
15049 return nullptr;
15050 const auto *Method =
15051 dyn_cast_or_null<CXXMethodDecl>(getCurFunctionDecl(true));
15052 if (!Method)
15053 return nullptr;
15054
15055 const CXXRecordDecl *Parent = Method->getParent();
15056 // In theory this is fixable if the lambda explicitly captures this, but
15057 // that's added complexity that's rarely going to be used.
15058 if (Parent->isLambda())
15059 return nullptr;
15060
15061 // FIXME: Use an actual Lookup operation instead of just traversing fields
15062 // in order to get base class fields.
15063 auto Field =
15064 llvm::find_if(Parent->fields(),
15065 [Name(SelfAssigned->getDeclName())](const FieldDecl *F) {
15066 return F->getDeclName() == Name;
15067 });
15068 return (Field != Parent->field_end()) ? *Field : nullptr;
15069}
15070
15071/// DiagnoseSelfAssignment - Emits a warning if a value is assigned to itself.
15072/// This warning suppressed in the event of macro expansions.
15073static void DiagnoseSelfAssignment(Sema &S, Expr *LHSExpr, Expr *RHSExpr,
15074 SourceLocation OpLoc, bool IsBuiltin) {
15075 if (S.inTemplateInstantiation())
15076 return;
15077 if (S.isUnevaluatedContext())
15078 return;
15079 if (OpLoc.isInvalid() || OpLoc.isMacroID())
15080 return;
15081 LHSExpr = LHSExpr->IgnoreParenImpCasts();
15082 RHSExpr = RHSExpr->IgnoreParenImpCasts();
15083 const DeclRefExpr *LHSDeclRef = dyn_cast<DeclRefExpr>(LHSExpr);
15084 const DeclRefExpr *RHSDeclRef = dyn_cast<DeclRefExpr>(RHSExpr);
15085 if (!LHSDeclRef || !RHSDeclRef ||
15086 LHSDeclRef->getLocation().isMacroID() ||
15087 RHSDeclRef->getLocation().isMacroID())
15088 return;
15089 const ValueDecl *LHSDecl =
15090 cast<ValueDecl>(LHSDeclRef->getDecl()->getCanonicalDecl());
15091 const ValueDecl *RHSDecl =
15092 cast<ValueDecl>(RHSDeclRef->getDecl()->getCanonicalDecl());
15093 if (LHSDecl != RHSDecl)
15094 return;
15095 if (LHSDecl->getType().isVolatileQualified())
15096 return;
15097 if (const ReferenceType *RefTy = LHSDecl->getType()->getAs<ReferenceType>())
15098 if (RefTy->getPointeeType().isVolatileQualified())
15099 return;
15100
15101 auto Diag = S.Diag(OpLoc, IsBuiltin ? diag::warn_self_assignment_builtin
15102 : diag::warn_self_assignment_overloaded)
15103 << LHSDeclRef->getType() << LHSExpr->getSourceRange()
15104 << RHSExpr->getSourceRange();
15105 if (const FieldDecl *SelfAssignField =
15106 S.getSelfAssignmentClassMemberCandidate(RHSDecl))
15107 Diag << 1 << SelfAssignField
15108 << FixItHint::CreateInsertion(LHSDeclRef->getBeginLoc(), "this->");
15109 else
15110 Diag << 0;
15111}
15112
15113/// Check if a bitwise-& is performed on an Objective-C pointer. This
15114/// is usually indicative of introspection within the Objective-C pointer.
15115static void checkObjCPointerIntrospection(Sema &S, ExprResult &L, ExprResult &R,
15116 SourceLocation OpLoc) {
15117 if (!S.getLangOpts().ObjC)
15118 return;
15119
15120 const Expr *ObjCPointerExpr = nullptr, *OtherExpr = nullptr;
15121 const Expr *LHS = L.get();
15122 const Expr *RHS = R.get();
15123
15124 if (LHS->IgnoreParenCasts()->getType()->isObjCObjectPointerType()) {
15125 ObjCPointerExpr = LHS;
15126 OtherExpr = RHS;
15127 }
15128 else if (RHS->IgnoreParenCasts()->getType()->isObjCObjectPointerType()) {
15129 ObjCPointerExpr = RHS;
15130 OtherExpr = LHS;
15131 }
15132
15133 // This warning is deliberately made very specific to reduce false
15134 // positives with logic that uses '&' for hashing. This logic mainly
15135 // looks for code trying to introspect into tagged pointers, which
15136 // code should generally never do.
15137 if (ObjCPointerExpr && isa<IntegerLiteral>(OtherExpr->IgnoreParenCasts())) {
15138 unsigned Diag = diag::warn_objc_pointer_masking;
15139 // Determine if we are introspecting the result of performSelectorXXX.
15140 const Expr *Ex = ObjCPointerExpr->IgnoreParenCasts();
15141 // Special case messages to -performSelector and friends, which
15142 // can return non-pointer values boxed in a pointer value.
15143 // Some clients may wish to silence warnings in this subcase.
15144 if (const ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(Ex)) {
15145 Selector S = ME->getSelector();
15146 StringRef SelArg0 = S.getNameForSlot(0);
15147 if (SelArg0.startswith("performSelector"))
15148 Diag = diag::warn_objc_pointer_masking_performSelector;
15149 }
15150
15151 S.Diag(OpLoc, Diag)
15152 << ObjCPointerExpr->getSourceRange();
15153 }
15154}
15155
15156static NamedDecl *getDeclFromExpr(Expr *E) {
15157 if (!E)
15158 return nullptr;
15159 if (auto *DRE = dyn_cast<DeclRefExpr>(E))
15160 return DRE->getDecl();
15161 if (auto *ME = dyn_cast<MemberExpr>(E))
15162 return ME->getMemberDecl();
15163 if (auto *IRE = dyn_cast<ObjCIvarRefExpr>(E))
15164 return IRE->getDecl();
15165 return nullptr;
15166}
15167
15168// This helper function promotes a binary operator's operands (which are of a
15169// half vector type) to a vector of floats and then truncates the result to
15170// a vector of either half or short.
15171static ExprResult convertHalfVecBinOp(Sema &S, ExprResult LHS, ExprResult RHS,
15172 BinaryOperatorKind Opc, QualType ResultTy,
15173 ExprValueKind VK, ExprObjectKind OK,
15174 bool IsCompAssign, SourceLocation OpLoc,
15175 FPOptionsOverride FPFeatures) {
15176 auto &Context = S.getASTContext();
15177 assert((isVector(ResultTy, Context.HalfTy) ||(static_cast <bool> ((isVector(ResultTy, Context.HalfTy
) || isVector(ResultTy, Context.ShortTy)) && "Result must be a vector of half or short"
) ? void (0) : __assert_fail ("(isVector(ResultTy, Context.HalfTy) || isVector(ResultTy, Context.ShortTy)) && \"Result must be a vector of half or short\""
, "clang/lib/Sema/SemaExpr.cpp", 15179, __extension__ __PRETTY_FUNCTION__
))
15178 isVector(ResultTy, Context.ShortTy)) &&(static_cast <bool> ((isVector(ResultTy, Context.HalfTy
) || isVector(ResultTy, Context.ShortTy)) && "Result must be a vector of half or short"
) ? void (0) : __assert_fail ("(isVector(ResultTy, Context.HalfTy) || isVector(ResultTy, Context.ShortTy)) && \"Result must be a vector of half or short\""
, "clang/lib/Sema/SemaExpr.cpp", 15179, __extension__ __PRETTY_FUNCTION__
))
15179 "Result must be a vector of half or short")(static_cast <bool> ((isVector(ResultTy, Context.HalfTy
) || isVector(ResultTy, Context.ShortTy)) && "Result must be a vector of half or short"
) ? void (0) : __assert_fail ("(isVector(ResultTy, Context.HalfTy) || isVector(ResultTy, Context.ShortTy)) && \"Result must be a vector of half or short\""
, "clang/lib/Sema/SemaExpr.cpp", 15179, __extension__ __PRETTY_FUNCTION__
))
;
15180 assert(isVector(LHS.get()->getType(), Context.HalfTy) &&(static_cast <bool> (isVector(LHS.get()->getType(), Context
.HalfTy) && isVector(RHS.get()->getType(), Context
.HalfTy) && "both operands expected to be a half vector"
) ? void (0) : __assert_fail ("isVector(LHS.get()->getType(), Context.HalfTy) && isVector(RHS.get()->getType(), Context.HalfTy) && \"both operands expected to be a half vector\""
, "clang/lib/Sema/SemaExpr.cpp", 15182, __extension__ __PRETTY_FUNCTION__
))
15181 isVector(RHS.get()->getType(), Context.HalfTy) &&(static_cast <bool> (isVector(LHS.get()->getType(), Context
.HalfTy) && isVector(RHS.get()->getType(), Context
.HalfTy) && "both operands expected to be a half vector"
) ? void (0) : __assert_fail ("isVector(LHS.get()->getType(), Context.HalfTy) && isVector(RHS.get()->getType(), Context.HalfTy) && \"both operands expected to be a half vector\""
, "clang/lib/Sema/SemaExpr.cpp", 15182, __extension__ __PRETTY_FUNCTION__
))
15182 "both operands expected to be a half vector")(static_cast <bool> (isVector(LHS.get()->getType(), Context
.HalfTy) && isVector(RHS.get()->getType(), Context
.HalfTy) && "both operands expected to be a half vector"
) ? void (0) : __assert_fail ("isVector(LHS.get()->getType(), Context.HalfTy) && isVector(RHS.get()->getType(), Context.HalfTy) && \"both operands expected to be a half vector\""
, "clang/lib/Sema/SemaExpr.cpp", 15182, __extension__ __PRETTY_FUNCTION__
))
;
15183
15184 RHS = convertVector(RHS.get(), Context.FloatTy, S);
15185 QualType BinOpResTy = RHS.get()->getType();
15186
15187 // If Opc is a comparison, ResultType is a vector of shorts. In that case,
15188 // change BinOpResTy to a vector of ints.
15189 if (isVector(ResultTy, Context.ShortTy))
15190 BinOpResTy = S.GetSignedVectorType(BinOpResTy);
15191
15192 if (IsCompAssign)
15193 return CompoundAssignOperator::Create(Context, LHS.get(), RHS.get(), Opc,
15194 ResultTy, VK, OK, OpLoc, FPFeatures,
15195 BinOpResTy, BinOpResTy);
15196
15197 LHS = convertVector(LHS.get(), Context.FloatTy, S);
15198 auto *BO = BinaryOperator::Create(Context, LHS.get(), RHS.get(), Opc,
15199 BinOpResTy, VK, OK, OpLoc, FPFeatures);
15200 return convertVector(BO, ResultTy->castAs<VectorType>()->getElementType(), S);
15201}
15202
15203static std::pair<ExprResult, ExprResult>
15204CorrectDelayedTyposInBinOp(Sema &S, BinaryOperatorKind Opc, Expr *LHSExpr,
15205 Expr *RHSExpr) {
15206 ExprResult LHS = LHSExpr, RHS = RHSExpr;
15207 if (!S.Context.isDependenceAllowed()) {
15208 // C cannot handle TypoExpr nodes on either side of a binop because it
15209 // doesn't handle dependent types properly, so make sure any TypoExprs have
15210 // been dealt with before checking the operands.
15211 LHS = S.CorrectDelayedTyposInExpr(LHS);
15212 RHS = S.CorrectDelayedTyposInExpr(
15213 RHS, /*InitDecl=*/nullptr, /*RecoverUncorrectedTypos=*/false,
15214 [Opc, LHS](Expr *E) {
15215 if (Opc != BO_Assign)
15216 return ExprResult(E);
15217 // Avoid correcting the RHS to the same Expr as the LHS.
15218 Decl *D = getDeclFromExpr(E);
15219 return (D && D == getDeclFromExpr(LHS.get())) ? ExprError() : E;
15220 });
15221 }
15222 return std::make_pair(LHS, RHS);
15223}
15224
15225/// Returns true if conversion between vectors of halfs and vectors of floats
15226/// is needed.
15227static bool needsConversionOfHalfVec(bool OpRequiresConversion, ASTContext &Ctx,
15228 Expr *E0, Expr *E1 = nullptr) {
15229 if (!OpRequiresConversion || Ctx.getLangOpts().NativeHalfType ||
15230 Ctx.getTargetInfo().useFP16ConversionIntrinsics())
15231 return false;
15232
15233 auto HasVectorOfHalfType = [&Ctx](Expr *E) {
15234 QualType Ty = E->IgnoreImplicit()->getType();
15235
15236 // Don't promote half precision neon vectors like float16x4_t in arm_neon.h
15237 // to vectors of floats. Although the element type of the vectors is __fp16,
15238 // the vectors shouldn't be treated as storage-only types. See the
15239 // discussion here: https://reviews.llvm.org/rG825235c140e7
15240 if (const VectorType *VT = Ty->getAs<VectorType>()) {
15241 if (VT->getVectorKind() == VectorType::NeonVector)
15242 return false;
15243 return VT->getElementType().getCanonicalType() == Ctx.HalfTy;
15244 }
15245 return false;
15246 };
15247
15248 return HasVectorOfHalfType(E0) && (!E1 || HasVectorOfHalfType(E1));
15249}
15250
15251/// CreateBuiltinBinOp - Creates a new built-in binary operation with
15252/// operator @p Opc at location @c TokLoc. This routine only supports
15253/// built-in operations; ActOnBinOp handles overloaded operators.
15254ExprResult Sema::CreateBuiltinBinOp(SourceLocation OpLoc,
15255 BinaryOperatorKind Opc,
15256 Expr *LHSExpr, Expr *RHSExpr) {
15257 if (getLangOpts().CPlusPlus11 && isa<InitListExpr>(RHSExpr)) {
15258 // The syntax only allows initializer lists on the RHS of assignment,
15259 // so we don't need to worry about accepting invalid code for
15260 // non-assignment operators.
15261 // C++11 5.17p9:
15262 // The meaning of x = {v} [...] is that of x = T(v) [...]. The meaning
15263 // of x = {} is x = T().
15264 InitializationKind Kind = InitializationKind::CreateDirectList(
15265 RHSExpr->getBeginLoc(), RHSExpr->getBeginLoc(), RHSExpr->getEndLoc());
15266 InitializedEntity Entity =
15267 InitializedEntity::InitializeTemporary(LHSExpr->getType());
15268 InitializationSequence InitSeq(*this, Entity, Kind, RHSExpr);
15269 ExprResult Init = InitSeq.Perform(*this, Entity, Kind, RHSExpr);
15270 if (Init.isInvalid())
15271 return Init;
15272 RHSExpr = Init.get();
15273 }
15274
15275 ExprResult LHS = LHSExpr, RHS = RHSExpr;
15276 QualType ResultTy; // Result type of the binary operator.
15277 // The following two variables are used for compound assignment operators
15278 QualType CompLHSTy; // Type of LHS after promotions for computation
15279 QualType CompResultTy; // Type of computation result
15280 ExprValueKind VK = VK_PRValue;
15281 ExprObjectKind OK = OK_Ordinary;
15282 bool ConvertHalfVec = false;
15283
15284 std::tie(LHS, RHS) = CorrectDelayedTyposInBinOp(*this, Opc, LHSExpr, RHSExpr);
15285 if (!LHS.isUsable() || !RHS.isUsable())
15286 return ExprError();
15287
15288 if (getLangOpts().OpenCL) {
15289 QualType LHSTy = LHSExpr->getType();
15290 QualType RHSTy = RHSExpr->getType();
15291 // OpenCLC v2.0 s6.13.11.1 allows atomic variables to be initialized by
15292 // the ATOMIC_VAR_INIT macro.
15293 if (LHSTy->isAtomicType() || RHSTy->isAtomicType()) {
15294 SourceRange SR(LHSExpr->getBeginLoc(), RHSExpr->getEndLoc());
15295 if (BO_Assign == Opc)
15296 Diag(OpLoc, diag::err_opencl_atomic_init) << 0 << SR;
15297 else
15298 ResultTy = InvalidOperands(OpLoc, LHS, RHS);
15299 return ExprError();
15300 }
15301
15302 // OpenCL special types - image, sampler, pipe, and blocks are to be used
15303 // only with a builtin functions and therefore should be disallowed here.
15304 if (LHSTy->isImageType() || RHSTy->isImageType() ||
15305 LHSTy->isSamplerT() || RHSTy->isSamplerT() ||
15306 LHSTy->isPipeType() || RHSTy->isPipeType() ||
15307 LHSTy->isBlockPointerType() || RHSTy->isBlockPointerType()) {
15308 ResultTy = InvalidOperands(OpLoc, LHS, RHS);
15309 return ExprError();
15310 }
15311 }
15312
15313 checkTypeSupport(LHSExpr->getType(), OpLoc, /*ValueDecl*/ nullptr);
15314 checkTypeSupport(RHSExpr->getType(), OpLoc, /*ValueDecl*/ nullptr);
15315
15316 switch (Opc) {
15317 case BO_Assign:
15318 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, QualType(), Opc);
15319 if (getLangOpts().CPlusPlus &&
15320 LHS.get()->getObjectKind() != OK_ObjCProperty) {
15321 VK = LHS.get()->getValueKind();
15322 OK = LHS.get()->getObjectKind();
15323 }
15324 if (!ResultTy.isNull()) {
15325 DiagnoseSelfAssignment(*this, LHS.get(), RHS.get(), OpLoc, true);
15326 DiagnoseSelfMove(LHS.get(), RHS.get(), OpLoc);
15327
15328 // Avoid copying a block to the heap if the block is assigned to a local
15329 // auto variable that is declared in the same scope as the block. This
15330 // optimization is unsafe if the local variable is declared in an outer
15331 // scope. For example:
15332 //
15333 // BlockTy b;
15334 // {
15335 // b = ^{...};
15336 // }
15337 // // It is unsafe to invoke the block here if it wasn't copied to the
15338 // // heap.
15339 // b();
15340
15341 if (auto *BE = dyn_cast<BlockExpr>(RHS.get()->IgnoreParens()))
15342 if (auto *DRE = dyn_cast<DeclRefExpr>(LHS.get()->IgnoreParens()))
15343 if (auto *VD = dyn_cast<VarDecl>(DRE->getDecl()))
15344 if (VD->hasLocalStorage() && getCurScope()->isDeclScope(VD))
15345 BE->getBlockDecl()->setCanAvoidCopyToHeap();
15346
15347 if (LHS.get()->getType().hasNonTrivialToPrimitiveCopyCUnion())
15348 checkNonTrivialCUnion(LHS.get()->getType(), LHS.get()->getExprLoc(),
15349 NTCUC_Assignment, NTCUK_Copy);
15350 }
15351 RecordModifiableNonNullParam(*this, LHS.get());
15352 break;
15353 case BO_PtrMemD:
15354 case BO_PtrMemI:
15355 ResultTy = CheckPointerToMemberOperands(LHS, RHS, VK, OpLoc,
15356 Opc == BO_PtrMemI);
15357 break;
15358 case BO_Mul:
15359 case BO_Div:
15360 ConvertHalfVec = true;
15361 ResultTy = CheckMultiplyDivideOperands(LHS, RHS, OpLoc, false,
15362 Opc == BO_Div);
15363 break;
15364 case BO_Rem:
15365 ResultTy = CheckRemainderOperands(LHS, RHS, OpLoc);
15366 break;
15367 case BO_Add:
15368 ConvertHalfVec = true;
15369 ResultTy = CheckAdditionOperands(LHS, RHS, OpLoc, Opc);
15370 break;
15371 case BO_Sub:
15372 ConvertHalfVec = true;
15373 ResultTy = CheckSubtractionOperands(LHS, RHS, OpLoc);
15374 break;
15375 case BO_Shl:
15376 case BO_Shr:
15377 ResultTy = CheckShiftOperands(LHS, RHS, OpLoc, Opc);
15378 break;
15379 case BO_LE:
15380 case BO_LT:
15381 case BO_GE:
15382 case BO_GT:
15383 ConvertHalfVec = true;
15384 ResultTy = CheckCompareOperands(LHS, RHS, OpLoc, Opc);
15385 break;
15386 case BO_EQ:
15387 case BO_NE:
15388 ConvertHalfVec = true;
15389 ResultTy = CheckCompareOperands(LHS, RHS, OpLoc, Opc);
15390 break;
15391 case BO_Cmp:
15392 ConvertHalfVec = true;
15393 ResultTy = CheckCompareOperands(LHS, RHS, OpLoc, Opc);
15394 assert(ResultTy.isNull() || ResultTy->getAsCXXRecordDecl())(static_cast <bool> (ResultTy.isNull() || ResultTy->
getAsCXXRecordDecl()) ? void (0) : __assert_fail ("ResultTy.isNull() || ResultTy->getAsCXXRecordDecl()"
, "clang/lib/Sema/SemaExpr.cpp", 15394, __extension__ __PRETTY_FUNCTION__
))
;
15395 break;
15396 case BO_And:
15397 checkObjCPointerIntrospection(*this, LHS, RHS, OpLoc);
15398 [[fallthrough]];
15399 case BO_Xor:
15400 case BO_Or:
15401 ResultTy = CheckBitwiseOperands(LHS, RHS, OpLoc, Opc);
15402 break;
15403 case BO_LAnd:
15404 case BO_LOr:
15405 ConvertHalfVec = true;
15406 ResultTy = CheckLogicalOperands(LHS, RHS, OpLoc, Opc);
15407 break;
15408 case BO_MulAssign:
15409 case BO_DivAssign:
15410 ConvertHalfVec = true;
15411 CompResultTy = CheckMultiplyDivideOperands(LHS, RHS, OpLoc, true,
15412 Opc == BO_DivAssign);
15413 CompLHSTy = CompResultTy;
15414 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
15415 ResultTy =
15416 CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy, Opc);
15417 break;
15418 case BO_RemAssign:
15419 CompResultTy = CheckRemainderOperands(LHS, RHS, OpLoc, true);
15420 CompLHSTy = CompResultTy;
15421 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
15422 ResultTy =
15423 CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy, Opc);
15424 break;
15425 case BO_AddAssign:
15426 ConvertHalfVec = true;
15427 CompResultTy = CheckAdditionOperands(LHS, RHS, OpLoc, Opc, &CompLHSTy);
15428 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
15429 ResultTy =
15430 CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy, Opc);
15431 break;
15432 case BO_SubAssign:
15433 ConvertHalfVec = true;
15434 CompResultTy = CheckSubtractionOperands(LHS, RHS, OpLoc, &CompLHSTy);
15435 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
15436 ResultTy =
15437 CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy, Opc);
15438 break;
15439 case BO_ShlAssign:
15440 case BO_ShrAssign:
15441 CompResultTy = CheckShiftOperands(LHS, RHS, OpLoc, Opc, true);
15442 CompLHSTy = CompResultTy;
15443 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
15444 ResultTy =
15445 CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy, Opc);
15446 break;
15447 case BO_AndAssign:
15448 case BO_OrAssign: // fallthrough
15449 DiagnoseSelfAssignment(*this, LHS.get(), RHS.get(), OpLoc, true);
15450 [[fallthrough]];
15451 case BO_XorAssign:
15452 CompResultTy = CheckBitwiseOperands(LHS, RHS, OpLoc, Opc);
15453 CompLHSTy = CompResultTy;
15454 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
15455 ResultTy =
15456 CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy, Opc);
15457 break;
15458 case BO_Comma:
15459 ResultTy = CheckCommaOperands(*this, LHS, RHS, OpLoc);
15460 if (getLangOpts().CPlusPlus && !RHS.isInvalid()) {
15461 VK = RHS.get()->getValueKind();
15462 OK = RHS.get()->getObjectKind();
15463 }
15464 break;
15465 }
15466 if (ResultTy.isNull() || LHS.isInvalid() || RHS.isInvalid())
15467 return ExprError();
15468
15469 // Some of the binary operations require promoting operands of half vector to
15470 // float vectors and truncating the result back to half vector. For now, we do
15471 // this only when HalfArgsAndReturn is set (that is, when the target is arm or
15472 // arm64).
15473 assert((static_cast <bool> ((Opc == BO_Comma || isVector(RHS.get
()->getType(), Context.HalfTy) == isVector(LHS.get()->getType
(), Context.HalfTy)) && "both sides are half vectors or neither sides are"
) ? void (0) : __assert_fail ("(Opc == BO_Comma || isVector(RHS.get()->getType(), Context.HalfTy) == isVector(LHS.get()->getType(), Context.HalfTy)) && \"both sides are half vectors or neither sides are\""
, "clang/lib/Sema/SemaExpr.cpp", 15476, __extension__ __PRETTY_FUNCTION__
))
15474 (Opc == BO_Comma || isVector(RHS.get()->getType(), Context.HalfTy) ==(static_cast <bool> ((Opc == BO_Comma || isVector(RHS.get
()->getType(), Context.HalfTy) == isVector(LHS.get()->getType
(), Context.HalfTy)) && "both sides are half vectors or neither sides are"
) ? void (0) : __assert_fail ("(Opc == BO_Comma || isVector(RHS.get()->getType(), Context.HalfTy) == isVector(LHS.get()->getType(), Context.HalfTy)) && \"both sides are half vectors or neither sides are\""
, "clang/lib/Sema/SemaExpr.cpp", 15476, __extension__ __PRETTY_FUNCTION__
))
15475 isVector(LHS.get()->getType(), Context.HalfTy)) &&(static_cast <bool> ((Opc == BO_Comma || isVector(RHS.get
()->getType(), Context.HalfTy) == isVector(LHS.get()->getType
(), Context.HalfTy)) && "both sides are half vectors or neither sides are"
) ? void (0) : __assert_fail ("(Opc == BO_Comma || isVector(RHS.get()->getType(), Context.HalfTy) == isVector(LHS.get()->getType(), Context.HalfTy)) && \"both sides are half vectors or neither sides are\""
, "clang/lib/Sema/SemaExpr.cpp", 15476, __extension__ __PRETTY_FUNCTION__
))
15476 "both sides are half vectors or neither sides are")(static_cast <bool> ((Opc == BO_Comma || isVector(RHS.get
()->getType(), Context.HalfTy) == isVector(LHS.get()->getType
(), Context.HalfTy)) && "both sides are half vectors or neither sides are"
) ? void (0) : __assert_fail ("(Opc == BO_Comma || isVector(RHS.get()->getType(), Context.HalfTy) == isVector(LHS.get()->getType(), Context.HalfTy)) && \"both sides are half vectors or neither sides are\""
, "clang/lib/Sema/SemaExpr.cpp", 15476, __extension__ __PRETTY_FUNCTION__
))
;
15477 ConvertHalfVec =
15478 needsConversionOfHalfVec(ConvertHalfVec, Context, LHS.get(), RHS.get());
15479
15480 // Check for array bounds violations for both sides of the BinaryOperator
15481 CheckArrayAccess(LHS.get());
15482 CheckArrayAccess(RHS.get());
15483
15484 if (const ObjCIsaExpr *OISA = dyn_cast<ObjCIsaExpr>(LHS.get()->IgnoreParenCasts())) {
15485 NamedDecl *ObjectSetClass = LookupSingleName(TUScope,
15486 &Context.Idents.get("object_setClass"),
15487 SourceLocation(), LookupOrdinaryName);
15488 if (ObjectSetClass && isa<ObjCIsaExpr>(LHS.get())) {
15489 SourceLocation RHSLocEnd = getLocForEndOfToken(RHS.get()->getEndLoc());
15490 Diag(LHS.get()->getExprLoc(), diag::warn_objc_isa_assign)
15491 << FixItHint::CreateInsertion(LHS.get()->getBeginLoc(),
15492 "object_setClass(")
15493 << FixItHint::CreateReplacement(SourceRange(OISA->getOpLoc(), OpLoc),
15494 ",")
15495 << FixItHint::CreateInsertion(RHSLocEnd, ")");
15496 }
15497 else
15498 Diag(LHS.get()->getExprLoc(), diag::warn_objc_isa_assign);
15499 }
15500 else if (const ObjCIvarRefExpr *OIRE =
15501 dyn_cast<ObjCIvarRefExpr>(LHS.get()->IgnoreParenCasts()))
15502 DiagnoseDirectIsaAccess(*this, OIRE, OpLoc, RHS.get());
15503
15504 // Opc is not a compound assignment if CompResultTy is null.
15505 if (CompResultTy.isNull()) {
15506 if (ConvertHalfVec)
15507 return convertHalfVecBinOp(*this, LHS, RHS, Opc, ResultTy, VK, OK, false,
15508 OpLoc, CurFPFeatureOverrides());
15509 return BinaryOperator::Create(Context, LHS.get(), RHS.get(), Opc, ResultTy,
15510 VK, OK, OpLoc, CurFPFeatureOverrides());
15511 }
15512
15513 // Handle compound assignments.
15514 if (getLangOpts().CPlusPlus && LHS.get()->getObjectKind() !=
15515 OK_ObjCProperty) {
15516 VK = VK_LValue;
15517 OK = LHS.get()->getObjectKind();
15518 }
15519
15520 // The LHS is not converted to the result type for fixed-point compound
15521 // assignment as the common type is computed on demand. Reset the CompLHSTy
15522 // to the LHS type we would have gotten after unary conversions.
15523 if (CompResultTy->isFixedPointType())
15524 CompLHSTy = UsualUnaryConversions(LHS.get()).get()->getType();
15525
15526 if (ConvertHalfVec)
15527 return convertHalfVecBinOp(*this, LHS, RHS, Opc, ResultTy, VK, OK, true,
15528 OpLoc, CurFPFeatureOverrides());
15529
15530 return CompoundAssignOperator::Create(
15531 Context, LHS.get(), RHS.get(), Opc, ResultTy, VK, OK, OpLoc,
15532 CurFPFeatureOverrides(), CompLHSTy, CompResultTy);
15533}
15534
15535/// DiagnoseBitwisePrecedence - Emit a warning when bitwise and comparison
15536/// operators are mixed in a way that suggests that the programmer forgot that
15537/// comparison operators have higher precedence. The most typical example of
15538/// such code is "flags & 0x0020 != 0", which is equivalent to "flags & 1".
15539static void DiagnoseBitwisePrecedence(Sema &Self, BinaryOperatorKind Opc,
15540 SourceLocation OpLoc, Expr *LHSExpr,
15541 Expr *RHSExpr) {
15542 BinaryOperator *LHSBO = dyn_cast<BinaryOperator>(LHSExpr);
15543 BinaryOperator *RHSBO = dyn_cast<BinaryOperator>(RHSExpr);
15544
15545 // Check that one of the sides is a comparison operator and the other isn't.
15546 bool isLeftComp = LHSBO && LHSBO->isComparisonOp();
15547 bool isRightComp = RHSBO && RHSBO->isComparisonOp();
15548 if (isLeftComp == isRightComp)
15549 return;
15550
15551 // Bitwise operations are sometimes used as eager logical ops.
15552 // Don't diagnose this.
15553 bool isLeftBitwise = LHSBO && LHSBO->isBitwiseOp();
15554 bool isRightBitwise = RHSBO && RHSBO->isBitwiseOp();
15555 if (isLeftBitwise || isRightBitwise)
15556 return;
15557
15558 SourceRange DiagRange = isLeftComp
15559 ? SourceRange(LHSExpr->getBeginLoc(), OpLoc)
15560 : SourceRange(OpLoc, RHSExpr->getEndLoc());
15561 StringRef OpStr = isLeftComp ? LHSBO->getOpcodeStr() : RHSBO->getOpcodeStr();
15562 SourceRange ParensRange =
15563 isLeftComp
15564 ? SourceRange(LHSBO->getRHS()->getBeginLoc(), RHSExpr->getEndLoc())
15565 : SourceRange(LHSExpr->getBeginLoc(), RHSBO->getLHS()->getEndLoc());
15566
15567 Self.Diag(OpLoc, diag::warn_precedence_bitwise_rel)
15568 << DiagRange << BinaryOperator::getOpcodeStr(Opc) << OpStr;
15569 SuggestParentheses(Self, OpLoc,
15570 Self.PDiag(diag::note_precedence_silence) << OpStr,
15571 (isLeftComp ? LHSExpr : RHSExpr)->getSourceRange());
15572 SuggestParentheses(Self, OpLoc,
15573 Self.PDiag(diag::note_precedence_bitwise_first)
15574 << BinaryOperator::getOpcodeStr(Opc),
15575 ParensRange);
15576}
15577
15578/// It accepts a '&&' expr that is inside a '||' one.
15579/// Emit a diagnostic together with a fixit hint that wraps the '&&' expression
15580/// in parentheses.
15581static void
15582EmitDiagnosticForLogicalAndInLogicalOr(Sema &Self, SourceLocation OpLoc,
15583 BinaryOperator *Bop) {
15584 assert(Bop->getOpcode() == BO_LAnd)(static_cast <bool> (Bop->getOpcode() == BO_LAnd) ? void
(0) : __assert_fail ("Bop->getOpcode() == BO_LAnd", "clang/lib/Sema/SemaExpr.cpp"
, 15584, __extension__ __PRETTY_FUNCTION__))
;
15585 Self.Diag(Bop->getOperatorLoc(), diag::warn_logical_and_in_logical_or)
15586 << Bop->getSourceRange() << OpLoc;
15587 SuggestParentheses(Self, Bop->getOperatorLoc(),
15588 Self.PDiag(diag::note_precedence_silence)
15589 << Bop->getOpcodeStr(),
15590 Bop->getSourceRange());
15591}
15592
15593/// Look for '&&' in the left hand of a '||' expr.
15594static void DiagnoseLogicalAndInLogicalOrLHS(Sema &S, SourceLocation OpLoc,
15595 Expr *LHSExpr, Expr *RHSExpr) {
15596 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(LHSExpr)) {
15597 if (Bop->getOpcode() == BO_LAnd) {
15598 // If it's "string_literal && a || b" don't warn since the precedence
15599 // doesn't matter.
15600 if (!isa<StringLiteral>(Bop->getLHS()->IgnoreParenImpCasts()))
15601 return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, Bop);
15602 } else if (Bop->getOpcode() == BO_LOr) {
15603 if (BinaryOperator *RBop = dyn_cast<BinaryOperator>(Bop->getRHS())) {
15604 // If it's "a || b && string_literal || c" we didn't warn earlier for
15605 // "a || b && string_literal", but warn now.
15606 if (RBop->getOpcode() == BO_LAnd &&
15607 isa<StringLiteral>(RBop->getRHS()->IgnoreParenImpCasts()))
15608 return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, RBop);
15609 }
15610 }
15611 }
15612}
15613
15614/// Look for '&&' in the right hand of a '||' expr.
15615static void DiagnoseLogicalAndInLogicalOrRHS(Sema &S, SourceLocation OpLoc,
15616 Expr *LHSExpr, Expr *RHSExpr) {
15617 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(RHSExpr)) {
15618 if (Bop->getOpcode() == BO_LAnd) {
15619 // If it's "a || b && string_literal" don't warn since the precedence
15620 // doesn't matter.
15621 if (!isa<StringLiteral>(Bop->getRHS()->IgnoreParenImpCasts()))
15622 return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, Bop);
15623 }
15624 }
15625}
15626
15627/// Look for bitwise op in the left or right hand of a bitwise op with
15628/// lower precedence and emit a diagnostic together with a fixit hint that wraps
15629/// the '&' expression in parentheses.
15630static void DiagnoseBitwiseOpInBitwiseOp(Sema &S, BinaryOperatorKind Opc,
15631 SourceLocation OpLoc, Expr *SubExpr) {
15632 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(SubExpr)) {
15633 if (Bop->isBitwiseOp() && Bop->getOpcode() < Opc) {
15634 S.Diag(Bop->getOperatorLoc(), diag::warn_bitwise_op_in_bitwise_op)
15635 << Bop->getOpcodeStr() << BinaryOperator::getOpcodeStr(Opc)
15636 << Bop->getSourceRange() << OpLoc;
15637 SuggestParentheses(S, Bop->getOperatorLoc(),
15638 S.PDiag(diag::note_precedence_silence)
15639 << Bop->getOpcodeStr(),
15640 Bop->getSourceRange());
15641 }
15642 }
15643}
15644
15645static void DiagnoseAdditionInShift(Sema &S, SourceLocation OpLoc,
15646 Expr *SubExpr, StringRef Shift) {
15647 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(SubExpr)) {
15648 if (Bop->getOpcode() == BO_Add || Bop->getOpcode() == BO_Sub) {
15649 StringRef Op = Bop->getOpcodeStr();
15650 S.Diag(Bop->getOperatorLoc(), diag::warn_addition_in_bitshift)
15651 << Bop->getSourceRange() << OpLoc << Shift << Op;
15652 SuggestParentheses(S, Bop->getOperatorLoc(),
15653 S.PDiag(diag::note_precedence_silence) << Op,
15654 Bop->getSourceRange());
15655 }
15656 }
15657}
15658
15659static void DiagnoseShiftCompare(Sema &S, SourceLocation OpLoc,
15660 Expr *LHSExpr, Expr *RHSExpr) {
15661 CXXOperatorCallExpr *OCE = dyn_cast<CXXOperatorCallExpr>(LHSExpr);
15662 if (!OCE)
15663 return;
15664
15665 FunctionDecl *FD = OCE->getDirectCallee();
15666 if (!FD || !FD->isOverloadedOperator())
15667 return;
15668
15669 OverloadedOperatorKind Kind = FD->getOverloadedOperator();
15670 if (Kind != OO_LessLess && Kind != OO_GreaterGreater)
15671 return;
15672
15673 S.Diag(OpLoc, diag::warn_overloaded_shift_in_comparison)
15674 << LHSExpr->getSourceRange() << RHSExpr->getSourceRange()
15675 << (Kind == OO_LessLess);
15676 SuggestParentheses(S, OCE->getOperatorLoc(),
15677 S.PDiag(diag::note_precedence_silence)
15678 << (Kind == OO_LessLess ? "<<" : ">>"),
15679 OCE->getSourceRange());
15680 SuggestParentheses(
15681 S, OpLoc, S.PDiag(diag::note_evaluate_comparison_first),
15682 SourceRange(OCE->getArg(1)->getBeginLoc(), RHSExpr->getEndLoc()));
15683}
15684
15685/// DiagnoseBinOpPrecedence - Emit warnings for expressions with tricky
15686/// precedence.
15687static void DiagnoseBinOpPrecedence(Sema &Self, BinaryOperatorKind Opc,
15688 SourceLocation OpLoc, Expr *LHSExpr,
15689 Expr *RHSExpr){
15690 // Diagnose "arg1 'bitwise' arg2 'eq' arg3".
15691 if (BinaryOperator::isBitwiseOp(Opc))
15692 DiagnoseBitwisePrecedence(Self, Opc, OpLoc, LHSExpr, RHSExpr);
15693
15694 // Diagnose "arg1 & arg2 | arg3"
15695 if ((Opc == BO_Or || Opc == BO_Xor) &&
15696 !OpLoc.isMacroID()/* Don't warn in macros. */) {
15697 DiagnoseBitwiseOpInBitwiseOp(Self, Opc, OpLoc, LHSExpr);
15698 DiagnoseBitwiseOpInBitwiseOp(Self, Opc, OpLoc, RHSExpr);
15699 }
15700
15701 // Warn about arg1 || arg2 && arg3, as GCC 4.3+ does.
15702 // We don't warn for 'assert(a || b && "bad")' since this is safe.
15703 if (Opc == BO_LOr && !OpLoc.isMacroID()/* Don't warn in macros. */) {
15704 DiagnoseLogicalAndInLogicalOrLHS(Self, OpLoc, LHSExpr, RHSExpr);
15705 DiagnoseLogicalAndInLogicalOrRHS(Self, OpLoc, LHSExpr, RHSExpr);
15706 }
15707
15708 if ((Opc == BO_Shl && LHSExpr->getType()->isIntegralType(Self.getASTContext()))
15709 || Opc == BO_Shr) {
15710 StringRef Shift = BinaryOperator::getOpcodeStr(Opc);
15711 DiagnoseAdditionInShift(Self, OpLoc, LHSExpr, Shift);
15712 DiagnoseAdditionInShift(Self, OpLoc, RHSExpr, Shift);
15713 }
15714
15715 // Warn on overloaded shift operators and comparisons, such as:
15716 // cout << 5 == 4;
15717 if (BinaryOperator::isComparisonOp(Opc))
15718 DiagnoseShiftCompare(Self, OpLoc, LHSExpr, RHSExpr);
15719}
15720
15721// Binary Operators. 'Tok' is the token for the operator.
15722ExprResult Sema::ActOnBinOp(Scope *S, SourceLocation TokLoc,
15723 tok::TokenKind Kind,
15724 Expr *LHSExpr, Expr *RHSExpr) {
15725 BinaryOperatorKind Opc = ConvertTokenKindToBinaryOpcode(Kind);
15726 assert(LHSExpr && "ActOnBinOp(): missing left expression")(static_cast <bool> (LHSExpr && "ActOnBinOp(): missing left expression"
) ? void (0) : __assert_fail ("LHSExpr && \"ActOnBinOp(): missing left expression\""
, "clang/lib/Sema/SemaExpr.cpp", 15726, __extension__ __PRETTY_FUNCTION__
))
;
15727 assert(RHSExpr && "ActOnBinOp(): missing right expression")(static_cast <bool> (RHSExpr && "ActOnBinOp(): missing right expression"
) ? void (0) : __assert_fail ("RHSExpr && \"ActOnBinOp(): missing right expression\""
, "clang/lib/Sema/SemaExpr.cpp", 15727, __extension__ __PRETTY_FUNCTION__
))
;
15728
15729 // Emit warnings for tricky precedence issues, e.g. "bitfield & 0x4 == 0"
15730 DiagnoseBinOpPrecedence(*this, Opc, TokLoc, LHSExpr, RHSExpr);
15731
15732 return BuildBinOp(S, TokLoc, Opc, LHSExpr, RHSExpr);
15733}
15734
15735void Sema::LookupBinOp(Scope *S, SourceLocation OpLoc, BinaryOperatorKind Opc,
15736 UnresolvedSetImpl &Functions) {
15737 OverloadedOperatorKind OverOp = BinaryOperator::getOverloadedOperator(Opc);
15738 if (OverOp != OO_None && OverOp != OO_Equal)
15739 LookupOverloadedOperatorName(OverOp, S, Functions);
15740
15741 // In C++20 onwards, we may have a second operator to look up.
15742 if (getLangOpts().CPlusPlus20) {
15743 if (OverloadedOperatorKind ExtraOp = getRewrittenOverloadedOperator(OverOp))
15744 LookupOverloadedOperatorName(ExtraOp, S, Functions);
15745 }
15746}
15747
15748/// Build an overloaded binary operator expression in the given scope.
15749static ExprResult BuildOverloadedBinOp(Sema &S, Scope *Sc, SourceLocation OpLoc,
15750 BinaryOperatorKind Opc,
15751 Expr *LHS, Expr *RHS) {
15752 switch (Opc) {
15753 case BO_Assign:
15754 // In the non-overloaded case, we warn about self-assignment (x = x) for
15755 // both simple assignment and certain compound assignments where algebra
15756 // tells us the operation yields a constant result. When the operator is
15757 // overloaded, we can't do the latter because we don't want to assume that
15758 // those algebraic identities still apply; for example, a path-building
15759 // library might use operator/= to append paths. But it's still reasonable
15760 // to assume that simple assignment is just moving/copying values around
15761 // and so self-assignment is likely a bug.
15762 DiagnoseSelfAssignment(S, LHS, RHS, OpLoc, false);
15763 [[fallthrough]];
15764 case BO_DivAssign:
15765 case BO_RemAssign:
15766 case BO_SubAssign:
15767 case BO_AndAssign:
15768 case BO_OrAssign:
15769 case BO_XorAssign:
15770 CheckIdentityFieldAssignment(LHS, RHS, OpLoc, S);
15771 break;
15772 default:
15773 break;
15774 }
15775
15776 // Find all of the overloaded operators visible from this point.
15777 UnresolvedSet<16> Functions;
15778 S.LookupBinOp(Sc, OpLoc, Opc, Functions);
15779
15780 // Build the (potentially-overloaded, potentially-dependent)
15781 // binary operation.
15782 return S.CreateOverloadedBinOp(OpLoc, Opc, Functions, LHS, RHS);
15783}
15784
15785ExprResult Sema::BuildBinOp(Scope *S, SourceLocation OpLoc,
15786 BinaryOperatorKind Opc,
15787 Expr *LHSExpr, Expr *RHSExpr) {
15788 ExprResult LHS, RHS;
15789 std::tie(LHS, RHS) = CorrectDelayedTyposInBinOp(*this, Opc, LHSExpr, RHSExpr);
15790 if (!LHS.isUsable() || !RHS.isUsable())
15791 return ExprError();
15792 LHSExpr = LHS.get();
15793 RHSExpr = RHS.get();
15794
15795 // We want to end up calling one of checkPseudoObjectAssignment
15796 // (if the LHS is a pseudo-object), BuildOverloadedBinOp (if
15797 // both expressions are overloadable or either is type-dependent),
15798 // or CreateBuiltinBinOp (in any other case). We also want to get
15799 // any placeholder types out of the way.
15800
15801 // Handle pseudo-objects in the LHS.
15802 if (const BuiltinType *pty = LHSExpr->getType()->getAsPlaceholderType()) {
15803 // Assignments with a pseudo-object l-value need special analysis.
15804 if (pty->getKind() == BuiltinType::PseudoObject &&
15805 BinaryOperator::isAssignmentOp(Opc))
15806 return checkPseudoObjectAssignment(S, OpLoc, Opc, LHSExpr, RHSExpr);
15807
15808 // Don't resolve overloads if the other type is overloadable.
15809 if (getLangOpts().CPlusPlus && pty->getKind() == BuiltinType::Overload) {
15810 // We can't actually test that if we still have a placeholder,
15811 // though. Fortunately, none of the exceptions we see in that
15812 // code below are valid when the LHS is an overload set. Note
15813 // that an overload set can be dependently-typed, but it never
15814 // instantiates to having an overloadable type.
15815 ExprResult resolvedRHS = CheckPlaceholderExpr(RHSExpr);
15816 if (resolvedRHS.isInvalid()) return ExprError();
15817 RHSExpr = resolvedRHS.get();
15818
15819 if (RHSExpr->isTypeDependent() ||
15820 RHSExpr->getType()->isOverloadableType())
15821 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
15822 }
15823
15824 // If we're instantiating "a.x < b" or "A::x < b" and 'x' names a function
15825 // template, diagnose the missing 'template' keyword instead of diagnosing
15826 // an invalid use of a bound member function.
15827 //
15828 // Note that "A::x < b" might be valid if 'b' has an overloadable type due
15829 // to C++1z [over.over]/1.4, but we already checked for that case above.
15830 if (Opc == BO_LT && inTemplateInstantiation() &&
15831 (pty->getKind() == BuiltinType::BoundMember ||
15832 pty->getKind() == BuiltinType::Overload)) {
15833 auto *OE = dyn_cast<OverloadExpr>(LHSExpr);
15834 if (OE && !OE->hasTemplateKeyword() && !OE->hasExplicitTemplateArgs() &&
15835 llvm::any_of(OE->decls(), [](NamedDecl *ND) {
15836 return isa<FunctionTemplateDecl>(ND);
15837 })) {
15838 Diag(OE->getQualifier() ? OE->getQualifierLoc().getBeginLoc()
15839 : OE->getNameLoc(),
15840 diag::err_template_kw_missing)
15841 << OE->getName().getAsString() << "";
15842 return ExprError();
15843 }
15844 }
15845
15846 ExprResult LHS = CheckPlaceholderExpr(LHSExpr);
15847 if (LHS.isInvalid()) return ExprError();
15848 LHSExpr = LHS.get();
15849 }
15850
15851 // Handle pseudo-objects in the RHS.
15852 if (const BuiltinType *pty = RHSExpr->getType()->getAsPlaceholderType()) {
15853 // An overload in the RHS can potentially be resolved by the type
15854 // being assigned to.
15855 if (Opc == BO_Assign && pty->getKind() == BuiltinType::Overload) {
15856 if (getLangOpts().CPlusPlus &&
15857 (LHSExpr->isTypeDependent() || RHSExpr->isTypeDependent() ||
15858 LHSExpr->getType()->isOverloadableType()))
15859 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
15860
15861 return CreateBuiltinBinOp(OpLoc, Opc, LHSExpr, RHSExpr);
15862 }
15863
15864 // Don't resolve overloads if the other type is overloadable.
15865 if (getLangOpts().CPlusPlus && pty->getKind() == BuiltinType::Overload &&
15866 LHSExpr->getType()->isOverloadableType())
15867 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
15868
15869 ExprResult resolvedRHS = CheckPlaceholderExpr(RHSExpr);
15870 if (!resolvedRHS.isUsable()) return ExprError();
15871 RHSExpr = resolvedRHS.get();
15872 }
15873
15874 if (getLangOpts().CPlusPlus) {
15875 // If either expression is type-dependent, always build an
15876 // overloaded op.
15877 if (LHSExpr->isTypeDependent() || RHSExpr->isTypeDependent())
15878 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
15879
15880 // Otherwise, build an overloaded op if either expression has an
15881 // overloadable type.
15882 if (LHSExpr->getType()->isOverloadableType() ||
15883 RHSExpr->getType()->isOverloadableType())
15884 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
15885 }
15886
15887 if (getLangOpts().RecoveryAST &&
15888 (LHSExpr->isTypeDependent() || RHSExpr->isTypeDependent())) {
15889 assert(!getLangOpts().CPlusPlus)(static_cast <bool> (!getLangOpts().CPlusPlus) ? void (
0) : __assert_fail ("!getLangOpts().CPlusPlus", "clang/lib/Sema/SemaExpr.cpp"
, 15889, __extension__ __PRETTY_FUNCTION__))
;
15890 assert((LHSExpr->containsErrors() || RHSExpr->containsErrors()) &&(static_cast <bool> ((LHSExpr->containsErrors() || RHSExpr
->containsErrors()) && "Should only occur in error-recovery path."
) ? void (0) : __assert_fail ("(LHSExpr->containsErrors() || RHSExpr->containsErrors()) && \"Should only occur in error-recovery path.\""
, "clang/lib/Sema/SemaExpr.cpp", 15891, __extension__ __PRETTY_FUNCTION__
))
15891 "Should only occur in error-recovery path.")(static_cast <bool> ((LHSExpr->containsErrors() || RHSExpr
->containsErrors()) && "Should only occur in error-recovery path."
) ? void (0) : __assert_fail ("(LHSExpr->containsErrors() || RHSExpr->containsErrors()) && \"Should only occur in error-recovery path.\""
, "clang/lib/Sema/SemaExpr.cpp", 15891, __extension__ __PRETTY_FUNCTION__
))
;
15892 if (BinaryOperator::isCompoundAssignmentOp(Opc))
15893 // C [6.15.16] p3:
15894 // An assignment expression has the value of the left operand after the
15895 // assignment, but is not an lvalue.
15896 return CompoundAssignOperator::Create(
15897 Context, LHSExpr, RHSExpr, Opc,
15898 LHSExpr->getType().getUnqualifiedType(), VK_PRValue, OK_Ordinary,
15899 OpLoc, CurFPFeatureOverrides());
15900 QualType ResultType;
15901 switch (Opc) {
15902 case BO_Assign:
15903 ResultType = LHSExpr->getType().getUnqualifiedType();
15904 break;
15905 case BO_LT:
15906 case BO_GT:
15907 case BO_LE:
15908 case BO_GE:
15909 case BO_EQ:
15910 case BO_NE:
15911 case BO_LAnd:
15912 case BO_LOr:
15913 // These operators have a fixed result type regardless of operands.
15914 ResultType = Context.IntTy;
15915 break;
15916 case BO_Comma:
15917 ResultType = RHSExpr->getType();
15918 break;
15919 default:
15920 ResultType = Context.DependentTy;
15921 break;
15922 }
15923 return BinaryOperator::Create(Context, LHSExpr, RHSExpr, Opc, ResultType,
15924 VK_PRValue, OK_Ordinary, OpLoc,
15925 CurFPFeatureOverrides());
15926 }
15927
15928 // Build a built-in binary operation.
15929 return CreateBuiltinBinOp(OpLoc, Opc, LHSExpr, RHSExpr);
15930}
15931
15932static bool isOverflowingIntegerType(ASTContext &Ctx, QualType T) {
15933 if (T.isNull() || T->isDependentType())
15934 return false;
15935
15936 if (!Ctx.isPromotableIntegerType(T))
15937 return true;
15938
15939 return Ctx.getIntWidth(T) >= Ctx.getIntWidth(Ctx.IntTy);
15940}
15941
15942ExprResult Sema::CreateBuiltinUnaryOp(SourceLocation OpLoc,
15943 UnaryOperatorKind Opc, Expr *InputExpr,
15944 bool IsAfterAmp) {
15945 ExprResult Input = InputExpr;
15946 ExprValueKind VK = VK_PRValue;
15947 ExprObjectKind OK = OK_Ordinary;
15948 QualType resultType;
15949 bool CanOverflow = false;
15950
15951 bool ConvertHalfVec = false;
15952 if (getLangOpts().OpenCL) {
15953 QualType Ty = InputExpr->getType();
15954 // The only legal unary operation for atomics is '&'.
15955 if ((Opc != UO_AddrOf && Ty->isAtomicType()) ||
15956 // OpenCL special types - image, sampler, pipe, and blocks are to be used
15957 // only with a builtin functions and therefore should be disallowed here.
15958 (Ty->isImageType() || Ty->isSamplerT() || Ty->isPipeType()
15959 || Ty->isBlockPointerType())) {
15960 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
15961 << InputExpr->getType()
15962 << Input.get()->getSourceRange());
15963 }
15964 }
15965
15966 if (getLangOpts().HLSL && OpLoc.isValid()) {
15967 if (Opc == UO_AddrOf)
15968 return ExprError(Diag(OpLoc, diag::err_hlsl_operator_unsupported) << 0);
15969 if (Opc == UO_Deref)
15970 return ExprError(Diag(OpLoc, diag::err_hlsl_operator_unsupported) << 1);
15971 }
15972
15973 switch (Opc) {
15974 case UO_PreInc:
15975 case UO_PreDec:
15976 case UO_PostInc:
15977 case UO_PostDec:
15978 resultType = CheckIncrementDecrementOperand(*this, Input.get(), VK, OK,
15979 OpLoc,
15980 Opc == UO_PreInc ||
15981 Opc == UO_PostInc,
15982 Opc == UO_PreInc ||
15983 Opc == UO_PreDec);
15984 CanOverflow = isOverflowingIntegerType(Context, resultType);
15985 break;
15986 case UO_AddrOf:
15987 resultType = CheckAddressOfOperand(Input, OpLoc);
15988 CheckAddressOfNoDeref(InputExpr);
15989 RecordModifiableNonNullParam(*this, InputExpr);
15990 break;
15991 case UO_Deref: {
15992 Input = DefaultFunctionArrayLvalueConversion(Input.get());
15993 if (Input.isInvalid()) return ExprError();
15994 resultType =
15995 CheckIndirectionOperand(*this, Input.get(), VK, OpLoc, IsAfterAmp);
15996 break;
15997 }
15998 case UO_Plus:
15999 case UO_Minus:
16000 CanOverflow = Opc == UO_Minus &&
16001 isOverflowingIntegerType(Context, Input.get()->getType());
16002 Input = UsualUnaryConversions(Input.get());
16003 if (Input.isInvalid()) return ExprError();
16004 // Unary plus and minus require promoting an operand of half vector to a
16005 // float vector and truncating the result back to a half vector. For now, we
16006 // do this only when HalfArgsAndReturns is set (that is, when the target is
16007 // arm or arm64).
16008 ConvertHalfVec = needsConversionOfHalfVec(true, Context, Input.get());
16009
16010 // If the operand is a half vector, promote it to a float vector.
16011 if (ConvertHalfVec)
16012 Input = convertVector(Input.get(), Context.FloatTy, *this);
16013 resultType = Input.get()->getType();
16014 if (resultType->isDependentType())
16015 break;
16016 if (resultType->isArithmeticType()) // C99 6.5.3.3p1
16017 break;
16018 else if (resultType->isVectorType() &&
16019 // The z vector extensions don't allow + or - with bool vectors.
16020 (!Context.getLangOpts().ZVector ||
16021 resultType->castAs<VectorType>()->getVectorKind() !=
16022 VectorType::AltiVecBool))
16023 break;
16024 else if (resultType->isVLSTBuiltinType()) // SVE vectors allow + and -
16025 break;
16026 else if (getLangOpts().CPlusPlus && // C++ [expr.unary.op]p6
16027 Opc == UO_Plus &&
16028 resultType->isPointerType())
16029 break;
16030
16031 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
16032 << resultType << Input.get()->getSourceRange());
16033
16034 case UO_Not: // bitwise complement
16035 Input = UsualUnaryConversions(Input.get());
16036 if (Input.isInvalid())
16037 return ExprError();
16038 resultType = Input.get()->getType();
16039 if (resultType->isDependentType())
16040 break;
16041 // C99 6.5.3.3p1. We allow complex int and float as a GCC extension.
16042 if (resultType->isComplexType() || resultType->isComplexIntegerType())
16043 // C99 does not support '~' for complex conjugation.
16044 Diag(OpLoc, diag::ext_integer_complement_complex)
16045 << resultType << Input.get()->getSourceRange();
16046 else if (resultType->hasIntegerRepresentation())
16047 break;
16048 else if (resultType->isExtVectorType() && Context.getLangOpts().OpenCL) {
16049 // OpenCL v1.1 s6.3.f: The bitwise operator not (~) does not operate
16050 // on vector float types.
16051 QualType T = resultType->castAs<ExtVectorType>()->getElementType();
16052 if (!T->isIntegerType())
16053 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
16054 << resultType << Input.get()->getSourceRange());
16055 } else {
16056 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
16057 << resultType << Input.get()->getSourceRange());
16058 }
16059 break;
16060
16061 case UO_LNot: // logical negation
16062 // Unlike +/-/~, integer promotions aren't done here (C99 6.5.3.3p5).
16063 Input = DefaultFunctionArrayLvalueConversion(Input.get());
16064 if (Input.isInvalid()) return ExprError();
16065 resultType = Input.get()->getType();
16066
16067 // Though we still have to promote half FP to float...
16068 if (resultType->isHalfType() && !Context.getLangOpts().NativeHalfType) {
16069 Input = ImpCastExprToType(Input.get(), Context.FloatTy, CK_FloatingCast).get();
16070 resultType = Context.FloatTy;
16071 }
16072
16073 if (resultType->isDependentType())
16074 break;
16075 if (resultType->isScalarType() && !isScopedEnumerationType(resultType)) {
16076 // C99 6.5.3.3p1: ok, fallthrough;
16077 if (Context.getLangOpts().CPlusPlus) {
16078 // C++03 [expr.unary.op]p8, C++0x [expr.unary.op]p9:
16079 // operand contextually converted to bool.
16080 Input = ImpCastExprToType(Input.get(), Context.BoolTy,
16081 ScalarTypeToBooleanCastKind(resultType));
16082 } else if (Context.getLangOpts().OpenCL &&
16083 Context.getLangOpts().OpenCLVersion < 120) {
16084 // OpenCL v1.1 6.3.h: The logical operator not (!) does not
16085 // operate on scalar float types.
16086 if (!resultType->isIntegerType() && !resultType->isPointerType())
16087 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
16088 << resultType << Input.get()->getSourceRange());
16089 }
16090 } else if (resultType->isExtVectorType()) {
16091 if (Context.getLangOpts().OpenCL &&
16092 Context.getLangOpts().getOpenCLCompatibleVersion() < 120) {
16093 // OpenCL v1.1 6.3.h: The logical operator not (!) does not
16094 // operate on vector float types.
16095 QualType T = resultType->castAs<ExtVectorType>()->getElementType();
16096 if (!T->isIntegerType())
16097 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
16098 << resultType << Input.get()->getSourceRange());
16099 }
16100 // Vector logical not returns the signed variant of the operand type.
16101 resultType = GetSignedVectorType(resultType);
16102 break;
16103 } else if (Context.getLangOpts().CPlusPlus && resultType->isVectorType()) {
16104 const VectorType *VTy = resultType->castAs<VectorType>();
16105 if (VTy->getVectorKind() != VectorType::GenericVector)
16106 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
16107 << resultType << Input.get()->getSourceRange());
16108
16109 // Vector logical not returns the signed variant of the operand type.
16110 resultType = GetSignedVectorType(resultType);
16111 break;
16112 } else {
16113 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
16114 << resultType << Input.get()->getSourceRange());
16115 }
16116
16117 // LNot always has type int. C99 6.5.3.3p5.
16118 // In C++, it's bool. C++ 5.3.1p8
16119 resultType = Context.getLogicalOperationType();
16120 break;
16121 case UO_Real:
16122 case UO_Imag:
16123 resultType = CheckRealImagOperand(*this, Input, OpLoc, Opc == UO_Real);
16124 // _Real maps ordinary l-values into ordinary l-values. _Imag maps ordinary
16125 // complex l-values to ordinary l-values and all other values to r-values.
16126 if (Input.isInvalid()) return ExprError();
16127 if (Opc == UO_Real || Input.get()->getType()->isAnyComplexType()) {
16128 if (Input.get()->isGLValue() &&
16129 Input.get()->getObjectKind() == OK_Ordinary)
16130 VK = Input.get()->getValueKind();
16131 } else if (!getLangOpts().CPlusPlus) {
16132 // In C, a volatile scalar is read by __imag. In C++, it is not.
16133 Input = DefaultLvalueConversion(Input.get());
16134 }
16135 break;
16136 case UO_Extension:
16137 resultType = Input.get()->getType();
16138 VK = Input.get()->getValueKind();
16139 OK = Input.get()->getObjectKind();
16140 break;
16141 case UO_Coawait:
16142 // It's unnecessary to represent the pass-through operator co_await in the
16143 // AST; just return the input expression instead.
16144 assert(!Input.get()->getType()->isDependentType() &&(static_cast <bool> (!Input.get()->getType()->isDependentType
() && "the co_await expression must be non-dependant before "
"building operator co_await") ? void (0) : __assert_fail ("!Input.get()->getType()->isDependentType() && \"the co_await expression must be non-dependant before \" \"building operator co_await\""
, "clang/lib/Sema/SemaExpr.cpp", 16146, __extension__ __PRETTY_FUNCTION__
))
16145 "the co_await expression must be non-dependant before "(static_cast <bool> (!Input.get()->getType()->isDependentType
() && "the co_await expression must be non-dependant before "
"building operator co_await") ? void (0) : __assert_fail ("!Input.get()->getType()->isDependentType() && \"the co_await expression must be non-dependant before \" \"building operator co_await\""
, "clang/lib/Sema/SemaExpr.cpp", 16146, __extension__ __PRETTY_FUNCTION__
))
16146 "building operator co_await")(static_cast <bool> (!Input.get()->getType()->isDependentType
() && "the co_await expression must be non-dependant before "
"building operator co_await") ? void (0) : __assert_fail ("!Input.get()->getType()->isDependentType() && \"the co_await expression must be non-dependant before \" \"building operator co_await\""
, "clang/lib/Sema/SemaExpr.cpp", 16146, __extension__ __PRETTY_FUNCTION__
))
;
16147 return Input;
16148 }
16149 if (resultType.isNull() || Input.isInvalid())
16150 return ExprError();
16151
16152 // Check for array bounds violations in the operand of the UnaryOperator,
16153 // except for the '*' and '&' operators that have to be handled specially
16154 // by CheckArrayAccess (as there are special cases like &array[arraysize]
16155 // that are explicitly defined as valid by the standard).
16156 if (Opc != UO_AddrOf && Opc != UO_Deref)
16157 CheckArrayAccess(Input.get());
16158
16159 auto *UO =
16160 UnaryOperator::Create(Context, Input.get(), Opc, resultType, VK, OK,
16161 OpLoc, CanOverflow, CurFPFeatureOverrides());
16162
16163 if (Opc == UO_Deref && UO->getType()->hasAttr(attr::NoDeref) &&
16164 !isa<ArrayType>(UO->getType().getDesugaredType(Context)) &&
16165 !isUnevaluatedContext())
16166 ExprEvalContexts.back().PossibleDerefs.insert(UO);
16167
16168 // Convert the result back to a half vector.
16169 if (ConvertHalfVec)
16170 return convertVector(UO, Context.HalfTy, *this);
16171 return UO;
16172}
16173
16174/// Determine whether the given expression is a qualified member
16175/// access expression, of a form that could be turned into a pointer to member
16176/// with the address-of operator.
16177bool Sema::isQualifiedMemberAccess(Expr *E) {
16178 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
16179 if (!DRE->getQualifier())
16180 return false;
16181
16182 ValueDecl *VD = DRE->getDecl();
16183 if (!VD->isCXXClassMember())
16184 return false;
16185
16186 if (isa<FieldDecl>(VD) || isa<IndirectFieldDecl>(VD))
16187 return true;
16188 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(VD))
16189 return Method->isInstance();
16190
16191 return false;
16192 }
16193
16194 if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(E)) {
16195 if (!ULE->getQualifier())
16196 return false;
16197
16198 for (NamedDecl *D : ULE->decls()) {
16199 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) {
16200 if (Method->isInstance())
16201 return true;
16202 } else {
16203 // Overload set does not contain methods.
16204 break;
16205 }
16206 }
16207
16208 return false;
16209 }
16210
16211 return false;
16212}
16213
16214ExprResult Sema::BuildUnaryOp(Scope *S, SourceLocation OpLoc,
16215 UnaryOperatorKind Opc, Expr *Input,
16216 bool IsAfterAmp) {
16217 // First things first: handle placeholders so that the
16218 // overloaded-operator check considers the right type.
16219 if (const BuiltinType *pty = Input->getType()->getAsPlaceholderType()) {
16220 // Increment and decrement of pseudo-object references.
16221 if (pty->getKind() == BuiltinType::PseudoObject &&
16222 UnaryOperator::isIncrementDecrementOp(Opc))
16223 return checkPseudoObjectIncDec(S, OpLoc, Opc, Input);
16224
16225 // extension is always a builtin operator.
16226 if (Opc == UO_Extension)
16227 return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
16228
16229 // & gets special logic for several kinds of placeholder.
16230 // The builtin code knows what to do.
16231 if (Opc == UO_AddrOf &&
16232 (pty->getKind() == BuiltinType::Overload ||
16233 pty->getKind() == BuiltinType::UnknownAny ||
16234 pty->getKind() == BuiltinType::BoundMember))
16235 return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
16236
16237 // Anything else needs to be handled now.
16238 ExprResult Result = CheckPlaceholderExpr(Input);
16239 if (Result.isInvalid()) return ExprError();
16240 Input = Result.get();
16241 }
16242
16243 if (getLangOpts().CPlusPlus && Input->getType()->isOverloadableType() &&
16244 UnaryOperator::getOverloadedOperator(Opc) != OO_None &&
16245 !(Opc == UO_AddrOf && isQualifiedMemberAccess(Input))) {
16246 // Find all of the overloaded operators visible from this point.
16247 UnresolvedSet<16> Functions;
16248 OverloadedOperatorKind OverOp = UnaryOperator::getOverloadedOperator(Opc);
16249 if (S && OverOp != OO_None)
16250 LookupOverloadedOperatorName(OverOp, S, Functions);
16251
16252 return CreateOverloadedUnaryOp(OpLoc, Opc, Functions, Input);
16253 }
16254
16255 return CreateBuiltinUnaryOp(OpLoc, Opc, Input, IsAfterAmp);
16256}
16257
16258// Unary Operators. 'Tok' is the token for the operator.
16259ExprResult Sema::ActOnUnaryOp(Scope *S, SourceLocation OpLoc, tok::TokenKind Op,
16260 Expr *Input, bool IsAfterAmp) {
16261 return BuildUnaryOp(S, OpLoc, ConvertTokenKindToUnaryOpcode(Op), Input,
16262 IsAfterAmp);
16263}
16264
16265/// ActOnAddrLabel - Parse the GNU address of label extension: "&&foo".
16266ExprResult Sema::ActOnAddrLabel(SourceLocation OpLoc, SourceLocation LabLoc,
16267 LabelDecl *TheDecl) {
16268 TheDecl->markUsed(Context);
16269 // Create the AST node. The address of a label always has type 'void*'.
16270 auto *Res = new (Context) AddrLabelExpr(
16271 OpLoc, LabLoc, TheDecl, Context.getPointerType(Context.VoidTy));
16272
16273 if (getCurFunction())
16274 getCurFunction()->AddrLabels.push_back(Res);
16275
16276 return Res;
16277}
16278
16279void Sema::ActOnStartStmtExpr() {
16280 PushExpressionEvaluationContext(ExprEvalContexts.back().Context);
16281}
16282
16283void Sema::ActOnStmtExprError() {
16284 // Note that function is also called by TreeTransform when leaving a
16285 // StmtExpr scope without rebuilding anything.
16286
16287 DiscardCleanupsInEvaluationContext();
16288 PopExpressionEvaluationContext();
16289}
16290
16291ExprResult Sema::ActOnStmtExpr(Scope *S, SourceLocation LPLoc, Stmt *SubStmt,
16292 SourceLocation RPLoc) {
16293 return BuildStmtExpr(LPLoc, SubStmt, RPLoc, getTemplateDepth(S));
16294}
16295
16296ExprResult Sema::BuildStmtExpr(SourceLocation LPLoc, Stmt *SubStmt,
16297 SourceLocation RPLoc, unsigned TemplateDepth) {
16298 assert(SubStmt && isa<CompoundStmt>(SubStmt) && "Invalid action invocation!")(static_cast <bool> (SubStmt && isa<CompoundStmt
>(SubStmt) && "Invalid action invocation!") ? void
(0) : __assert_fail ("SubStmt && isa<CompoundStmt>(SubStmt) && \"Invalid action invocation!\""
, "clang/lib/Sema/SemaExpr.cpp", 16298, __extension__ __PRETTY_FUNCTION__
))
;
16299 CompoundStmt *Compound = cast<CompoundStmt>(SubStmt);
16300
16301 if (hasAnyUnrecoverableErrorsInThisFunction())
16302 DiscardCleanupsInEvaluationContext();
16303 assert(!Cleanup.exprNeedsCleanups() &&(static_cast <bool> (!Cleanup.exprNeedsCleanups() &&
"cleanups within StmtExpr not correctly bound!") ? void (0) :
__assert_fail ("!Cleanup.exprNeedsCleanups() && \"cleanups within StmtExpr not correctly bound!\""
, "clang/lib/Sema/SemaExpr.cpp", 16304, __extension__ __PRETTY_FUNCTION__
))
16304 "cleanups within StmtExpr not correctly bound!")(static_cast <bool> (!Cleanup.exprNeedsCleanups() &&
"cleanups within StmtExpr not correctly bound!") ? void (0) :
__assert_fail ("!Cleanup.exprNeedsCleanups() && \"cleanups within StmtExpr not correctly bound!\""
, "clang/lib/Sema/SemaExpr.cpp", 16304, __extension__ __PRETTY_FUNCTION__
))
;
16305 PopExpressionEvaluationContext();
16306
16307 // FIXME: there are a variety of strange constraints to enforce here, for
16308 // example, it is not possible to goto into a stmt expression apparently.
16309 // More semantic analysis is needed.
16310
16311 // If there are sub-stmts in the compound stmt, take the type of the last one
16312 // as the type of the stmtexpr.
16313 QualType Ty = Context.VoidTy;
16314 bool StmtExprMayBindToTemp = false;
16315 if (!Compound->body_empty()) {
16316 // For GCC compatibility we get the last Stmt excluding trailing NullStmts.
16317 if (const auto *LastStmt =
16318 dyn_cast<ValueStmt>(Compound->getStmtExprResult())) {
16319 if (const Expr *Value = LastStmt->getExprStmt()) {
16320 StmtExprMayBindToTemp = true;
16321 Ty = Value->getType();
16322 }
16323 }
16324 }
16325
16326 // FIXME: Check that expression type is complete/non-abstract; statement
16327 // expressions are not lvalues.
16328 Expr *ResStmtExpr =
16329 new (Context) StmtExpr(Compound, Ty, LPLoc, RPLoc, TemplateDepth);
16330 if (StmtExprMayBindToTemp)
16331 return MaybeBindToTemporary(ResStmtExpr);
16332 return ResStmtExpr;
16333}
16334
16335ExprResult Sema::ActOnStmtExprResult(ExprResult ER) {
16336 if (ER.isInvalid())
16337 return ExprError();
16338
16339 // Do function/array conversion on the last expression, but not
16340 // lvalue-to-rvalue. However, initialize an unqualified type.
16341 ER = DefaultFunctionArrayConversion(ER.get());
16342 if (ER.isInvalid())
16343 return ExprError();
16344 Expr *E = ER.get();
16345
16346 if (E->isTypeDependent())
16347 return E;
16348
16349 // In ARC, if the final expression ends in a consume, splice
16350 // the consume out and bind it later. In the alternate case
16351 // (when dealing with a retainable type), the result
16352 // initialization will create a produce. In both cases the
16353 // result will be +1, and we'll need to balance that out with
16354 // a bind.
16355 auto *Cast = dyn_cast<ImplicitCastExpr>(E);
16356 if (Cast && Cast->getCastKind() == CK_ARCConsumeObject)
16357 return Cast->getSubExpr();
16358
16359 // FIXME: Provide a better location for the initialization.
16360 return PerformCopyInitialization(
16361 InitializedEntity::InitializeStmtExprResult(
16362 E->getBeginLoc(), E->getType().getUnqualifiedType()),
16363 SourceLocation(), E);
16364}
16365
16366ExprResult Sema::BuildBuiltinOffsetOf(SourceLocation BuiltinLoc,
16367 TypeSourceInfo *TInfo,
16368 ArrayRef<OffsetOfComponent> Components,
16369 SourceLocation RParenLoc) {
16370 QualType ArgTy = TInfo->getType();
16371 bool Dependent = ArgTy->isDependentType();
16372 SourceRange TypeRange = TInfo->getTypeLoc().getLocalSourceRange();
16373
16374 // We must have at least one component that refers to the type, and the first
16375 // one is known to be a field designator. Verify that the ArgTy represents
16376 // a struct/union/class.
16377 if (!Dependent && !ArgTy->isRecordType())
16378 return ExprError(Diag(BuiltinLoc, diag::err_offsetof_record_type)
16379 << ArgTy << TypeRange);
16380
16381 // Type must be complete per C99 7.17p3 because a declaring a variable
16382 // with an incomplete type would be ill-formed.
16383 if (!Dependent
16384 && RequireCompleteType(BuiltinLoc, ArgTy,
16385 diag::err_offsetof_incomplete_type, TypeRange))
16386 return ExprError();
16387
16388 bool DidWarnAboutNonPOD = false;
16389 QualType CurrentType = ArgTy;
16390 SmallVector<OffsetOfNode, 4> Comps;
16391 SmallVector<Expr*, 4> Exprs;
16392 for (const OffsetOfComponent &OC : Components) {
16393 if (OC.isBrackets) {
16394 // Offset of an array sub-field. TODO: Should we allow vector elements?
16395 if (!CurrentType->isDependentType()) {
16396 const ArrayType *AT = Context.getAsArrayType(CurrentType);
16397 if(!AT)
16398 return ExprError(Diag(OC.LocEnd, diag::err_offsetof_array_type)
16399 << CurrentType);
16400 CurrentType = AT->getElementType();
16401 } else
16402 CurrentType = Context.DependentTy;
16403
16404 ExprResult IdxRval = DefaultLvalueConversion(static_cast<Expr*>(OC.U.E));
16405 if (IdxRval.isInvalid())
16406 return ExprError();
16407 Expr *Idx = IdxRval.get();
16408
16409 // The expression must be an integral expression.
16410 // FIXME: An integral constant expression?
16411 if (!Idx->isTypeDependent() && !Idx->isValueDependent() &&
16412 !Idx->getType()->isIntegerType())
16413 return ExprError(
16414 Diag(Idx->getBeginLoc(), diag::err_typecheck_subscript_not_integer)
16415 << Idx->getSourceRange());
16416
16417 // Record this array index.
16418 Comps.push_back(OffsetOfNode(OC.LocStart, Exprs.size(), OC.LocEnd));
16419 Exprs.push_back(Idx);
16420 continue;
16421 }
16422
16423 // Offset of a field.
16424 if (CurrentType->isDependentType()) {
16425 // We have the offset of a field, but we can't look into the dependent
16426 // type. Just record the identifier of the field.
16427 Comps.push_back(OffsetOfNode(OC.LocStart, OC.U.IdentInfo, OC.LocEnd));
16428 CurrentType = Context.DependentTy;
16429 continue;
16430 }
16431
16432 // We need to have a complete type to look into.
16433 if (RequireCompleteType(OC.LocStart, CurrentType,
16434 diag::err_offsetof_incomplete_type))
16435 return ExprError();
16436
16437 // Look for the designated field.
16438 const RecordType *RC = CurrentType->getAs<RecordType>();
16439 if (!RC)
16440 return ExprError(Diag(OC.LocEnd, diag::err_offsetof_record_type)
16441 << CurrentType);
16442 RecordDecl *RD = RC->getDecl();
16443
16444 // C++ [lib.support.types]p5:
16445 // The macro offsetof accepts a restricted set of type arguments in this
16446 // International Standard. type shall be a POD structure or a POD union
16447 // (clause 9).
16448 // C++11 [support.types]p4:
16449 // If type is not a standard-layout class (Clause 9), the results are
16450 // undefined.
16451 if (CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) {
16452 bool IsSafe = LangOpts.CPlusPlus11? CRD->isStandardLayout() : CRD->isPOD();
16453 unsigned DiagID =
16454 LangOpts.CPlusPlus11? diag::ext_offsetof_non_standardlayout_type
16455 : diag::ext_offsetof_non_pod_type;
16456
16457 if (!IsSafe && !DidWarnAboutNonPOD &&
16458 DiagRuntimeBehavior(BuiltinLoc, nullptr,
16459 PDiag(DiagID)
16460 << SourceRange(Components[0].LocStart, OC.LocEnd)
16461 << CurrentType))
16462 DidWarnAboutNonPOD = true;
16463 }
16464
16465 // Look for the field.
16466 LookupResult R(*this, OC.U.IdentInfo, OC.LocStart, LookupMemberName);
16467 LookupQualifiedName(R, RD);
16468 FieldDecl *MemberDecl = R.getAsSingle<FieldDecl>();
16469 IndirectFieldDecl *IndirectMemberDecl = nullptr;
16470 if (!MemberDecl) {
16471 if ((IndirectMemberDecl = R.getAsSingle<IndirectFieldDecl>()))
16472 MemberDecl = IndirectMemberDecl->getAnonField();
16473 }
16474
16475 if (!MemberDecl)
16476 return ExprError(Diag(BuiltinLoc, diag::err_no_member)
16477 << OC.U.IdentInfo << RD << SourceRange(OC.LocStart,
16478 OC.LocEnd));
16479
16480 // C99 7.17p3:
16481 // (If the specified member is a bit-field, the behavior is undefined.)
16482 //
16483 // We diagnose this as an error.
16484 if (MemberDecl->isBitField()) {
16485 Diag(OC.LocEnd, diag::err_offsetof_bitfield)
16486 << MemberDecl->getDeclName()
16487 << SourceRange(BuiltinLoc, RParenLoc);
16488 Diag(MemberDecl->getLocation(), diag::note_bitfield_decl);
16489 return ExprError();
16490 }
16491
16492 RecordDecl *Parent = MemberDecl->getParent();
16493 if (IndirectMemberDecl)
16494 Parent = cast<RecordDecl>(IndirectMemberDecl->getDeclContext());
16495
16496 // If the member was found in a base class, introduce OffsetOfNodes for
16497 // the base class indirections.
16498 CXXBasePaths Paths;
16499 if (IsDerivedFrom(OC.LocStart, CurrentType, Context.getTypeDeclType(Parent),
16500 Paths)) {
16501 if (Paths.getDetectedVirtual()) {
16502 Diag(OC.LocEnd, diag::err_offsetof_field_of_virtual_base)
16503 << MemberDecl->getDeclName()
16504 << SourceRange(BuiltinLoc, RParenLoc);
16505 return ExprError();
16506 }
16507
16508 CXXBasePath &Path = Paths.front();
16509 for (const CXXBasePathElement &B : Path)
16510 Comps.push_back(OffsetOfNode(B.Base));
16511 }
16512
16513 if (IndirectMemberDecl) {
16514 for (auto *FI : IndirectMemberDecl->chain()) {
16515 assert(isa<FieldDecl>(FI))(static_cast <bool> (isa<FieldDecl>(FI)) ? void (
0) : __assert_fail ("isa<FieldDecl>(FI)", "clang/lib/Sema/SemaExpr.cpp"
, 16515, __extension__ __PRETTY_FUNCTION__))
;
16516 Comps.push_back(OffsetOfNode(OC.LocStart,
16517 cast<FieldDecl>(FI), OC.LocEnd));
16518 }
16519 } else
16520 Comps.push_back(OffsetOfNode(OC.LocStart, MemberDecl, OC.LocEnd));
16521
16522 CurrentType = MemberDecl->getType().getNonReferenceType();
16523 }
16524
16525 return OffsetOfExpr::Create(Context, Context.getSizeType(), BuiltinLoc, TInfo,
16526 Comps, Exprs, RParenLoc);
16527}
16528
16529ExprResult Sema::ActOnBuiltinOffsetOf(Scope *S,
16530 SourceLocation BuiltinLoc,
16531 SourceLocation TypeLoc,
16532 ParsedType ParsedArgTy,
16533 ArrayRef<OffsetOfComponent> Components,
16534 SourceLocation RParenLoc) {
16535
16536 TypeSourceInfo *ArgTInfo;
16537 QualType ArgTy = GetTypeFromParser(ParsedArgTy, &ArgTInfo);
16538 if (ArgTy.isNull())
16539 return ExprError();
16540
16541 if (!ArgTInfo)
16542 ArgTInfo = Context.getTrivialTypeSourceInfo(ArgTy, TypeLoc);
16543
16544 return BuildBuiltinOffsetOf(BuiltinLoc, ArgTInfo, Components, RParenLoc);
16545}
16546
16547
16548ExprResult Sema::ActOnChooseExpr(SourceLocation BuiltinLoc,
16549 Expr *CondExpr,
16550 Expr *LHSExpr, Expr *RHSExpr,
16551 SourceLocation RPLoc) {
16552 assert((CondExpr && LHSExpr && RHSExpr) && "Missing type argument(s)")(static_cast <bool> ((CondExpr && LHSExpr &&
RHSExpr) && "Missing type argument(s)") ? void (0) :
__assert_fail ("(CondExpr && LHSExpr && RHSExpr) && \"Missing type argument(s)\""
, "clang/lib/Sema/SemaExpr.cpp", 16552, __extension__ __PRETTY_FUNCTION__
))
;
16553
16554 ExprValueKind VK = VK_PRValue;
16555 ExprObjectKind OK = OK_Ordinary;
16556 QualType resType;
16557 bool CondIsTrue = false;
16558 if (CondExpr->isTypeDependent() || CondExpr->isValueDependent()) {
16559 resType = Context.DependentTy;
16560 } else {
16561 // The conditional expression is required to be a constant expression.
16562 llvm::APSInt condEval(32);
16563 ExprResult CondICE = VerifyIntegerConstantExpression(
16564 CondExpr, &condEval, diag::err_typecheck_choose_expr_requires_constant);
16565 if (CondICE.isInvalid())
16566 return ExprError();
16567 CondExpr = CondICE.get();
16568 CondIsTrue = condEval.getZExtValue();
16569
16570 // If the condition is > zero, then the AST type is the same as the LHSExpr.
16571 Expr *ActiveExpr = CondIsTrue ? LHSExpr : RHSExpr;
16572
16573 resType = ActiveExpr->getType();
16574 VK = ActiveExpr->getValueKind();
16575 OK = ActiveExpr->getObjectKind();
16576 }
16577
16578 return new (Context) ChooseExpr(BuiltinLoc, CondExpr, LHSExpr, RHSExpr,
16579 resType, VK, OK, RPLoc, CondIsTrue);
16580}
16581
16582//===----------------------------------------------------------------------===//
16583// Clang Extensions.
16584//===----------------------------------------------------------------------===//
16585
16586/// ActOnBlockStart - This callback is invoked when a block literal is started.
16587void Sema::ActOnBlockStart(SourceLocation CaretLoc, Scope *CurScope) {
16588 BlockDecl *Block = BlockDecl::Create(Context, CurContext, CaretLoc);
16589
16590 if (LangOpts.CPlusPlus) {
16591 MangleNumberingContext *MCtx;
16592 Decl *ManglingContextDecl;
16593 std::tie(MCtx, ManglingContextDecl) =
16594 getCurrentMangleNumberContext(Block->getDeclContext());
16595 if (MCtx) {
16596 unsigned ManglingNumber = MCtx->getManglingNumber(Block);
16597 Block->setBlockMangling(ManglingNumber, ManglingContextDecl);
16598 }
16599 }
16600
16601 PushBlockScope(CurScope, Block);
16602 CurContext->addDecl(Block);
16603 if (CurScope)
16604 PushDeclContext(CurScope, Block);
16605 else
16606 CurContext = Block;
16607
16608 getCurBlock()->HasImplicitReturnType = true;
16609
16610 // Enter a new evaluation context to insulate the block from any
16611 // cleanups from the enclosing full-expression.
16612 PushExpressionEvaluationContext(
16613 ExpressionEvaluationContext::PotentiallyEvaluated);
16614}
16615
16616void Sema::ActOnBlockArguments(SourceLocation CaretLoc, Declarator &ParamInfo,
16617 Scope *CurScope) {
16618 assert(ParamInfo.getIdentifier() == nullptr &&(static_cast <bool> (ParamInfo.getIdentifier() == nullptr
&& "block-id should have no identifier!") ? void (0)
: __assert_fail ("ParamInfo.getIdentifier() == nullptr && \"block-id should have no identifier!\""
, "clang/lib/Sema/SemaExpr.cpp", 16619, __extension__ __PRETTY_FUNCTION__
))
16619 "block-id should have no identifier!")(static_cast <bool> (ParamInfo.getIdentifier() == nullptr
&& "block-id should have no identifier!") ? void (0)
: __assert_fail ("ParamInfo.getIdentifier() == nullptr && \"block-id should have no identifier!\""
, "clang/lib/Sema/SemaExpr.cpp", 16619, __extension__ __PRETTY_FUNCTION__
))
;
16620 assert(ParamInfo.getContext() == DeclaratorContext::BlockLiteral)(static_cast <bool> (ParamInfo.getContext() == DeclaratorContext
::BlockLiteral) ? void (0) : __assert_fail ("ParamInfo.getContext() == DeclaratorContext::BlockLiteral"
, "clang/lib/Sema/SemaExpr.cpp", 16620, __extension__ __PRETTY_FUNCTION__
))
;
16621 BlockScopeInfo *CurBlock = getCurBlock();
16622
16623 TypeSourceInfo *Sig = GetTypeForDeclarator(ParamInfo, CurScope);
16624 QualType T = Sig->getType();
16625
16626 // FIXME: We should allow unexpanded parameter packs here, but that would,
16627 // in turn, make the block expression contain unexpanded parameter packs.
16628 if (DiagnoseUnexpandedParameterPack(CaretLoc, Sig, UPPC_Block)) {
16629 // Drop the parameters.
16630 FunctionProtoType::ExtProtoInfo EPI;
16631 EPI.HasTrailingReturn = false;
16632 EPI.TypeQuals.addConst();
16633 T = Context.getFunctionType(Context.DependentTy, std::nullopt, EPI);
16634 Sig = Context.getTrivialTypeSourceInfo(T);
16635 }
16636
16637 // GetTypeForDeclarator always produces a function type for a block
16638 // literal signature. Furthermore, it is always a FunctionProtoType
16639 // unless the function was written with a typedef.
16640 assert(T->isFunctionType() &&(static_cast <bool> (T->isFunctionType() && "GetTypeForDeclarator made a non-function block signature"
) ? void (0) : __assert_fail ("T->isFunctionType() && \"GetTypeForDeclarator made a non-function block signature\""
, "clang/lib/Sema/SemaExpr.cpp", 16641, __extension__ __PRETTY_FUNCTION__
))
16641 "GetTypeForDeclarator made a non-function block signature")(static_cast <bool> (T->isFunctionType() && "GetTypeForDeclarator made a non-function block signature"
) ? void (0) : __assert_fail ("T->isFunctionType() && \"GetTypeForDeclarator made a non-function block signature\""
, "clang/lib/Sema/SemaExpr.cpp", 16641, __extension__ __PRETTY_FUNCTION__
))
;
16642
16643 // Look for an explicit signature in that function type.
16644 FunctionProtoTypeLoc ExplicitSignature;
16645
16646 if ((ExplicitSignature = Sig->getTypeLoc()
16647 .getAsAdjusted<FunctionProtoTypeLoc>())) {
16648
16649 // Check whether that explicit signature was synthesized by
16650 // GetTypeForDeclarator. If so, don't save that as part of the
16651 // written signature.
16652 if (ExplicitSignature.getLocalRangeBegin() ==
16653 ExplicitSignature.getLocalRangeEnd()) {
16654 // This would be much cheaper if we stored TypeLocs instead of
16655 // TypeSourceInfos.
16656 TypeLoc Result = ExplicitSignature.getReturnLoc();
16657 unsigned Size = Result.getFullDataSize();
16658 Sig = Context.CreateTypeSourceInfo(Result.getType(), Size);
16659 Sig->getTypeLoc().initializeFullCopy(Result, Size);
16660
16661 ExplicitSignature = FunctionProtoTypeLoc();
16662 }
16663 }
16664
16665 CurBlock->TheDecl->setSignatureAsWritten(Sig);
16666 CurBlock->FunctionType = T;
16667
16668 const auto *Fn = T->castAs<FunctionType>();
16669 QualType RetTy = Fn->getReturnType();
16670 bool isVariadic =
16671 (isa<FunctionProtoType>(Fn) && cast<FunctionProtoType>(Fn)->isVariadic());
16672
16673 CurBlock->TheDecl->setIsVariadic(isVariadic);
16674
16675 // Context.DependentTy is used as a placeholder for a missing block
16676 // return type. TODO: what should we do with declarators like:
16677 // ^ * { ... }
16678 // If the answer is "apply template argument deduction"....
16679 if (RetTy != Context.DependentTy) {
16680 CurBlock->ReturnType = RetTy;
16681 CurBlock->TheDecl->setBlockMissingReturnType(false);
16682 CurBlock->HasImplicitReturnType = false;
16683 }
16684
16685 // Push block parameters from the declarator if we had them.
16686 SmallVector<ParmVarDecl*, 8> Params;
16687 if (ExplicitSignature) {
16688 for (unsigned I = 0, E = ExplicitSignature.getNumParams(); I != E; ++I) {
16689 ParmVarDecl *Param = ExplicitSignature.getParam(I);
16690 if (Param->getIdentifier() == nullptr && !Param->isImplicit() &&
16691 !Param->isInvalidDecl() && !getLangOpts().CPlusPlus) {
16692 // Diagnose this as an extension in C17 and earlier.
16693 if (!getLangOpts().C2x)
16694 Diag(Param->getLocation(), diag::ext_parameter_name_omitted_c2x);
16695 }
16696 Params.push_back(Param);
16697 }
16698
16699 // Fake up parameter variables if we have a typedef, like
16700 // ^ fntype { ... }
16701 } else if (const FunctionProtoType *Fn = T->getAs<FunctionProtoType>()) {
16702 for (const auto &I : Fn->param_types()) {
16703 ParmVarDecl *Param = BuildParmVarDeclForTypedef(
16704 CurBlock->TheDecl, ParamInfo.getBeginLoc(), I);
16705 Params.push_back(Param);
16706 }
16707 }
16708
16709 // Set the parameters on the block decl.
16710 if (!Params.empty()) {
16711 CurBlock->TheDecl->setParams(Params);
16712 CheckParmsForFunctionDef(CurBlock->TheDecl->parameters(),
16713 /*CheckParameterNames=*/false);
16714 }
16715
16716 // Finally we can process decl attributes.
16717 ProcessDeclAttributes(CurScope, CurBlock->TheDecl, ParamInfo);
16718
16719 // Put the parameter variables in scope.
16720 for (auto *AI : CurBlock->TheDecl->parameters()) {
16721 AI->setOwningFunction(CurBlock->TheDecl);
16722
16723 // If this has an identifier, add it to the scope stack.
16724 if (AI->getIdentifier()) {
16725 CheckShadow(CurBlock->TheScope, AI);
16726
16727 PushOnScopeChains(AI, CurBlock->TheScope);
16728 }
16729 }
16730}
16731
16732/// ActOnBlockError - If there is an error parsing a block, this callback
16733/// is invoked to pop the information about the block from the action impl.
16734void Sema::ActOnBlockError(SourceLocation CaretLoc, Scope *CurScope) {
16735 // Leave the expression-evaluation context.
16736 DiscardCleanupsInEvaluationContext();
16737 PopExpressionEvaluationContext();
16738
16739 // Pop off CurBlock, handle nested blocks.
16740 PopDeclContext();
16741 PopFunctionScopeInfo();
16742}
16743
16744/// ActOnBlockStmtExpr - This is called when the body of a block statement
16745/// literal was successfully completed. ^(int x){...}
16746ExprResult Sema::ActOnBlockStmtExpr(SourceLocation CaretLoc,
16747 Stmt *Body, Scope *CurScope) {
16748 // If blocks are disabled, emit an error.
16749 if (!LangOpts.Blocks)
16750 Diag(CaretLoc, diag::err_blocks_disable) << LangOpts.OpenCL;
16751
16752 // Leave the expression-evaluation context.
16753 if (hasAnyUnrecoverableErrorsInThisFunction())
16754 DiscardCleanupsInEvaluationContext();
16755 assert(!Cleanup.exprNeedsCleanups() &&(static_cast <bool> (!Cleanup.exprNeedsCleanups() &&
"cleanups within block not correctly bound!") ? void (0) : __assert_fail
("!Cleanup.exprNeedsCleanups() && \"cleanups within block not correctly bound!\""
, "clang/lib/Sema/SemaExpr.cpp", 16756, __extension__ __PRETTY_FUNCTION__
))
16756 "cleanups within block not correctly bound!")(static_cast <bool> (!Cleanup.exprNeedsCleanups() &&
"cleanups within block not correctly bound!") ? void (0) : __assert_fail
("!Cleanup.exprNeedsCleanups() && \"cleanups within block not correctly bound!\""
, "clang/lib/Sema/SemaExpr.cpp", 16756, __extension__ __PRETTY_FUNCTION__
))
;
16757 PopExpressionEvaluationContext();
16758
16759 BlockScopeInfo *BSI = cast<BlockScopeInfo>(FunctionScopes.back());
16760 BlockDecl *BD = BSI->TheDecl;
16761
16762 if (BSI->HasImplicitReturnType)
16763 deduceClosureReturnType(*BSI);
16764
16765 QualType RetTy = Context.VoidTy;
16766 if (!BSI->ReturnType.isNull())
16767 RetTy = BSI->ReturnType;
16768
16769 bool NoReturn = BD->hasAttr<NoReturnAttr>();
16770 QualType BlockTy;
16771
16772 // If the user wrote a function type in some form, try to use that.
16773 if (!BSI->FunctionType.isNull()) {
16774 const FunctionType *FTy = BSI->FunctionType->castAs<FunctionType>();
16775
16776 FunctionType::ExtInfo Ext = FTy->getExtInfo();
16777 if (NoReturn && !Ext.getNoReturn()) Ext = Ext.withNoReturn(true);
16778
16779 // Turn protoless block types into nullary block types.
16780 if (isa<FunctionNoProtoType>(FTy)) {
16781 FunctionProtoType::ExtProtoInfo EPI;
16782 EPI.ExtInfo = Ext;
16783 BlockTy = Context.getFunctionType(RetTy, std::nullopt, EPI);
16784
16785 // Otherwise, if we don't need to change anything about the function type,
16786 // preserve its sugar structure.
16787 } else if (FTy->getReturnType() == RetTy &&
16788 (!NoReturn || FTy->getNoReturnAttr())) {
16789 BlockTy = BSI->FunctionType;
16790
16791 // Otherwise, make the minimal modifications to the function type.
16792 } else {
16793 const FunctionProtoType *FPT = cast<FunctionProtoType>(FTy);
16794 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
16795 EPI.TypeQuals = Qualifiers();
16796 EPI.ExtInfo = Ext;
16797 BlockTy = Context.getFunctionType(RetTy, FPT->getParamTypes(), EPI);
16798 }
16799
16800 // If we don't have a function type, just build one from nothing.
16801 } else {
16802 FunctionProtoType::ExtProtoInfo EPI;
16803 EPI.ExtInfo = FunctionType::ExtInfo().withNoReturn(NoReturn);
16804 BlockTy = Context.getFunctionType(RetTy, std::nullopt, EPI);
16805 }
16806
16807 DiagnoseUnusedParameters(BD->parameters());
16808 BlockTy = Context.getBlockPointerType(BlockTy);
16809
16810 // If needed, diagnose invalid gotos and switches in the block.
16811 if (getCurFunction()->NeedsScopeChecking() &&
16812 !PP.isCodeCompletionEnabled())
16813 DiagnoseInvalidJumps(cast<CompoundStmt>(Body));
16814
16815 BD->setBody(cast<CompoundStmt>(Body));
16816
16817 if (Body && getCurFunction()->HasPotentialAvailabilityViolations)
16818 DiagnoseUnguardedAvailabilityViolations(BD);
16819
16820 // Try to apply the named return value optimization. We have to check again
16821 // if we can do this, though, because blocks keep return statements around
16822 // to deduce an implicit return type.
16823 if (getLangOpts().CPlusPlus && RetTy->isRecordType() &&
16824 !BD->isDependentContext())
16825 computeNRVO(Body, BSI);
16826
16827 if (RetTy.hasNonTrivialToPrimitiveDestructCUnion() ||
16828 RetTy.hasNonTrivialToPrimitiveCopyCUnion())
16829 checkNonTrivialCUnion(RetTy, BD->getCaretLocation(), NTCUC_FunctionReturn,
16830 NTCUK_Destruct|NTCUK_Copy);
16831
16832 PopDeclContext();
16833
16834 // Set the captured variables on the block.
16835 SmallVector<BlockDecl::Capture, 4> Captures;
16836 for (Capture &Cap : BSI->Captures) {
16837 if (Cap.isInvalid() || Cap.isThisCapture())
16838 continue;
16839 // Cap.getVariable() is always a VarDecl because
16840 // blocks cannot capture structured bindings or other ValueDecl kinds.
16841 auto *Var = cast<VarDecl>(Cap.getVariable());
16842 Expr *CopyExpr = nullptr;
16843 if (getLangOpts().CPlusPlus && Cap.isCopyCapture()) {
16844 if (const RecordType *Record =
16845 Cap.getCaptureType()->getAs<RecordType>()) {
16846 // The capture logic needs the destructor, so make sure we mark it.
16847 // Usually this is unnecessary because most local variables have
16848 // their destructors marked at declaration time, but parameters are
16849 // an exception because it's technically only the call site that
16850 // actually requires the destructor.
16851 if (isa<ParmVarDecl>(Var))
16852 FinalizeVarWithDestructor(Var, Record);
16853
16854 // Enter a separate potentially-evaluated context while building block
16855 // initializers to isolate their cleanups from those of the block
16856 // itself.
16857 // FIXME: Is this appropriate even when the block itself occurs in an
16858 // unevaluated operand?
16859 EnterExpressionEvaluationContext EvalContext(
16860 *this, ExpressionEvaluationContext::PotentiallyEvaluated);
16861
16862 SourceLocation Loc = Cap.getLocation();
16863
16864 ExprResult Result = BuildDeclarationNameExpr(
16865 CXXScopeSpec(), DeclarationNameInfo(Var->getDeclName(), Loc), Var);
16866
16867 // According to the blocks spec, the capture of a variable from
16868 // the stack requires a const copy constructor. This is not true
16869 // of the copy/move done to move a __block variable to the heap.
16870 if (!Result.isInvalid() &&
16871 !Result.get()->getType().isConstQualified()) {
16872 Result = ImpCastExprToType(Result.get(),
16873 Result.get()->getType().withConst(),
16874 CK_NoOp, VK_LValue);
16875 }
16876
16877 if (!Result.isInvalid()) {
16878 Result = PerformCopyInitialization(
16879 InitializedEntity::InitializeBlock(Var->getLocation(),
16880 Cap.getCaptureType()),
16881 Loc, Result.get());
16882 }
16883
16884 // Build a full-expression copy expression if initialization
16885 // succeeded and used a non-trivial constructor. Recover from
16886 // errors by pretending that the copy isn't necessary.
16887 if (!Result.isInvalid() &&
16888 !cast<CXXConstructExpr>(Result.get())->getConstructor()
16889 ->isTrivial()) {
16890 Result = MaybeCreateExprWithCleanups(Result);
16891 CopyExpr = Result.get();
16892 }
16893 }
16894 }
16895
16896 BlockDecl::Capture NewCap(Var, Cap.isBlockCapture(), Cap.isNested(),
16897 CopyExpr);
16898 Captures.push_back(NewCap);
16899 }
16900 BD->setCaptures(Context, Captures, BSI->CXXThisCaptureIndex != 0);
16901
16902 // Pop the block scope now but keep it alive to the end of this function.
16903 AnalysisBasedWarnings::Policy WP = AnalysisWarnings.getDefaultPolicy();
16904 PoppedFunctionScopePtr ScopeRAII = PopFunctionScopeInfo(&WP, BD, BlockTy);
16905
16906 BlockExpr *Result = new (Context) BlockExpr(BD, BlockTy);
16907
16908 // If the block isn't obviously global, i.e. it captures anything at
16909 // all, then we need to do a few things in the surrounding context:
16910 if (Result->getBlockDecl()->hasCaptures()) {
16911 // First, this expression has a new cleanup object.
16912 ExprCleanupObjects.push_back(Result->getBlockDecl());
16913 Cleanup.setExprNeedsCleanups(true);
16914
16915 // It also gets a branch-protected scope if any of the captured
16916 // variables needs destruction.
16917 for (const auto &CI : Result->getBlockDecl()->captures()) {
16918 const VarDecl *var = CI.getVariable();
16919 if (var->getType().isDestructedType() != QualType::DK_none) {
16920 setFunctionHasBranchProtectedScope();
16921 break;
16922 }
16923 }
16924 }
16925
16926 if (getCurFunction())
16927 getCurFunction()->addBlock(BD);
16928
16929 return Result;
16930}
16931
16932ExprResult Sema::ActOnVAArg(SourceLocation BuiltinLoc, Expr *E, ParsedType Ty,
16933 SourceLocation RPLoc) {
16934 TypeSourceInfo *TInfo;
16935 GetTypeFromParser(Ty, &TInfo);
16936 return BuildVAArgExpr(BuiltinLoc, E, TInfo, RPLoc);
16937}
16938
16939ExprResult Sema::BuildVAArgExpr(SourceLocation BuiltinLoc,
16940 Expr *E, TypeSourceInfo *TInfo,
16941 SourceLocation RPLoc) {
16942 Expr *OrigExpr = E;
16943 bool IsMS = false;
16944
16945 // CUDA device code does not support varargs.
16946 if (getLangOpts().CUDA && getLangOpts().CUDAIsDevice) {
16947 if (const FunctionDecl *F = dyn_cast<FunctionDecl>(CurContext)) {
16948 CUDAFunctionTarget T = IdentifyCUDATarget(F);
16949 if (T == CFT_Global || T == CFT_Device || T == CFT_HostDevice)
16950 return ExprError(Diag(E->getBeginLoc(), diag::err_va_arg_in_device));
16951 }
16952 }
16953
16954 // NVPTX does not support va_arg expression.
16955 if (getLangOpts().OpenMP && getLangOpts().OpenMPIsDevice &&
16956 Context.getTargetInfo().getTriple().isNVPTX())
16957 targetDiag(E->getBeginLoc(), diag::err_va_arg_in_device);
16958
16959 // It might be a __builtin_ms_va_list. (But don't ever mark a va_arg()
16960 // as Microsoft ABI on an actual Microsoft platform, where
16961 // __builtin_ms_va_list and __builtin_va_list are the same.)
16962 if (!E->isTypeDependent() && Context.getTargetInfo().hasBuiltinMSVaList() &&
16963 Context.getTargetInfo().getBuiltinVaListKind() != TargetInfo::CharPtrBuiltinVaList) {
16964 QualType MSVaListType = Context.getBuiltinMSVaListType();
16965 if (Context.hasSameType(MSVaListType, E->getType())) {
16966 if (CheckForModifiableLvalue(E, BuiltinLoc, *this))
16967 return ExprError();
16968 IsMS = true;
16969 }
16970 }
16971
16972 // Get the va_list type
16973 QualType VaListType = Context.getBuiltinVaListType();
16974 if (!IsMS) {
16975 if (VaListType->isArrayType()) {
16976 // Deal with implicit array decay; for example, on x86-64,
16977 // va_list is an array, but it's supposed to decay to
16978 // a pointer for va_arg.
16979 VaListType = Context.getArrayDecayedType(VaListType);
16980 // Make sure the input expression also decays appropriately.
16981 ExprResult Result = UsualUnaryConversions(E);
16982 if (Result.isInvalid())
16983 return ExprError();
16984 E = Result.get();
16985 } else if (VaListType->isRecordType() && getLangOpts().CPlusPlus) {
16986 // If va_list is a record type and we are compiling in C++ mode,
16987 // check the argument using reference binding.
16988 InitializedEntity Entity = InitializedEntity::InitializeParameter(
16989 Context, Context.getLValueReferenceType(VaListType), false);
16990 ExprResult Init = PerformCopyInitialization(Entity, SourceLocation(), E);
16991 if (Init.isInvalid())
16992 return ExprError();
16993 E = Init.getAs<Expr>();
16994 } else {
16995 // Otherwise, the va_list argument must be an l-value because
16996 // it is modified by va_arg.
16997 if (!E->isTypeDependent() &&
16998 CheckForModifiableLvalue(E, BuiltinLoc, *this))
16999 return ExprError();
17000 }
17001 }
17002
17003 if (!IsMS && !E->isTypeDependent() &&
17004 !Context.hasSameType(VaListType, E->getType()))
17005 return ExprError(
17006 Diag(E->getBeginLoc(),
17007 diag::err_first_argument_to_va_arg_not_of_type_va_list)
17008 << OrigExpr->getType() << E->getSourceRange());
17009
17010 if (!TInfo->getType()->isDependentType()) {
17011 if (RequireCompleteType(TInfo->getTypeLoc().getBeginLoc(), TInfo->getType(),
17012 diag::err_second_parameter_to_va_arg_incomplete,
17013 TInfo->getTypeLoc()))
17014 return ExprError();
17015
17016 if (RequireNonAbstractType(TInfo->getTypeLoc().getBeginLoc(),
17017 TInfo->getType(),
17018 diag::err_second_parameter_to_va_arg_abstract,
17019 TInfo->getTypeLoc()))
17020 return ExprError();
17021
17022 if (!TInfo->getType().isPODType(Context)) {
17023 Diag(TInfo->getTypeLoc().getBeginLoc(),
17024 TInfo->getType()->isObjCLifetimeType()
17025 ? diag::warn_second_parameter_to_va_arg_ownership_qualified
17026 : diag::warn_second_parameter_to_va_arg_not_pod)
17027 << TInfo->getType()
17028 << TInfo->getTypeLoc().getSourceRange();
17029 }
17030
17031 // Check for va_arg where arguments of the given type will be promoted
17032 // (i.e. this va_arg is guaranteed to have undefined behavior).
17033 QualType PromoteType;
17034 if (Context.isPromotableIntegerType(TInfo->getType())) {
17035 PromoteType = Context.getPromotedIntegerType(TInfo->getType());
17036 // [cstdarg.syn]p1 defers the C++ behavior to what the C standard says,
17037 // and C2x 7.16.1.1p2 says, in part:
17038 // If type is not compatible with the type of the actual next argument
17039 // (as promoted according to the default argument promotions), the
17040 // behavior is undefined, except for the following cases:
17041 // - both types are pointers to qualified or unqualified versions of
17042 // compatible types;
17043 // - one type is a signed integer type, the other type is the
17044 // corresponding unsigned integer type, and the value is
17045 // representable in both types;
17046 // - one type is pointer to qualified or unqualified void and the
17047 // other is a pointer to a qualified or unqualified character type.
17048 // Given that type compatibility is the primary requirement (ignoring
17049 // qualifications), you would think we could call typesAreCompatible()
17050 // directly to test this. However, in C++, that checks for *same type*,
17051 // which causes false positives when passing an enumeration type to
17052 // va_arg. Instead, get the underlying type of the enumeration and pass
17053 // that.
17054 QualType UnderlyingType = TInfo->getType();
17055 if (const auto *ET = UnderlyingType->getAs<EnumType>())
17056 UnderlyingType = ET->getDecl()->getIntegerType();
17057 if (Context.typesAreCompatible(PromoteType, UnderlyingType,
17058 /*CompareUnqualified*/ true))
17059 PromoteType = QualType();
17060
17061 // If the types are still not compatible, we need to test whether the
17062 // promoted type and the underlying type are the same except for
17063 // signedness. Ask the AST for the correctly corresponding type and see
17064 // if that's compatible.
17065 if (!PromoteType.isNull() && !UnderlyingType->isBooleanType() &&
17066 PromoteType->isUnsignedIntegerType() !=
17067 UnderlyingType->isUnsignedIntegerType()) {
17068 UnderlyingType =
17069 UnderlyingType->isUnsignedIntegerType()
17070 ? Context.getCorrespondingSignedType(UnderlyingType)
17071 : Context.getCorrespondingUnsignedType(UnderlyingType);
17072 if (Context.typesAreCompatible(PromoteType, UnderlyingType,
17073 /*CompareUnqualified*/ true))
17074 PromoteType = QualType();
17075 }
17076 }
17077 if (TInfo->getType()->isSpecificBuiltinType(BuiltinType::Float))
17078 PromoteType = Context.DoubleTy;
17079 if (!PromoteType.isNull())
17080 DiagRuntimeBehavior(TInfo->getTypeLoc().getBeginLoc(), E,
17081 PDiag(diag::warn_second_parameter_to_va_arg_never_compatible)
17082 << TInfo->getType()
17083 << PromoteType
17084 << TInfo->getTypeLoc().getSourceRange());
17085 }
17086
17087 QualType T = TInfo->getType().getNonLValueExprType(Context);
17088 return new (Context) VAArgExpr(BuiltinLoc, E, TInfo, RPLoc, T, IsMS);
17089}
17090
17091ExprResult Sema::ActOnGNUNullExpr(SourceLocation TokenLoc) {
17092 // The type of __null will be int or long, depending on the size of
17093 // pointers on the target.
17094 QualType Ty;
17095 unsigned pw = Context.getTargetInfo().getPointerWidth(LangAS::Default);
17096 if (pw == Context.getTargetInfo().getIntWidth())
17097 Ty = Context.IntTy;
17098 else if (pw == Context.getTargetInfo().getLongWidth())
17099 Ty = Context.LongTy;
17100 else if (pw == Context.getTargetInfo().getLongLongWidth())
17101 Ty = Context.LongLongTy;
17102 else {
17103 llvm_unreachable("I don't know size of pointer!")::llvm::llvm_unreachable_internal("I don't know size of pointer!"
, "clang/lib/Sema/SemaExpr.cpp", 17103)
;
17104 }
17105
17106 return new (Context) GNUNullExpr(Ty, TokenLoc);
17107}
17108
17109static CXXRecordDecl *LookupStdSourceLocationImpl(Sema &S, SourceLocation Loc) {
17110 CXXRecordDecl *ImplDecl = nullptr;
17111
17112 // Fetch the std::source_location::__impl decl.
17113 if (NamespaceDecl *Std = S.getStdNamespace()) {
17114 LookupResult ResultSL(S, &S.PP.getIdentifierTable().get("source_location"),
17115 Loc, Sema::LookupOrdinaryName);
17116 if (S.LookupQualifiedName(ResultSL, Std)) {
17117 if (auto *SLDecl = ResultSL.getAsSingle<RecordDecl>()) {
17118 LookupResult ResultImpl(S, &S.PP.getIdentifierTable().get("__impl"),
17119 Loc, Sema::LookupOrdinaryName);
17120 if ((SLDecl->isCompleteDefinition() || SLDecl->isBeingDefined()) &&
17121 S.LookupQualifiedName(ResultImpl, SLDecl)) {
17122 ImplDecl = ResultImpl.getAsSingle<CXXRecordDecl>();
17123 }
17124 }
17125 }
17126 }
17127
17128 if (!ImplDecl || !ImplDecl->isCompleteDefinition()) {
17129 S.Diag(Loc, diag::err_std_source_location_impl_not_found);
17130 return nullptr;
17131 }
17132
17133 // Verify that __impl is a trivial struct type, with no base classes, and with
17134 // only the four expected fields.
17135 if (ImplDecl->isUnion() || !ImplDecl->isStandardLayout() ||
17136 ImplDecl->getNumBases() != 0) {
17137 S.Diag(Loc, diag::err_std_source_location_impl_malformed);
17138 return nullptr;
17139 }
17140
17141 unsigned Count = 0;
17142 for (FieldDecl *F : ImplDecl->fields()) {
17143 StringRef Name = F->getName();
17144
17145 if (Name == "_M_file_name") {
17146 if (F->getType() !=
17147 S.Context.getPointerType(S.Context.CharTy.withConst()))
17148 break;
17149 Count++;
17150 } else if (Name == "_M_function_name") {
17151 if (F->getType() !=
17152 S.Context.getPointerType(S.Context.CharTy.withConst()))
17153 break;
17154 Count++;
17155 } else if (Name == "_M_line") {
17156 if (!F->getType()->isIntegerType())
17157 break;
17158 Count++;
17159 } else if (Name == "_M_column") {
17160 if (!F->getType()->isIntegerType())
17161 break;
17162 Count++;
17163 } else {
17164 Count = 100; // invalid
17165 break;
17166 }
17167 }
17168 if (Count != 4) {
17169 S.Diag(Loc, diag::err_std_source_location_impl_malformed);
17170 return nullptr;
17171 }
17172
17173 return ImplDecl;
17174}
17175
17176ExprResult Sema::ActOnSourceLocExpr(SourceLocExpr::IdentKind Kind,
17177 SourceLocation BuiltinLoc,
17178 SourceLocation RPLoc) {
17179 QualType ResultTy;
17180 switch (Kind) {
17181 case SourceLocExpr::File:
17182 case SourceLocExpr::FileName:
17183 case SourceLocExpr::Function: {
17184 QualType ArrTy = Context.getStringLiteralArrayType(Context.CharTy, 0);
17185 ResultTy =
17186 Context.getPointerType(ArrTy->getAsArrayTypeUnsafe()->getElementType());
17187 break;
17188 }
17189 case SourceLocExpr::Line:
17190 case SourceLocExpr::Column:
17191 ResultTy = Context.UnsignedIntTy;
17192 break;
17193 case SourceLocExpr::SourceLocStruct:
17194 if (!StdSourceLocationImplDecl) {
17195 StdSourceLocationImplDecl =
17196 LookupStdSourceLocationImpl(*this, BuiltinLoc);
17197 if (!StdSourceLocationImplDecl)
17198 return ExprError();
17199 }
17200 ResultTy = Context.getPointerType(
17201 Context.getRecordType(StdSourceLocationImplDecl).withConst());
17202 break;
17203 }
17204
17205 return BuildSourceLocExpr(Kind, ResultTy, BuiltinLoc, RPLoc, CurContext);
17206}
17207
17208ExprResult Sema::BuildSourceLocExpr(SourceLocExpr::IdentKind Kind,
17209 QualType ResultTy,
17210 SourceLocation BuiltinLoc,
17211 SourceLocation RPLoc,
17212 DeclContext *ParentContext) {
17213 return new (Context)
17214 SourceLocExpr(Context, Kind, ResultTy, BuiltinLoc, RPLoc, ParentContext);
17215}
17216
17217bool Sema::CheckConversionToObjCLiteral(QualType DstType, Expr *&Exp,
17218 bool Diagnose) {
17219 if (!getLangOpts().ObjC)
17220 return false;
17221
17222 const ObjCObjectPointerType *PT = DstType->getAs<ObjCObjectPointerType>();
17223 if (!PT)
17224 return false;
17225 const ObjCInterfaceDecl *ID = PT->getInterfaceDecl();
17226
17227 // Ignore any parens, implicit casts (should only be
17228 // array-to-pointer decays), and not-so-opaque values. The last is
17229 // important for making this trigger for property assignments.
17230 Expr *SrcExpr = Exp->IgnoreParenImpCasts();
17231 if (OpaqueValueExpr *OV = dyn_cast<OpaqueValueExpr>(SrcExpr))
17232 if (OV->getSourceExpr())
17233 SrcExpr = OV->getSourceExpr()->IgnoreParenImpCasts();
17234
17235 if (auto *SL = dyn_cast<StringLiteral>(SrcExpr)) {
17236 if (!PT->isObjCIdType() &&
17237 !(ID && ID->getIdentifier()->isStr("NSString")))
17238 return false;
17239 if (!SL->isOrdinary())
17240 return false;
17241
17242 if (Diagnose) {
17243 Diag(SL->getBeginLoc(), diag::err_missing_atsign_prefix)
17244 << /*string*/0 << FixItHint::CreateInsertion(SL->getBeginLoc(), "@");
17245 Exp = BuildObjCStringLiteral(SL->getBeginLoc(), SL).get();
17246 }
17247 return true;
17248 }
17249
17250 if ((isa<IntegerLiteral>(SrcExpr) || isa<CharacterLiteral>(SrcExpr) ||
17251 isa<FloatingLiteral>(SrcExpr) || isa<ObjCBoolLiteralExpr>(SrcExpr) ||
17252 isa<CXXBoolLiteralExpr>(SrcExpr)) &&
17253 !SrcExpr->isNullPointerConstant(
17254 getASTContext(), Expr::NPC_NeverValueDependent)) {
17255 if (!ID || !ID->getIdentifier()->isStr("NSNumber"))
17256 return false;
17257 if (Diagnose) {
17258 Diag(SrcExpr->getBeginLoc(), diag::err_missing_atsign_prefix)
17259 << /*number*/1
17260 << FixItHint::CreateInsertion(SrcExpr->getBeginLoc(), "@");
17261 Expr *NumLit =
17262 BuildObjCNumericLiteral(SrcExpr->getBeginLoc(), SrcExpr).get();
17263 if (NumLit)
17264 Exp = NumLit;
17265 }
17266 return true;
17267 }
17268
17269 return false;
17270}
17271
17272static bool maybeDiagnoseAssignmentToFunction(Sema &S, QualType DstType,
17273 const Expr *SrcExpr) {
17274 if (!DstType->isFunctionPointerType() ||
17275 !SrcExpr->getType()->isFunctionType())
17276 return false;
17277
17278 auto *DRE = dyn_cast<DeclRefExpr>(SrcExpr->IgnoreParenImpCasts());
17279 if (!DRE)
17280 return false;
17281
17282 auto *FD = dyn_cast<FunctionDecl>(DRE->getDecl());
17283 if (!FD)
17284 return false;
17285
17286 return !S.checkAddressOfFunctionIsAvailable(FD,
17287 /*Complain=*/true,
17288 SrcExpr->getBeginLoc());
17289}
17290
17291bool Sema::DiagnoseAssignmentResult(AssignConvertType ConvTy,
17292 SourceLocation Loc,
17293 QualType DstType, QualType SrcType,
17294 Expr *SrcExpr, AssignmentAction Action,
17295 bool *Complained) {
17296 if (Complained)
17297 *Complained = false;
17298
17299 // Decode the result (notice that AST's are still created for extensions).
17300 bool CheckInferredResultType = false;
17301 bool isInvalid = false;
17302 unsigned DiagKind = 0;
17303 ConversionFixItGenerator ConvHints;
17304 bool MayHaveConvFixit = false;
17305 bool MayHaveFunctionDiff = false;
17306 const ObjCInterfaceDecl *IFace = nullptr;
17307 const ObjCProtocolDecl *PDecl = nullptr;
17308
17309 switch (ConvTy) {
17310 case Compatible:
17311 DiagnoseAssignmentEnum(DstType, SrcType, SrcExpr);
17312 return false;
17313
17314 case PointerToInt:
17315 if (getLangOpts().CPlusPlus) {
17316 DiagKind = diag::err_typecheck_convert_pointer_int;
17317 isInvalid = true;
17318 } else {
17319 DiagKind = diag::ext_typecheck_convert_pointer_int;
17320 }
17321 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
17322 MayHaveConvFixit = true;
17323 break;
17324 case IntToPointer:
17325 if (getLangOpts().CPlusPlus) {
17326 DiagKind = diag::err_typecheck_convert_int_pointer;
17327 isInvalid = true;
17328 } else {
17329 DiagKind = diag::ext_typecheck_convert_int_pointer;
17330 }
17331 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
17332 MayHaveConvFixit = true;
17333 break;
17334 case IncompatibleFunctionPointerStrict:
17335 DiagKind =
17336 diag::warn_typecheck_convert_incompatible_function_pointer_strict;
17337 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
17338 MayHaveConvFixit = true;
17339 break;
17340 case IncompatibleFunctionPointer:
17341 if (getLangOpts().CPlusPlus) {
17342 DiagKind = diag::err_typecheck_convert_incompatible_function_pointer;
17343 isInvalid = true;
17344 } else {
17345 DiagKind = diag::ext_typecheck_convert_incompatible_function_pointer;
17346 }
17347 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
17348 MayHaveConvFixit = true;
17349 break;
17350 case IncompatiblePointer:
17351 if (Action == AA_Passing_CFAudited) {
17352 DiagKind = diag::err_arc_typecheck_convert_incompatible_pointer;
17353 } else if (getLangOpts().CPlusPlus) {
17354 DiagKind = diag::err_typecheck_convert_incompatible_pointer;
17355 isInvalid = true;
17356 } else {
17357 DiagKind = diag::ext_typecheck_convert_incompatible_pointer;
17358 }
17359 CheckInferredResultType = DstType->isObjCObjectPointerType() &&
17360 SrcType->isObjCObjectPointerType();
17361 if (!CheckInferredResultType) {
17362 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
17363 } else if (CheckInferredResultType) {
17364 SrcType = SrcType.getUnqualifiedType();
17365 DstType = DstType.getUnqualifiedType();
17366 }
17367 MayHaveConvFixit = true;
17368 break;
17369 case IncompatiblePointerSign:
17370 if (getLangOpts().CPlusPlus) {
17371 DiagKind = diag::err_typecheck_convert_incompatible_pointer_sign;
17372 isInvalid = true;
17373 } else {
17374 DiagKind = diag::ext_typecheck_convert_incompatible_pointer_sign;
17375 }
17376 break;
17377 case FunctionVoidPointer:
17378 if (getLangOpts().CPlusPlus) {
17379 DiagKind = diag::err_typecheck_convert_pointer_void_func;
17380 isInvalid = true;
17381 } else {
17382 DiagKind = diag::ext_typecheck_convert_pointer_void_func;
17383 }
17384 break;
17385 case IncompatiblePointerDiscardsQualifiers: {
17386 // Perform array-to-pointer decay if necessary.
17387 if (SrcType->isArrayType()) SrcType = Context.getArrayDecayedType(SrcType);
17388
17389 isInvalid = true;
17390
17391 Qualifiers lhq = SrcType->getPointeeType().getQualifiers();
17392 Qualifiers rhq = DstType->getPointeeType().getQualifiers();
17393 if (lhq.getAddressSpace() != rhq.getAddressSpace()) {
17394 DiagKind = diag::err_typecheck_incompatible_address_space;
17395 break;
17396
17397 } else if (lhq.getObjCLifetime() != rhq.getObjCLifetime()) {
17398 DiagKind = diag::err_typecheck_incompatible_ownership;
17399 break;
17400 }
17401
17402 llvm_unreachable("unknown error case for discarding qualifiers!")::llvm::llvm_unreachable_internal("unknown error case for discarding qualifiers!"
, "clang/lib/Sema/SemaExpr.cpp", 17402)
;
17403 // fallthrough
17404 }
17405 case CompatiblePointerDiscardsQualifiers:
17406 // If the qualifiers lost were because we were applying the
17407 // (deprecated) C++ conversion from a string literal to a char*
17408 // (or wchar_t*), then there was no error (C++ 4.2p2). FIXME:
17409 // Ideally, this check would be performed in
17410 // checkPointerTypesForAssignment. However, that would require a
17411 // bit of refactoring (so that the second argument is an
17412 // expression, rather than a type), which should be done as part
17413 // of a larger effort to fix checkPointerTypesForAssignment for
17414 // C++ semantics.
17415 if (getLangOpts().CPlusPlus &&
17416 IsStringLiteralToNonConstPointerConversion(SrcExpr, DstType))
17417 return false;
17418 if (getLangOpts().CPlusPlus) {
17419 DiagKind = diag::err_typecheck_convert_discards_qualifiers;
17420 isInvalid = true;
17421 } else {
17422 DiagKind = diag::ext_typecheck_convert_discards_qualifiers;
17423 }
17424
17425 break;
17426 case IncompatibleNestedPointerQualifiers:
17427 if (getLangOpts().CPlusPlus) {
17428 isInvalid = true;
17429 DiagKind = diag::err_nested_pointer_qualifier_mismatch;
17430 } else {
17431 DiagKind = diag::ext_nested_pointer_qualifier_mismatch;
17432 }
17433 break;
17434 case IncompatibleNestedPointerAddressSpaceMismatch:
17435 DiagKind = diag::err_typecheck_incompatible_nested_address_space;
17436 isInvalid = true;
17437 break;
17438 case IntToBlockPointer:
17439 DiagKind = diag::err_int_to_block_pointer;
17440 isInvalid = true;
17441 break;
17442 case IncompatibleBlockPointer:
17443 DiagKind = diag::err_typecheck_convert_incompatible_block_pointer;
17444 isInvalid = true;
17445 break;
17446 case IncompatibleObjCQualifiedId: {
17447 if (SrcType->isObjCQualifiedIdType()) {
17448 const ObjCObjectPointerType *srcOPT =
17449 SrcType->castAs<ObjCObjectPointerType>();
17450 for (auto *srcProto : srcOPT->quals()) {
17451 PDecl = srcProto;
17452 break;
17453 }
17454 if (const ObjCInterfaceType *IFaceT =
17455 DstType->castAs<ObjCObjectPointerType>()->getInterfaceType())
17456 IFace = IFaceT->getDecl();
17457 }
17458 else if (DstType->isObjCQualifiedIdType()) {
17459 const ObjCObjectPointerType *dstOPT =
17460 DstType->castAs<ObjCObjectPointerType>();
17461 for (auto *dstProto : dstOPT->quals()) {
17462 PDecl = dstProto;
17463 break;
17464 }
17465 if (const ObjCInterfaceType *IFaceT =
17466 SrcType->castAs<ObjCObjectPointerType>()->getInterfaceType())
17467 IFace = IFaceT->getDecl();
17468 }
17469 if (getLangOpts().CPlusPlus) {
17470 DiagKind = diag::err_incompatible_qualified_id;
17471 isInvalid = true;
17472 } else {
17473 DiagKind = diag::warn_incompatible_qualified_id;
17474 }
17475 break;
17476 }
17477 case IncompatibleVectors:
17478 if (getLangOpts().CPlusPlus) {
17479 DiagKind = diag::err_incompatible_vectors;
17480 isInvalid = true;
17481 } else {
17482 DiagKind = diag::warn_incompatible_vectors;
17483 }
17484 break;
17485 case IncompatibleObjCWeakRef:
17486 DiagKind = diag::err_arc_weak_unavailable_assign;
17487 isInvalid = true;
17488 break;
17489 case Incompatible:
17490 if (maybeDiagnoseAssignmentToFunction(*this, DstType, SrcExpr)) {
17491 if (Complained)
17492 *Complained = true;
17493 return true;
17494 }
17495
17496 DiagKind = diag::err_typecheck_convert_incompatible;
17497 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
17498 MayHaveConvFixit = true;
17499 isInvalid = true;
17500 MayHaveFunctionDiff = true;
17501 break;
17502 }
17503
17504 QualType FirstType, SecondType;
17505 switch (Action) {
17506 case AA_Assigning:
17507 case AA_Initializing:
17508 // The destination type comes first.
17509 FirstType = DstType;
17510 SecondType = SrcType;
17511 break;
17512
17513 case AA_Returning:
17514 case AA_Passing:
17515 case AA_Passing_CFAudited:
17516 case AA_Converting:
17517 case AA_Sending:
17518 case AA_Casting:
17519 // The source type comes first.
17520 FirstType = SrcType;
17521 SecondType = DstType;
17522 break;
17523 }
17524
17525 PartialDiagnostic FDiag = PDiag(DiagKind);
17526 AssignmentAction ActionForDiag = Action;
17527 if (Action == AA_Passing_CFAudited)
17528 ActionForDiag = AA_Passing;
17529
17530 FDiag << FirstType << SecondType << ActionForDiag
17531 << SrcExpr->getSourceRange();
17532
17533 if (DiagKind == diag::ext_typecheck_convert_incompatible_pointer_sign ||
17534 DiagKind == diag::err_typecheck_convert_incompatible_pointer_sign) {
17535 auto isPlainChar = [](const clang::Type *Type) {
17536 return Type->isSpecificBuiltinType(BuiltinType::Char_S) ||
17537 Type->isSpecificBuiltinType(BuiltinType::Char_U);
17538 };
17539 FDiag << (isPlainChar(FirstType->getPointeeOrArrayElementType()) ||
17540 isPlainChar(SecondType->getPointeeOrArrayElementType()));
17541 }
17542
17543 // If we can fix the conversion, suggest the FixIts.
17544 if (!ConvHints.isNull()) {
17545 for (FixItHint &H : ConvHints.Hints)
17546 FDiag << H;
17547 }
17548
17549 if (MayHaveConvFixit) { FDiag << (unsigned) (ConvHints.Kind); }
17550
17551 if (MayHaveFunctionDiff)
17552 HandleFunctionTypeMismatch(FDiag, SecondType, FirstType);
17553
17554 Diag(Loc, FDiag);
17555 if ((DiagKind == diag::warn_incompatible_qualified_id ||
17556 DiagKind == diag::err_incompatible_qualified_id) &&
17557 PDecl && IFace && !IFace->hasDefinition())
17558 Diag(IFace->getLocation(), diag::note_incomplete_class_and_qualified_id)
17559 << IFace << PDecl;
17560
17561 if (SecondType == Context.OverloadTy)
17562 NoteAllOverloadCandidates(OverloadExpr::find(SrcExpr).Expression,
17563 FirstType, /*TakingAddress=*/true);
17564
17565 if (CheckInferredResultType)
17566 EmitRelatedResultTypeNote(SrcExpr);
17567
17568 if (Action == AA_Returning && ConvTy == IncompatiblePointer)
17569 EmitRelatedResultTypeNoteForReturn(DstType);
17570
17571 if (Complained)
17572 *Complained = true;
17573 return isInvalid;
17574}
17575
17576ExprResult Sema::VerifyIntegerConstantExpression(Expr *E,
17577 llvm::APSInt *Result,
17578 AllowFoldKind CanFold) {
17579 class SimpleICEDiagnoser : public VerifyICEDiagnoser {
17580 public:
17581 SemaDiagnosticBuilder diagnoseNotICEType(Sema &S, SourceLocation Loc,
17582 QualType T) override {
17583 return S.Diag(Loc, diag::err_ice_not_integral)
17584 << T << S.LangOpts.CPlusPlus;
17585 }
17586 SemaDiagnosticBuilder diagnoseNotICE(Sema &S, SourceLocation Loc) override {
17587 return S.Diag(Loc, diag::err_expr_not_ice) << S.LangOpts.CPlusPlus;
17588 }
17589 } Diagnoser;
17590
17591 return VerifyIntegerConstantExpression(E, Result, Diagnoser, CanFold);
17592}
17593
17594ExprResult Sema::VerifyIntegerConstantExpression(Expr *E,
17595 llvm::APSInt *Result,
17596 unsigned DiagID,
17597 AllowFoldKind CanFold) {
17598 class IDDiagnoser : public VerifyICEDiagnoser {
17599 unsigned DiagID;
17600
17601 public:
17602 IDDiagnoser(unsigned DiagID)
17603 : VerifyICEDiagnoser(DiagID == 0), DiagID(DiagID) { }
17604
17605 SemaDiagnosticBuilder diagnoseNotICE(Sema &S, SourceLocation Loc) override {
17606 return S.Diag(Loc, DiagID);
17607 }
17608 } Diagnoser(DiagID);
17609
17610 return VerifyIntegerConstantExpression(E, Result, Diagnoser, CanFold);
17611}
17612
17613Sema::SemaDiagnosticBuilder
17614Sema::VerifyICEDiagnoser::diagnoseNotICEType(Sema &S, SourceLocation Loc,
17615 QualType T) {
17616 return diagnoseNotICE(S, Loc);
17617}
17618
17619Sema::SemaDiagnosticBuilder
17620Sema::VerifyICEDiagnoser::diagnoseFold(Sema &S, SourceLocation Loc) {
17621 return S.Diag(Loc, diag::ext_expr_not_ice) << S.LangOpts.CPlusPlus;
17622}
17623
17624ExprResult
17625Sema::VerifyIntegerConstantExpression(Expr *E, llvm::APSInt *Result,
17626 VerifyICEDiagnoser &Diagnoser,
17627 AllowFoldKind CanFold) {
17628 SourceLocation DiagLoc = E->getBeginLoc();
17629
17630 if (getLangOpts().CPlusPlus11) {
17631 // C++11 [expr.const]p5:
17632 // If an expression of literal class type is used in a context where an
17633 // integral constant expression is required, then that class type shall
17634 // have a single non-explicit conversion function to an integral or
17635 // unscoped enumeration type
17636 ExprResult Converted;
17637 class CXX11ConvertDiagnoser : public ICEConvertDiagnoser {
17638 VerifyICEDiagnoser &BaseDiagnoser;
17639 public:
17640 CXX11ConvertDiagnoser(VerifyICEDiagnoser &BaseDiagnoser)
17641 : ICEConvertDiagnoser(/*AllowScopedEnumerations*/ false,
17642 BaseDiagnoser.Suppress, true),
17643 BaseDiagnoser(BaseDiagnoser) {}
17644
17645 SemaDiagnosticBuilder diagnoseNotInt(Sema &S, SourceLocation Loc,
17646 QualType T) override {
17647 return BaseDiagnoser.diagnoseNotICEType(S, Loc, T);
17648 }
17649
17650 SemaDiagnosticBuilder diagnoseIncomplete(
17651 Sema &S, SourceLocation Loc, QualType T) override {
17652 return S.Diag(Loc, diag::err_ice_incomplete_type) << T;
17653 }
17654
17655 SemaDiagnosticBuilder diagnoseExplicitConv(
17656 Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) override {
17657 return S.Diag(Loc, diag::err_ice_explicit_conversion) << T << ConvTy;
17658 }
17659
17660 SemaDiagnosticBuilder noteExplicitConv(
17661 Sema &S, CXXConversionDecl *Conv, QualType ConvTy) override {
17662 return S.Diag(Conv->getLocation(), diag::note_ice_conversion_here)
17663 << ConvTy->isEnumeralType() << ConvTy;
17664 }
17665
17666 SemaDiagnosticBuilder diagnoseAmbiguous(
17667 Sema &S, SourceLocation Loc, QualType T) override {
17668 return S.Diag(Loc, diag::err_ice_ambiguous_conversion) << T;
17669 }
17670
17671 SemaDiagnosticBuilder noteAmbiguous(
17672 Sema &S, CXXConversionDecl *Conv, QualType ConvTy) override {
17673 return S.Diag(Conv->getLocation(), diag::note_ice_conversion_here)
17674 << ConvTy->isEnumeralType() << ConvTy;
17675 }
17676
17677 SemaDiagnosticBuilder diagnoseConversion(
17678 Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) override {
17679 llvm_unreachable("conversion functions are permitted")::llvm::llvm_unreachable_internal("conversion functions are permitted"
, "clang/lib/Sema/SemaExpr.cpp", 17679)
;
17680 }
17681 } ConvertDiagnoser(Diagnoser);
17682
17683 Converted = PerformContextualImplicitConversion(DiagLoc, E,
17684 ConvertDiagnoser);
17685 if (Converted.isInvalid())
17686 return Converted;
17687 E = Converted.get();
17688 if (!E->getType()->isIntegralOrUnscopedEnumerationType())
17689 return ExprError();
17690 } else if (!E->getType()->isIntegralOrUnscopedEnumerationType()) {
17691 // An ICE must be of integral or unscoped enumeration type.
17692 if (!Diagnoser.Suppress)
17693 Diagnoser.diagnoseNotICEType(*this, DiagLoc, E->getType())
17694 << E->getSourceRange();
17695 return ExprError();
17696 }
17697
17698 ExprResult RValueExpr = DefaultLvalueConversion(E);
17699 if (RValueExpr.isInvalid())
17700 return ExprError();
17701
17702 E = RValueExpr.get();
17703
17704 // Circumvent ICE checking in C++11 to avoid evaluating the expression twice
17705 // in the non-ICE case.
17706 if (!getLangOpts().CPlusPlus11 && E->isIntegerConstantExpr(Context)) {
17707 if (Result)
17708 *Result = E->EvaluateKnownConstIntCheckOverflow(Context);
17709 if (!isa<ConstantExpr>(E))
17710 E = Result ? ConstantExpr::Create(Context, E, APValue(*Result))
17711 : ConstantExpr::Create(Context, E);
17712 return E;
17713 }
17714
17715 Expr::EvalResult EvalResult;
17716 SmallVector<PartialDiagnosticAt, 8> Notes;
17717 EvalResult.Diag = &Notes;
17718
17719 // Try to evaluate the expression, and produce diagnostics explaining why it's
17720 // not a constant expression as a side-effect.
17721 bool Folded =
17722 E->EvaluateAsRValue(EvalResult, Context, /*isConstantContext*/ true) &&
17723 EvalResult.Val.isInt() && !EvalResult.HasSideEffects;
17724
17725 if (!isa<ConstantExpr>(E))
17726 E = ConstantExpr::Create(Context, E, EvalResult.Val);
17727
17728 // In C++11, we can rely on diagnostics being produced for any expression
17729 // which is not a constant expression. If no diagnostics were produced, then
17730 // this is a constant expression.
17731 if (Folded && getLangOpts().CPlusPlus11 && Notes.empty()) {
17732 if (Result)
17733 *Result = EvalResult.Val.getInt();
17734 return E;
17735 }
17736
17737 // If our only note is the usual "invalid subexpression" note, just point
17738 // the caret at its location rather than producing an essentially
17739 // redundant note.
17740 if (Notes.size() == 1 && Notes[0].second.getDiagID() ==
17741 diag::note_invalid_subexpr_in_const_expr) {
17742 DiagLoc = Notes[0].first;
17743 Notes.clear();
17744 }
17745
17746 if (!Folded || !CanFold) {
17747 if (!Diagnoser.Suppress) {
17748 Diagnoser.diagnoseNotICE(*this, DiagLoc) << E->getSourceRange();
17749 for (const PartialDiagnosticAt &Note : Notes)
17750 Diag(Note.first, Note.second);
17751 }
17752
17753 return ExprError();
17754 }
17755
17756 Diagnoser.diagnoseFold(*this, DiagLoc) << E->getSourceRange();
17757 for (const PartialDiagnosticAt &Note : Notes)
17758 Diag(Note.first, Note.second);
17759
17760 if (Result)
17761 *Result = EvalResult.Val.getInt();
17762 return E;
17763}
17764
17765namespace {
17766 // Handle the case where we conclude a expression which we speculatively
17767 // considered to be unevaluated is actually evaluated.
17768 class TransformToPE : public TreeTransform<TransformToPE> {
17769 typedef TreeTransform<TransformToPE> BaseTransform;
17770
17771 public:
17772 TransformToPE(Sema &SemaRef) : BaseTransform(SemaRef) { }
17773
17774 // Make sure we redo semantic analysis
17775 bool AlwaysRebuild() { return true; }
17776 bool ReplacingOriginal() { return true; }
17777
17778 // We need to special-case DeclRefExprs referring to FieldDecls which
17779 // are not part of a member pointer formation; normal TreeTransforming
17780 // doesn't catch this case because of the way we represent them in the AST.
17781 // FIXME: This is a bit ugly; is it really the best way to handle this
17782 // case?
17783 //
17784 // Error on DeclRefExprs referring to FieldDecls.
17785 ExprResult TransformDeclRefExpr(DeclRefExpr *E) {
17786 if (isa<FieldDecl>(E->getDecl()) &&
17787 !SemaRef.isUnevaluatedContext())
17788 return SemaRef.Diag(E->getLocation(),
17789 diag::err_invalid_non_static_member_use)
17790 << E->getDecl() << E->getSourceRange();
17791
17792 return BaseTransform::TransformDeclRefExpr(E);
17793 }
17794
17795 // Exception: filter out member pointer formation
17796 ExprResult TransformUnaryOperator(UnaryOperator *E) {
17797 if (E->getOpcode() == UO_AddrOf && E->getType()->isMemberPointerType())
17798 return E;
17799
17800 return BaseTransform::TransformUnaryOperator(E);
17801 }
17802
17803 // The body of a lambda-expression is in a separate expression evaluation
17804 // context so never needs to be transformed.
17805 // FIXME: Ideally we wouldn't transform the closure type either, and would
17806 // just recreate the capture expressions and lambda expression.
17807 StmtResult TransformLambdaBody(LambdaExpr *E, Stmt *Body) {
17808 return SkipLambdaBody(E, Body);
17809 }
17810 };
17811}
17812
17813ExprResult Sema::TransformToPotentiallyEvaluated(Expr *E) {
17814 assert(isUnevaluatedContext() &&(static_cast <bool> (isUnevaluatedContext() && "Should only transform unevaluated expressions"
) ? void (0) : __assert_fail ("isUnevaluatedContext() && \"Should only transform unevaluated expressions\""
, "clang/lib/Sema/SemaExpr.cpp", 17815, __extension__ __PRETTY_FUNCTION__
))
17815 "Should only transform unevaluated expressions")(static_cast <bool> (isUnevaluatedContext() && "Should only transform unevaluated expressions"
) ? void (0) : __assert_fail ("isUnevaluatedContext() && \"Should only transform unevaluated expressions\""
, "clang/lib/Sema/SemaExpr.cpp", 17815, __extension__ __PRETTY_FUNCTION__
))
;
17816 ExprEvalContexts.back().Context =
17817 ExprEvalContexts[ExprEvalContexts.size()-2].Context;
17818 if (isUnevaluatedContext())
17819 return E;
17820 return TransformToPE(*this).TransformExpr(E);
17821}
17822
17823TypeSourceInfo *Sema::TransformToPotentiallyEvaluated(TypeSourceInfo *TInfo) {
17824 assert(isUnevaluatedContext() &&(static_cast <bool> (isUnevaluatedContext() && "Should only transform unevaluated expressions"
) ? void (0) : __assert_fail ("isUnevaluatedContext() && \"Should only transform unevaluated expressions\""
, "clang/lib/Sema/SemaExpr.cpp", 17825, __extension__ __PRETTY_FUNCTION__
))
17825 "Should only transform unevaluated expressions")(static_cast <bool> (isUnevaluatedContext() && "Should only transform unevaluated expressions"
) ? void (0) : __assert_fail ("isUnevaluatedContext() && \"Should only transform unevaluated expressions\""
, "clang/lib/Sema/SemaExpr.cpp", 17825, __extension__ __PRETTY_FUNCTION__
))
;
17826 ExprEvalContexts.back().Context =
17827 ExprEvalContexts[ExprEvalContexts.size() - 2].Context;
17828 if (isUnevaluatedContext())
17829 return TInfo;
17830 return TransformToPE(*this).TransformType(TInfo);
17831}
17832
17833void
17834Sema::PushExpressionEvaluationContext(
17835 ExpressionEvaluationContext NewContext, Decl *LambdaContextDecl,
17836 ExpressionEvaluationContextRecord::ExpressionKind ExprContext) {
17837 ExprEvalContexts.emplace_back(NewContext, ExprCleanupObjects.size(), Cleanup,
17838 LambdaContextDecl, ExprContext);
17839
17840 // Discarded statements and immediate contexts nested in other
17841 // discarded statements or immediate context are themselves
17842 // a discarded statement or an immediate context, respectively.
17843 ExprEvalContexts.back().InDiscardedStatement =
17844 ExprEvalContexts[ExprEvalContexts.size() - 2]
17845 .isDiscardedStatementContext();
17846 ExprEvalContexts.back().InImmediateFunctionContext =
17847 ExprEvalContexts[ExprEvalContexts.size() - 2]
17848 .isImmediateFunctionContext();
17849
17850 Cleanup.reset();
17851 if (!MaybeODRUseExprs.empty())
17852 std::swap(MaybeODRUseExprs, ExprEvalContexts.back().SavedMaybeODRUseExprs);
17853}
17854
17855void
17856Sema::PushExpressionEvaluationContext(
17857 ExpressionEvaluationContext NewContext, ReuseLambdaContextDecl_t,
17858 ExpressionEvaluationContextRecord::ExpressionKind ExprContext) {
17859 Decl *ClosureContextDecl = ExprEvalContexts.back().ManglingContextDecl;
17860 PushExpressionEvaluationContext(NewContext, ClosureContextDecl, ExprContext);
17861}
17862
17863namespace {
17864
17865const DeclRefExpr *CheckPossibleDeref(Sema &S, const Expr *PossibleDeref) {
17866 PossibleDeref = PossibleDeref->IgnoreParenImpCasts();
17867 if (const auto *E = dyn_cast<UnaryOperator>(PossibleDeref)) {
17868 if (E->getOpcode() == UO_Deref)
17869 return CheckPossibleDeref(S, E->getSubExpr());
17870 } else if (const auto *E = dyn_cast<ArraySubscriptExpr>(PossibleDeref)) {
17871 return CheckPossibleDeref(S, E->getBase());
17872 } else if (const auto *E = dyn_cast<MemberExpr>(PossibleDeref)) {
17873 return CheckPossibleDeref(S, E->getBase());
17874 } else if (const auto E = dyn_cast<DeclRefExpr>(PossibleDeref)) {
17875 QualType Inner;
17876 QualType Ty = E->getType();
17877 if (const auto *Ptr = Ty->getAs<PointerType>())
17878 Inner = Ptr->getPointeeType();
17879 else if (const auto *Arr = S.Context.getAsArrayType(Ty))
17880 Inner = Arr->getElementType();
17881 else
17882 return nullptr;
17883
17884 if (Inner->hasAttr(attr::NoDeref))
17885 return E;
17886 }
17887 return nullptr;
17888}
17889
17890} // namespace
17891
17892void Sema::WarnOnPendingNoDerefs(ExpressionEvaluationContextRecord &Rec) {
17893 for (const Expr *E : Rec.PossibleDerefs) {
17894 const DeclRefExpr *DeclRef = CheckPossibleDeref(*this, E);
17895 if (DeclRef) {
17896 const ValueDecl *Decl = DeclRef->getDecl();
17897 Diag(E->getExprLoc(), diag::warn_dereference_of_noderef_type)
17898 << Decl->getName() << E->getSourceRange();
17899 Diag(Decl->getLocation(), diag::note_previous_decl) << Decl->getName();
17900 } else {
17901 Diag(E->getExprLoc(), diag::warn_dereference_of_noderef_type_no_decl)
17902 << E->getSourceRange();
17903 }
17904 }
17905 Rec.PossibleDerefs.clear();
17906}
17907
17908/// Check whether E, which is either a discarded-value expression or an
17909/// unevaluated operand, is a simple-assignment to a volatlie-qualified lvalue,
17910/// and if so, remove it from the list of volatile-qualified assignments that
17911/// we are going to warn are deprecated.
17912void Sema::CheckUnusedVolatileAssignment(Expr *E) {
17913 if (!E->getType().isVolatileQualified() || !getLangOpts().CPlusPlus20)
17914 return;
17915
17916 // Note: ignoring parens here is not justified by the standard rules, but
17917 // ignoring parentheses seems like a more reasonable approach, and this only
17918 // drives a deprecation warning so doesn't affect conformance.
17919 if (auto *BO = dyn_cast<BinaryOperator>(E->IgnoreParenImpCasts())) {
17920 if (BO->getOpcode() == BO_Assign) {
17921 auto &LHSs = ExprEvalContexts.back().VolatileAssignmentLHSs;
17922 llvm::erase_value(LHSs, BO->getLHS());
17923 }
17924 }
17925}
17926
17927ExprResult Sema::CheckForImmediateInvocation(ExprResult E, FunctionDecl *Decl) {
17928 if (isUnevaluatedContext() || !E.isUsable() || !Decl ||
17929 !Decl->isConsteval() || isConstantEvaluated() ||
17930 isCheckingDefaultArgumentOrInitializer() ||
17931 RebuildingImmediateInvocation || isImmediateFunctionContext())
17932 return E;
17933
17934 /// Opportunistically remove the callee from ReferencesToConsteval if we can.
17935 /// It's OK if this fails; we'll also remove this in
17936 /// HandleImmediateInvocations, but catching it here allows us to avoid
17937 /// walking the AST looking for it in simple cases.
17938 if (auto *Call = dyn_cast<CallExpr>(E.get()->IgnoreImplicit()))
17939 if (auto *DeclRef =
17940 dyn_cast<DeclRefExpr>(Call->getCallee()->IgnoreImplicit()))
17941 ExprEvalContexts.back().ReferenceToConsteval.erase(DeclRef);
17942
17943 E = MaybeCreateExprWithCleanups(E);
17944
17945 ConstantExpr *Res = ConstantExpr::Create(
17946 getASTContext(), E.get(),
17947 ConstantExpr::getStorageKind(Decl->getReturnType().getTypePtr(),
17948 getASTContext()),
17949 /*IsImmediateInvocation*/ true);
17950 /// Value-dependent constant expressions should not be immediately
17951 /// evaluated until they are instantiated.
17952 if (!Res->isValueDependent())
17953 ExprEvalContexts.back().ImmediateInvocationCandidates.emplace_back(Res, 0);
17954 return Res;
17955}
17956
17957static void EvaluateAndDiagnoseImmediateInvocation(
17958 Sema &SemaRef, Sema::ImmediateInvocationCandidate Candidate) {
17959 llvm::SmallVector<PartialDiagnosticAt, 8> Notes;
17960 Expr::EvalResult Eval;
17961 Eval.Diag = &Notes;
17962 ConstantExpr *CE = Candidate.getPointer();
17963 bool Result = CE->EvaluateAsConstantExpr(
17964 Eval, SemaRef.getASTContext(), ConstantExprKind::ImmediateInvocation);
17965 if (!Result || !Notes.empty()) {
17966 SemaRef.FailedImmediateInvocations.insert(CE);
17967 Expr *InnerExpr = CE->getSubExpr()->IgnoreImplicit();
17968 if (auto *FunctionalCast = dyn_cast<CXXFunctionalCastExpr>(InnerExpr))
17969 InnerExpr = FunctionalCast->getSubExpr();
17970 FunctionDecl *FD = nullptr;
17971 if (auto *Call = dyn_cast<CallExpr>(InnerExpr))
17972 FD = cast<FunctionDecl>(Call->getCalleeDecl());
17973 else if (auto *Call = dyn_cast<CXXConstructExpr>(InnerExpr))
17974 FD = Call->getConstructor();
17975 else
17976 llvm_unreachable("unhandled decl kind")::llvm::llvm_unreachable_internal("unhandled decl kind", "clang/lib/Sema/SemaExpr.cpp"
, 17976)
;
17977 assert(FD && FD->isConsteval())(static_cast <bool> (FD && FD->isConsteval()
) ? void (0) : __assert_fail ("FD && FD->isConsteval()"
, "clang/lib/Sema/SemaExpr.cpp", 17977, __extension__ __PRETTY_FUNCTION__
))
;
17978 SemaRef.Diag(CE->getBeginLoc(), diag::err_invalid_consteval_call) << FD;
17979 if (auto Context =
17980 SemaRef.InnermostDeclarationWithDelayedImmediateInvocations()) {
17981 SemaRef.Diag(Context->Loc, diag::note_invalid_consteval_initializer)
17982 << Context->Decl;
17983 SemaRef.Diag(Context->Decl->getBeginLoc(), diag::note_declared_at);
17984 }
17985 for (auto &Note : Notes)
17986 SemaRef.Diag(Note.first, Note.second);
17987 return;
17988 }
17989 CE->MoveIntoResult(Eval.Val, SemaRef.getASTContext());
17990}
17991
17992static void RemoveNestedImmediateInvocation(
17993 Sema &SemaRef, Sema::ExpressionEvaluationContextRecord &Rec,
17994 SmallVector<Sema::ImmediateInvocationCandidate, 4>::reverse_iterator It) {
17995 struct ComplexRemove : TreeTransform<ComplexRemove> {
17996 using Base = TreeTransform<ComplexRemove>;
17997 llvm::SmallPtrSetImpl<DeclRefExpr *> &DRSet;
17998 SmallVector<Sema::ImmediateInvocationCandidate, 4> &IISet;
17999 SmallVector<Sema::ImmediateInvocationCandidate, 4>::reverse_iterator
18000 CurrentII;
18001 ComplexRemove(Sema &SemaRef, llvm::SmallPtrSetImpl<DeclRefExpr *> &DR,
18002 SmallVector<Sema::ImmediateInvocationCandidate, 4> &II,
18003 SmallVector<Sema::ImmediateInvocationCandidate,
18004 4>::reverse_iterator Current)
18005 : Base(SemaRef), DRSet(DR), IISet(II), CurrentII(Current) {}
18006 void RemoveImmediateInvocation(ConstantExpr* E) {
18007 auto It = std::find_if(CurrentII, IISet.rend(),
18008 [E](Sema::ImmediateInvocationCandidate Elem) {
18009 return Elem.getPointer() == E;
18010 });
18011 // It is possible that some subexpression of the current immediate
18012 // invocation was handled from another expression evaluation context. Do
18013 // not handle the current immediate invocation if some of its
18014 // subexpressions failed before.
18015 if (It == IISet.rend()) {
18016 if (SemaRef.FailedImmediateInvocations.contains(E))
18017 CurrentII->setInt(1);
18018 } else {
18019 It->setInt(1); // Mark as deleted
18020 }
18021 }
18022 ExprResult TransformConstantExpr(ConstantExpr *E) {
18023 if (!E->isImmediateInvocation())
18024 return Base::TransformConstantExpr(E);
18025 RemoveImmediateInvocation(E);
18026 return Base::TransformExpr(E->getSubExpr());
18027 }
18028 /// Base::TransfromCXXOperatorCallExpr doesn't traverse the callee so
18029 /// we need to remove its DeclRefExpr from the DRSet.
18030 ExprResult TransformCXXOperatorCallExpr(CXXOperatorCallExpr *E) {
18031 DRSet.erase(cast<DeclRefExpr>(E->getCallee()->IgnoreImplicit()));
18032 return Base::TransformCXXOperatorCallExpr(E);
18033 }
18034 /// Base::TransformInitializer skip ConstantExpr so we need to visit them
18035 /// here.
18036 ExprResult TransformInitializer(Expr *Init, bool NotCopyInit) {
18037 if (!Init)
18038 return Init;
18039 /// ConstantExpr are the first layer of implicit node to be removed so if
18040 /// Init isn't a ConstantExpr, no ConstantExpr will be skipped.
18041 if (auto *CE = dyn_cast<ConstantExpr>(Init))
18042 if (CE->isImmediateInvocation())
18043 RemoveImmediateInvocation(CE);
18044 return Base::TransformInitializer(Init, NotCopyInit);
18045 }
18046 ExprResult TransformDeclRefExpr(DeclRefExpr *E) {
18047 DRSet.erase(E);
18048 return E;
18049 }
18050 ExprResult TransformLambdaExpr(LambdaExpr *E) {
18051 // Do not rebuild lambdas to avoid creating a new type.
18052 // Lambdas have already been processed inside their eval context.
18053 return E;
18054 }
18055 bool AlwaysRebuild() { return false; }
18056 bool ReplacingOriginal() { return true; }
18057 bool AllowSkippingCXXConstructExpr() {
18058 bool Res = AllowSkippingFirstCXXConstructExpr;
18059 AllowSkippingFirstCXXConstructExpr = true;
18060 return Res;
18061 }
18062 bool AllowSkippingFirstCXXConstructExpr = true;
18063 } Transformer(SemaRef, Rec.ReferenceToConsteval,
18064 Rec.ImmediateInvocationCandidates, It);
18065
18066 /// CXXConstructExpr with a single argument are getting skipped by
18067 /// TreeTransform in some situtation because they could be implicit. This
18068 /// can only occur for the top-level CXXConstructExpr because it is used
18069 /// nowhere in the expression being transformed therefore will not be rebuilt.
18070 /// Setting AllowSkippingFirstCXXConstructExpr to false will prevent from
18071 /// skipping the first CXXConstructExpr.
18072 if (isa<CXXConstructExpr>(It->getPointer()->IgnoreImplicit()))
18073 Transformer.AllowSkippingFirstCXXConstructExpr = false;
18074
18075 ExprResult Res = Transformer.TransformExpr(It->getPointer()->getSubExpr());
18076 // The result may not be usable in case of previous compilation errors.
18077 // In this case evaluation of the expression may result in crash so just
18078 // don't do anything further with the result.
18079 if (Res.isUsable()) {
18080 Res = SemaRef.MaybeCreateExprWithCleanups(Res);
18081 It->getPointer()->setSubExpr(Res.get());
18082 }
18083}
18084
18085static void
18086HandleImmediateInvocations(Sema &SemaRef,
18087 Sema::ExpressionEvaluationContextRecord &Rec) {
18088 if ((Rec.ImmediateInvocationCandidates.size() == 0 &&
18089 Rec.ReferenceToConsteval.size() == 0) ||
18090 SemaRef.RebuildingImmediateInvocation)
18091 return;
18092
18093 /// When we have more than 1 ImmediateInvocationCandidates or previously
18094 /// failed immediate invocations, we need to check for nested
18095 /// ImmediateInvocationCandidates in order to avoid duplicate diagnostics.
18096 /// Otherwise we only need to remove ReferenceToConsteval in the immediate
18097 /// invocation.
18098 if (Rec.ImmediateInvocationCandidates.size() > 1 ||
18099 !SemaRef.FailedImmediateInvocations.empty()) {
18100
18101 /// Prevent sema calls during the tree transform from adding pointers that
18102 /// are already in the sets.
18103 llvm::SaveAndRestore DisableIITracking(
18104 SemaRef.RebuildingImmediateInvocation, true);
18105
18106 /// Prevent diagnostic during tree transfrom as they are duplicates
18107 Sema::TentativeAnalysisScope DisableDiag(SemaRef);
18108
18109 for (auto It = Rec.ImmediateInvocationCandidates.rbegin();
18110 It != Rec.ImmediateInvocationCandidates.rend(); It++)
18111 if (!It->getInt())
18112 RemoveNestedImmediateInvocation(SemaRef, Rec, It);
18113 } else if (Rec.ImmediateInvocationCandidates.size() == 1 &&
18114 Rec.ReferenceToConsteval.size()) {
18115 struct SimpleRemove : RecursiveASTVisitor<SimpleRemove> {
18116 llvm::SmallPtrSetImpl<DeclRefExpr *> &DRSet;
18117 SimpleRemove(llvm::SmallPtrSetImpl<DeclRefExpr *> &S) : DRSet(S) {}
18118 bool VisitDeclRefExpr(DeclRefExpr *E) {
18119 DRSet.erase(E);
18120 return DRSet.size();
18121 }
18122 } Visitor(Rec.ReferenceToConsteval);
18123 Visitor.TraverseStmt(
18124 Rec.ImmediateInvocationCandidates.front().getPointer()->getSubExpr());
18125 }
18126 for (auto CE : Rec.ImmediateInvocationCandidates)
18127 if (!CE.getInt())
18128 EvaluateAndDiagnoseImmediateInvocation(SemaRef, CE);
18129 for (auto *DR : Rec.ReferenceToConsteval) {
18130 NamedDecl *ND = cast<FunctionDecl>(DR->getDecl());
18131 if (auto *MD = llvm::dyn_cast<CXXMethodDecl>(ND);
18132 MD && (MD->isLambdaStaticInvoker() || isLambdaCallOperator(MD)))
18133 ND = MD->getParent();
18134 SemaRef.Diag(DR->getBeginLoc(), diag::err_invalid_consteval_take_address)
18135 << ND << isa<CXXRecordDecl>(ND);
18136 SemaRef.Diag(ND->getLocation(), diag::note_declared_at);
18137 }
18138}
18139
18140void Sema::PopExpressionEvaluationContext() {
18141 ExpressionEvaluationContextRecord& Rec = ExprEvalContexts.back();
18142 unsigned NumTypos = Rec.NumTypos;
18143
18144 if (!Rec.Lambdas.empty()) {
18145 using ExpressionKind = ExpressionEvaluationContextRecord::ExpressionKind;
18146 if (!getLangOpts().CPlusPlus20 &&
18147 (Rec.ExprContext == ExpressionKind::EK_TemplateArgument ||
18148 Rec.isUnevaluated() ||
18149 (Rec.isConstantEvaluated() && !getLangOpts().CPlusPlus17))) {
18150 unsigned D;
18151 if (Rec.isUnevaluated()) {
18152 // C++11 [expr.prim.lambda]p2:
18153 // A lambda-expression shall not appear in an unevaluated operand
18154 // (Clause 5).
18155 D = diag::err_lambda_unevaluated_operand;
18156 } else if (Rec.isConstantEvaluated() && !getLangOpts().CPlusPlus17) {
18157 // C++1y [expr.const]p2:
18158 // A conditional-expression e is a core constant expression unless the
18159 // evaluation of e, following the rules of the abstract machine, would
18160 // evaluate [...] a lambda-expression.
18161 D = diag::err_lambda_in_constant_expression;
18162 } else if (Rec.ExprContext == ExpressionKind::EK_TemplateArgument) {
18163 // C++17 [expr.prim.lamda]p2:
18164 // A lambda-expression shall not appear [...] in a template-argument.
18165 D = diag::err_lambda_in_invalid_context;
18166 } else
18167 llvm_unreachable("Couldn't infer lambda error message.")::llvm::llvm_unreachable_internal("Couldn't infer lambda error message."
, "clang/lib/Sema/SemaExpr.cpp", 18167)
;
18168
18169 for (const auto *L : Rec.Lambdas)
18170 Diag(L->getBeginLoc(), D);
18171 }
18172 }
18173
18174 WarnOnPendingNoDerefs(Rec);
18175 HandleImmediateInvocations(*this, Rec);
18176
18177 // Warn on any volatile-qualified simple-assignments that are not discarded-
18178 // value expressions nor unevaluated operands (those cases get removed from
18179 // this list by CheckUnusedVolatileAssignment).
18180 for (auto *BO : Rec.VolatileAssignmentLHSs)
18181 Diag(BO->getBeginLoc(), diag::warn_deprecated_simple_assign_volatile)
18182 << BO->getType();
18183
18184 // When are coming out of an unevaluated context, clear out any
18185 // temporaries that we may have created as part of the evaluation of
18186 // the expression in that context: they aren't relevant because they
18187 // will never be constructed.
18188 if (Rec.isUnevaluated() || Rec.isConstantEvaluated()) {
18189 ExprCleanupObjects.erase(ExprCleanupObjects.begin() + Rec.NumCleanupObjects,
18190 ExprCleanupObjects.end());
18191 Cleanup = Rec.ParentCleanup;
18192 CleanupVarDeclMarking();
18193 std::swap(MaybeODRUseExprs, Rec.SavedMaybeODRUseExprs);
18194 // Otherwise, merge the contexts together.
18195 } else {
18196 Cleanup.mergeFrom(Rec.ParentCleanup);
18197 MaybeODRUseExprs.insert(Rec.SavedMaybeODRUseExprs.begin(),
18198 Rec.SavedMaybeODRUseExprs.end());
18199 }
18200
18201 // Pop the current expression evaluation context off the stack.
18202 ExprEvalContexts.pop_back();
18203
18204 // The global expression evaluation context record is never popped.
18205 ExprEvalContexts.back().NumTypos += NumTypos;
18206}
18207
18208void Sema::DiscardCleanupsInEvaluationContext() {
18209 ExprCleanupObjects.erase(
18210 ExprCleanupObjects.begin() + ExprEvalContexts.back().NumCleanupObjects,
18211 ExprCleanupObjects.end());
18212 Cleanup.reset();
18213 MaybeODRUseExprs.clear();
18214}
18215
18216ExprResult Sema::HandleExprEvaluationContextForTypeof(Expr *E) {
18217 ExprResult Result = CheckPlaceholderExpr(E);
18218 if (Result.isInvalid())
18219 return ExprError();
18220 E = Result.get();
18221 if (!E->getType()->isVariablyModifiedType())
18222 return E;
18223 return TransformToPotentiallyEvaluated(E);
18224}
18225
18226/// Are we in a context that is potentially constant evaluated per C++20
18227/// [expr.const]p12?
18228static bool isPotentiallyConstantEvaluatedContext(Sema &SemaRef) {
18229 /// C++2a [expr.const]p12:
18230 // An expression or conversion is potentially constant evaluated if it is
18231 switch (SemaRef.ExprEvalContexts.back().Context) {
18232 case Sema::ExpressionEvaluationContext::ConstantEvaluated:
18233 case Sema::ExpressionEvaluationContext::ImmediateFunctionContext:
18234
18235 // -- a manifestly constant-evaluated expression,
18236 case Sema::ExpressionEvaluationContext::PotentiallyEvaluated:
18237 case Sema::ExpressionEvaluationContext::PotentiallyEvaluatedIfUsed:
18238 case Sema::ExpressionEvaluationContext::DiscardedStatement:
18239 // -- a potentially-evaluated expression,
18240 case Sema::ExpressionEvaluationContext::UnevaluatedList:
18241 // -- an immediate subexpression of a braced-init-list,
18242
18243 // -- [FIXME] an expression of the form & cast-expression that occurs
18244 // within a templated entity
18245 // -- a subexpression of one of the above that is not a subexpression of
18246 // a nested unevaluated operand.
18247 return true;
18248
18249 case Sema::ExpressionEvaluationContext::Unevaluated:
18250 case Sema::ExpressionEvaluationContext::UnevaluatedAbstract:
18251 // Expressions in this context are never evaluated.
18252 return false;
18253 }
18254 llvm_unreachable("Invalid context")::llvm::llvm_unreachable_internal("Invalid context", "clang/lib/Sema/SemaExpr.cpp"
, 18254)
;
18255}
18256
18257/// Return true if this function has a calling convention that requires mangling
18258/// in the size of the parameter pack.
18259static bool funcHasParameterSizeMangling(Sema &S, FunctionDecl *FD) {
18260 // These manglings don't do anything on non-Windows or non-x86 platforms, so
18261 // we don't need parameter type sizes.
18262 const llvm::Triple &TT = S.Context.getTargetInfo().getTriple();
18263 if (!TT.isOSWindows() || !TT.isX86())
18264 return false;
18265
18266 // If this is C++ and this isn't an extern "C" function, parameters do not
18267 // need to be complete. In this case, C++ mangling will apply, which doesn't
18268 // use the size of the parameters.
18269 if (S.getLangOpts().CPlusPlus && !FD->isExternC())
18270 return false;
18271
18272 // Stdcall, fastcall, and vectorcall need this special treatment.
18273 CallingConv CC = FD->getType()->castAs<FunctionType>()->getCallConv();
18274 switch (CC) {
18275 case CC_X86StdCall:
18276 case CC_X86FastCall:
18277 case CC_X86VectorCall:
18278 return true;
18279 default:
18280 break;
18281 }
18282 return false;
18283}
18284
18285/// Require that all of the parameter types of function be complete. Normally,
18286/// parameter types are only required to be complete when a function is called
18287/// or defined, but to mangle functions with certain calling conventions, the
18288/// mangler needs to know the size of the parameter list. In this situation,
18289/// MSVC doesn't emit an error or instantiate templates. Instead, MSVC mangles
18290/// the function as _foo@0, i.e. zero bytes of parameters, which will usually
18291/// result in a linker error. Clang doesn't implement this behavior, and instead
18292/// attempts to error at compile time.
18293static void CheckCompleteParameterTypesForMangler(Sema &S, FunctionDecl *FD,
18294 SourceLocation Loc) {
18295 class ParamIncompleteTypeDiagnoser : public Sema::TypeDiagnoser {
18296 FunctionDecl *FD;
18297 ParmVarDecl *Param;
18298
18299 public:
18300 ParamIncompleteTypeDiagnoser(FunctionDecl *FD, ParmVarDecl *Param)
18301 : FD(FD), Param(Param) {}
18302
18303 void diagnose(Sema &S, SourceLocation Loc, QualType T) override {
18304 CallingConv CC = FD->getType()->castAs<FunctionType>()->getCallConv();
18305 StringRef CCName;
18306 switch (CC) {
18307 case CC_X86StdCall:
18308 CCName = "stdcall";
18309 break;
18310 case CC_X86FastCall:
18311 CCName = "fastcall";
18312 break;
18313 case CC_X86VectorCall:
18314 CCName = "vectorcall";
18315 break;
18316 default:
18317 llvm_unreachable("CC does not need mangling")::llvm::llvm_unreachable_internal("CC does not need mangling"
, "clang/lib/Sema/SemaExpr.cpp", 18317)
;
18318 }
18319
18320 S.Diag(Loc, diag::err_cconv_incomplete_param_type)
18321 << Param->getDeclName() << FD->getDeclName() << CCName;
18322 }
18323 };
18324
18325 for (ParmVarDecl *Param : FD->parameters()) {
18326 ParamIncompleteTypeDiagnoser Diagnoser(FD, Param);
18327 S.RequireCompleteType(Loc, Param->getType(), Diagnoser);
18328 }
18329}
18330
18331namespace {
18332enum class OdrUseContext {
18333 /// Declarations in this context are not odr-used.
18334 None,
18335 /// Declarations in this context are formally odr-used, but this is a
18336 /// dependent context.
18337 Dependent,
18338 /// Declarations in this context are odr-used but not actually used (yet).
18339 FormallyOdrUsed,
18340 /// Declarations in this context are used.
18341 Used
18342};
18343}
18344
18345/// Are we within a context in which references to resolved functions or to
18346/// variables result in odr-use?
18347static OdrUseContext isOdrUseContext(Sema &SemaRef) {
18348 OdrUseContext Result;
18349
18350 switch (SemaRef.ExprEvalContexts.back().Context) {
18351 case Sema::ExpressionEvaluationContext::Unevaluated:
18352 case Sema::ExpressionEvaluationContext::UnevaluatedList:
18353 case Sema::ExpressionEvaluationContext::UnevaluatedAbstract:
18354 return OdrUseContext::None;
18355
18356 case Sema::ExpressionEvaluationContext::ConstantEvaluated:
18357 case Sema::ExpressionEvaluationContext::ImmediateFunctionContext:
18358 case Sema::ExpressionEvaluationContext::PotentiallyEvaluated:
18359 Result = OdrUseContext::Used;
18360 break;
18361
18362 case Sema::ExpressionEvaluationContext::DiscardedStatement:
18363 Result = OdrUseContext::FormallyOdrUsed;
18364 break;
18365
18366 case Sema::ExpressionEvaluationContext::PotentiallyEvaluatedIfUsed:
18367 // A default argument formally results in odr-use, but doesn't actually
18368 // result in a use in any real sense until it itself is used.
18369 Result = OdrUseContext::FormallyOdrUsed;
18370 break;
18371 }
18372
18373 if (SemaRef.CurContext->isDependentContext())
18374 return OdrUseContext::Dependent;
18375
18376 return Result;
18377}
18378
18379static bool isImplicitlyDefinableConstexprFunction(FunctionDecl *Func) {
18380 if (!Func->isConstexpr())
18381 return false;
18382
18383 if (Func->isImplicitlyInstantiable() || !Func->isUserProvided())
18384 return true;
18385 auto *CCD = dyn_cast<CXXConstructorDecl>(Func);
18386 return CCD && CCD->getInheritedConstructor();
18387}
18388
18389/// Mark a function referenced, and check whether it is odr-used
18390/// (C++ [basic.def.odr]p2, C99 6.9p3)
18391void Sema::MarkFunctionReferenced(SourceLocation Loc, FunctionDecl *Func,
18392 bool MightBeOdrUse) {
18393 assert(Func && "No function?")(static_cast <bool> (Func && "No function?") ? void
(0) : __assert_fail ("Func && \"No function?\"", "clang/lib/Sema/SemaExpr.cpp"
, 18393, __extension__ __PRETTY_FUNCTION__))
;
18394
18395 Func->setReferenced();
18396
18397 // Recursive functions aren't really used until they're used from some other
18398 // context.
18399 bool IsRecursiveCall = CurContext == Func;
18400
18401 // C++11 [basic.def.odr]p3:
18402 // A function whose name appears as a potentially-evaluated expression is
18403 // odr-used if it is the unique lookup result or the selected member of a
18404 // set of overloaded functions [...].
18405 //
18406 // We (incorrectly) mark overload resolution as an unevaluated context, so we
18407 // can just check that here.
18408 OdrUseContext OdrUse =
18409 MightBeOdrUse ? isOdrUseContext(*this) : OdrUseContext::None;
18410 if (IsRecursiveCall && OdrUse == OdrUseContext::Used)
18411 OdrUse = OdrUseContext::FormallyOdrUsed;
18412
18413 // Trivial default constructors and destructors are never actually used.
18414 // FIXME: What about other special members?
18415 if (Func->isTrivial() && !Func->hasAttr<DLLExportAttr>() &&
18416 OdrUse == OdrUseContext::Used) {
18417 if (auto *Constructor = dyn_cast<CXXConstructorDecl>(Func))
18418 if (Constructor->isDefaultConstructor())
18419 OdrUse = OdrUseContext::FormallyOdrUsed;
18420 if (isa<CXXDestructorDecl>(Func))
18421 OdrUse = OdrUseContext::FormallyOdrUsed;
18422 }
18423
18424 // C++20 [expr.const]p12:
18425 // A function [...] is needed for constant evaluation if it is [...] a
18426 // constexpr function that is named by an expression that is potentially
18427 // constant evaluated
18428 bool NeededForConstantEvaluation =
18429 isPotentiallyConstantEvaluatedContext(*this) &&
18430 isImplicitlyDefinableConstexprFunction(Func);
18431
18432 // Determine whether we require a function definition to exist, per
18433 // C++11 [temp.inst]p3:
18434 // Unless a function template specialization has been explicitly
18435 // instantiated or explicitly specialized, the function template
18436 // specialization is implicitly instantiated when the specialization is
18437 // referenced in a context that requires a function definition to exist.
18438 // C++20 [temp.inst]p7:
18439 // The existence of a definition of a [...] function is considered to
18440 // affect the semantics of the program if the [...] function is needed for
18441 // constant evaluation by an expression
18442 // C++20 [basic.def.odr]p10:
18443 // Every program shall contain exactly one definition of every non-inline
18444 // function or variable that is odr-used in that program outside of a
18445 // discarded statement
18446 // C++20 [special]p1:
18447 // The implementation will implicitly define [defaulted special members]
18448 // if they are odr-used or needed for constant evaluation.
18449 //
18450 // Note that we skip the implicit instantiation of templates that are only
18451 // used in unused default arguments or by recursive calls to themselves.
18452 // This is formally non-conforming, but seems reasonable in practice.
18453 bool NeedDefinition = !IsRecursiveCall && (OdrUse == OdrUseContext::Used ||
18454 NeededForConstantEvaluation);
18455
18456 // C++14 [temp.expl.spec]p6:
18457 // If a template [...] is explicitly specialized then that specialization
18458 // shall be declared before the first use of that specialization that would
18459 // cause an implicit instantiation to take place, in every translation unit
18460 // in which such a use occurs
18461 if (NeedDefinition &&
18462 (Func->getTemplateSpecializationKind() != TSK_Undeclared ||
18463 Func->getMemberSpecializationInfo()))
18464 checkSpecializationReachability(Loc, Func);
18465
18466 if (getLangOpts().CUDA)
18467 CheckCUDACall(Loc, Func);
18468
18469 // If we need a definition, try to create one.
18470 if (NeedDefinition && !Func->getBody()) {
18471 runWithSufficientStackSpace(Loc, [&] {
18472 if (CXXConstructorDecl *Constructor =
18473 dyn_cast<CXXConstructorDecl>(Func)) {
18474 Constructor = cast<CXXConstructorDecl>(Constructor->getFirstDecl());
18475 if (Constructor->isDefaulted() && !Constructor->isDeleted()) {
18476 if (Constructor->isDefaultConstructor()) {
18477 if (Constructor->isTrivial() &&
18478 !Constructor->hasAttr<DLLExportAttr>())
18479 return;
18480 DefineImplicitDefaultConstructor(Loc, Constructor);
18481 } else if (Constructor->isCopyConstructor()) {
18482 DefineImplicitCopyConstructor(Loc, Constructor);
18483 } else if (Constructor->isMoveConstructor()) {
18484 DefineImplicitMoveConstructor(Loc, Constructor);
18485 }
18486 } else if (Constructor->getInheritedConstructor()) {
18487 DefineInheritingConstructor(Loc, Constructor);
18488 }
18489 } else if (CXXDestructorDecl *Destructor =
18490 dyn_cast<CXXDestructorDecl>(Func)) {
18491 Destructor = cast<CXXDestructorDecl>(Destructor->getFirstDecl());
18492 if (Destructor->isDefaulted() && !Destructor->isDeleted()) {
18493 if (Destructor->isTrivial() && !Destructor->hasAttr<DLLExportAttr>())
18494 return;
18495 DefineImplicitDestructor(Loc, Destructor);
18496 }
18497 if (Destructor->isVirtual() && getLangOpts().AppleKext)
18498 MarkVTableUsed(Loc, Destructor->getParent());
18499 } else if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(Func)) {
18500 if (MethodDecl->isOverloadedOperator() &&
18501 MethodDecl->getOverloadedOperator() == OO_Equal) {
18502 MethodDecl = cast<CXXMethodDecl>(MethodDecl->getFirstDecl());
18503 if (MethodDecl->isDefaulted() && !MethodDecl->isDeleted()) {
18504 if (MethodDecl->isCopyAssignmentOperator())
18505 DefineImplicitCopyAssignment(Loc, MethodDecl);
18506 else if (MethodDecl->isMoveAssignmentOperator())
18507 DefineImplicitMoveAssignment(Loc, MethodDecl);
18508 }
18509 } else if (isa<CXXConversionDecl>(MethodDecl) &&
18510 MethodDecl->getParent()->isLambda()) {
18511 CXXConversionDecl *Conversion =
18512 cast<CXXConversionDecl>(MethodDecl->getFirstDecl());
18513 if (Conversion->isLambdaToBlockPointerConversion())
18514 DefineImplicitLambdaToBlockPointerConversion(Loc, Conversion);
18515 else
18516 DefineImplicitLambdaToFunctionPointerConversion(Loc, Conversion);
18517 } else if (MethodDecl->isVirtual() && getLangOpts().AppleKext)
18518 MarkVTableUsed(Loc, MethodDecl->getParent());
18519 }
18520
18521 if (Func->isDefaulted() && !Func->isDeleted()) {
18522 DefaultedComparisonKind DCK = getDefaultedComparisonKind(Func);
18523 if (DCK != DefaultedComparisonKind::None)
18524 DefineDefaultedComparison(Loc, Func, DCK);
18525 }
18526
18527 // Implicit instantiation of function templates and member functions of
18528 // class templates.
18529 if (Func->isImplicitlyInstantiable()) {
18530 TemplateSpecializationKind TSK =
18531 Func->getTemplateSpecializationKindForInstantiation();
18532 SourceLocation PointOfInstantiation = Func->getPointOfInstantiation();
18533 bool FirstInstantiation = PointOfInstantiation.isInvalid();
18534 if (FirstInstantiation) {
18535 PointOfInstantiation = Loc;
18536 if (auto *MSI = Func->getMemberSpecializationInfo())
18537 MSI->setPointOfInstantiation(Loc);
18538 // FIXME: Notify listener.
18539 else
18540 Func->setTemplateSpecializationKind(TSK, PointOfInstantiation);
18541 } else if (TSK != TSK_ImplicitInstantiation) {
18542 // Use the point of use as the point of instantiation, instead of the
18543 // point of explicit instantiation (which we track as the actual point
18544 // of instantiation). This gives better backtraces in diagnostics.
18545 PointOfInstantiation = Loc;
18546 }
18547
18548 if (FirstInstantiation || TSK != TSK_ImplicitInstantiation ||
18549 Func->isConstexpr()) {
18550 if (isa<CXXRecordDecl>(Func->getDeclContext()) &&
18551 cast<CXXRecordDecl>(Func->getDeclContext())->isLocalClass() &&
18552 CodeSynthesisContexts.size())
18553 PendingLocalImplicitInstantiations.push_back(
18554 std::make_pair(Func, PointOfInstantiation));
18555 else if (Func->isConstexpr())
18556 // Do not defer instantiations of constexpr functions, to avoid the
18557 // expression evaluator needing to call back into Sema if it sees a
18558 // call to such a function.
18559 InstantiateFunctionDefinition(PointOfInstantiation, Func);
18560 else {
18561 Func->setInstantiationIsPending(true);
18562 PendingInstantiations.push_back(
18563 std::make_pair(Func, PointOfInstantiation));
18564 // Notify the consumer that a function was implicitly instantiated.
18565 Consumer.HandleCXXImplicitFunctionInstantiation(Func);
18566 }
18567 }
18568 } else {
18569 // Walk redefinitions, as some of them may be instantiable.
18570 for (auto *i : Func->redecls()) {
18571 if (!i->isUsed(false) && i->isImplicitlyInstantiable())
18572 MarkFunctionReferenced(Loc, i, MightBeOdrUse);
18573 }
18574 }
18575 });
18576 }
18577
18578 // If a constructor was defined in the context of a default parameter
18579 // or of another default member initializer (ie a PotentiallyEvaluatedIfUsed
18580 // context), its initializers may not be referenced yet.
18581 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Func)) {
18582 for (CXXCtorInitializer *Init : Constructor->inits()) {
18583 if (Init->isInClassMemberInitializer())
18584 runWithSufficientStackSpace(Init->getSourceLocation(), [&]() {
18585 MarkDeclarationsReferencedInExpr(Init->getInit());
18586 });
18587 }
18588 }
18589
18590 // C++14 [except.spec]p17:
18591 // An exception-specification is considered to be needed when:
18592 // - the function is odr-used or, if it appears in an unevaluated operand,
18593 // would be odr-used if the expression were potentially-evaluated;
18594 //
18595 // Note, we do this even if MightBeOdrUse is false. That indicates that the
18596 // function is a pure virtual function we're calling, and in that case the
18597 // function was selected by overload resolution and we need to resolve its
18598 // exception specification for a different reason.
18599 const FunctionProtoType *FPT = Func->getType()->getAs<FunctionProtoType>();
18600 if (FPT && isUnresolvedExceptionSpec(FPT->getExceptionSpecType()))
18601 ResolveExceptionSpec(Loc, FPT);
18602
18603 // If this is the first "real" use, act on that.
18604 if (OdrUse == OdrUseContext::Used && !Func->isUsed(/*CheckUsedAttr=*/false)) {
18605 // Keep track of used but undefined functions.
18606 if (!Func->isDefined()) {
18607 if (mightHaveNonExternalLinkage(Func))
18608 UndefinedButUsed.insert(std::make_pair(Func->getCanonicalDecl(), Loc));
18609 else if (Func->getMostRecentDecl()->isInlined() &&
18610 !LangOpts.GNUInline &&
18611 !Func->getMostRecentDecl()->hasAttr<GNUInlineAttr>())
18612 UndefinedButUsed.insert(std::make_pair(Func->getCanonicalDecl(), Loc));
18613 else if (isExternalWithNoLinkageType(Func))
18614 UndefinedButUsed.insert(std::make_pair(Func->getCanonicalDecl(), Loc));
18615 }
18616
18617 // Some x86 Windows calling conventions mangle the size of the parameter
18618 // pack into the name. Computing the size of the parameters requires the
18619 // parameter types to be complete. Check that now.
18620 if (funcHasParameterSizeMangling(*this, Func))
18621 CheckCompleteParameterTypesForMangler(*this, Func, Loc);
18622
18623 // In the MS C++ ABI, the compiler emits destructor variants where they are
18624 // used. If the destructor is used here but defined elsewhere, mark the
18625 // virtual base destructors referenced. If those virtual base destructors
18626 // are inline, this will ensure they are defined when emitting the complete
18627 // destructor variant. This checking may be redundant if the destructor is
18628 // provided later in this TU.
18629 if (Context.getTargetInfo().getCXXABI().isMicrosoft()) {
18630 if (auto *Dtor = dyn_cast<CXXDestructorDecl>(Func)) {
18631 CXXRecordDecl *Parent = Dtor->getParent();
18632 if (Parent->getNumVBases() > 0 && !Dtor->getBody())
18633 CheckCompleteDestructorVariant(Loc, Dtor);
18634 }
18635 }
18636
18637 Func->markUsed(Context);
18638 }
18639}
18640
18641/// Directly mark a variable odr-used. Given a choice, prefer to use
18642/// MarkVariableReferenced since it does additional checks and then
18643/// calls MarkVarDeclODRUsed.
18644/// If the variable must be captured:
18645/// - if FunctionScopeIndexToStopAt is null, capture it in the CurContext
18646/// - else capture it in the DeclContext that maps to the
18647/// *FunctionScopeIndexToStopAt on the FunctionScopeInfo stack.
18648static void
18649MarkVarDeclODRUsed(ValueDecl *V, SourceLocation Loc, Sema &SemaRef,
18650 const unsigned *const FunctionScopeIndexToStopAt = nullptr) {
18651 // Keep track of used but undefined variables.
18652 // FIXME: We shouldn't suppress this warning for static data members.
18653 VarDecl *Var = V->getPotentiallyDecomposedVarDecl();
18654 assert(Var && "expected a capturable variable")(static_cast <bool> (Var && "expected a capturable variable"
) ? void (0) : __assert_fail ("Var && \"expected a capturable variable\""
, "clang/lib/Sema/SemaExpr.cpp", 18654, __extension__ __PRETTY_FUNCTION__
))
;
18655
18656 if (Var->hasDefinition(SemaRef.Context) == VarDecl::DeclarationOnly &&
18657 (!Var->isExternallyVisible() || Var->isInline() ||
18658 SemaRef.isExternalWithNoLinkageType(Var)) &&
18659 !(Var->isStaticDataMember() && Var->hasInit())) {
18660 SourceLocation &old = SemaRef.UndefinedButUsed[Var->getCanonicalDecl()];
18661 if (old.isInvalid())
18662 old = Loc;
18663 }
18664 QualType CaptureType, DeclRefType;
18665 if (SemaRef.LangOpts.OpenMP)
18666 SemaRef.tryCaptureOpenMPLambdas(V);
18667 SemaRef.tryCaptureVariable(V, Loc, Sema::TryCapture_Implicit,
18668 /*EllipsisLoc*/ SourceLocation(),
18669 /*BuildAndDiagnose*/ true, CaptureType,
18670 DeclRefType, FunctionScopeIndexToStopAt);
18671
18672 if (SemaRef.LangOpts.CUDA && Var->hasGlobalStorage()) {
18673 auto *FD = dyn_cast_or_null<FunctionDecl>(SemaRef.CurContext);
18674 auto VarTarget = SemaRef.IdentifyCUDATarget(Var);
18675 auto UserTarget = SemaRef.IdentifyCUDATarget(FD);
18676 if (VarTarget == Sema::CVT_Host &&
18677 (UserTarget == Sema::CFT_Device || UserTarget == Sema::CFT_HostDevice ||
18678 UserTarget == Sema::CFT_Global)) {
18679 // Diagnose ODR-use of host global variables in device functions.
18680 // Reference of device global variables in host functions is allowed
18681 // through shadow variables therefore it is not diagnosed.
18682 if (SemaRef.LangOpts.CUDAIsDevice) {
18683 SemaRef.targetDiag(Loc, diag::err_ref_bad_target)
18684 << /*host*/ 2 << /*variable*/ 1 << Var << UserTarget;
18685 SemaRef.targetDiag(Var->getLocation(),
18686 Var->getType().isConstQualified()
18687 ? diag::note_cuda_const_var_unpromoted
18688 : diag::note_cuda_host_var);
18689 }
18690 } else if (VarTarget == Sema::CVT_Device &&
18691 (UserTarget == Sema::CFT_Host ||
18692 UserTarget == Sema::CFT_HostDevice)) {
18693 // Record a CUDA/HIP device side variable if it is ODR-used
18694 // by host code. This is done conservatively, when the variable is
18695 // referenced in any of the following contexts:
18696 // - a non-function context
18697 // - a host function
18698 // - a host device function
18699 // This makes the ODR-use of the device side variable by host code to
18700 // be visible in the device compilation for the compiler to be able to
18701 // emit template variables instantiated by host code only and to
18702 // externalize the static device side variable ODR-used by host code.
18703 if (!Var->hasExternalStorage())
18704 SemaRef.getASTContext().CUDADeviceVarODRUsedByHost.insert(Var);
18705 else if (SemaRef.LangOpts.GPURelocatableDeviceCode)
18706 SemaRef.getASTContext().CUDAExternalDeviceDeclODRUsedByHost.insert(Var);
18707 }
18708 }
18709
18710 V->markUsed(SemaRef.Context);
18711}
18712
18713void Sema::MarkCaptureUsedInEnclosingContext(ValueDecl *Capture,
18714 SourceLocation Loc,
18715 unsigned CapturingScopeIndex) {
18716 MarkVarDeclODRUsed(Capture, Loc, *this, &CapturingScopeIndex);
18717}
18718
18719void diagnoseUncapturableValueReferenceOrBinding(Sema &S, SourceLocation loc,
18720 ValueDecl *var) {
18721 DeclContext *VarDC = var->getDeclContext();
18722
18723 // If the parameter still belongs to the translation unit, then
18724 // we're actually just using one parameter in the declaration of
18725 // the next.
18726 if (isa<ParmVarDecl>(var) &&
18727 isa<TranslationUnitDecl>(VarDC))
18728 return;
18729
18730 // For C code, don't diagnose about capture if we're not actually in code
18731 // right now; it's impossible to write a non-constant expression outside of
18732 // function context, so we'll get other (more useful) diagnostics later.
18733 //
18734 // For C++, things get a bit more nasty... it would be nice to suppress this
18735 // diagnostic for certain cases like using a local variable in an array bound
18736 // for a member of a local class, but the correct predicate is not obvious.
18737 if (!S.getLangOpts().CPlusPlus && !S.CurContext->isFunctionOrMethod())
18738 return;
18739
18740 unsigned ValueKind = isa<BindingDecl>(var) ? 1 : 0;
18741 unsigned ContextKind = 3; // unknown
18742 if (isa<CXXMethodDecl>(VarDC) &&
18743 cast<CXXRecordDecl>(VarDC->getParent())->isLambda()) {
18744 ContextKind = 2;
18745 } else if (isa<FunctionDecl>(VarDC)) {
18746 ContextKind = 0;
18747 } else if (isa<BlockDecl>(VarDC)) {
18748 ContextKind = 1;
18749 }
18750
18751 S.Diag(loc, diag::err_reference_to_local_in_enclosing_context)
18752 << var << ValueKind << ContextKind << VarDC;
18753 S.Diag(var->getLocation(), diag::note_entity_declared_at)
18754 << var;
18755
18756 // FIXME: Add additional diagnostic info about class etc. which prevents
18757 // capture.
18758}
18759
18760static bool isVariableAlreadyCapturedInScopeInfo(CapturingScopeInfo *CSI,
18761 ValueDecl *Var,
18762 bool &SubCapturesAreNested,
18763 QualType &CaptureType,
18764 QualType &DeclRefType) {
18765 // Check whether we've already captured it.
18766 if (CSI->CaptureMap.count(Var)) {
18767 // If we found a capture, any subcaptures are nested.
18768 SubCapturesAreNested = true;
18769
18770 // Retrieve the capture type for this variable.
18771 CaptureType = CSI->getCapture(Var).getCaptureType();
18772
18773 // Compute the type of an expression that refers to this variable.
18774 DeclRefType = CaptureType.getNonReferenceType();
18775
18776 // Similarly to mutable captures in lambda, all the OpenMP captures by copy
18777 // are mutable in the sense that user can change their value - they are
18778 // private instances of the captured declarations.
18779 const Capture &Cap = CSI->getCapture(Var);
18780 if (Cap.isCopyCapture() &&
18781 !(isa<LambdaScopeInfo>(CSI) && cast<LambdaScopeInfo>(CSI)->Mutable) &&
18782 !(isa<CapturedRegionScopeInfo>(CSI) &&
18783 cast<CapturedRegionScopeInfo>(CSI)->CapRegionKind == CR_OpenMP))
18784 DeclRefType.addConst();
18785 return true;
18786 }
18787 return false;
18788}
18789
18790// Only block literals, captured statements, and lambda expressions can
18791// capture; other scopes don't work.
18792static DeclContext *getParentOfCapturingContextOrNull(DeclContext *DC,
18793 ValueDecl *Var,
18794 SourceLocation Loc,
18795 const bool Diagnose,
18796 Sema &S) {
18797 if (isa<BlockDecl>(DC) || isa<CapturedDecl>(DC) || isLambdaCallOperator(DC))
18798 return getLambdaAwareParentOfDeclContext(DC);
18799
18800 VarDecl *Underlying = Var->getPotentiallyDecomposedVarDecl();
18801 if (Underlying) {
18802 if (Underlying->hasLocalStorage() && Diagnose)
18803 diagnoseUncapturableValueReferenceOrBinding(S, Loc, Var);
18804 }
18805 return nullptr;
18806}
18807
18808// Certain capturing entities (lambdas, blocks etc.) are not allowed to capture
18809// certain types of variables (unnamed, variably modified types etc.)
18810// so check for eligibility.
18811static bool isVariableCapturable(CapturingScopeInfo *CSI, ValueDecl *Var,
18812 SourceLocation Loc, const bool Diagnose,
18813 Sema &S) {
18814
18815 assert((isa<VarDecl, BindingDecl>(Var)) &&(static_cast <bool> ((isa<VarDecl, BindingDecl>(Var
)) && "Only variables and structured bindings can be captured"
) ? void (0) : __assert_fail ("(isa<VarDecl, BindingDecl>(Var)) && \"Only variables and structured bindings can be captured\""
, "clang/lib/Sema/SemaExpr.cpp", 18816, __extension__ __PRETTY_FUNCTION__
))
18816 "Only variables and structured bindings can be captured")(static_cast <bool> ((isa<VarDecl, BindingDecl>(Var
)) && "Only variables and structured bindings can be captured"
) ? void (0) : __assert_fail ("(isa<VarDecl, BindingDecl>(Var)) && \"Only variables and structured bindings can be captured\""
, "clang/lib/Sema/SemaExpr.cpp", 18816, __extension__ __PRETTY_FUNCTION__
))
;
18817
18818 bool IsBlock = isa<BlockScopeInfo>(CSI);
18819 bool IsLambda = isa<LambdaScopeInfo>(CSI);
18820
18821 // Lambdas are not allowed to capture unnamed variables
18822 // (e.g. anonymous unions).
18823 // FIXME: The C++11 rule don't actually state this explicitly, but I'm
18824 // assuming that's the intent.
18825 if (IsLambda && !Var->getDeclName()) {
18826 if (Diagnose) {
18827 S.Diag(Loc, diag::err_lambda_capture_anonymous_var);
18828 S.Diag(Var->getLocation(), diag::note_declared_at);
18829 }
18830 return false;
18831 }
18832
18833 // Prohibit variably-modified types in blocks; they're difficult to deal with.
18834 if (Var->getType()->isVariablyModifiedType() && IsBlock) {
18835 if (Diagnose) {
18836 S.Diag(Loc, diag::err_ref_vm_type);
18837 S.Diag(Var->getLocation(), diag::note_previous_decl) << Var;
18838 }
18839 return false;
18840 }
18841 // Prohibit structs with flexible array members too.
18842 // We cannot capture what is in the tail end of the struct.
18843 if (const RecordType *VTTy = Var->getType()->getAs<RecordType>()) {
18844 if (VTTy->getDecl()->hasFlexibleArrayMember()) {
18845 if (Diagnose) {
18846 if (IsBlock)
18847 S.Diag(Loc, diag::err_ref_flexarray_type);
18848 else
18849 S.Diag(Loc, diag::err_lambda_capture_flexarray_type) << Var;
18850 S.Diag(Var->getLocation(), diag::note_previous_decl) << Var;
18851 }
18852 return false;
18853 }
18854 }
18855 const bool HasBlocksAttr = Var->hasAttr<BlocksAttr>();
18856 // Lambdas and captured statements are not allowed to capture __block
18857 // variables; they don't support the expected semantics.
18858 if (HasBlocksAttr && (IsLambda || isa<CapturedRegionScopeInfo>(CSI))) {
18859 if (Diagnose) {
18860 S.Diag(Loc, diag::err_capture_block_variable) << Var << !IsLambda;
18861 S.Diag(Var->getLocation(), diag::note_previous_decl) << Var;
18862 }
18863 return false;
18864 }
18865 // OpenCL v2.0 s6.12.5: Blocks cannot reference/capture other blocks
18866 if (S.getLangOpts().OpenCL && IsBlock &&
18867 Var->getType()->isBlockPointerType()) {
18868 if (Diagnose)
18869 S.Diag(Loc, diag::err_opencl_block_ref_block);
18870 return false;
18871 }
18872
18873 if (isa<BindingDecl>(Var)) {
18874 if (!IsLambda || !S.getLangOpts().CPlusPlus) {
18875 if (Diagnose)
18876 diagnoseUncapturableValueReferenceOrBinding(S, Loc, Var);
18877 return false;
18878 } else if (Diagnose && S.getLangOpts().CPlusPlus) {
18879 S.Diag(Loc, S.LangOpts.CPlusPlus20
18880 ? diag::warn_cxx17_compat_capture_binding
18881 : diag::ext_capture_binding)
18882 << Var;
18883 S.Diag(Var->getLocation(), diag::note_entity_declared_at) << Var;
18884 }
18885 }
18886
18887 return true;
18888}
18889
18890// Returns true if the capture by block was successful.
18891static bool captureInBlock(BlockScopeInfo *BSI, ValueDecl *Var,
18892 SourceLocation Loc, const bool BuildAndDiagnose,
18893 QualType &CaptureType, QualType &DeclRefType,
18894 const bool Nested, Sema &S, bool Invalid) {
18895 bool ByRef = false;
18896
18897 // Blocks are not allowed to capture arrays, excepting OpenCL.
18898 // OpenCL v2.0 s1.12.5 (revision 40): arrays are captured by reference
18899 // (decayed to pointers).
18900 if (!Invalid && !S.getLangOpts().OpenCL && CaptureType->isArrayType()) {
18901 if (BuildAndDiagnose) {
18902 S.Diag(Loc, diag::err_ref_array_type);
18903 S.Diag(Var->getLocation(), diag::note_previous_decl) << Var;
18904 Invalid = true;
18905 } else {
18906 return false;
18907 }
18908 }
18909
18910 // Forbid the block-capture of autoreleasing variables.
18911 if (!Invalid &&
18912 CaptureType.getObjCLifetime() == Qualifiers::OCL_Autoreleasing) {
18913 if (BuildAndDiagnose) {
18914 S.Diag(Loc, diag::err_arc_autoreleasing_capture)
18915 << /*block*/ 0;
18916 S.Diag(Var->getLocation(), diag::note_previous_decl) << Var;
18917 Invalid = true;
18918 } else {
18919 return false;
18920 }
18921 }
18922
18923 // Warn about implicitly autoreleasing indirect parameters captured by blocks.
18924 if (const auto *PT = CaptureType->getAs<PointerType>()) {
18925 QualType PointeeTy = PT->getPointeeType();
18926
18927 if (!Invalid && PointeeTy->getAs<ObjCObjectPointerType>() &&
18928 PointeeTy.getObjCLifetime() == Qualifiers::OCL_Autoreleasing &&
18929 !S.Context.hasDirectOwnershipQualifier(PointeeTy)) {
18930 if (BuildAndDiagnose) {
18931 SourceLocation VarLoc = Var->getLocation();
18932 S.Diag(Loc, diag::warn_block_capture_autoreleasing);
18933 S.Diag(VarLoc, diag::note_declare_parameter_strong);
18934 }
18935 }
18936 }
18937
18938 const bool HasBlocksAttr = Var->hasAttr<BlocksAttr>();
18939 if (HasBlocksAttr || CaptureType->isReferenceType() ||
18940 (S.getLangOpts().OpenMP && S.isOpenMPCapturedDecl(Var))) {
18941 // Block capture by reference does not change the capture or
18942 // declaration reference types.
18943 ByRef = true;
18944 } else {
18945 // Block capture by copy introduces 'const'.
18946 CaptureType = CaptureType.getNonReferenceType().withConst();
18947 DeclRefType = CaptureType;
18948 }
18949
18950 // Actually capture the variable.
18951 if (BuildAndDiagnose)
18952 BSI->addCapture(Var, HasBlocksAttr, ByRef, Nested, Loc, SourceLocation(),
18953 CaptureType, Invalid);
18954
18955 return !Invalid;
18956}
18957
18958/// Capture the given variable in the captured region.
18959static bool captureInCapturedRegion(
18960 CapturedRegionScopeInfo *RSI, ValueDecl *Var, SourceLocation Loc,
18961 const bool BuildAndDiagnose, QualType &CaptureType, QualType &DeclRefType,
18962 const bool RefersToCapturedVariable, Sema::TryCaptureKind Kind,
18963 bool IsTopScope, Sema &S, bool Invalid) {
18964 // By default, capture variables by reference.
18965 bool ByRef = true;
18966 if (IsTopScope && Kind != Sema::TryCapture_Implicit) {
18967 ByRef = (Kind == Sema::TryCapture_ExplicitByRef);
18968 } else if (S.getLangOpts().OpenMP && RSI->CapRegionKind == CR_OpenMP) {
18969 // Using an LValue reference type is consistent with Lambdas (see below).
18970 if (S.isOpenMPCapturedDecl(Var)) {
18971 bool HasConst = DeclRefType.isConstQualified();
18972 DeclRefType = DeclRefType.getUnqualifiedType();
18973 // Don't lose diagnostics about assignments to const.
18974 if (HasConst)
18975 DeclRefType.addConst();
18976 }
18977 // Do not capture firstprivates in tasks.
18978 if (S.isOpenMPPrivateDecl(Var, RSI->OpenMPLevel, RSI->OpenMPCaptureLevel) !=
18979 OMPC_unknown)
18980 return true;
18981 ByRef = S.isOpenMPCapturedByRef(Var, RSI->OpenMPLevel,
18982 RSI->OpenMPCaptureLevel);
18983 }
18984
18985 if (ByRef)
18986 CaptureType = S.Context.getLValueReferenceType(DeclRefType);
18987 else
18988 CaptureType = DeclRefType;
18989
18990 // Actually capture the variable.
18991 if (BuildAndDiagnose)
18992 RSI->addCapture(Var, /*isBlock*/ false, ByRef, RefersToCapturedVariable,
18993 Loc, SourceLocation(), CaptureType, Invalid);
18994
18995 return !Invalid;
18996}
18997
18998/// Capture the given variable in the lambda.
18999static bool captureInLambda(LambdaScopeInfo *LSI, ValueDecl *Var,
19000 SourceLocation Loc, const bool BuildAndDiagnose,
19001 QualType &CaptureType, QualType &DeclRefType,
19002 const bool RefersToCapturedVariable,
19003 const Sema::TryCaptureKind Kind,
19004 SourceLocation EllipsisLoc, const bool IsTopScope,
19005 Sema &S, bool Invalid) {
19006 // Determine whether we are capturing by reference or by value.
19007 bool ByRef = false;
19008 if (IsTopScope && Kind != Sema::TryCapture_Implicit) {
19009 ByRef = (Kind == Sema::TryCapture_ExplicitByRef);
19010 } else {
19011 ByRef = (LSI->ImpCaptureStyle == LambdaScopeInfo::ImpCap_LambdaByref);
19012 }
19013
19014 BindingDecl *BD = dyn_cast<BindingDecl>(Var);
19015 // FIXME: We should support capturing structured bindings in OpenMP.
19016 if (!Invalid && BD && S.LangOpts.OpenMP) {
19017 if (BuildAndDiagnose) {
19018 S.Diag(Loc, diag::err_capture_binding_openmp) << Var;
19019 S.Diag(Var->getLocation(), diag::note_entity_declared_at) << Var;
19020 }
19021 Invalid = true;
19022 }
19023
19024 if (BuildAndDiagnose && S.Context.getTargetInfo().getTriple().isWasm() &&
19025 CaptureType.getNonReferenceType()->isWebAssemblyReferenceType()) {
19026 S.Diag(Loc, diag::err_wasm_ca_reference) << 0;
19027 Invalid = true;
19028 }
19029
19030 // Compute the type of the field that will capture this variable.
19031 if (ByRef) {
19032 // C++11 [expr.prim.lambda]p15:
19033 // An entity is captured by reference if it is implicitly or
19034 // explicitly captured but not captured by copy. It is
19035 // unspecified whether additional unnamed non-static data
19036 // members are declared in the closure type for entities
19037 // captured by reference.
19038 //
19039 // FIXME: It is not clear whether we want to build an lvalue reference
19040 // to the DeclRefType or to CaptureType.getNonReferenceType(). GCC appears
19041 // to do the former, while EDG does the latter. Core issue 1249 will
19042 // clarify, but for now we follow GCC because it's a more permissive and
19043 // easily defensible position.
19044 CaptureType = S.Context.getLValueReferenceType(DeclRefType);
19045 } else {
19046 // C++11 [expr.prim.lambda]p14:
19047 // For each entity captured by copy, an unnamed non-static
19048 // data member is declared in the closure type. The
19049 // declaration order of these members is unspecified. The type
19050 // of such a data member is the type of the corresponding
19051 // captured entity if the entity is not a reference to an
19052 // object, or the referenced type otherwise. [Note: If the
19053 // captured entity is a reference to a function, the
19054 // corresponding data member is also a reference to a
19055 // function. - end note ]
19056 if (const ReferenceType *RefType = CaptureType->getAs<ReferenceType>()){
19057 if (!RefType->getPointeeType()->isFunctionType())
19058 CaptureType = RefType->getPointeeType();
19059 }
19060
19061 // Forbid the lambda copy-capture of autoreleasing variables.
19062 if (!Invalid &&
19063 CaptureType.getObjCLifetime() == Qualifiers::OCL_Autoreleasing) {
19064 if (BuildAndDiagnose) {
19065 S.Diag(Loc, diag::err_arc_autoreleasing_capture) << /*lambda*/ 1;
19066 S.Diag(Var->getLocation(), diag::note_previous_decl)
19067 << Var->getDeclName();
19068 Invalid = true;
19069 } else {
19070 return false;
19071 }
19072 }
19073
19074 // Make sure that by-copy captures are of a complete and non-abstract type.
19075 if (!Invalid && BuildAndDiagnose) {
19076 if (!CaptureType->isDependentType() &&
19077 S.RequireCompleteSizedType(
19078 Loc, CaptureType,
19079 diag::err_capture_of_incomplete_or_sizeless_type,
19080 Var->getDeclName()))
19081 Invalid = true;
19082 else if (S.RequireNonAbstractType(Loc, CaptureType,
19083 diag::err_capture_of_abstract_type))
19084 Invalid = true;
19085 }
19086 }
19087
19088 // Compute the type of a reference to this captured variable.
19089 if (ByRef)
19090 DeclRefType = CaptureType.getNonReferenceType();
19091 else {
19092 // C++ [expr.prim.lambda]p5:
19093 // The closure type for a lambda-expression has a public inline
19094 // function call operator [...]. This function call operator is
19095 // declared const (9.3.1) if and only if the lambda-expression's
19096 // parameter-declaration-clause is not followed by mutable.
19097 DeclRefType = CaptureType.getNonReferenceType();
19098 if (!LSI->Mutable && !CaptureType->isReferenceType())
19099 DeclRefType.addConst();
19100 }
19101
19102 // Add the capture.
19103 if (BuildAndDiagnose)
19104 LSI->addCapture(Var, /*isBlock=*/false, ByRef, RefersToCapturedVariable,
19105 Loc, EllipsisLoc, CaptureType, Invalid);
19106
19107 return !Invalid;
19108}
19109
19110static bool canCaptureVariableByCopy(ValueDecl *Var,
19111 const ASTContext &Context) {
19112 // Offer a Copy fix even if the type is dependent.
19113 if (Var->getType()->isDependentType())
19114 return true;
19115 QualType T = Var->getType().getNonReferenceType();
19116 if (T.isTriviallyCopyableType(Context))
19117 return true;
19118 if (CXXRecordDecl *RD = T->getAsCXXRecordDecl()) {
19119
19120 if (!(RD = RD->getDefinition()))
19121 return false;
19122 if (RD->hasSimpleCopyConstructor())
19123 return true;
19124 if (RD->hasUserDeclaredCopyConstructor())
19125 for (CXXConstructorDecl *Ctor : RD->ctors())
19126 if (Ctor->isCopyConstructor())
19127 return !Ctor->isDeleted();
19128 }
19129 return false;
19130}
19131
19132/// Create up to 4 fix-its for explicit reference and value capture of \p Var or
19133/// default capture. Fixes may be omitted if they aren't allowed by the
19134/// standard, for example we can't emit a default copy capture fix-it if we
19135/// already explicitly copy capture capture another variable.
19136static void buildLambdaCaptureFixit(Sema &Sema, LambdaScopeInfo *LSI,
19137 ValueDecl *Var) {
19138 assert(LSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_None)(static_cast <bool> (LSI->ImpCaptureStyle == CapturingScopeInfo
::ImpCap_None) ? void (0) : __assert_fail ("LSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_None"
, "clang/lib/Sema/SemaExpr.cpp", 19138, __extension__ __PRETTY_FUNCTION__
))
;
19139 // Don't offer Capture by copy of default capture by copy fixes if Var is
19140 // known not to be copy constructible.
19141 bool ShouldOfferCopyFix = canCaptureVariableByCopy(Var, Sema.getASTContext());
19142
19143 SmallString<32> FixBuffer;
19144 StringRef Separator = LSI->NumExplicitCaptures > 0 ? ", " : "";
19145 if (Var->getDeclName().isIdentifier() && !Var->getName().empty()) {
19146 SourceLocation VarInsertLoc = LSI->IntroducerRange.getEnd();
19147 if (ShouldOfferCopyFix) {
19148 // Offer fixes to insert an explicit capture for the variable.
19149 // [] -> [VarName]
19150 // [OtherCapture] -> [OtherCapture, VarName]
19151 FixBuffer.assign({Separator, Var->getName()});
19152 Sema.Diag(VarInsertLoc, diag::note_lambda_variable_capture_fixit)
19153 << Var << /*value*/ 0
19154 << FixItHint::CreateInsertion(VarInsertLoc, FixBuffer);
19155 }
19156 // As above but capture by reference.
19157 FixBuffer.assign({Separator, "&", Var->getName()});
19158 Sema.Diag(VarInsertLoc, diag::note_lambda_variable_capture_fixit)
19159 << Var << /*reference*/ 1
19160 << FixItHint::CreateInsertion(VarInsertLoc, FixBuffer);
19161 }
19162
19163 // Only try to offer default capture if there are no captures excluding this
19164 // and init captures.
19165 // [this]: OK.
19166 // [X = Y]: OK.
19167 // [&A, &B]: Don't offer.
19168 // [A, B]: Don't offer.
19169 if (llvm::any_of(LSI->Captures, [](Capture &C) {
19170 return !C.isThisCapture() && !C.isInitCapture();
19171 }))
19172 return;
19173
19174 // The default capture specifiers, '=' or '&', must appear first in the
19175 // capture body.
19176 SourceLocation DefaultInsertLoc =
19177 LSI->IntroducerRange.getBegin().getLocWithOffset(1);
19178
19179 if (ShouldOfferCopyFix) {
19180 bool CanDefaultCopyCapture = true;
19181 // [=, *this] OK since c++17
19182 // [=, this] OK since c++20
19183 if (LSI->isCXXThisCaptured() && !Sema.getLangOpts().CPlusPlus20)
19184 CanDefaultCopyCapture = Sema.getLangOpts().CPlusPlus17
19185 ? LSI->getCXXThisCapture().isCopyCapture()
19186 : false;
19187 // We can't use default capture by copy if any captures already specified
19188 // capture by copy.
19189 if (CanDefaultCopyCapture && llvm::none_of(LSI->Captures, [](Capture &C) {
19190 return !C.isThisCapture() && !C.isInitCapture() && C.isCopyCapture();
19191 })) {
19192 FixBuffer.assign({"=", Separator});
19193 Sema.Diag(DefaultInsertLoc, diag::note_lambda_default_capture_fixit)
19194 << /*value*/ 0
19195 << FixItHint::CreateInsertion(DefaultInsertLoc, FixBuffer);
19196 }
19197 }
19198
19199 // We can't use default capture by reference if any captures already specified
19200 // capture by reference.
19201 if (llvm::none_of(LSI->Captures, [](Capture &C) {
19202 return !C.isInitCapture() && C.isReferenceCapture() &&
19203 !C.isThisCapture();
19204 })) {
19205 FixBuffer.assign({"&", Separator});
19206 Sema.Diag(DefaultInsertLoc, diag::note_lambda_default_capture_fixit)
19207 << /*reference*/ 1
19208 << FixItHint::CreateInsertion(DefaultInsertLoc, FixBuffer);
19209 }
19210}
19211
19212bool Sema::tryCaptureVariable(
19213 ValueDecl *Var, SourceLocation ExprLoc, TryCaptureKind Kind,
19214 SourceLocation EllipsisLoc, bool BuildAndDiagnose, QualType &CaptureType,
19215 QualType &DeclRefType, const unsigned *const FunctionScopeIndexToStopAt) {
19216 // An init-capture is notionally from the context surrounding its
19217 // declaration, but its parent DC is the lambda class.
19218 DeclContext *VarDC = Var->getDeclContext();
19219 DeclContext *DC = CurContext;
19220
19221 // tryCaptureVariable is called every time a DeclRef is formed,
19222 // it can therefore have non-negigible impact on performances.
19223 // For local variables and when there is no capturing scope,
19224 // we can bailout early.
19225 if (CapturingFunctionScopes == 0 && (!BuildAndDiagnose || VarDC == DC))
19226 return true;
19227
19228 const auto *VD = dyn_cast<VarDecl>(Var);
19229 if (VD) {
19230 if (VD->isInitCapture())
19231 VarDC = VarDC->getParent();
19232 } else {
19233 VD = Var->getPotentiallyDecomposedVarDecl();
19234 }
19235 assert(VD && "Cannot capture a null variable")(static_cast <bool> (VD && "Cannot capture a null variable"
) ? void (0) : __assert_fail ("VD && \"Cannot capture a null variable\""
, "clang/lib/Sema/SemaExpr.cpp", 19235, __extension__ __PRETTY_FUNCTION__
))
;
19236
19237 const unsigned MaxFunctionScopesIndex = FunctionScopeIndexToStopAt
19238 ? *FunctionScopeIndexToStopAt : FunctionScopes.size() - 1;
19239 // We need to sync up the Declaration Context with the
19240 // FunctionScopeIndexToStopAt
19241 if (FunctionScopeIndexToStopAt) {
19242 unsigned FSIndex = FunctionScopes.size() - 1;
19243 while (FSIndex != MaxFunctionScopesIndex) {
19244 DC = getLambdaAwareParentOfDeclContext(DC);
19245 --FSIndex;
19246 }
19247 }
19248
19249 // Capture global variables if it is required to use private copy of this
19250 // variable.
19251 bool IsGlobal = !VD->hasLocalStorage();
19252 if (IsGlobal &&
19253 !(LangOpts.OpenMP && isOpenMPCapturedDecl(Var, /*CheckScopeInfo=*/true,
19254 MaxFunctionScopesIndex)))
19255 return true;
19256
19257 if (isa<VarDecl>(Var))
19258 Var = cast<VarDecl>(Var->getCanonicalDecl());
19259
19260 // Walk up the stack to determine whether we can capture the variable,
19261 // performing the "simple" checks that don't depend on type. We stop when
19262 // we've either hit the declared scope of the variable or find an existing
19263 // capture of that variable. We start from the innermost capturing-entity
19264 // (the DC) and ensure that all intervening capturing-entities
19265 // (blocks/lambdas etc.) between the innermost capturer and the variable`s
19266 // declcontext can either capture the variable or have already captured
19267 // the variable.
19268 CaptureType = Var->getType();
19269 DeclRefType = CaptureType.getNonReferenceType();
19270 bool Nested = false;
19271 bool Explicit = (Kind != TryCapture_Implicit);
19272 unsigned FunctionScopesIndex = MaxFunctionScopesIndex;
19273 do {
19274
19275 LambdaScopeInfo *LSI = nullptr;
19276 if (!FunctionScopes.empty())
19277 LSI = dyn_cast_or_null<LambdaScopeInfo>(
19278 FunctionScopes[FunctionScopesIndex]);
19279
19280 bool IsInScopeDeclarationContext =
19281 !LSI || LSI->AfterParameterList || CurContext == LSI->CallOperator;
19282
19283 if (LSI && !LSI->AfterParameterList) {
19284 // This allows capturing parameters from a default value which does not
19285 // seems correct
19286 if (isa<ParmVarDecl>(Var) && !Var->getDeclContext()->isFunctionOrMethod())
19287 return true;
19288 }
19289 // If the variable is declared in the current context, there is no need to
19290 // capture it.
19291 if (IsInScopeDeclarationContext &&
19292 FunctionScopesIndex == MaxFunctionScopesIndex && VarDC == DC)
19293 return true;
19294
19295 // When evaluating some attributes (like enable_if) we might refer to a
19296 // function parameter appertaining to the same declaration as that
19297 // attribute.
19298 if (const auto *Parm = dyn_cast<ParmVarDecl>(Var);
19299 Parm && Parm->getDeclContext() == DC)
19300 return true;
19301
19302 // Only block literals, captured statements, and lambda expressions can
19303 // capture; other scopes don't work.
19304 DeclContext *ParentDC =
19305 !IsInScopeDeclarationContext
19306 ? DC->getParent()
19307 : getParentOfCapturingContextOrNull(DC, Var, ExprLoc,
19308 BuildAndDiagnose, *this);
19309 // We need to check for the parent *first* because, if we *have*
19310 // private-captured a global variable, we need to recursively capture it in
19311 // intermediate blocks, lambdas, etc.
19312 if (!ParentDC) {
19313 if (IsGlobal) {
19314 FunctionScopesIndex = MaxFunctionScopesIndex - 1;
19315 break;
19316 }
19317 return true;
19318 }
19319
19320 FunctionScopeInfo *FSI = FunctionScopes[FunctionScopesIndex];
19321 CapturingScopeInfo *CSI = cast<CapturingScopeInfo>(FSI);
19322
19323 // Check whether we've already captured it.
19324 if (isVariableAlreadyCapturedInScopeInfo(CSI, Var, Nested, CaptureType,
19325 DeclRefType)) {
19326 CSI->getCapture(Var).markUsed(BuildAndDiagnose);
19327 break;
19328 }
19329 // If we are instantiating a generic lambda call operator body,
19330 // we do not want to capture new variables. What was captured
19331 // during either a lambdas transformation or initial parsing
19332 // should be used.
19333 if (isGenericLambdaCallOperatorSpecialization(DC)) {
19334 if (BuildAndDiagnose) {
19335 LambdaScopeInfo *LSI = cast<LambdaScopeInfo>(CSI);
19336 if (LSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_None) {
19337 Diag(ExprLoc, diag::err_lambda_impcap) << Var;
19338 Diag(Var->getLocation(), diag::note_previous_decl) << Var;
19339 Diag(LSI->Lambda->getBeginLoc(), diag::note_lambda_decl);
19340 buildLambdaCaptureFixit(*this, LSI, Var);
19341 } else
19342 diagnoseUncapturableValueReferenceOrBinding(*this, ExprLoc, Var);
19343 }
19344 return true;
19345 }
19346
19347 // Try to capture variable-length arrays types.
19348 if (Var->getType()->isVariablyModifiedType()) {
19349 // We're going to walk down into the type and look for VLA
19350 // expressions.
19351 QualType QTy = Var->getType();
19352 if (ParmVarDecl *PVD = dyn_cast_or_null<ParmVarDecl>(Var))
19353 QTy = PVD->getOriginalType();
19354 captureVariablyModifiedType(Context, QTy, CSI);
19355 }
19356
19357 if (getLangOpts().OpenMP) {
19358 if (auto *RSI = dyn_cast<CapturedRegionScopeInfo>(CSI)) {
19359 // OpenMP private variables should not be captured in outer scope, so
19360 // just break here. Similarly, global variables that are captured in a
19361 // target region should not be captured outside the scope of the region.
19362 if (RSI->CapRegionKind == CR_OpenMP) {
19363 OpenMPClauseKind IsOpenMPPrivateDecl = isOpenMPPrivateDecl(
19364 Var, RSI->OpenMPLevel, RSI->OpenMPCaptureLevel);
19365 // If the variable is private (i.e. not captured) and has variably
19366 // modified type, we still need to capture the type for correct
19367 // codegen in all regions, associated with the construct. Currently,
19368 // it is captured in the innermost captured region only.
19369 if (IsOpenMPPrivateDecl != OMPC_unknown &&
19370 Var->getType()->isVariablyModifiedType()) {
19371 QualType QTy = Var->getType();
19372 if (ParmVarDecl *PVD = dyn_cast_or_null<ParmVarDecl>(Var))
19373 QTy = PVD->getOriginalType();
19374 for (int I = 1, E = getNumberOfConstructScopes(RSI->OpenMPLevel);
19375 I < E; ++I) {
19376 auto *OuterRSI = cast<CapturedRegionScopeInfo>(
19377 FunctionScopes[FunctionScopesIndex - I]);
19378 assert(RSI->OpenMPLevel == OuterRSI->OpenMPLevel &&(static_cast <bool> (RSI->OpenMPLevel == OuterRSI->
OpenMPLevel && "Wrong number of captured regions associated with the "
"OpenMP construct.") ? void (0) : __assert_fail ("RSI->OpenMPLevel == OuterRSI->OpenMPLevel && \"Wrong number of captured regions associated with the \" \"OpenMP construct.\""
, "clang/lib/Sema/SemaExpr.cpp", 19380, __extension__ __PRETTY_FUNCTION__
))
19379 "Wrong number of captured regions associated with the "(static_cast <bool> (RSI->OpenMPLevel == OuterRSI->
OpenMPLevel && "Wrong number of captured regions associated with the "
"OpenMP construct.") ? void (0) : __assert_fail ("RSI->OpenMPLevel == OuterRSI->OpenMPLevel && \"Wrong number of captured regions associated with the \" \"OpenMP construct.\""
, "clang/lib/Sema/SemaExpr.cpp", 19380, __extension__ __PRETTY_FUNCTION__
))
19380 "OpenMP construct.")(static_cast <bool> (RSI->OpenMPLevel == OuterRSI->
OpenMPLevel && "Wrong number of captured regions associated with the "
"OpenMP construct.") ? void (0) : __assert_fail ("RSI->OpenMPLevel == OuterRSI->OpenMPLevel && \"Wrong number of captured regions associated with the \" \"OpenMP construct.\""
, "clang/lib/Sema/SemaExpr.cpp", 19380, __extension__ __PRETTY_FUNCTION__
))
;
19381 captureVariablyModifiedType(Context, QTy, OuterRSI);
19382 }
19383 }
19384 bool IsTargetCap =
19385 IsOpenMPPrivateDecl != OMPC_private &&
19386 isOpenMPTargetCapturedDecl(Var, RSI->OpenMPLevel,
19387 RSI->OpenMPCaptureLevel);
19388 // Do not capture global if it is not privatized in outer regions.
19389 bool IsGlobalCap =
19390 IsGlobal && isOpenMPGlobalCapturedDecl(Var, RSI->OpenMPLevel,
19391 RSI->OpenMPCaptureLevel);
19392
19393 // When we detect target captures we are looking from inside the
19394 // target region, therefore we need to propagate the capture from the
19395 // enclosing region. Therefore, the capture is not initially nested.
19396 if (IsTargetCap)
19397 adjustOpenMPTargetScopeIndex(FunctionScopesIndex, RSI->OpenMPLevel);
19398
19399 if (IsTargetCap || IsOpenMPPrivateDecl == OMPC_private ||
19400 (IsGlobal && !IsGlobalCap)) {
19401 Nested = !IsTargetCap;
19402 bool HasConst = DeclRefType.isConstQualified();
19403 DeclRefType = DeclRefType.getUnqualifiedType();
19404 // Don't lose diagnostics about assignments to const.
19405 if (HasConst)
19406 DeclRefType.addConst();
19407 CaptureType = Context.getLValueReferenceType(DeclRefType);
19408 break;
19409 }
19410 }
19411 }
19412 }
19413 if (CSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_None && !Explicit) {
19414 // No capture-default, and this is not an explicit capture
19415 // so cannot capture this variable.
19416 if (BuildAndDiagnose) {
19417 Diag(ExprLoc, diag::err_lambda_impcap) << Var;
19418 Diag(Var->getLocation(), diag::note_previous_decl) << Var;
19419 auto *LSI = cast<LambdaScopeInfo>(CSI);
19420 if (LSI->Lambda) {
19421 Diag(LSI->Lambda->getBeginLoc(), diag::note_lambda_decl);
19422 buildLambdaCaptureFixit(*this, LSI, Var);
19423 }
19424 // FIXME: If we error out because an outer lambda can not implicitly
19425 // capture a variable that an inner lambda explicitly captures, we
19426 // should have the inner lambda do the explicit capture - because
19427 // it makes for cleaner diagnostics later. This would purely be done
19428 // so that the diagnostic does not misleadingly claim that a variable
19429 // can not be captured by a lambda implicitly even though it is captured
19430 // explicitly. Suggestion:
19431 // - create const bool VariableCaptureWasInitiallyExplicit = Explicit
19432 // at the function head
19433 // - cache the StartingDeclContext - this must be a lambda
19434 // - captureInLambda in the innermost lambda the variable.
19435 }
19436 return true;
19437 }
19438 Explicit = false;
19439 FunctionScopesIndex--;
19440 if (IsInScopeDeclarationContext)
19441 DC = ParentDC;
19442 } while (!VarDC->Equals(DC));
19443
19444 // Walk back down the scope stack, (e.g. from outer lambda to inner lambda)
19445 // computing the type of the capture at each step, checking type-specific
19446 // requirements, and adding captures if requested.
19447 // If the variable had already been captured previously, we start capturing
19448 // at the lambda nested within that one.
19449 bool Invalid = false;
19450 for (unsigned I = ++FunctionScopesIndex, N = MaxFunctionScopesIndex + 1; I != N;
19451 ++I) {
19452 CapturingScopeInfo *CSI = cast<CapturingScopeInfo>(FunctionScopes[I]);
19453
19454 // Certain capturing entities (lambdas, blocks etc.) are not allowed to capture
19455 // certain types of variables (unnamed, variably modified types etc.)
19456 // so check for eligibility.
19457 if (!Invalid)
19458 Invalid =
19459 !isVariableCapturable(CSI, Var, ExprLoc, BuildAndDiagnose, *this);
19460
19461 // After encountering an error, if we're actually supposed to capture, keep
19462 // capturing in nested contexts to suppress any follow-on diagnostics.
19463 if (Invalid && !BuildAndDiagnose)
19464 return true;
19465
19466 if (BlockScopeInfo *BSI = dyn_cast<BlockScopeInfo>(CSI)) {
19467 Invalid = !captureInBlock(BSI, Var, ExprLoc, BuildAndDiagnose, CaptureType,
19468 DeclRefType, Nested, *this, Invalid);
19469 Nested = true;
19470 } else if (CapturedRegionScopeInfo *RSI = dyn_cast<CapturedRegionScopeInfo>(CSI)) {
19471 Invalid = !captureInCapturedRegion(
19472 RSI, Var, ExprLoc, BuildAndDiagnose, CaptureType, DeclRefType, Nested,
19473 Kind, /*IsTopScope*/ I == N - 1, *this, Invalid);
19474 Nested = true;
19475 } else {
19476 LambdaScopeInfo *LSI = cast<LambdaScopeInfo>(CSI);
19477 Invalid =
19478 !captureInLambda(LSI, Var, ExprLoc, BuildAndDiagnose, CaptureType,
19479 DeclRefType, Nested, Kind, EllipsisLoc,
19480 /*IsTopScope*/ I == N - 1, *this, Invalid);
19481 Nested = true;
19482 }
19483
19484 if (Invalid && !BuildAndDiagnose)
19485 return true;
19486 }
19487 return Invalid;
19488}
19489
19490bool Sema::tryCaptureVariable(ValueDecl *Var, SourceLocation Loc,
19491 TryCaptureKind Kind, SourceLocation EllipsisLoc) {
19492 QualType CaptureType;
19493 QualType DeclRefType;
19494 return tryCaptureVariable(Var, Loc, Kind, EllipsisLoc,
19495 /*BuildAndDiagnose=*/true, CaptureType,
19496 DeclRefType, nullptr);
19497}
19498
19499bool Sema::NeedToCaptureVariable(ValueDecl *Var, SourceLocation Loc) {
19500 QualType CaptureType;
19501 QualType DeclRefType;
19502 return !tryCaptureVariable(Var, Loc, TryCapture_Implicit, SourceLocation(),
19503 /*BuildAndDiagnose=*/false, CaptureType,
19504 DeclRefType, nullptr);
19505}
19506
19507QualType Sema::getCapturedDeclRefType(ValueDecl *Var, SourceLocation Loc) {
19508 QualType CaptureType;
19509 QualType DeclRefType;
19510
19511 // Determine whether we can capture this variable.
19512 if (tryCaptureVariable(Var, Loc, TryCapture_Implicit, SourceLocation(),
19513 /*BuildAndDiagnose=*/false, CaptureType,
19514 DeclRefType, nullptr))
19515 return QualType();
19516
19517 return DeclRefType;
19518}
19519
19520namespace {
19521// Helper to copy the template arguments from a DeclRefExpr or MemberExpr.
19522// The produced TemplateArgumentListInfo* points to data stored within this
19523// object, so should only be used in contexts where the pointer will not be
19524// used after the CopiedTemplateArgs object is destroyed.
19525class CopiedTemplateArgs {
19526 bool HasArgs;
19527 TemplateArgumentListInfo TemplateArgStorage;
19528public:
19529 template<typename RefExpr>
19530 CopiedTemplateArgs(RefExpr *E) : HasArgs(E->hasExplicitTemplateArgs()) {
19531 if (HasArgs)
19532 E->copyTemplateArgumentsInto(TemplateArgStorage);
19533 }
19534 operator TemplateArgumentListInfo*()
19535#ifdef __has_cpp_attribute
19536#if0 __has_cpp_attribute(clang::lifetimebound)1
19537 [[clang::lifetimebound]]
19538#endif
19539#endif
19540 {
19541 return HasArgs ? &TemplateArgStorage : nullptr;
19542 }
19543};
19544}
19545
19546/// Walk the set of potential results of an expression and mark them all as
19547/// non-odr-uses if they satisfy the side-conditions of the NonOdrUseReason.
19548///
19549/// \return A new expression if we found any potential results, ExprEmpty() if
19550/// not, and ExprError() if we diagnosed an error.
19551static ExprResult rebuildPotentialResultsAsNonOdrUsed(Sema &S, Expr *E,
19552 NonOdrUseReason NOUR) {
19553 // Per C++11 [basic.def.odr], a variable is odr-used "unless it is
19554 // an object that satisfies the requirements for appearing in a
19555 // constant expression (5.19) and the lvalue-to-rvalue conversion (4.1)
19556 // is immediately applied." This function handles the lvalue-to-rvalue
19557 // conversion part.
19558 //
19559 // If we encounter a node that claims to be an odr-use but shouldn't be, we
19560 // transform it into the relevant kind of non-odr-use node and rebuild the
19561 // tree of nodes leading to it.
19562 //
19563 // This is a mini-TreeTransform that only transforms a restricted subset of
19564 // nodes (and only certain operands of them).
19565
19566 // Rebuild a subexpression.
19567 auto Rebuild = [&](Expr *Sub) {
19568 return rebuildPotentialResultsAsNonOdrUsed(S, Sub, NOUR);
19569 };
19570
19571 // Check whether a potential result satisfies the requirements of NOUR.
19572 auto IsPotentialResultOdrUsed = [&](NamedDecl *D) {
19573 // Any entity other than a VarDecl is always odr-used whenever it's named
19574 // in a potentially-evaluated expression.
19575 auto *VD = dyn_cast<VarDecl>(D);
19576 if (!VD)
19577 return true;
19578
19579 // C++2a [basic.def.odr]p4:
19580 // A variable x whose name appears as a potentially-evalauted expression
19581 // e is odr-used by e unless
19582 // -- x is a reference that is usable in constant expressions, or
19583 // -- x is a variable of non-reference type that is usable in constant
19584 // expressions and has no mutable subobjects, and e is an element of
19585 // the set of potential results of an expression of
19586 // non-volatile-qualified non-class type to which the lvalue-to-rvalue
19587 // conversion is applied, or
19588 // -- x is a variable of non-reference type, and e is an element of the
19589 // set of potential results of a discarded-value expression to which
19590 // the lvalue-to-rvalue conversion is not applied
19591 //
19592 // We check the first bullet and the "potentially-evaluated" condition in
19593 // BuildDeclRefExpr. We check the type requirements in the second bullet
19594 // in CheckLValueToRValueConversionOperand below.
19595 switch (NOUR) {
19596 case NOUR_None:
19597 case NOUR_Unevaluated:
19598 llvm_unreachable("unexpected non-odr-use-reason")::llvm::llvm_unreachable_internal("unexpected non-odr-use-reason"
, "clang/lib/Sema/SemaExpr.cpp", 19598)
;
19599
19600 case NOUR_Constant:
19601 // Constant references were handled when they were built.
19602 if (VD->getType()->isReferenceType())
19603 return true;
19604 if (auto *RD = VD->getType()->getAsCXXRecordDecl())
19605 if (RD->hasMutableFields())
19606 return true;
19607 if (!VD->isUsableInConstantExpressions(S.Context))
19608 return true;
19609 break;
19610
19611 case NOUR_Discarded:
19612 if (VD->getType()->isReferenceType())
19613 return true;
19614 break;
19615 }
19616 return false;
19617 };
19618
19619 // Mark that this expression does not constitute an odr-use.
19620 auto MarkNotOdrUsed = [&] {
19621 S.MaybeODRUseExprs.remove(E);
19622 if (LambdaScopeInfo *LSI = S.getCurLambda())
19623 LSI->markVariableExprAsNonODRUsed(E);
19624 };
19625
19626 // C++2a [basic.def.odr]p2:
19627 // The set of potential results of an expression e is defined as follows:
19628 switch (E->getStmtClass()) {
19629 // -- If e is an id-expression, ...
19630 case Expr::DeclRefExprClass: {
19631 auto *DRE = cast<DeclRefExpr>(E);
19632 if (DRE->isNonOdrUse() || IsPotentialResultOdrUsed(DRE->getDecl()))
19633 break;
19634
19635 // Rebuild as a non-odr-use DeclRefExpr.
19636 MarkNotOdrUsed();
19637 return DeclRefExpr::Create(
19638 S.Context, DRE->getQualifierLoc(), DRE->getTemplateKeywordLoc(),
19639 DRE->getDecl(), DRE->refersToEnclosingVariableOrCapture(),
19640 DRE->getNameInfo(), DRE->getType(), DRE->getValueKind(),
19641 DRE->getFoundDecl(), CopiedTemplateArgs(DRE), NOUR);
19642 }
19643
19644 case Expr::FunctionParmPackExprClass: {
19645 auto *FPPE = cast<FunctionParmPackExpr>(E);
19646 // If any of the declarations in the pack is odr-used, then the expression
19647 // as a whole constitutes an odr-use.
19648 for (VarDecl *D : *FPPE)
19649 if (IsPotentialResultOdrUsed(D))
19650 return ExprEmpty();
19651
19652 // FIXME: Rebuild as a non-odr-use FunctionParmPackExpr? In practice,
19653 // nothing cares about whether we marked this as an odr-use, but it might
19654 // be useful for non-compiler tools.
19655 MarkNotOdrUsed();
19656 break;
19657 }
19658
19659 // -- If e is a subscripting operation with an array operand...
19660 case Expr::ArraySubscriptExprClass: {
19661 auto *ASE = cast<ArraySubscriptExpr>(E);
19662 Expr *OldBase = ASE->getBase()->IgnoreImplicit();
19663 if (!OldBase->getType()->isArrayType())
19664 break;
19665 ExprResult Base = Rebuild(OldBase);
19666 if (!Base.isUsable())
19667 return Base;
19668 Expr *LHS = ASE->getBase() == ASE->getLHS() ? Base.get() : ASE->getLHS();
19669 Expr *RHS = ASE->getBase() == ASE->getRHS() ? Base.get() : ASE->getRHS();
19670 SourceLocation LBracketLoc = ASE->getBeginLoc(); // FIXME: Not stored.
19671 return S.ActOnArraySubscriptExpr(nullptr, LHS, LBracketLoc, RHS,
19672 ASE->getRBracketLoc());
19673 }
19674
19675 case Expr::MemberExprClass: {
19676 auto *ME = cast<MemberExpr>(E);
19677 // -- If e is a class member access expression [...] naming a non-static
19678 // data member...
19679 if (isa<FieldDecl>(ME->getMemberDecl())) {
19680 ExprResult Base = Rebuild(ME->getBase());
19681 if (!Base.isUsable())
19682 return Base;
19683 return MemberExpr::Create(
19684 S.Context, Base.get(), ME->isArrow(), ME->getOperatorLoc(),
19685 ME->getQualifierLoc(), ME->getTemplateKeywordLoc(),
19686 ME->getMemberDecl(), ME->getFoundDecl(), ME->getMemberNameInfo(),
19687 CopiedTemplateArgs(ME), ME->getType(), ME->getValueKind(),
19688 ME->getObjectKind(), ME->isNonOdrUse());
19689 }
19690
19691 if (ME->getMemberDecl()->isCXXInstanceMember())
19692 break;
19693
19694 // -- If e is a class member access expression naming a static data member,
19695 // ...
19696 if (ME->isNonOdrUse() || IsPotentialResultOdrUsed(ME->getMemberDecl()))
19697 break;
19698
19699 // Rebuild as a non-odr-use MemberExpr.
19700 MarkNotOdrUsed();
19701 return MemberExpr::Create(
19702 S.Context, ME->getBase(), ME->isArrow(), ME->getOperatorLoc(),
19703 ME->getQualifierLoc(), ME->getTemplateKeywordLoc(), ME->getMemberDecl(),
19704 ME->getFoundDecl(), ME->getMemberNameInfo(), CopiedTemplateArgs(ME),
19705 ME->getType(), ME->getValueKind(), ME->getObjectKind(), NOUR);
19706 }
19707
19708 case Expr::BinaryOperatorClass: {
19709 auto *BO = cast<BinaryOperator>(E);
19710 Expr *LHS = BO->getLHS();
19711 Expr *RHS = BO->getRHS();
19712 // -- If e is a pointer-to-member expression of the form e1 .* e2 ...
19713 if (BO->getOpcode() == BO_PtrMemD) {
19714 ExprResult Sub = Rebuild(LHS);
19715 if (!Sub.isUsable())
19716 return Sub;
19717 LHS = Sub.get();
19718 // -- If e is a comma expression, ...
19719 } else if (BO->getOpcode() == BO_Comma) {
19720 ExprResult Sub = Rebuild(RHS);
19721 if (!Sub.isUsable())
19722 return Sub;
19723 RHS = Sub.get();
19724 } else {
19725 break;
19726 }
19727 return S.BuildBinOp(nullptr, BO->getOperatorLoc(), BO->getOpcode(),
19728 LHS, RHS);
19729 }
19730
19731 // -- If e has the form (e1)...
19732 case Expr::ParenExprClass: {
19733 auto *PE = cast<ParenExpr>(E);
19734 ExprResult Sub = Rebuild(PE->getSubExpr());
19735 if (!Sub.isUsable())
19736 return Sub;
19737 return S.ActOnParenExpr(PE->getLParen(), PE->getRParen(), Sub.get());
19738 }
19739
19740 // -- If e is a glvalue conditional expression, ...
19741 // We don't apply this to a binary conditional operator. FIXME: Should we?
19742 case Expr::ConditionalOperatorClass: {
19743 auto *CO = cast<ConditionalOperator>(E);
19744 ExprResult LHS = Rebuild(CO->getLHS());
19745 if (LHS.isInvalid())
19746 return ExprError();
19747 ExprResult RHS = Rebuild(CO->getRHS());
19748 if (RHS.isInvalid())
19749 return ExprError();
19750 if (!LHS.isUsable() && !RHS.isUsable())
19751 return ExprEmpty();
19752 if (!LHS.isUsable())
19753 LHS = CO->getLHS();
19754 if (!RHS.isUsable())
19755 RHS = CO->getRHS();
19756 return S.ActOnConditionalOp(CO->getQuestionLoc(), CO->getColonLoc(),
19757 CO->getCond(), LHS.get(), RHS.get());
19758 }
19759
19760 // [Clang extension]
19761 // -- If e has the form __extension__ e1...
19762 case Expr::UnaryOperatorClass: {
19763 auto *UO = cast<UnaryOperator>(E);
19764 if (UO->getOpcode() != UO_Extension)
19765 break;
19766 ExprResult Sub = Rebuild(UO->getSubExpr());
19767 if (!Sub.isUsable())
19768 return Sub;
19769 return S.BuildUnaryOp(nullptr, UO->getOperatorLoc(), UO_Extension,
19770 Sub.get());
19771 }
19772
19773 // [Clang extension]
19774 // -- If e has the form _Generic(...), the set of potential results is the
19775 // union of the sets of potential results of the associated expressions.
19776 case Expr::GenericSelectionExprClass: {
19777 auto *GSE = cast<GenericSelectionExpr>(E);
19778
19779 SmallVector<Expr *, 4> AssocExprs;
19780 bool AnyChanged = false;
19781 for (Expr *OrigAssocExpr : GSE->getAssocExprs()) {
19782 ExprResult AssocExpr = Rebuild(OrigAssocExpr);
19783 if (AssocExpr.isInvalid())
19784 return ExprError();
19785 if (AssocExpr.isUsable()) {
19786 AssocExprs.push_back(AssocExpr.get());
19787 AnyChanged = true;
19788 } else {
19789 AssocExprs.push_back(OrigAssocExpr);
19790 }
19791 }
19792
19793 return AnyChanged ? S.CreateGenericSelectionExpr(
19794 GSE->getGenericLoc(), GSE->getDefaultLoc(),
19795 GSE->getRParenLoc(), GSE->getControllingExpr(),
19796 GSE->getAssocTypeSourceInfos(), AssocExprs)
19797 : ExprEmpty();
19798 }
19799
19800 // [Clang extension]
19801 // -- If e has the form __builtin_choose_expr(...), the set of potential
19802 // results is the union of the sets of potential results of the
19803 // second and third subexpressions.
19804 case Expr::ChooseExprClass: {
19805 auto *CE = cast<ChooseExpr>(E);
19806
19807 ExprResult LHS = Rebuild(CE->getLHS());
19808 if (LHS.isInvalid())
19809 return ExprError();
19810
19811 ExprResult RHS = Rebuild(CE->getLHS());
19812 if (RHS.isInvalid())
19813 return ExprError();
19814
19815 if (!LHS.get() && !RHS.get())
19816 return ExprEmpty();
19817 if (!LHS.isUsable())
19818 LHS = CE->getLHS();
19819 if (!RHS.isUsable())
19820 RHS = CE->getRHS();
19821
19822 return S.ActOnChooseExpr(CE->getBuiltinLoc(), CE->getCond(), LHS.get(),
19823 RHS.get(), CE->getRParenLoc());
19824 }
19825
19826 // Step through non-syntactic nodes.
19827 case Expr::ConstantExprClass: {
19828 auto *CE = cast<ConstantExpr>(E);
19829 ExprResult Sub = Rebuild(CE->getSubExpr());
19830 if (!Sub.isUsable())
19831 return Sub;
19832 return ConstantExpr::Create(S.Context, Sub.get());
19833 }
19834
19835 // We could mostly rely on the recursive rebuilding to rebuild implicit
19836 // casts, but not at the top level, so rebuild them here.
19837 case Expr::ImplicitCastExprClass: {
19838 auto *ICE = cast<ImplicitCastExpr>(E);
19839 // Only step through the narrow set of cast kinds we expect to encounter.
19840 // Anything else suggests we've left the region in which potential results
19841 // can be found.
19842 switch (ICE->getCastKind()) {
19843 case CK_NoOp:
19844 case CK_DerivedToBase:
19845 case CK_UncheckedDerivedToBase: {
19846 ExprResult Sub = Rebuild(ICE->getSubExpr());
19847 if (!Sub.isUsable())
19848 return Sub;
19849 CXXCastPath Path(ICE->path());
19850 return S.ImpCastExprToType(Sub.get(), ICE->getType(), ICE->getCastKind(),
19851 ICE->getValueKind(), &Path);
19852 }
19853
19854 default:
19855 break;
19856 }
19857 break;
19858 }
19859
19860 default:
19861 break;
19862 }
19863
19864 // Can't traverse through this node. Nothing to do.
19865 return ExprEmpty();
19866}
19867
19868ExprResult Sema::CheckLValueToRValueConversionOperand(Expr *E) {
19869 // Check whether the operand is or contains an object of non-trivial C union
19870 // type.
19871 if (E->getType().isVolatileQualified() &&
19872 (E->getType().hasNonTrivialToPrimitiveDestructCUnion() ||
19873 E->getType().hasNonTrivialToPrimitiveCopyCUnion()))
19874 checkNonTrivialCUnion(E->getType(), E->getExprLoc(),
19875 Sema::NTCUC_LValueToRValueVolatile,
19876 NTCUK_Destruct|NTCUK_Copy);
19877
19878 // C++2a [basic.def.odr]p4:
19879 // [...] an expression of non-volatile-qualified non-class type to which
19880 // the lvalue-to-rvalue conversion is applied [...]
19881 if (E->getType().isVolatileQualified() || E->getType()->getAs<RecordType>())
19882 return E;
19883
19884 ExprResult Result =
19885 rebuildPotentialResultsAsNonOdrUsed(*this, E, NOUR_Constant);
19886 if (Result.isInvalid())
19887 return ExprError();
19888 return Result.get() ? Result : E;
19889}
19890
19891ExprResult Sema::ActOnConstantExpression(ExprResult Res) {
19892 Res = CorrectDelayedTyposInExpr(Res);
19893
19894 if (!Res.isUsable())
19895 return Res;
19896
19897 // If a constant-expression is a reference to a variable where we delay
19898 // deciding whether it is an odr-use, just assume we will apply the
19899 // lvalue-to-rvalue conversion. In the one case where this doesn't happen
19900 // (a non-type template argument), we have special handling anyway.
19901 return CheckLValueToRValueConversionOperand(Res.get());
19902}
19903
19904void Sema::CleanupVarDeclMarking() {
19905 // Iterate through a local copy in case MarkVarDeclODRUsed makes a recursive
19906 // call.
19907 MaybeODRUseExprSet LocalMaybeODRUseExprs;
19908 std::swap(LocalMaybeODRUseExprs, MaybeODRUseExprs);
19909
19910 for (Expr *E : LocalMaybeODRUseExprs) {
19911 if (auto *DRE = dyn_cast<DeclRefExpr>(E)) {
19912 MarkVarDeclODRUsed(cast<VarDecl>(DRE->getDecl()),
19913 DRE->getLocation(), *this);
19914 } else if (auto *ME = dyn_cast<MemberExpr>(E)) {
19915 MarkVarDeclODRUsed(cast<VarDecl>(ME->getMemberDecl()), ME->getMemberLoc(),
19916 *this);
19917 } else if (auto *FP = dyn_cast<FunctionParmPackExpr>(E)) {
19918 for (VarDecl *VD : *FP)
19919 MarkVarDeclODRUsed(VD, FP->getParameterPackLocation(), *this);
19920 } else {
19921 llvm_unreachable("Unexpected expression")::llvm::llvm_unreachable_internal("Unexpected expression", "clang/lib/Sema/SemaExpr.cpp"
, 19921)
;
19922 }
19923 }
19924
19925 assert(MaybeODRUseExprs.empty() &&(static_cast <bool> (MaybeODRUseExprs.empty() &&
"MarkVarDeclODRUsed failed to cleanup MaybeODRUseExprs?") ? void
(0) : __assert_fail ("MaybeODRUseExprs.empty() && \"MarkVarDeclODRUsed failed to cleanup MaybeODRUseExprs?\""
, "clang/lib/Sema/SemaExpr.cpp", 19926, __extension__ __PRETTY_FUNCTION__
))
19926 "MarkVarDeclODRUsed failed to cleanup MaybeODRUseExprs?")(static_cast <bool> (MaybeODRUseExprs.empty() &&
"MarkVarDeclODRUsed failed to cleanup MaybeODRUseExprs?") ? void
(0) : __assert_fail ("MaybeODRUseExprs.empty() && \"MarkVarDeclODRUsed failed to cleanup MaybeODRUseExprs?\""
, "clang/lib/Sema/SemaExpr.cpp", 19926, __extension__ __PRETTY_FUNCTION__
))
;
19927}
19928
19929static void DoMarkPotentialCapture(Sema &SemaRef, SourceLocation Loc,
19930 ValueDecl *Var, Expr *E) {
19931 VarDecl *VD = Var->getPotentiallyDecomposedVarDecl();
19932 if (!VD)
19933 return;
19934
19935 const bool RefersToEnclosingScope =
19936 (SemaRef.CurContext != VD->getDeclContext() &&
19937 VD->getDeclContext()->isFunctionOrMethod() && VD->hasLocalStorage());
19938 if (RefersToEnclosingScope) {
19939 LambdaScopeInfo *const LSI =
19940 SemaRef.getCurLambda(/*IgnoreNonLambdaCapturingScope=*/true);
19941 if (LSI && (!LSI->CallOperator ||
19942 !LSI->CallOperator->Encloses(Var->getDeclContext()))) {
19943 // If a variable could potentially be odr-used, defer marking it so
19944 // until we finish analyzing the full expression for any
19945 // lvalue-to-rvalue
19946 // or discarded value conversions that would obviate odr-use.
19947 // Add it to the list of potential captures that will be analyzed
19948 // later (ActOnFinishFullExpr) for eventual capture and odr-use marking
19949 // unless the variable is a reference that was initialized by a constant
19950 // expression (this will never need to be captured or odr-used).
19951 //
19952 // FIXME: We can simplify this a lot after implementing P0588R1.
19953 assert(E && "Capture variable should be used in an expression.")(static_cast <bool> (E && "Capture variable should be used in an expression."
) ? void (0) : __assert_fail ("E && \"Capture variable should be used in an expression.\""
, "clang/lib/Sema/SemaExpr.cpp", 19953, __extension__ __PRETTY_FUNCTION__
))
;
19954 if (!Var->getType()->isReferenceType() ||
19955 !VD->isUsableInConstantExpressions(SemaRef.Context))
19956 LSI->addPotentialCapture(E->IgnoreParens());
19957 }
19958 }
19959}
19960
19961static void DoMarkVarDeclReferenced(
19962 Sema &SemaRef, SourceLocation Loc, VarDecl *Var, Expr *E,
19963 llvm::DenseMap<const VarDecl *, int> &RefsMinusAssignments) {
19964 assert((!E || isa<DeclRefExpr>(E) || isa<MemberExpr>(E) ||(static_cast <bool> ((!E || isa<DeclRefExpr>(E) ||
isa<MemberExpr>(E) || isa<FunctionParmPackExpr>(
E)) && "Invalid Expr argument to DoMarkVarDeclReferenced"
) ? void (0) : __assert_fail ("(!E || isa<DeclRefExpr>(E) || isa<MemberExpr>(E) || isa<FunctionParmPackExpr>(E)) && \"Invalid Expr argument to DoMarkVarDeclReferenced\""
, "clang/lib/Sema/SemaExpr.cpp", 19966, __extension__ __PRETTY_FUNCTION__
))
19965 isa<FunctionParmPackExpr>(E)) &&(static_cast <bool> ((!E || isa<DeclRefExpr>(E) ||
isa<MemberExpr>(E) || isa<FunctionParmPackExpr>(
E)) && "Invalid Expr argument to DoMarkVarDeclReferenced"
) ? void (0) : __assert_fail ("(!E || isa<DeclRefExpr>(E) || isa<MemberExpr>(E) || isa<FunctionParmPackExpr>(E)) && \"Invalid Expr argument to DoMarkVarDeclReferenced\""
, "clang/lib/Sema/SemaExpr.cpp", 19966, __extension__ __PRETTY_FUNCTION__
))
19966 "Invalid Expr argument to DoMarkVarDeclReferenced")(static_cast <bool> ((!E || isa<DeclRefExpr>(E) ||
isa<MemberExpr>(E) || isa<FunctionParmPackExpr>(
E)) && "Invalid Expr argument to DoMarkVarDeclReferenced"
) ? void (0) : __assert_fail ("(!E || isa<DeclRefExpr>(E) || isa<MemberExpr>(E) || isa<FunctionParmPackExpr>(E)) && \"Invalid Expr argument to DoMarkVarDeclReferenced\""
, "clang/lib/Sema/SemaExpr.cpp", 19966, __extension__ __PRETTY_FUNCTION__
))
;
19967 Var->setReferenced();
19968
19969 if (Var->isInvalidDecl())
19970 return;
19971
19972 auto *MSI = Var->getMemberSpecializationInfo();
19973 TemplateSpecializationKind TSK = MSI ? MSI->getTemplateSpecializationKind()
19974 : Var->getTemplateSpecializationKind();
19975
19976 OdrUseContext OdrUse = isOdrUseContext(SemaRef);
19977 bool UsableInConstantExpr =
19978 Var->mightBeUsableInConstantExpressions(SemaRef.Context);
19979
19980 if (Var->isLocalVarDeclOrParm() && !Var->hasExternalStorage()) {
19981 RefsMinusAssignments.insert({Var, 0}).first->getSecond()++;
19982 }
19983
19984 // C++20 [expr.const]p12:
19985 // A variable [...] is needed for constant evaluation if it is [...] a
19986 // variable whose name appears as a potentially constant evaluated
19987 // expression that is either a contexpr variable or is of non-volatile
19988 // const-qualified integral type or of reference type
19989 bool NeededForConstantEvaluation =
19990 isPotentiallyConstantEvaluatedContext(SemaRef) && UsableInConstantExpr;
19991
19992 bool NeedDefinition =
19993 OdrUse == OdrUseContext::Used || NeededForConstantEvaluation;
19994
19995 assert(!isa<VarTemplatePartialSpecializationDecl>(Var) &&(static_cast <bool> (!isa<VarTemplatePartialSpecializationDecl
>(Var) && "Can't instantiate a partial template specialization."
) ? void (0) : __assert_fail ("!isa<VarTemplatePartialSpecializationDecl>(Var) && \"Can't instantiate a partial template specialization.\""
, "clang/lib/Sema/SemaExpr.cpp", 19996, __extension__ __PRETTY_FUNCTION__
))
19996 "Can't instantiate a partial template specialization.")(static_cast <bool> (!isa<VarTemplatePartialSpecializationDecl
>(Var) && "Can't instantiate a partial template specialization."
) ? void (0) : __assert_fail ("!isa<VarTemplatePartialSpecializationDecl>(Var) && \"Can't instantiate a partial template specialization.\""
, "clang/lib/Sema/SemaExpr.cpp", 19996, __extension__ __PRETTY_FUNCTION__
))
;
19997
19998 // If this might be a member specialization of a static data member, check
19999 // the specialization is visible. We already did the checks for variable
20000 // template specializations when we created them.
20001 if (NeedDefinition && TSK != TSK_Undeclared &&
20002 !isa<VarTemplateSpecializationDecl>(Var))
20003 SemaRef.checkSpecializationVisibility(Loc, Var);
20004
20005 // Perform implicit instantiation of static data members, static data member
20006 // templates of class templates, and variable template specializations. Delay
20007 // instantiations of variable templates, except for those that could be used
20008 // in a constant expression.
20009 if (NeedDefinition && isTemplateInstantiation(TSK)) {
20010 // Per C++17 [temp.explicit]p10, we may instantiate despite an explicit
20011 // instantiation declaration if a variable is usable in a constant
20012 // expression (among other cases).
20013 bool TryInstantiating =
20014 TSK == TSK_ImplicitInstantiation ||
20015 (TSK == TSK_ExplicitInstantiationDeclaration && UsableInConstantExpr);
20016
20017 if (TryInstantiating) {
20018 SourceLocation PointOfInstantiation =
20019 MSI ? MSI->getPointOfInstantiation() : Var->getPointOfInstantiation();
20020 bool FirstInstantiation = PointOfInstantiation.isInvalid();
20021 if (FirstInstantiation) {
20022 PointOfInstantiation = Loc;
20023 if (MSI)
20024 MSI->setPointOfInstantiation(PointOfInstantiation);
20025 // FIXME: Notify listener.
20026 else
20027 Var->setTemplateSpecializationKind(TSK, PointOfInstantiation);
20028 }
20029
20030 if (UsableInConstantExpr) {
20031 // Do not defer instantiations of variables that could be used in a
20032 // constant expression.
20033 SemaRef.runWithSufficientStackSpace(PointOfInstantiation, [&] {
20034 SemaRef.InstantiateVariableDefinition(PointOfInstantiation, Var);
20035 });
20036
20037 // Re-set the member to trigger a recomputation of the dependence bits
20038 // for the expression.
20039 if (auto *DRE = dyn_cast_or_null<DeclRefExpr>(E))
20040 DRE->setDecl(DRE->getDecl());
20041 else if (auto *ME = dyn_cast_or_null<MemberExpr>(E))
20042 ME->setMemberDecl(ME->getMemberDecl());
20043 } else if (FirstInstantiation) {
20044 SemaRef.PendingInstantiations
20045 .push_back(std::make_pair(Var, PointOfInstantiation));
20046 } else {
20047 bool Inserted = false;
20048 for (auto &I : SemaRef.SavedPendingInstantiations) {
20049 auto Iter = llvm::find_if(
20050 I, [Var](const Sema::PendingImplicitInstantiation &P) {
20051 return P.first == Var;
20052 });
20053 if (Iter != I.end()) {
20054 SemaRef.PendingInstantiations.push_back(*Iter);
20055 I.erase(Iter);
20056 Inserted = true;
20057 break;
20058 }
20059 }
20060
20061 // FIXME: For a specialization of a variable template, we don't
20062 // distinguish between "declaration and type implicitly instantiated"
20063 // and "implicit instantiation of definition requested", so we have
20064 // no direct way to avoid enqueueing the pending instantiation
20065 // multiple times.
20066 if (isa<VarTemplateSpecializationDecl>(Var) && !Inserted)
20067 SemaRef.PendingInstantiations
20068 .push_back(std::make_pair(Var, PointOfInstantiation));
20069 }
20070 }
20071 }
20072
20073 // C++2a [basic.def.odr]p4:
20074 // A variable x whose name appears as a potentially-evaluated expression e
20075 // is odr-used by e unless
20076 // -- x is a reference that is usable in constant expressions
20077 // -- x is a variable of non-reference type that is usable in constant
20078 // expressions and has no mutable subobjects [FIXME], and e is an
20079 // element of the set of potential results of an expression of
20080 // non-volatile-qualified non-class type to which the lvalue-to-rvalue
20081 // conversion is applied
20082 // -- x is a variable of non-reference type, and e is an element of the set
20083 // of potential results of a discarded-value expression to which the
20084 // lvalue-to-rvalue conversion is not applied [FIXME]
20085 //
20086 // We check the first part of the second bullet here, and
20087 // Sema::CheckLValueToRValueConversionOperand deals with the second part.
20088 // FIXME: To get the third bullet right, we need to delay this even for
20089 // variables that are not usable in constant expressions.
20090
20091 // If we already know this isn't an odr-use, there's nothing more to do.
20092 if (DeclRefExpr *DRE = dyn_cast_or_null<DeclRefExpr>(E))
20093 if (DRE->isNonOdrUse())
20094 return;
20095 if (MemberExpr *ME = dyn_cast_or_null<MemberExpr>(E))
20096 if (ME->isNonOdrUse())
20097 return;
20098
20099 switch (OdrUse) {
20100 case OdrUseContext::None:
20101 // In some cases, a variable may not have been marked unevaluated, if it
20102 // appears in a defaukt initializer.
20103 assert((!E || isa<FunctionParmPackExpr>(E) ||(static_cast <bool> ((!E || isa<FunctionParmPackExpr
>(E) || SemaRef.isUnevaluatedContext()) && "missing non-odr-use marking for unevaluated decl ref"
) ? void (0) : __assert_fail ("(!E || isa<FunctionParmPackExpr>(E) || SemaRef.isUnevaluatedContext()) && \"missing non-odr-use marking for unevaluated decl ref\""
, "clang/lib/Sema/SemaExpr.cpp", 20105, __extension__ __PRETTY_FUNCTION__
))
20104 SemaRef.isUnevaluatedContext()) &&(static_cast <bool> ((!E || isa<FunctionParmPackExpr
>(E) || SemaRef.isUnevaluatedContext()) && "missing non-odr-use marking for unevaluated decl ref"
) ? void (0) : __assert_fail ("(!E || isa<FunctionParmPackExpr>(E) || SemaRef.isUnevaluatedContext()) && \"missing non-odr-use marking for unevaluated decl ref\""
, "clang/lib/Sema/SemaExpr.cpp", 20105, __extension__ __PRETTY_FUNCTION__
))
20105 "missing non-odr-use marking for unevaluated decl ref")(static_cast <bool> ((!E || isa<FunctionParmPackExpr
>(E) || SemaRef.isUnevaluatedContext()) && "missing non-odr-use marking for unevaluated decl ref"
) ? void (0) : __assert_fail ("(!E || isa<FunctionParmPackExpr>(E) || SemaRef.isUnevaluatedContext()) && \"missing non-odr-use marking for unevaluated decl ref\""
, "clang/lib/Sema/SemaExpr.cpp", 20105, __extension__ __PRETTY_FUNCTION__
))
;
20106 break;
20107
20108 case OdrUseContext::FormallyOdrUsed:
20109 // FIXME: Ignoring formal odr-uses results in incorrect lambda capture
20110 // behavior.
20111 break;
20112
20113 case OdrUseContext::Used:
20114 // If we might later find that this expression isn't actually an odr-use,
20115 // delay the marking.
20116 if (E && Var->isUsableInConstantExpressions(SemaRef.Context))
20117 SemaRef.MaybeODRUseExprs.insert(E);
20118 else
20119 MarkVarDeclODRUsed(Var, Loc, SemaRef);
20120 break;
20121
20122 case OdrUseContext::Dependent:
20123 // If this is a dependent context, we don't need to mark variables as
20124 // odr-used, but we may still need to track them for lambda capture.
20125 // FIXME: Do we also need to do this inside dependent typeid expressions
20126 // (which are modeled as unevaluated at this point)?
20127 DoMarkPotentialCapture(SemaRef, Loc, Var, E);
20128 break;
20129 }
20130}
20131
20132static void DoMarkBindingDeclReferenced(Sema &SemaRef, SourceLocation Loc,
20133 BindingDecl *BD, Expr *E) {
20134 BD->setReferenced();
20135
20136 if (BD->isInvalidDecl())
20137 return;
20138
20139 OdrUseContext OdrUse = isOdrUseContext(SemaRef);
20140 if (OdrUse == OdrUseContext::Used) {
20141 QualType CaptureType, DeclRefType;
20142 SemaRef.tryCaptureVariable(BD, Loc, Sema::TryCapture_Implicit,
20143 /*EllipsisLoc*/ SourceLocation(),
20144 /*BuildAndDiagnose*/ true, CaptureType,
20145 DeclRefType,
20146 /*FunctionScopeIndexToStopAt*/ nullptr);
20147 } else if (OdrUse == OdrUseContext::Dependent) {
20148 DoMarkPotentialCapture(SemaRef, Loc, BD, E);
20149 }
20150}
20151
20152/// Mark a variable referenced, and check whether it is odr-used
20153/// (C++ [basic.def.odr]p2, C99 6.9p3). Note that this should not be
20154/// used directly for normal expressions referring to VarDecl.
20155void Sema::MarkVariableReferenced(SourceLocation Loc, VarDecl *Var) {
20156 DoMarkVarDeclReferenced(*this, Loc, Var, nullptr, RefsMinusAssignments);
20157}
20158
20159static void
20160MarkExprReferenced(Sema &SemaRef, SourceLocation Loc, Decl *D, Expr *E,
20161 bool MightBeOdrUse,
20162 llvm::DenseMap<const VarDecl *, int> &RefsMinusAssignments) {
20163 if (SemaRef.isInOpenMPDeclareTargetContext())
20164 SemaRef.checkDeclIsAllowedInOpenMPTarget(E, D);
20165
20166 if (VarDecl *Var = dyn_cast<VarDecl>(D)) {
20167 DoMarkVarDeclReferenced(SemaRef, Loc, Var, E, RefsMinusAssignments);
20168 return;
20169 }
20170
20171 if (BindingDecl *Decl = dyn_cast<BindingDecl>(D)) {
20172 DoMarkBindingDeclReferenced(SemaRef, Loc, Decl, E);
20173 return;
20174 }
20175
20176 SemaRef.MarkAnyDeclReferenced(Loc, D, MightBeOdrUse);
20177
20178 // If this is a call to a method via a cast, also mark the method in the
20179 // derived class used in case codegen can devirtualize the call.
20180 const MemberExpr *ME = dyn_cast<MemberExpr>(E);
20181 if (!ME)
20182 return;
20183 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ME->getMemberDecl());
20184 if (!MD)
20185 return;
20186 // Only attempt to devirtualize if this is truly a virtual call.
20187 bool IsVirtualCall = MD->isVirtual() &&
20188 ME->performsVirtualDispatch(SemaRef.getLangOpts());
20189 if (!IsVirtualCall)
20190 return;
20191
20192 // If it's possible to devirtualize the call, mark the called function
20193 // referenced.
20194 CXXMethodDecl *DM = MD->getDevirtualizedMethod(
20195 ME->getBase(), SemaRef.getLangOpts().AppleKext);
20196 if (DM)
20197 SemaRef.MarkAnyDeclReferenced(Loc, DM, MightBeOdrUse);
20198}
20199
20200/// Perform reference-marking and odr-use handling for a DeclRefExpr.
20201///
20202/// Note, this may change the dependence of the DeclRefExpr, and so needs to be
20203/// handled with care if the DeclRefExpr is not newly-created.
20204void Sema::MarkDeclRefReferenced(DeclRefExpr *E, const Expr *Base) {
20205 // TODO: update this with DR# once a defect report is filed.
20206 // C++11 defect. The address of a pure member should not be an ODR use, even
20207 // if it's a qualified reference.
20208 bool OdrUse = true;
20209 if (const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(E->getDecl()))
20210 if (Method->isVirtual() &&
20211 !Method->getDevirtualizedMethod(Base, getLangOpts().AppleKext))
20212 OdrUse = false;
20213
20214 if (auto *FD = dyn_cast<FunctionDecl>(E->getDecl()))
20215 if (!isUnevaluatedContext() && !isConstantEvaluated() &&
20216 !isImmediateFunctionContext() &&
20217 !isCheckingDefaultArgumentOrInitializer() && FD->isConsteval() &&
20218 !RebuildingImmediateInvocation && !FD->isDependentContext())
20219 ExprEvalContexts.back().ReferenceToConsteval.insert(E);
20220 MarkExprReferenced(*this, E->getLocation(), E->getDecl(), E, OdrUse,
20221 RefsMinusAssignments);
20222}
20223
20224/// Perform reference-marking and odr-use handling for a MemberExpr.
20225void Sema::MarkMemberReferenced(MemberExpr *E) {
20226 // C++11 [basic.def.odr]p2:
20227 // A non-overloaded function whose name appears as a potentially-evaluated
20228 // expression or a member of a set of candidate functions, if selected by
20229 // overload resolution when referred to from a potentially-evaluated
20230 // expression, is odr-used, unless it is a pure virtual function and its
20231 // name is not explicitly qualified.
20232 bool MightBeOdrUse = true;
20233 if (E->performsVirtualDispatch(getLangOpts())) {
20234 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(E->getMemberDecl()))
20235 if (Method->isPure())
20236 MightBeOdrUse = false;
20237 }
20238 SourceLocation Loc =
20239 E->getMemberLoc().isValid() ? E->getMemberLoc() : E->getBeginLoc();
20240 MarkExprReferenced(*this, Loc, E->getMemberDecl(), E, MightBeOdrUse,
20241 RefsMinusAssignments);
20242}
20243
20244/// Perform reference-marking and odr-use handling for a FunctionParmPackExpr.
20245void Sema::MarkFunctionParmPackReferenced(FunctionParmPackExpr *E) {
20246 for (VarDecl *VD : *E)
20247 MarkExprReferenced(*this, E->getParameterPackLocation(), VD, E, true,
20248 RefsMinusAssignments);
20249}
20250
20251/// Perform marking for a reference to an arbitrary declaration. It
20252/// marks the declaration referenced, and performs odr-use checking for
20253/// functions and variables. This method should not be used when building a
20254/// normal expression which refers to a variable.
20255void Sema::MarkAnyDeclReferenced(SourceLocation Loc, Decl *D,
20256 bool MightBeOdrUse) {
20257 if (MightBeOdrUse) {
20258 if (auto *VD = dyn_cast<VarDecl>(D)) {
20259 MarkVariableReferenced(Loc, VD);
20260 return;
20261 }
20262 }
20263 if (auto *FD = dyn_cast<FunctionDecl>(D)) {
20264 MarkFunctionReferenced(Loc, FD, MightBeOdrUse);
20265 return;
20266 }
20267 D->setReferenced();
20268}
20269
20270namespace {
20271 // Mark all of the declarations used by a type as referenced.
20272 // FIXME: Not fully implemented yet! We need to have a better understanding
20273 // of when we're entering a context we should not recurse into.
20274 // FIXME: This is and EvaluatedExprMarker are more-or-less equivalent to
20275 // TreeTransforms rebuilding the type in a new context. Rather than
20276 // duplicating the TreeTransform logic, we should consider reusing it here.
20277 // Currently that causes problems when rebuilding LambdaExprs.
20278 class MarkReferencedDecls : public RecursiveASTVisitor<MarkReferencedDecls> {
20279 Sema &S;
20280 SourceLocation Loc;
20281
20282 public:
20283 typedef RecursiveASTVisitor<MarkReferencedDecls> Inherited;
20284
20285 MarkReferencedDecls(Sema &S, SourceLocation Loc) : S(S), Loc(Loc) { }
20286
20287 bool TraverseTemplateArgument(const TemplateArgument &Arg);
20288 };
20289}
20290
20291bool MarkReferencedDecls::TraverseTemplateArgument(
20292 const TemplateArgument &Arg) {
20293 {
20294 // A non-type template argument is a constant-evaluated context.
20295 EnterExpressionEvaluationContext Evaluated(
20296 S, Sema::ExpressionEvaluationContext::ConstantEvaluated);
20297 if (Arg.getKind() == TemplateArgument::Declaration) {
20298 if (Decl *D = Arg.getAsDecl())
20299 S.MarkAnyDeclReferenced(Loc, D, true);
20300 } else if (Arg.getKind() == TemplateArgument::Expression) {
20301 S.MarkDeclarationsReferencedInExpr(Arg.getAsExpr(), false);
20302 }
20303 }
20304
20305 return Inherited::TraverseTemplateArgument(Arg);
20306}
20307
20308void Sema::MarkDeclarationsReferencedInType(SourceLocation Loc, QualType T) {
20309 MarkReferencedDecls Marker(*this, Loc);
20310 Marker.TraverseType(T);
20311}
20312
20313namespace {
20314/// Helper class that marks all of the declarations referenced by
20315/// potentially-evaluated subexpressions as "referenced".
20316class EvaluatedExprMarker : public UsedDeclVisitor<EvaluatedExprMarker> {
20317public:
20318 typedef UsedDeclVisitor<EvaluatedExprMarker> Inherited;
20319 bool SkipLocalVariables;
20320 ArrayRef<const Expr *> StopAt;
20321
20322 EvaluatedExprMarker(Sema &S, bool SkipLocalVariables,
20323 ArrayRef<const Expr *> StopAt)
20324 : Inherited(S), SkipLocalVariables(SkipLocalVariables), StopAt(StopAt) {}
20325
20326 void visitUsedDecl(SourceLocation Loc, Decl *D) {
20327 S.MarkFunctionReferenced(Loc, cast<FunctionDecl>(D));
20328 }
20329
20330 void Visit(Expr *E) {
20331 if (llvm::is_contained(StopAt, E))
20332 return;
20333 Inherited::Visit(E);
20334 }
20335
20336 void VisitConstantExpr(ConstantExpr *E) {
20337 // Don't mark declarations within a ConstantExpression, as this expression
20338 // will be evaluated and folded to a value.
20339 }
20340
20341 void VisitDeclRefExpr(DeclRefExpr *E) {
20342 // If we were asked not to visit local variables, don't.
20343 if (SkipLocalVariables) {
20344 if (VarDecl *VD = dyn_cast<VarDecl>(E->getDecl()))
20345 if (VD->hasLocalStorage())
20346 return;
20347 }
20348
20349 // FIXME: This can trigger the instantiation of the initializer of a
20350 // variable, which can cause the expression to become value-dependent
20351 // or error-dependent. Do we need to propagate the new dependence bits?
20352 S.MarkDeclRefReferenced(E);
20353 }
20354
20355 void VisitMemberExpr(MemberExpr *E) {
20356 S.MarkMemberReferenced(E);
20357 Visit(E->getBase());
20358 }
20359};
20360} // namespace
20361
20362/// Mark any declarations that appear within this expression or any
20363/// potentially-evaluated subexpressions as "referenced".
20364///
20365/// \param SkipLocalVariables If true, don't mark local variables as
20366/// 'referenced'.
20367/// \param StopAt Subexpressions that we shouldn't recurse into.
20368void Sema::MarkDeclarationsReferencedInExpr(Expr *E,
20369 bool SkipLocalVariables,
20370 ArrayRef<const Expr*> StopAt) {
20371 EvaluatedExprMarker(*this, SkipLocalVariables, StopAt).Visit(E);
20372}
20373
20374/// Emit a diagnostic when statements are reachable.
20375/// FIXME: check for reachability even in expressions for which we don't build a
20376/// CFG (eg, in the initializer of a global or in a constant expression).
20377/// For example,
20378/// namespace { auto *p = new double[3][false ? (1, 2) : 3]; }
20379bool Sema::DiagIfReachable(SourceLocation Loc, ArrayRef<const Stmt *> Stmts,
20380 const PartialDiagnostic &PD) {
20381 if (!Stmts.empty() && getCurFunctionOrMethodDecl()) {
20382 if (!FunctionScopes.empty())
20383 FunctionScopes.back()->PossiblyUnreachableDiags.push_back(
20384 sema::PossiblyUnreachableDiag(PD, Loc, Stmts));
20385 return true;
20386 }
20387
20388 // The initializer of a constexpr variable or of the first declaration of a
20389 // static data member is not syntactically a constant evaluated constant,
20390 // but nonetheless is always required to be a constant expression, so we
20391 // can skip diagnosing.
20392 // FIXME: Using the mangling context here is a hack.
20393 if (auto *VD = dyn_cast_or_null<VarDecl>(
20394 ExprEvalContexts.back().ManglingContextDecl)) {
20395 if (VD->isConstexpr() ||
20396 (VD->isStaticDataMember() && VD->isFirstDecl() && !VD->isInline()))
20397 return false;
20398 // FIXME: For any other kind of variable, we should build a CFG for its
20399 // initializer and check whether the context in question is reachable.
20400 }
20401
20402 Diag(Loc, PD);
20403 return true;
20404}
20405
20406/// Emit a diagnostic that describes an effect on the run-time behavior
20407/// of the program being compiled.
20408///
20409/// This routine emits the given diagnostic when the code currently being
20410/// type-checked is "potentially evaluated", meaning that there is a
20411/// possibility that the code will actually be executable. Code in sizeof()
20412/// expressions, code used only during overload resolution, etc., are not
20413/// potentially evaluated. This routine will suppress such diagnostics or,
20414/// in the absolutely nutty case of potentially potentially evaluated
20415/// expressions (C++ typeid), queue the diagnostic to potentially emit it
20416/// later.
20417///
20418/// This routine should be used for all diagnostics that describe the run-time
20419/// behavior of a program, such as passing a non-POD value through an ellipsis.
20420/// Failure to do so will likely result in spurious diagnostics or failures
20421/// during overload resolution or within sizeof/alignof/typeof/typeid.
20422bool Sema::DiagRuntimeBehavior(SourceLocation Loc, ArrayRef<const Stmt*> Stmts,
20423 const PartialDiagnostic &PD) {
20424
20425 if (ExprEvalContexts.back().isDiscardedStatementContext())
20426 return false;
20427
20428 switch (ExprEvalContexts.back().Context) {
20429 case ExpressionEvaluationContext::Unevaluated:
20430 case ExpressionEvaluationContext::UnevaluatedList:
20431 case ExpressionEvaluationContext::UnevaluatedAbstract:
20432 case ExpressionEvaluationContext::DiscardedStatement:
20433 // The argument will never be evaluated, so don't complain.
20434 break;
20435
20436 case ExpressionEvaluationContext::ConstantEvaluated:
20437 case ExpressionEvaluationContext::ImmediateFunctionContext:
20438 // Relevant diagnostics should be produced by constant evaluation.
20439 break;
20440
20441 case ExpressionEvaluationContext::PotentiallyEvaluated:
20442 case ExpressionEvaluationContext::PotentiallyEvaluatedIfUsed:
20443 return DiagIfReachable(Loc, Stmts, PD);
20444 }
20445
20446 return false;
20447}
20448
20449bool Sema::DiagRuntimeBehavior(SourceLocation Loc, const Stmt *Statement,
20450 const PartialDiagnostic &PD) {
20451 return DiagRuntimeBehavior(
20452 Loc, Statement ? llvm::ArrayRef(Statement) : std::nullopt, PD);
20453}
20454
20455bool Sema::CheckCallReturnType(QualType ReturnType, SourceLocation Loc,
20456 CallExpr *CE, FunctionDecl *FD) {
20457 if (ReturnType->isVoidType() || !ReturnType->isIncompleteType())
20458 return false;
20459
20460 // If we're inside a decltype's expression, don't check for a valid return
20461 // type or construct temporaries until we know whether this is the last call.
20462 if (ExprEvalContexts.back().ExprContext ==
20463 ExpressionEvaluationContextRecord::EK_Decltype) {
20464 ExprEvalContexts.back().DelayedDecltypeCalls.push_back(CE);
20465 return false;
20466 }
20467
20468 class CallReturnIncompleteDiagnoser : public TypeDiagnoser {
20469 FunctionDecl *FD;
20470 CallExpr *CE;
20471
20472 public:
20473 CallReturnIncompleteDiagnoser(FunctionDecl *FD, CallExpr *CE)
20474 : FD(FD), CE(CE) { }
20475
20476 void diagnose(Sema &S, SourceLocation Loc, QualType T) override {
20477 if (!FD) {
20478 S.Diag(Loc, diag::err_call_incomplete_return)
20479 << T << CE->getSourceRange();
20480 return;
20481 }
20482
20483 S.Diag(Loc, diag::err_call_function_incomplete_return)
20484 << CE->getSourceRange() << FD << T;
20485 S.Diag(FD->getLocation(), diag::note_entity_declared_at)
20486 << FD->getDeclName();
20487 }
20488 } Diagnoser(FD, CE);
20489
20490 if (RequireCompleteType(Loc, ReturnType, Diagnoser))
20491 return true;
20492
20493 return false;
20494}
20495
20496// Diagnose the s/=/==/ and s/\|=/!=/ typos. Note that adding parentheses
20497// will prevent this condition from triggering, which is what we want.
20498void Sema::DiagnoseAssignmentAsCondition(Expr *E) {
20499 SourceLocation Loc;
20500
20501 unsigned diagnostic = diag::warn_condition_is_assignment;
20502 bool IsOrAssign = false;
20503
20504 if (BinaryOperator *Op = dyn_cast<BinaryOperator>(E)) {
20505 if (Op->getOpcode() != BO_Assign && Op->getOpcode() != BO_OrAssign)
20506 return;
20507
20508 IsOrAssign = Op->getOpcode() == BO_OrAssign;
20509
20510 // Greylist some idioms by putting them into a warning subcategory.
20511 if (ObjCMessageExpr *ME
20512 = dyn_cast<ObjCMessageExpr>(Op->getRHS()->IgnoreParenCasts())) {
20513 Selector Sel = ME->getSelector();
20514
20515 // self = [<foo> init...]
20516 if (isSelfExpr(Op->getLHS()) && ME->getMethodFamily() == OMF_init)
20517 diagnostic = diag::warn_condition_is_idiomatic_assignment;
20518
20519 // <foo> = [<bar> nextObject]
20520 else if (Sel.isUnarySelector() && Sel.getNameForSlot(0) == "nextObject")
20521 diagnostic = diag::warn_condition_is_idiomatic_assignment;
20522 }
20523
20524 Loc = Op->getOperatorLoc();
20525 } else if (CXXOperatorCallExpr *Op = dyn_cast<CXXOperatorCallExpr>(E)) {
20526 if (Op->getOperator() != OO_Equal && Op->getOperator() != OO_PipeEqual)
20527 return;
20528
20529 IsOrAssign = Op->getOperator() == OO_PipeEqual;
20530 Loc = Op->getOperatorLoc();
20531 } else if (PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(E))
20532 return DiagnoseAssignmentAsCondition(POE->getSyntacticForm());
20533 else {
20534 // Not an assignment.
20535 return;
20536 }
20537
20538 Diag(Loc, diagnostic) << E->getSourceRange();
20539
20540 SourceLocation Open = E->getBeginLoc();
20541 SourceLocation Close = getLocForEndOfToken(E->getSourceRange().getEnd());
20542 Diag(Loc, diag::note_condition_assign_silence)
20543 << FixItHint::CreateInsertion(Open, "(")
20544 << FixItHint::CreateInsertion(Close, ")");
20545
20546 if (IsOrAssign)
20547 Diag(Loc, diag::note_condition_or_assign_to_comparison)
20548 << FixItHint::CreateReplacement(Loc, "!=");
20549 else
20550 Diag(Loc, diag::note_condition_assign_to_comparison)
20551 << FixItHint::CreateReplacement(Loc, "==");
20552}
20553
20554/// Redundant parentheses over an equality comparison can indicate
20555/// that the user intended an assignment used as condition.
20556void Sema::DiagnoseEqualityWithExtraParens(ParenExpr *ParenE) {
20557 // Don't warn if the parens came from a macro.
20558 SourceLocation parenLoc = ParenE->getBeginLoc();
20559 if (parenLoc.isInvalid() || parenLoc.isMacroID())
20560 return;
20561 // Don't warn for dependent expressions.
20562 if (ParenE->isTypeDependent())
20563 return;
20564
20565 Expr *E = ParenE->IgnoreParens();
20566
20567 if (BinaryOperator *opE = dyn_cast<BinaryOperator>(E))
20568 if (opE->getOpcode() == BO_EQ &&
20569 opE->getLHS()->IgnoreParenImpCasts()->isModifiableLvalue(Context)
20570 == Expr::MLV_Valid) {
20571 SourceLocation Loc = opE->getOperatorLoc();
20572
20573 Diag(Loc, diag::warn_equality_with_extra_parens) << E->getSourceRange();
20574 SourceRange ParenERange = ParenE->getSourceRange();
20575 Diag(Loc, diag::note_equality_comparison_silence)
20576 << FixItHint::CreateRemoval(ParenERange.getBegin())
20577 << FixItHint::CreateRemoval(ParenERange.getEnd());
20578 Diag(Loc, diag::note_equality_comparison_to_assign)
20579 << FixItHint::CreateReplacement(Loc, "=");
20580 }
20581}
20582
20583ExprResult Sema::CheckBooleanCondition(SourceLocation Loc, Expr *E,
20584 bool IsConstexpr) {
20585 DiagnoseAssignmentAsCondition(E);
20586 if (ParenExpr *parenE = dyn_cast<ParenExpr>(E))
20587 DiagnoseEqualityWithExtraParens(parenE);
20588
20589 ExprResult result = CheckPlaceholderExpr(E);
20590 if (result.isInvalid()) return ExprError();
20591 E = result.get();
20592
20593 if (!E->isTypeDependent()) {
20594 if (getLangOpts().CPlusPlus)
20595 return CheckCXXBooleanCondition(E, IsConstexpr); // C++ 6.4p4
20596
20597 ExprResult ERes = DefaultFunctionArrayLvalueConversion(E);
20598 if (ERes.isInvalid())
20599 return ExprError();
20600 E = ERes.get();
20601
20602 QualType T = E->getType();
20603 if (!T->isScalarType()) { // C99 6.8.4.1p1
20604 Diag(Loc, diag::err_typecheck_statement_requires_scalar)
20605 << T << E->getSourceRange();
20606 return ExprError();
20607 }
20608 CheckBoolLikeConversion(E, Loc);
20609 }
20610
20611 return E;
20612}
20613
20614Sema::ConditionResult Sema::ActOnCondition(Scope *S, SourceLocation Loc,
20615 Expr *SubExpr, ConditionKind CK,
20616 bool MissingOK) {
20617 // MissingOK indicates whether having no condition expression is valid
20618 // (for loop) or invalid (e.g. while loop).
20619 if (!SubExpr)
20620 return MissingOK ? ConditionResult() : ConditionError();
20621
20622 ExprResult Cond;
20623 switch (CK) {
20624 case ConditionKind::Boolean:
20625 Cond = CheckBooleanCondition(Loc, SubExpr);
20626 break;
20627
20628 case ConditionKind::ConstexprIf:
20629 Cond = CheckBooleanCondition(Loc, SubExpr, true);
20630 break;
20631
20632 case ConditionKind::Switch:
20633 Cond = CheckSwitchCondition(Loc, SubExpr);
20634 break;
20635 }
20636 if (Cond.isInvalid()) {
20637 Cond = CreateRecoveryExpr(SubExpr->getBeginLoc(), SubExpr->getEndLoc(),
20638 {SubExpr}, PreferredConditionType(CK));
20639 if (!Cond.get())
20640 return ConditionError();
20641 }
20642 // FIXME: FullExprArg doesn't have an invalid bit, so check nullness instead.
20643 FullExprArg FullExpr = MakeFullExpr(Cond.get(), Loc);
20644 if (!FullExpr.get())
20645 return ConditionError();
20646
20647 return ConditionResult(*this, nullptr, FullExpr,
20648 CK == ConditionKind::ConstexprIf);
20649}
20650
20651namespace {
20652 /// A visitor for rebuilding a call to an __unknown_any expression
20653 /// to have an appropriate type.
20654 struct RebuildUnknownAnyFunction
20655 : StmtVisitor<RebuildUnknownAnyFunction, ExprResult> {
20656
20657 Sema &S;
20658
20659 RebuildUnknownAnyFunction(Sema &S) : S(S) {}
20660
20661 ExprResult VisitStmt(Stmt *S) {
20662 llvm_unreachable("unexpected statement!")::llvm::llvm_unreachable_internal("unexpected statement!", "clang/lib/Sema/SemaExpr.cpp"
, 20662)
;
20663 }
20664
20665 ExprResult VisitExpr(Expr *E) {
20666 S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_call)
20667 << E->getSourceRange();
20668 return ExprError();
20669 }
20670
20671 /// Rebuild an expression which simply semantically wraps another
20672 /// expression which it shares the type and value kind of.
20673 template <class T> ExprResult rebuildSugarExpr(T *E) {
20674 ExprResult SubResult = Visit(E->getSubExpr());
20675 if (SubResult.isInvalid()) return ExprError();
20676
20677 Expr *SubExpr = SubResult.get();
20678 E->setSubExpr(SubExpr);
20679 E->setType(SubExpr->getType());
20680 E->setValueKind(SubExpr->getValueKind());
20681 assert(E->getObjectKind() == OK_Ordinary)(static_cast <bool> (E->getObjectKind() == OK_Ordinary
) ? void (0) : __assert_fail ("E->getObjectKind() == OK_Ordinary"
, "clang/lib/Sema/SemaExpr.cpp", 20681, __extension__ __PRETTY_FUNCTION__
))
;
20682 return E;
20683 }
20684
20685 ExprResult VisitParenExpr(ParenExpr *E) {
20686 return rebuildSugarExpr(E);
20687 }
20688
20689 ExprResult VisitUnaryExtension(UnaryOperator *E) {
20690 return rebuildSugarExpr(E);
20691 }
20692
20693 ExprResult VisitUnaryAddrOf(UnaryOperator *E) {
20694 ExprResult SubResult = Visit(E->getSubExpr());
20695 if (SubResult.isInvalid()) return ExprError();
20696
20697 Expr *SubExpr = SubResult.get();
20698 E->setSubExpr(SubExpr);
20699 E->setType(S.Context.getPointerType(SubExpr->getType()));
20700 assert(E->isPRValue())(static_cast <bool> (E->isPRValue()) ? void (0) : __assert_fail
("E->isPRValue()", "clang/lib/Sema/SemaExpr.cpp", 20700, __extension__
__PRETTY_FUNCTION__))
;
20701 assert(E->getObjectKind() == OK_Ordinary)(static_cast <bool> (E->getObjectKind() == OK_Ordinary
) ? void (0) : __assert_fail ("E->getObjectKind() == OK_Ordinary"
, "clang/lib/Sema/SemaExpr.cpp", 20701, __extension__ __PRETTY_FUNCTION__
))
;
20702 return E;
20703 }
20704
20705 ExprResult resolveDecl(Expr *E, ValueDecl *VD) {
20706 if (!isa<FunctionDecl>(VD)) return VisitExpr(E);
20707
20708 E->setType(VD->getType());
20709
20710 assert(E->isPRValue())(static_cast <bool> (E->isPRValue()) ? void (0) : __assert_fail
("E->isPRValue()", "clang/lib/Sema/SemaExpr.cpp", 20710, __extension__
__PRETTY_FUNCTION__))
;
20711 if (S.getLangOpts().CPlusPlus &&
20712 !(isa<CXXMethodDecl>(VD) &&
20713 cast<CXXMethodDecl>(VD)->isInstance()))
20714 E->setValueKind(VK_LValue);
20715
20716 return E;
20717 }
20718
20719 ExprResult VisitMemberExpr(MemberExpr *E) {
20720 return resolveDecl(E, E->getMemberDecl());
20721 }
20722
20723 ExprResult VisitDeclRefExpr(DeclRefExpr *E) {
20724 return resolveDecl(E, E->getDecl());
20725 }
20726 };
20727}
20728
20729/// Given a function expression of unknown-any type, try to rebuild it
20730/// to have a function type.
20731static ExprResult rebuildUnknownAnyFunction(Sema &S, Expr *FunctionExpr) {
20732 ExprResult Result = RebuildUnknownAnyFunction(S).Visit(FunctionExpr);
20733 if (Result.isInvalid()) return ExprError();
20734 return S.DefaultFunctionArrayConversion(Result.get());
20735}
20736
20737namespace {
20738 /// A visitor for rebuilding an expression of type __unknown_anytype
20739 /// into one which resolves the type directly on the referring
20740 /// expression. Strict preservation of the original source
20741 /// structure is not a goal.
20742 struct RebuildUnknownAnyExpr
20743 : StmtVisitor<RebuildUnknownAnyExpr, ExprResult> {
20744
20745 Sema &S;
20746
20747 /// The current destination type.
20748 QualType DestType;
20749
20750 RebuildUnknownAnyExpr(Sema &S, QualType CastType)
20751 : S(S), DestType(CastType) {}
20752
20753 ExprResult VisitStmt(Stmt *S) {
20754 llvm_unreachable("unexpected statement!")::llvm::llvm_unreachable_internal("unexpected statement!", "clang/lib/Sema/SemaExpr.cpp"
, 20754)
;
20755 }
20756
20757 ExprResult VisitExpr(Expr *E) {
20758 S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_expr)
20759 << E->getSourceRange();
20760 return ExprError();
20761 }
20762
20763 ExprResult VisitCallExpr(CallExpr *E);
20764 ExprResult VisitObjCMessageExpr(ObjCMessageExpr *E);
20765
20766 /// Rebuild an expression which simply semantically wraps another
20767 /// expression which it shares the type and value kind of.
20768 template <class T> ExprResult rebuildSugarExpr(T *E) {
20769 ExprResult SubResult = Visit(E->getSubExpr());
20770 if (SubResult.isInvalid()) return ExprError();
20771 Expr *SubExpr = SubResult.get();
20772 E->setSubExpr(SubExpr);
20773 E->setType(SubExpr->getType());
20774 E->setValueKind(SubExpr->getValueKind());
20775 assert(E->getObjectKind() == OK_Ordinary)(static_cast <bool> (E->getObjectKind() == OK_Ordinary
) ? void (0) : __assert_fail ("E->getObjectKind() == OK_Ordinary"
, "clang/lib/Sema/SemaExpr.cpp", 20775, __extension__ __PRETTY_FUNCTION__
))
;
20776 return E;
20777 }
20778
20779 ExprResult VisitParenExpr(ParenExpr *E) {
20780 return rebuildSugarExpr(E);
20781 }
20782
20783 ExprResult VisitUnaryExtension(UnaryOperator *E) {
20784 return rebuildSugarExpr(E);
20785 }
20786
20787 ExprResult VisitUnaryAddrOf(UnaryOperator *E) {
20788 const PointerType *Ptr = DestType->getAs<PointerType>();
20789 if (!Ptr) {
20790 S.Diag(E->getOperatorLoc(), diag::err_unknown_any_addrof)
20791 << E->getSourceRange();
20792 return ExprError();
20793 }
20794
20795 if (isa<CallExpr>(E->getSubExpr())) {
20796 S.Diag(E->getOperatorLoc(), diag::err_unknown_any_addrof_call)
20797 << E->getSourceRange();
20798 return ExprError();
20799 }
20800
20801 assert(E->isPRValue())(static_cast <bool> (E->isPRValue()) ? void (0) : __assert_fail
("E->isPRValue()", "clang/lib/Sema/SemaExpr.cpp", 20801, __extension__
__PRETTY_FUNCTION__))
;
20802 assert(E->getObjectKind() == OK_Ordinary)(static_cast <bool> (E->getObjectKind() == OK_Ordinary
) ? void (0) : __assert_fail ("E->getObjectKind() == OK_Ordinary"
, "clang/lib/Sema/SemaExpr.cpp", 20802, __extension__ __PRETTY_FUNCTION__
))
;
20803 E->setType(DestType);
20804
20805 // Build the sub-expression as if it were an object of the pointee type.
20806 DestType = Ptr->getPointeeType();
20807 ExprResult SubResult = Visit(E->getSubExpr());
20808 if (SubResult.isInvalid()) return ExprError();
20809 E->setSubExpr(SubResult.get());
20810 return E;
20811 }
20812
20813 ExprResult VisitImplicitCastExpr(ImplicitCastExpr *E);
20814
20815 ExprResult resolveDecl(Expr *E, ValueDecl *VD);
20816
20817 ExprResult VisitMemberExpr(MemberExpr *E) {
20818 return resolveDecl(E, E->getMemberDecl());
20819 }
20820
20821 ExprResult VisitDeclRefExpr(DeclRefExpr *E) {
20822 return resolveDecl(E, E->getDecl());
20823 }
20824 };
20825}
20826
20827/// Rebuilds a call expression which yielded __unknown_anytype.
20828ExprResult RebuildUnknownAnyExpr::VisitCallExpr(CallExpr *E) {
20829 Expr *CalleeExpr = E->getCallee();
20830
20831 enum FnKind {
20832 FK_MemberFunction,
20833 FK_FunctionPointer,
20834 FK_BlockPointer
20835 };
20836
20837 FnKind Kind;
20838 QualType CalleeType = CalleeExpr->getType();
20839 if (CalleeType == S.Context.BoundMemberTy) {
20840 assert(isa<CXXMemberCallExpr>(E) || isa<CXXOperatorCallExpr>(E))(static_cast <bool> (isa<CXXMemberCallExpr>(E) ||
isa<CXXOperatorCallExpr>(E)) ? void (0) : __assert_fail
("isa<CXXMemberCallExpr>(E) || isa<CXXOperatorCallExpr>(E)"
, "clang/lib/Sema/SemaExpr.cpp", 20840, __extension__ __PRETTY_FUNCTION__
))
;
20841 Kind = FK_MemberFunction;
20842 CalleeType = Expr::findBoundMemberType(CalleeExpr);
20843 } else if (const PointerType *Ptr = CalleeType->getAs<PointerType>()) {
20844 CalleeType = Ptr->getPointeeType();
20845 Kind = FK_FunctionPointer;
20846 } else {
20847 CalleeType = CalleeType->castAs<BlockPointerType>()->getPointeeType();
20848 Kind = FK_BlockPointer;
20849 }
20850 const FunctionType *FnType = CalleeType->castAs<FunctionType>();
20851
20852 // Verify that this is a legal result type of a function.
20853 if (DestType->isArrayType() || DestType->isFunctionType()) {
20854 unsigned diagID = diag::err_func_returning_array_function;
20855 if (Kind == FK_BlockPointer)
20856 diagID = diag::err_block_returning_array_function;
20857
20858 S.Diag(E->getExprLoc(), diagID)
20859 << DestType->isFunctionType() << DestType;
20860 return ExprError();
20861 }
20862
20863 // Otherwise, go ahead and set DestType as the call's result.
20864 E->setType(DestType.getNonLValueExprType(S.Context));
20865 E->setValueKind(Expr::getValueKindForType(DestType));
20866 assert(E->getObjectKind() == OK_Ordinary)(static_cast <bool> (E->getObjectKind() == OK_Ordinary
) ? void (0) : __assert_fail ("E->getObjectKind() == OK_Ordinary"
, "clang/lib/Sema/SemaExpr.cpp", 20866, __extension__ __PRETTY_FUNCTION__
))
;
20867
20868 // Rebuild the function type, replacing the result type with DestType.
20869 const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FnType);
20870 if (Proto) {
20871 // __unknown_anytype(...) is a special case used by the debugger when
20872 // it has no idea what a function's signature is.
20873 //
20874 // We want to build this call essentially under the K&R
20875 // unprototyped rules, but making a FunctionNoProtoType in C++
20876 // would foul up all sorts of assumptions. However, we cannot
20877 // simply pass all arguments as variadic arguments, nor can we
20878 // portably just call the function under a non-variadic type; see
20879 // the comment on IR-gen's TargetInfo::isNoProtoCallVariadic.
20880 // However, it turns out that in practice it is generally safe to
20881 // call a function declared as "A foo(B,C,D);" under the prototype
20882 // "A foo(B,C,D,...);". The only known exception is with the
20883 // Windows ABI, where any variadic function is implicitly cdecl
20884 // regardless of its normal CC. Therefore we change the parameter
20885 // types to match the types of the arguments.
20886 //
20887 // This is a hack, but it is far superior to moving the
20888 // corresponding target-specific code from IR-gen to Sema/AST.
20889
20890 ArrayRef<QualType> ParamTypes = Proto->getParamTypes();
20891 SmallVector<QualType, 8> ArgTypes;
20892 if (ParamTypes.empty() && Proto->isVariadic()) { // the special case
20893 ArgTypes.reserve(E->getNumArgs());
20894 for (unsigned i = 0, e = E->getNumArgs(); i != e; ++i) {
20895 ArgTypes.push_back(S.Context.getReferenceQualifiedType(E->getArg(i)));
20896 }
20897 ParamTypes = ArgTypes;
20898 }
20899 DestType = S.Context.getFunctionType(DestType, ParamTypes,
20900 Proto->getExtProtoInfo());
20901 } else {
20902 DestType = S.Context.getFunctionNoProtoType(DestType,
20903 FnType->getExtInfo());
20904 }
20905
20906 // Rebuild the appropriate pointer-to-function type.
20907 switch (Kind) {
20908 case FK_MemberFunction:
20909 // Nothing to do.
20910 break;
20911
20912 case FK_FunctionPointer:
20913 DestType = S.Context.getPointerType(DestType);
20914 break;
20915
20916 case FK_BlockPointer:
20917 DestType = S.Context.getBlockPointerType(DestType);
20918 break;
20919 }
20920
20921 // Finally, we can recurse.
20922 ExprResult CalleeResult = Visit(CalleeExpr);
20923 if (!CalleeResult.isUsable()) return ExprError();
20924 E->setCallee(CalleeResult.get());
20925
20926 // Bind a temporary if necessary.
20927 return S.MaybeBindToTemporary(E);
20928}
20929
20930ExprResult RebuildUnknownAnyExpr::VisitObjCMessageExpr(ObjCMessageExpr *E) {
20931 // Verify that this is a legal result type of a call.
20932 if (DestType->isArrayType() || DestType->isFunctionType()) {
20933 S.Diag(E->getExprLoc(), diag::err_func_returning_array_function)
20934 << DestType->isFunctionType() << DestType;
20935 return ExprError();
20936 }
20937
20938 // Rewrite the method result type if available.
20939 if (ObjCMethodDecl *Method = E->getMethodDecl()) {
20940 assert(Method->getReturnType() == S.Context.UnknownAnyTy)(static_cast <bool> (Method->getReturnType() == S.Context
.UnknownAnyTy) ? void (0) : __assert_fail ("Method->getReturnType() == S.Context.UnknownAnyTy"
, "clang/lib/Sema/SemaExpr.cpp", 20940, __extension__ __PRETTY_FUNCTION__
))
;
20941 Method->setReturnType(DestType);
20942 }
20943
20944 // Change the type of the message.
20945 E->setType(DestType.getNonReferenceType());
20946 E->setValueKind(Expr::getValueKindForType(DestType));
20947
20948 return S.MaybeBindToTemporary(E);
20949}
20950
20951ExprResult RebuildUnknownAnyExpr::VisitImplicitCastExpr(ImplicitCastExpr *E) {
20952 // The only case we should ever see here is a function-to-pointer decay.
20953 if (E->getCastKind() == CK_FunctionToPointerDecay) {
20954 assert(E->isPRValue())(static_cast <bool> (E->isPRValue()) ? void (0) : __assert_fail
("E->isPRValue()", "clang/lib/Sema/SemaExpr.cpp", 20954, __extension__
__PRETTY_FUNCTION__))
;
20955 assert(E->getObjectKind() == OK_Ordinary)(static_cast <bool> (E->getObjectKind() == OK_Ordinary
) ? void (0) : __assert_fail ("E->getObjectKind() == OK_Ordinary"
, "clang/lib/Sema/SemaExpr.cpp", 20955, __extension__ __PRETTY_FUNCTION__
))
;
20956
20957 E->setType(DestType);
20958
20959 // Rebuild the sub-expression as the pointee (function) type.
20960 DestType = DestType->castAs<PointerType>()->getPointeeType();
20961
20962 ExprResult Result = Visit(E->getSubExpr());
20963 if (!Result.isUsable()) return ExprError();
20964
20965 E->setSubExpr(Result.get());
20966 return E;
20967 } else if (E->getCastKind() == CK_LValueToRValue) {
20968 assert(E->isPRValue())(static_cast <bool> (E->isPRValue()) ? void (0) : __assert_fail
("E->isPRValue()", "clang/lib/Sema/SemaExpr.cpp", 20968, __extension__
__PRETTY_FUNCTION__))
;
20969 assert(E->getObjectKind() == OK_Ordinary)(static_cast <bool> (E->getObjectKind() == OK_Ordinary
) ? void (0) : __assert_fail ("E->getObjectKind() == OK_Ordinary"
, "clang/lib/Sema/SemaExpr.cpp", 20969, __extension__ __PRETTY_FUNCTION__
))
;
20970
20971 assert(isa<BlockPointerType>(E->getType()))(static_cast <bool> (isa<BlockPointerType>(E->
getType())) ? void (0) : __assert_fail ("isa<BlockPointerType>(E->getType())"
, "clang/lib/Sema/SemaExpr.cpp", 20971, __extension__ __PRETTY_FUNCTION__
))
;
20972
20973 E->setType(DestType);
20974
20975 // The sub-expression has to be a lvalue reference, so rebuild it as such.
20976 DestType = S.Context.getLValueReferenceType(DestType);
20977
20978 ExprResult Result = Visit(E->getSubExpr());
20979 if (!Result.isUsable()) return ExprError();
20980
20981 E->setSubExpr(Result.get());
20982 return E;
20983 } else {
20984 llvm_unreachable("Unhandled cast type!")::llvm::llvm_unreachable_internal("Unhandled cast type!", "clang/lib/Sema/SemaExpr.cpp"
, 20984)
;
20985 }
20986}
20987
20988ExprResult RebuildUnknownAnyExpr::resolveDecl(Expr *E, ValueDecl *VD) {
20989 ExprValueKind ValueKind = VK_LValue;
20990 QualType Type = DestType;
20991
20992 // We know how to make this work for certain kinds of decls:
20993
20994 // - functions
20995 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(VD)) {
20996 if (const PointerType *Ptr = Type->getAs<PointerType>()) {
20997 DestType = Ptr->getPointeeType();
20998 ExprResult Result = resolveDecl(E, VD);
20999 if (Result.isInvalid()) return ExprError();
21000 return S.ImpCastExprToType(Result.get(), Type, CK_FunctionToPointerDecay,
21001 VK_PRValue);
21002 }
21003
21004 if (!Type->isFunctionType()) {
21005 S.Diag(E->getExprLoc(), diag::err_unknown_any_function)
21006 << VD << E->getSourceRange();
21007 return ExprError();
21008 }
21009 if (const FunctionProtoType *FT = Type->getAs<FunctionProtoType>()) {
21010 // We must match the FunctionDecl's type to the hack introduced in
21011 // RebuildUnknownAnyExpr::VisitCallExpr to vararg functions of unknown
21012 // type. See the lengthy commentary in that routine.
21013 QualType FDT = FD->getType();
21014 const FunctionType *FnType = FDT->castAs<FunctionType>();
21015 const FunctionProtoType *Proto = dyn_cast_or_null<FunctionProtoType>(FnType);
21016 DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E);
21017 if (DRE && Proto && Proto->getParamTypes().empty() && Proto->isVariadic()) {
21018 SourceLocation Loc = FD->getLocation();
21019 FunctionDecl *NewFD = FunctionDecl::Create(
21020 S.Context, FD->getDeclContext(), Loc, Loc,
21021 FD->getNameInfo().getName(), DestType, FD->getTypeSourceInfo(),
21022 SC_None, S.getCurFPFeatures().isFPConstrained(),
21023 false /*isInlineSpecified*/, FD->hasPrototype(),
21024 /*ConstexprKind*/ ConstexprSpecKind::Unspecified);
21025
21026 if (FD->getQualifier())
21027 NewFD->setQualifierInfo(FD->getQualifierLoc());
21028
21029 SmallVector<ParmVarDecl*, 16> Params;
21030 for (const auto &AI : FT->param_types()) {
21031 ParmVarDecl *Param =
21032 S.BuildParmVarDeclForTypedef(FD, Loc, AI);
21033 Param->setScopeInfo(0, Params.size());
21034 Params.push_back(Param);
21035 }
21036 NewFD->setParams(Params);
21037 DRE->setDecl(NewFD);
21038 VD = DRE->getDecl();
21039 }
21040 }
21041
21042 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD))
21043 if (MD->isInstance()) {
21044 ValueKind = VK_PRValue;
21045 Type = S.Context.BoundMemberTy;
21046 }
21047
21048 // Function references aren't l-values in C.
21049 if (!S.getLangOpts().CPlusPlus)
21050 ValueKind = VK_PRValue;
21051
21052 // - variables
21053 } else if (isa<VarDecl>(VD)) {
21054 if (const ReferenceType *RefTy = Type->getAs<ReferenceType>()) {
21055 Type = RefTy->getPointeeType();
21056 } else if (Type->isFunctionType()) {
21057 S.Diag(E->getExprLoc(), diag::err_unknown_any_var_function_type)
21058 << VD << E->getSourceRange();
21059 return ExprError();
21060 }
21061
21062 // - nothing else
21063 } else {
21064 S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_decl)
21065 << VD << E->getSourceRange();
21066 return ExprError();
21067 }
21068
21069 // Modifying the declaration like this is friendly to IR-gen but
21070 // also really dangerous.
21071 VD->setType(DestType);
21072 E->setType(Type);
21073 E->setValueKind(ValueKind);
21074 return E;
21075}
21076
21077/// Check a cast of an unknown-any type. We intentionally only
21078/// trigger this for C-style casts.
21079ExprResult Sema::checkUnknownAnyCast(SourceRange TypeRange, QualType CastType,
21080 Expr *CastExpr, CastKind &CastKind,
21081 ExprValueKind &VK, CXXCastPath &Path) {
21082 // The type we're casting to must be either void or complete.
21083 if (!CastType->isVoidType() &&
21084 RequireCompleteType(TypeRange.getBegin(), CastType,
21085 diag::err_typecheck_cast_to_incomplete))
21086 return ExprError();
21087
21088 // Rewrite the casted expression from scratch.
21089 ExprResult result = RebuildUnknownAnyExpr(*this, CastType).Visit(CastExpr);
21090 if (!result.isUsable()) return ExprError();
21091
21092 CastExpr = result.get();
21093 VK = CastExpr->getValueKind();
21094 CastKind = CK_NoOp;
21095
21096 return CastExpr;
21097}
21098
21099ExprResult Sema::forceUnknownAnyToType(Expr *E, QualType ToType) {
21100 return RebuildUnknownAnyExpr(*this, ToType).Visit(E);
21101}
21102
21103ExprResult Sema::checkUnknownAnyArg(SourceLocation callLoc,
21104 Expr *arg, QualType &paramType) {
21105 // If the syntactic form of the argument is not an explicit cast of
21106 // any sort, just do default argument promotion.
21107 ExplicitCastExpr *castArg = dyn_cast<ExplicitCastExpr>(arg->IgnoreParens());
21108 if (!castArg) {
21109 ExprResult result = DefaultArgumentPromotion(arg);
21110 if (result.isInvalid()) return ExprError();
21111 paramType = result.get()->getType();
21112 return result;
21113 }
21114
21115 // Otherwise, use the type that was written in the explicit cast.
21116 assert(!arg->hasPlaceholderType())(static_cast <bool> (!arg->hasPlaceholderType()) ? void
(0) : __assert_fail ("!arg->hasPlaceholderType()", "clang/lib/Sema/SemaExpr.cpp"
, 21116, __extension__ __PRETTY_FUNCTION__))
;
21117 paramType = castArg->getTypeAsWritten();
21118
21119 // Copy-initialize a parameter of that type.
21120 InitializedEntity entity =
21121 InitializedEntity::InitializeParameter(Context, paramType,
21122 /*consumed*/ false);
21123 return PerformCopyInitialization(entity, callLoc, arg);
21124}
21125
21126static ExprResult diagnoseUnknownAnyExpr(Sema &S, Expr *E) {
21127 Expr *orig = E;
21128 unsigned diagID = diag::err_uncasted_use_of_unknown_any;
21129 while (true) {
21130 E = E->IgnoreParenImpCasts();
21131 if (CallExpr *call = dyn_cast<CallExpr>(E)) {
21132 E = call->getCallee();
21133 diagID = diag::err_uncasted_call_of_unknown_any;
21134 } else {
21135 break;
21136 }
21137 }
21138
21139 SourceLocation loc;
21140 NamedDecl *d;
21141 if (DeclRefExpr *ref = dyn_cast<DeclRefExpr>(E)) {
21142 loc = ref->getLocation();
21143 d = ref->getDecl();
21144 } else if (MemberExpr *mem = dyn_cast<MemberExpr>(E)) {
21145 loc = mem->getMemberLoc();
21146 d = mem->getMemberDecl();
21147 } else if (ObjCMessageExpr *msg = dyn_cast<ObjCMessageExpr>(E)) {
21148 diagID = diag::err_uncasted_call_of_unknown_any;
21149 loc = msg->getSelectorStartLoc();
21150 d = msg->getMethodDecl();
21151 if (!d) {
21152 S.Diag(loc, diag::err_uncasted_send_to_unknown_any_method)
21153 << static_cast<unsigned>(msg->isClassMessage()) << msg->getSelector()
21154 << orig->getSourceRange();
21155 return ExprError();
21156 }
21157 } else {
21158 S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_expr)
21159 << E->getSourceRange();
21160 return ExprError();
21161 }
21162
21163 S.Diag(loc, diagID) << d << orig->getSourceRange();
21164
21165 // Never recoverable.
21166 return ExprError();
21167}
21168
21169/// Check for operands with placeholder types and complain if found.
21170/// Returns ExprError() if there was an error and no recovery was possible.
21171ExprResult Sema::CheckPlaceholderExpr(Expr *E) {
21172 if (!Context.isDependenceAllowed()) {
21173 // C cannot handle TypoExpr nodes on either side of a binop because it
21174 // doesn't handle dependent types properly, so make sure any TypoExprs have
21175 // been dealt with before checking the operands.
21176 ExprResult Result = CorrectDelayedTyposInExpr(E);
21177 if (!Result.isUsable()) return ExprError();
21178 E = Result.get();
21179 }
21180
21181 const BuiltinType *placeholderType = E->getType()->getAsPlaceholderType();
21182 if (!placeholderType) return E;
21183
21184 switch (placeholderType->getKind()) {
21185
21186 // Overloaded expressions.
21187 case BuiltinType::Overload: {
21188 // Try to resolve a single function template specialization.
21189 // This is obligatory.
21190 ExprResult Result = E;
21191 if (ResolveAndFixSingleFunctionTemplateSpecialization(Result, false))
21192 return Result;
21193
21194 // No guarantees that ResolveAndFixSingleFunctionTemplateSpecialization
21195 // leaves Result unchanged on failure.
21196 Result = E;
21197 if (resolveAndFixAddressOfSingleOverloadCandidate(Result))
21198 return Result;
21199
21200 // If that failed, try to recover with a call.
21201 tryToRecoverWithCall(Result, PDiag(diag::err_ovl_unresolvable),
21202 /*complain*/ true);
21203 return Result;
21204 }
21205
21206 // Bound member functions.
21207 case BuiltinType::BoundMember: {
21208 ExprResult result = E;
21209 const Expr *BME = E->IgnoreParens();
21210 PartialDiagnostic PD = PDiag(diag::err_bound_member_function);
21211 // Try to give a nicer diagnostic if it is a bound member that we recognize.
21212 if (isa<CXXPseudoDestructorExpr>(BME)) {
21213 PD = PDiag(diag::err_dtor_expr_without_call) << /*pseudo-destructor*/ 1;
21214 } else if (const auto *ME = dyn_cast<MemberExpr>(BME)) {
21215 if (ME->getMemberNameInfo().getName().getNameKind() ==
21216 DeclarationName::CXXDestructorName)
21217 PD = PDiag(diag::err_dtor_expr_without_call) << /*destructor*/ 0;
21218 }
21219 tryToRecoverWithCall(result, PD,
21220 /*complain*/ true);
21221 return result;
21222 }
21223
21224 // ARC unbridged casts.
21225 case BuiltinType::ARCUnbridgedCast: {
21226 Expr *realCast = stripARCUnbridgedCast(E);
21227 diagnoseARCUnbridgedCast(realCast);
21228 return realCast;
21229 }
21230
21231 // Expressions of unknown type.
21232 case BuiltinType::UnknownAny:
21233 return diagnoseUnknownAnyExpr(*this, E);
21234
21235 // Pseudo-objects.
21236 case BuiltinType::PseudoObject:
21237 return checkPseudoObjectRValue(E);
21238
21239 case BuiltinType::BuiltinFn: {
21240 // Accept __noop without parens by implicitly converting it to a call expr.
21241 auto *DRE = dyn_cast<DeclRefExpr>(E->IgnoreParenImpCasts());
21242 if (DRE) {
21243 auto *FD = cast<FunctionDecl>(DRE->getDecl());
21244 unsigned BuiltinID = FD->getBuiltinID();
21245 if (BuiltinID == Builtin::BI__noop) {
21246 E = ImpCastExprToType(E, Context.getPointerType(FD->getType()),
21247 CK_BuiltinFnToFnPtr)
21248 .get();
21249 return CallExpr::Create(Context, E, /*Args=*/{}, Context.IntTy,
21250 VK_PRValue, SourceLocation(),
21251 FPOptionsOverride());
21252 }
21253
21254 if (Context.BuiltinInfo.isInStdNamespace(BuiltinID)) {
21255 // Any use of these other than a direct call is ill-formed as of C++20,
21256 // because they are not addressable functions. In earlier language
21257 // modes, warn and force an instantiation of the real body.
21258 Diag(E->getBeginLoc(),
21259 getLangOpts().CPlusPlus20
21260 ? diag::err_use_of_unaddressable_function
21261 : diag::warn_cxx20_compat_use_of_unaddressable_function);
21262 if (FD->isImplicitlyInstantiable()) {
21263 // Require a definition here because a normal attempt at
21264 // instantiation for a builtin will be ignored, and we won't try
21265 // again later. We assume that the definition of the template
21266 // precedes this use.
21267 InstantiateFunctionDefinition(E->getBeginLoc(), FD,
21268 /*Recursive=*/false,
21269 /*DefinitionRequired=*/true,
21270 /*AtEndOfTU=*/false);
21271 }
21272 // Produce a properly-typed reference to the function.
21273 CXXScopeSpec SS;
21274 SS.Adopt(DRE->getQualifierLoc());
21275 TemplateArgumentListInfo TemplateArgs;
21276 DRE->copyTemplateArgumentsInto(TemplateArgs);
21277 return BuildDeclRefExpr(
21278 FD, FD->getType(), VK_LValue, DRE->getNameInfo(),
21279 DRE->hasQualifier() ? &SS : nullptr, DRE->getFoundDecl(),
21280 DRE->getTemplateKeywordLoc(),
21281 DRE->hasExplicitTemplateArgs() ? &TemplateArgs : nullptr);
21282 }
21283 }
21284
21285 Diag(E->getBeginLoc(), diag::err_builtin_fn_use);
21286 return ExprError();
21287 }
21288
21289 case BuiltinType::IncompleteMatrixIdx:
21290 Diag(cast<MatrixSubscriptExpr>(E->IgnoreParens())
21291 ->getRowIdx()
21292 ->getBeginLoc(),
21293 diag::err_matrix_incomplete_index);
21294 return ExprError();
21295
21296 // Expressions of unknown type.
21297 case BuiltinType::OMPArraySection:
21298 Diag(E->getBeginLoc(), diag::err_omp_array_section_use);
21299 return ExprError();
21300
21301 // Expressions of unknown type.
21302 case BuiltinType::OMPArrayShaping:
21303 return ExprError(Diag(E->getBeginLoc(), diag::err_omp_array_shaping_use));
21304
21305 case BuiltinType::OMPIterator:
21306 return ExprError(Diag(E->getBeginLoc(), diag::err_omp_iterator_use));
21307
21308 // Everything else should be impossible.
21309#define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
21310 case BuiltinType::Id:
21311#include "clang/Basic/OpenCLImageTypes.def"
21312#define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \
21313 case BuiltinType::Id:
21314#include "clang/Basic/OpenCLExtensionTypes.def"
21315#define SVE_TYPE(Name, Id, SingletonId) \
21316 case BuiltinType::Id:
21317#include "clang/Basic/AArch64SVEACLETypes.def"
21318#define PPC_VECTOR_TYPE(Name, Id, Size) \
21319 case BuiltinType::Id:
21320#include "clang/Basic/PPCTypes.def"
21321#define RVV_TYPE(Name, Id, SingletonId) case BuiltinType::Id:
21322#include "clang/Basic/RISCVVTypes.def"
21323#define WASM_TYPE(Name, Id, SingletonId) case BuiltinType::Id:
21324#include "clang/Basic/WebAssemblyReferenceTypes.def"
21325#define BUILTIN_TYPE(Id, SingletonId) case BuiltinType::Id:
21326#define PLACEHOLDER_TYPE(Id, SingletonId)
21327#include "clang/AST/BuiltinTypes.def"
21328 break;
21329 }
21330
21331 llvm_unreachable("invalid placeholder type!")::llvm::llvm_unreachable_internal("invalid placeholder type!"
, "clang/lib/Sema/SemaExpr.cpp", 21331)
;
21332}
21333
21334bool Sema::CheckCaseExpression(Expr *E) {
21335 if (E->isTypeDependent())
21336 return true;
21337 if (E->isValueDependent() || E->isIntegerConstantExpr(Context))
21338 return E->getType()->isIntegralOrEnumerationType();
21339 return false;
21340}
21341
21342/// ActOnObjCBoolLiteral - Parse {__objc_yes,__objc_no} literals.
21343ExprResult
21344Sema::ActOnObjCBoolLiteral(SourceLocation OpLoc, tok::TokenKind Kind) {
21345 assert((Kind == tok::kw___objc_yes || Kind == tok::kw___objc_no) &&(static_cast <bool> ((Kind == tok::kw___objc_yes || Kind
== tok::kw___objc_no) && "Unknown Objective-C Boolean value!"
) ? void (0) : __assert_fail ("(Kind == tok::kw___objc_yes || Kind == tok::kw___objc_no) && \"Unknown Objective-C Boolean value!\""
, "clang/lib/Sema/SemaExpr.cpp", 21346, __extension__ __PRETTY_FUNCTION__
))
21346 "Unknown Objective-C Boolean value!")(static_cast <bool> ((Kind == tok::kw___objc_yes || Kind
== tok::kw___objc_no) && "Unknown Objective-C Boolean value!"
) ? void (0) : __assert_fail ("(Kind == tok::kw___objc_yes || Kind == tok::kw___objc_no) && \"Unknown Objective-C Boolean value!\""
, "clang/lib/Sema/SemaExpr.cpp", 21346, __extension__ __PRETTY_FUNCTION__
))
;
21347 QualType BoolT = Context.ObjCBuiltinBoolTy;
21348 if (!Context.getBOOLDecl()) {
21349 LookupResult Result(*this, &Context.Idents.get("BOOL"), OpLoc,
21350 Sema::LookupOrdinaryName);
21351 if (LookupName(Result, getCurScope()) && Result.isSingleResult()) {
21352 NamedDecl *ND = Result.getFoundDecl();
21353 if (TypedefDecl *TD = dyn_cast<TypedefDecl>(ND))
21354 Context.setBOOLDecl(TD);
21355 }
21356 }
21357 if (Context.getBOOLDecl())
21358 BoolT = Context.getBOOLType();
21359 return new (Context)
21360 ObjCBoolLiteralExpr(Kind == tok::kw___objc_yes, BoolT, OpLoc);
21361}
21362
21363ExprResult Sema::ActOnObjCAvailabilityCheckExpr(
21364 llvm::ArrayRef<AvailabilitySpec> AvailSpecs, SourceLocation AtLoc,
21365 SourceLocation RParen) {
21366 auto FindSpecVersion =
21367 [&](StringRef Platform) -> std::optional<VersionTuple> {
21368 auto Spec = llvm::find_if(AvailSpecs, [&](const AvailabilitySpec &Spec) {
21369 return Spec.getPlatform() == Platform;
21370 });
21371 // Transcribe the "ios" availability check to "maccatalyst" when compiling
21372 // for "maccatalyst" if "maccatalyst" is not specified.
21373 if (Spec == AvailSpecs.end() && Platform == "maccatalyst") {
21374 Spec = llvm::find_if(AvailSpecs, [&](const AvailabilitySpec &Spec) {
21375 return Spec.getPlatform() == "ios";
21376 });
21377 }
21378 if (Spec == AvailSpecs.end())
21379 return std::nullopt;
21380 return Spec->getVersion();
21381 };
21382
21383 VersionTuple Version;
21384 if (auto MaybeVersion =
21385 FindSpecVersion(Context.getTargetInfo().getPlatformName()))
21386 Version = *MaybeVersion;
21387
21388 // The use of `@available` in the enclosing context should be analyzed to
21389 // warn when it's used inappropriately (i.e. not if(@available)).
21390 if (FunctionScopeInfo *Context = getCurFunctionAvailabilityContext())
21391 Context->HasPotentialAvailabilityViolations = true;
21392
21393 return new (Context)
21394 ObjCAvailabilityCheckExpr(Version, AtLoc, RParen, Context.BoolTy);
21395}
21396
21397ExprResult Sema::CreateRecoveryExpr(SourceLocation Begin, SourceLocation End,
21398 ArrayRef<Expr *> SubExprs, QualType T) {
21399 if (!Context.getLangOpts().RecoveryAST)
21400 return ExprError();
21401
21402 if (isSFINAEContext())
21403 return ExprError();
21404
21405 if (T.isNull() || T->isUndeducedType() ||
21406 !Context.getLangOpts().RecoveryASTType)
21407 // We don't know the concrete type, fallback to dependent type.
21408 T = Context.DependentTy;
21409
21410 return RecoveryExpr::Create(Context, T, Begin, End, SubExprs);
21411}