Bug Summary

File:build/source/clang/lib/Sema/SemaExpr.cpp
Warning:line 9966, column 29
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 -D _DEBUG -D _GLIBCXX_ASSERTIONS -D _GNU_SOURCE -D _LIBCPP_ENABLE_ASSERTIONS -D __STDC_CONSTANT_MACROS -D __STDC_FORMAT_MACROS -D __STDC_LIMIT_MACROS -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 _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/= -source-date-epoch 1679263708 -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-03-19-235853-16322-1 -x c++ /build/source/clang/lib/Sema/SemaExpr.cpp

/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/Initialization.h"
45#include "clang/Sema/Lookup.h"
46#include "clang/Sema/Overload.h"
47#include "clang/Sema/ParsedTemplate.h"
48#include "clang/Sema/Scope.h"
49#include "clang/Sema/ScopeInfo.h"
50#include "clang/Sema/SemaFixItUtils.h"
51#include "clang/Sema/SemaInternal.h"
52#include "clang/Sema/Template.h"
53#include "llvm/ADT/STLExtras.h"
54#include "llvm/ADT/StringExtras.h"
55#include "llvm/Support/Casting.h"
56#include "llvm/Support/ConvertUTF.h"
57#include "llvm/Support/SaveAndRestore.h"
58#include "llvm/Support/TypeSize.h"
59#include <optional>
60
61using namespace clang;
62using namespace sema;
63
64/// Determine whether the use of this declaration is valid, without
65/// emitting diagnostics.
66bool Sema::CanUseDecl(NamedDecl *D, bool TreatUnavailableAsInvalid) {
67 // See if this is an auto-typed variable whose initializer we are parsing.
68 if (ParsingInitForAutoVars.count(D))
69 return false;
70
71 // See if this is a deleted function.
72 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
73 if (FD->isDeleted())
74 return false;
75
76 // If the function has a deduced return type, and we can't deduce it,
77 // then we can't use it either.
78 if (getLangOpts().CPlusPlus14 && FD->getReturnType()->isUndeducedType() &&
79 DeduceReturnType(FD, SourceLocation(), /*Diagnose*/ false))
80 return false;
81
82 // See if this is an aligned allocation/deallocation function that is
83 // unavailable.
84 if (TreatUnavailableAsInvalid &&
85 isUnavailableAlignedAllocationFunction(*FD))
86 return false;
87 }
88
89 // See if this function is unavailable.
90 if (TreatUnavailableAsInvalid && D->getAvailability() == AR_Unavailable &&
91 cast<Decl>(CurContext)->getAvailability() != AR_Unavailable)
92 return false;
93
94 if (isa<UnresolvedUsingIfExistsDecl>(D))
95 return false;
96
97 return true;
98}
99
100static void DiagnoseUnusedOfDecl(Sema &S, NamedDecl *D, SourceLocation Loc) {
101 // Warn if this is used but marked unused.
102 if (const auto *A = D->getAttr<UnusedAttr>()) {
103 // [[maybe_unused]] should not diagnose uses, but __attribute__((unused))
104 // should diagnose them.
105 if (A->getSemanticSpelling() != UnusedAttr::CXX11_maybe_unused &&
106 A->getSemanticSpelling() != UnusedAttr::C2x_maybe_unused) {
107 const Decl *DC = cast_or_null<Decl>(S.getCurObjCLexicalContext());
108 if (DC && !DC->hasAttr<UnusedAttr>())
109 S.Diag(Loc, diag::warn_used_but_marked_unused) << D;
110 }
111 }
112}
113
114/// Emit a note explaining that this function is deleted.
115void Sema::NoteDeletedFunction(FunctionDecl *Decl) {
116 assert(Decl && Decl->isDeleted())(static_cast <bool> (Decl && Decl->isDeleted
()) ? void (0) : __assert_fail ("Decl && Decl->isDeleted()"
, "clang/lib/Sema/SemaExpr.cpp", 116, __extension__ __PRETTY_FUNCTION__
))
;
117
118 if (Decl->isDefaulted()) {
119 // If the method was explicitly defaulted, point at that declaration.
120 if (!Decl->isImplicit())
121 Diag(Decl->getLocation(), diag::note_implicitly_deleted);
122
123 // Try to diagnose why this special member function was implicitly
124 // deleted. This might fail, if that reason no longer applies.
125 DiagnoseDeletedDefaultedFunction(Decl);
126 return;
127 }
128
129 auto *Ctor = dyn_cast<CXXConstructorDecl>(Decl);
130 if (Ctor && Ctor->isInheritingConstructor())
131 return NoteDeletedInheritingConstructor(Ctor);
132
133 Diag(Decl->getLocation(), diag::note_availability_specified_here)
134 << Decl << 1;
135}
136
137/// Determine whether a FunctionDecl was ever declared with an
138/// explicit storage class.
139static bool hasAnyExplicitStorageClass(const FunctionDecl *D) {
140 for (auto *I : D->redecls()) {
141 if (I->getStorageClass() != SC_None)
142 return true;
143 }
144 return false;
145}
146
147/// Check whether we're in an extern inline function and referring to a
148/// variable or function with internal linkage (C11 6.7.4p3).
149///
150/// This is only a warning because we used to silently accept this code, but
151/// in many cases it will not behave correctly. This is not enabled in C++ mode
152/// because the restriction language is a bit weaker (C++11 [basic.def.odr]p6)
153/// and so while there may still be user mistakes, most of the time we can't
154/// prove that there are errors.
155static void diagnoseUseOfInternalDeclInInlineFunction(Sema &S,
156 const NamedDecl *D,
157 SourceLocation Loc) {
158 // This is disabled under C++; there are too many ways for this to fire in
159 // contexts where the warning is a false positive, or where it is technically
160 // correct but benign.
161 if (S.getLangOpts().CPlusPlus)
162 return;
163
164 // Check if this is an inlined function or method.
165 FunctionDecl *Current = S.getCurFunctionDecl();
166 if (!Current)
167 return;
168 if (!Current->isInlined())
169 return;
170 if (!Current->isExternallyVisible())
171 return;
172
173 // Check if the decl has internal linkage.
174 if (D->getFormalLinkage() != InternalLinkage)
175 return;
176
177 // Downgrade from ExtWarn to Extension if
178 // (1) the supposedly external inline function is in the main file,
179 // and probably won't be included anywhere else.
180 // (2) the thing we're referencing is a pure function.
181 // (3) the thing we're referencing is another inline function.
182 // This last can give us false negatives, but it's better than warning on
183 // wrappers for simple C library functions.
184 const FunctionDecl *UsedFn = dyn_cast<FunctionDecl>(D);
185 bool DowngradeWarning = S.getSourceManager().isInMainFile(Loc);
186 if (!DowngradeWarning && UsedFn)
187 DowngradeWarning = UsedFn->isInlined() || UsedFn->hasAttr<ConstAttr>();
188
189 S.Diag(Loc, DowngradeWarning ? diag::ext_internal_in_extern_inline_quiet
190 : diag::ext_internal_in_extern_inline)
191 << /*IsVar=*/!UsedFn << D;
192
193 S.MaybeSuggestAddingStaticToDecl(Current);
194
195 S.Diag(D->getCanonicalDecl()->getLocation(), diag::note_entity_declared_at)
196 << D;
197}
198
199void Sema::MaybeSuggestAddingStaticToDecl(const FunctionDecl *Cur) {
200 const FunctionDecl *First = Cur->getFirstDecl();
201
202 // Suggest "static" on the function, if possible.
203 if (!hasAnyExplicitStorageClass(First)) {
204 SourceLocation DeclBegin = First->getSourceRange().getBegin();
205 Diag(DeclBegin, diag::note_convert_inline_to_static)
206 << Cur << FixItHint::CreateInsertion(DeclBegin, "static ");
207 }
208}
209
210/// Determine whether the use of this declaration is valid, and
211/// emit any corresponding diagnostics.
212///
213/// This routine diagnoses various problems with referencing
214/// declarations that can occur when using a declaration. For example,
215/// it might warn if a deprecated or unavailable declaration is being
216/// used, or produce an error (and return true) if a C++0x deleted
217/// function is being used.
218///
219/// \returns true if there was an error (this declaration cannot be
220/// referenced), false otherwise.
221///
222bool Sema::DiagnoseUseOfDecl(NamedDecl *D, ArrayRef<SourceLocation> Locs,
223 const ObjCInterfaceDecl *UnknownObjCClass,
224 bool ObjCPropertyAccess,
225 bool AvoidPartialAvailabilityChecks,
226 ObjCInterfaceDecl *ClassReceiver,
227 bool SkipTrailingRequiresClause) {
228 SourceLocation Loc = Locs.front();
229 if (getLangOpts().CPlusPlus && isa<FunctionDecl>(D)) {
230 // If there were any diagnostics suppressed by template argument deduction,
231 // emit them now.
232 auto Pos = SuppressedDiagnostics.find(D->getCanonicalDecl());
233 if (Pos != SuppressedDiagnostics.end()) {
234 for (const PartialDiagnosticAt &Suppressed : Pos->second)
235 Diag(Suppressed.first, Suppressed.second);
236
237 // Clear out the list of suppressed diagnostics, so that we don't emit
238 // them again for this specialization. However, we don't obsolete this
239 // entry from the table, because we want to avoid ever emitting these
240 // diagnostics again.
241 Pos->second.clear();
242 }
243
244 // C++ [basic.start.main]p3:
245 // The function 'main' shall not be used within a program.
246 if (cast<FunctionDecl>(D)->isMain())
247 Diag(Loc, diag::ext_main_used);
248
249 diagnoseUnavailableAlignedAllocation(*cast<FunctionDecl>(D), Loc);
250 }
251
252 // See if this is an auto-typed variable whose initializer we are parsing.
253 if (ParsingInitForAutoVars.count(D)) {
254 if (isa<BindingDecl>(D)) {
255 Diag(Loc, diag::err_binding_cannot_appear_in_own_initializer)
256 << D->getDeclName();
257 } else {
258 Diag(Loc, diag::err_auto_variable_cannot_appear_in_own_initializer)
259 << D->getDeclName() << cast<VarDecl>(D)->getType();
260 }
261 return true;
262 }
263
264 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
265 // See if this is a deleted function.
266 if (FD->isDeleted()) {
267 auto *Ctor = dyn_cast<CXXConstructorDecl>(FD);
268 if (Ctor && Ctor->isInheritingConstructor())
269 Diag(Loc, diag::err_deleted_inherited_ctor_use)
270 << Ctor->getParent()
271 << Ctor->getInheritedConstructor().getConstructor()->getParent();
272 else
273 Diag(Loc, diag::err_deleted_function_use);
274 NoteDeletedFunction(FD);
275 return true;
276 }
277
278 // [expr.prim.id]p4
279 // A program that refers explicitly or implicitly to a function with a
280 // trailing requires-clause whose constraint-expression is not satisfied,
281 // other than to declare it, is ill-formed. [...]
282 //
283 // See if this is a function with constraints that need to be satisfied.
284 // Check this before deducing the return type, as it might instantiate the
285 // definition.
286 if (!SkipTrailingRequiresClause && FD->getTrailingRequiresClause()) {
287 ConstraintSatisfaction Satisfaction;
288 if (CheckFunctionConstraints(FD, Satisfaction, Loc,
289 /*ForOverloadResolution*/ true))
290 // A diagnostic will have already been generated (non-constant
291 // constraint expression, for example)
292 return true;
293 if (!Satisfaction.IsSatisfied) {
294 Diag(Loc,
295 diag::err_reference_to_function_with_unsatisfied_constraints)
296 << D;
297 DiagnoseUnsatisfiedConstraint(Satisfaction);
298 return true;
299 }
300 }
301
302 // If the function has a deduced return type, and we can't deduce it,
303 // then we can't use it either.
304 if (getLangOpts().CPlusPlus14 && FD->getReturnType()->isUndeducedType() &&
305 DeduceReturnType(FD, Loc))
306 return true;
307
308 if (getLangOpts().CUDA && !CheckCUDACall(Loc, FD))
309 return true;
310
311 if (getLangOpts().SYCLIsDevice && !checkSYCLDeviceFunction(Loc, FD))
312 return true;
313 }
314
315 if (auto *MD = dyn_cast<CXXMethodDecl>(D)) {
316 // Lambdas are only default-constructible or assignable in C++2a onwards.
317 if (MD->getParent()->isLambda() &&
318 ((isa<CXXConstructorDecl>(MD) &&
319 cast<CXXConstructorDecl>(MD)->isDefaultConstructor()) ||
320 MD->isCopyAssignmentOperator() || MD->isMoveAssignmentOperator())) {
321 Diag(Loc, diag::warn_cxx17_compat_lambda_def_ctor_assign)
322 << !isa<CXXConstructorDecl>(MD);
323 }
324 }
325
326 auto getReferencedObjCProp = [](const NamedDecl *D) ->
327 const ObjCPropertyDecl * {
328 if (const auto *MD = dyn_cast<ObjCMethodDecl>(D))
329 return MD->findPropertyDecl();
330 return nullptr;
331 };
332 if (const ObjCPropertyDecl *ObjCPDecl = getReferencedObjCProp(D)) {
333 if (diagnoseArgIndependentDiagnoseIfAttrs(ObjCPDecl, Loc))
334 return true;
335 } else if (diagnoseArgIndependentDiagnoseIfAttrs(D, Loc)) {
336 return true;
337 }
338
339 // [OpenMP 4.0], 2.15 declare reduction Directive, Restrictions
340 // Only the variables omp_in and omp_out are allowed in the combiner.
341 // Only the variables omp_priv and omp_orig are allowed in the
342 // initializer-clause.
343 auto *DRD = dyn_cast<OMPDeclareReductionDecl>(CurContext);
344 if (LangOpts.OpenMP && DRD && !CurContext->containsDecl(D) &&
345 isa<VarDecl>(D)) {
346 Diag(Loc, diag::err_omp_wrong_var_in_declare_reduction)
347 << getCurFunction()->HasOMPDeclareReductionCombiner;
348 Diag(D->getLocation(), diag::note_entity_declared_at) << D;
349 return true;
350 }
351
352 // [OpenMP 5.0], 2.19.7.3. declare mapper Directive, Restrictions
353 // List-items in map clauses on this construct may only refer to the declared
354 // variable var and entities that could be referenced by a procedure defined
355 // at the same location.
356 // [OpenMP 5.2] Also allow iterator declared variables.
357 if (LangOpts.OpenMP && isa<VarDecl>(D) &&
358 !isOpenMPDeclareMapperVarDeclAllowed(cast<VarDecl>(D))) {
359 Diag(Loc, diag::err_omp_declare_mapper_wrong_var)
360 << getOpenMPDeclareMapperVarName();
361 Diag(D->getLocation(), diag::note_entity_declared_at) << D;
362 return true;
363 }
364
365 if (const auto *EmptyD = dyn_cast<UnresolvedUsingIfExistsDecl>(D)) {
366 Diag(Loc, diag::err_use_of_empty_using_if_exists);
367 Diag(EmptyD->getLocation(), diag::note_empty_using_if_exists_here);
368 return true;
369 }
370
371 DiagnoseAvailabilityOfDecl(D, Locs, UnknownObjCClass, ObjCPropertyAccess,
372 AvoidPartialAvailabilityChecks, ClassReceiver);
373
374 DiagnoseUnusedOfDecl(*this, D, Loc);
375
376 diagnoseUseOfInternalDeclInInlineFunction(*this, D, Loc);
377
378 if (auto *VD = dyn_cast<ValueDecl>(D))
379 checkTypeSupport(VD->getType(), Loc, VD);
380
381 if (LangOpts.SYCLIsDevice || (LangOpts.OpenMP && LangOpts.OpenMPIsDevice)) {
382 if (!Context.getTargetInfo().isTLSSupported())
383 if (const auto *VD = dyn_cast<VarDecl>(D))
384 if (VD->getTLSKind() != VarDecl::TLS_None)
385 targetDiag(*Locs.begin(), diag::err_thread_unsupported);
386 }
387
388 if (isa<ParmVarDecl>(D) && isa<RequiresExprBodyDecl>(D->getDeclContext()) &&
389 !isUnevaluatedContext()) {
390 // C++ [expr.prim.req.nested] p3
391 // A local parameter shall only appear as an unevaluated operand
392 // (Clause 8) within the constraint-expression.
393 Diag(Loc, diag::err_requires_expr_parameter_referenced_in_evaluated_context)
394 << D;
395 Diag(D->getLocation(), diag::note_entity_declared_at) << D;
396 return true;
397 }
398
399 return false;
400}
401
402/// DiagnoseSentinelCalls - This routine checks whether a call or
403/// message-send is to a declaration with the sentinel attribute, and
404/// if so, it checks that the requirements of the sentinel are
405/// satisfied.
406void Sema::DiagnoseSentinelCalls(NamedDecl *D, SourceLocation Loc,
407 ArrayRef<Expr *> Args) {
408 const SentinelAttr *attr = D->getAttr<SentinelAttr>();
409 if (!attr)
410 return;
411
412 // The number of formal parameters of the declaration.
413 unsigned numFormalParams;
414
415 // The kind of declaration. This is also an index into a %select in
416 // the diagnostic.
417 enum CalleeType { CT_Function, CT_Method, CT_Block } calleeType;
418
419 if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) {
420 numFormalParams = MD->param_size();
421 calleeType = CT_Method;
422 } else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
423 numFormalParams = FD->param_size();
424 calleeType = CT_Function;
425 } else if (isa<VarDecl>(D)) {
426 QualType type = cast<ValueDecl>(D)->getType();
427 const FunctionType *fn = nullptr;
428 if (const PointerType *ptr = type->getAs<PointerType>()) {
429 fn = ptr->getPointeeType()->getAs<FunctionType>();
430 if (!fn) return;
431 calleeType = CT_Function;
432 } else if (const BlockPointerType *ptr = type->getAs<BlockPointerType>()) {
433 fn = ptr->getPointeeType()->castAs<FunctionType>();
434 calleeType = CT_Block;
435 } else {
436 return;
437 }
438
439 if (const FunctionProtoType *proto = dyn_cast<FunctionProtoType>(fn)) {
440 numFormalParams = proto->getNumParams();
441 } else {
442 numFormalParams = 0;
443 }
444 } else {
445 return;
446 }
447
448 // "nullPos" is the number of formal parameters at the end which
449 // effectively count as part of the variadic arguments. This is
450 // useful if you would prefer to not have *any* formal parameters,
451 // but the language forces you to have at least one.
452 unsigned nullPos = attr->getNullPos();
453 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", 453, __extension__ __PRETTY_FUNCTION__
))
;
454 numFormalParams = (nullPos > numFormalParams ? 0 : numFormalParams - nullPos);
455
456 // The number of arguments which should follow the sentinel.
457 unsigned numArgsAfterSentinel = attr->getSentinel();
458
459 // If there aren't enough arguments for all the formal parameters,
460 // the sentinel, and the args after the sentinel, complain.
461 if (Args.size() < numFormalParams + numArgsAfterSentinel + 1) {
462 Diag(Loc, diag::warn_not_enough_argument) << D->getDeclName();
463 Diag(D->getLocation(), diag::note_sentinel_here) << int(calleeType);
464 return;
465 }
466
467 // Otherwise, find the sentinel expression.
468 Expr *sentinelExpr = Args[Args.size() - numArgsAfterSentinel - 1];
469 if (!sentinelExpr) return;
470 if (sentinelExpr->isValueDependent()) return;
471 if (Context.isSentinelNullExpr(sentinelExpr)) return;
472
473 // Pick a reasonable string to insert. Optimistically use 'nil', 'nullptr',
474 // or 'NULL' if those are actually defined in the context. Only use
475 // 'nil' for ObjC methods, where it's much more likely that the
476 // variadic arguments form a list of object pointers.
477 SourceLocation MissingNilLoc = getLocForEndOfToken(sentinelExpr->getEndLoc());
478 std::string NullValue;
479 if (calleeType == CT_Method && PP.isMacroDefined("nil"))
480 NullValue = "nil";
481 else if (getLangOpts().CPlusPlus11)
482 NullValue = "nullptr";
483 else if (PP.isMacroDefined("NULL"))
484 NullValue = "NULL";
485 else
486 NullValue = "(void*) 0";
487
488 if (MissingNilLoc.isInvalid())
489 Diag(Loc, diag::warn_missing_sentinel) << int(calleeType);
490 else
491 Diag(MissingNilLoc, diag::warn_missing_sentinel)
492 << int(calleeType)
493 << FixItHint::CreateInsertion(MissingNilLoc, ", " + NullValue);
494 Diag(D->getLocation(), diag::note_sentinel_here) << int(calleeType);
495}
496
497SourceRange Sema::getExprRange(Expr *E) const {
498 return E ? E->getSourceRange() : SourceRange();
499}
500
501//===----------------------------------------------------------------------===//
502// Standard Promotions and Conversions
503//===----------------------------------------------------------------------===//
504
505/// DefaultFunctionArrayConversion (C99 6.3.2.1p3, C99 6.3.2.1p4).
506ExprResult Sema::DefaultFunctionArrayConversion(Expr *E, bool Diagnose) {
507 // Handle any placeholder expressions which made it here.
508 if (E->hasPlaceholderType()) {
509 ExprResult result = CheckPlaceholderExpr(E);
510 if (result.isInvalid()) return ExprError();
511 E = result.get();
512 }
513
514 QualType Ty = E->getType();
515 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", 515, __extension__ __PRETTY_FUNCTION__
))
;
516
517 if (Ty->isFunctionType()) {
518 if (auto *DRE = dyn_cast<DeclRefExpr>(E->IgnoreParenCasts()))
519 if (auto *FD = dyn_cast<FunctionDecl>(DRE->getDecl()))
520 if (!checkAddressOfFunctionIsAvailable(FD, Diagnose, E->getExprLoc()))
521 return ExprError();
522
523 E = ImpCastExprToType(E, Context.getPointerType(Ty),
524 CK_FunctionToPointerDecay).get();
525 } else if (Ty->isArrayType()) {
526 // In C90 mode, arrays only promote to pointers if the array expression is
527 // an lvalue. The relevant legalese is C90 6.2.2.1p3: "an lvalue that has
528 // type 'array of type' is converted to an expression that has type 'pointer
529 // to type'...". In C99 this was changed to: C99 6.3.2.1p3: "an expression
530 // that has type 'array of type' ...". The relevant change is "an lvalue"
531 // (C90) to "an expression" (C99).
532 //
533 // C++ 4.2p1:
534 // An lvalue or rvalue of type "array of N T" or "array of unknown bound of
535 // T" can be converted to an rvalue of type "pointer to T".
536 //
537 if (getLangOpts().C99 || getLangOpts().CPlusPlus || E->isLValue()) {
538 ExprResult Res = ImpCastExprToType(E, Context.getArrayDecayedType(Ty),
539 CK_ArrayToPointerDecay);
540 if (Res.isInvalid())
541 return ExprError();
542 E = Res.get();
543 }
544 }
545 return E;
546}
547
548static void CheckForNullPointerDereference(Sema &S, Expr *E) {
549 // Check to see if we are dereferencing a null pointer. If so,
550 // and if not volatile-qualified, this is undefined behavior that the
551 // optimizer will delete, so warn about it. People sometimes try to use this
552 // to get a deterministic trap and are surprised by clang's behavior. This
553 // only handles the pattern "*null", which is a very syntactic check.
554 const auto *UO = dyn_cast<UnaryOperator>(E->IgnoreParenCasts());
555 if (UO && UO->getOpcode() == UO_Deref &&
556 UO->getSubExpr()->getType()->isPointerType()) {
557 const LangAS AS =
558 UO->getSubExpr()->getType()->getPointeeType().getAddressSpace();
559 if ((!isTargetAddressSpace(AS) ||
560 (isTargetAddressSpace(AS) && toTargetAddressSpace(AS) == 0)) &&
561 UO->getSubExpr()->IgnoreParenCasts()->isNullPointerConstant(
562 S.Context, Expr::NPC_ValueDependentIsNotNull) &&
563 !UO->getType().isVolatileQualified()) {
564 S.DiagRuntimeBehavior(UO->getOperatorLoc(), UO,
565 S.PDiag(diag::warn_indirection_through_null)
566 << UO->getSubExpr()->getSourceRange());
567 S.DiagRuntimeBehavior(UO->getOperatorLoc(), UO,
568 S.PDiag(diag::note_indirection_through_null));
569 }
570 }
571}
572
573static void DiagnoseDirectIsaAccess(Sema &S, const ObjCIvarRefExpr *OIRE,
574 SourceLocation AssignLoc,
575 const Expr* RHS) {
576 const ObjCIvarDecl *IV = OIRE->getDecl();
577 if (!IV)
578 return;
579
580 DeclarationName MemberName = IV->getDeclName();
581 IdentifierInfo *Member = MemberName.getAsIdentifierInfo();
582 if (!Member || !Member->isStr("isa"))
583 return;
584
585 const Expr *Base = OIRE->getBase();
586 QualType BaseType = Base->getType();
587 if (OIRE->isArrow())
588 BaseType = BaseType->getPointeeType();
589 if (const ObjCObjectType *OTy = BaseType->getAs<ObjCObjectType>())
590 if (ObjCInterfaceDecl *IDecl = OTy->getInterface()) {
591 ObjCInterfaceDecl *ClassDeclared = nullptr;
592 ObjCIvarDecl *IV = IDecl->lookupInstanceVariable(Member, ClassDeclared);
593 if (!ClassDeclared->getSuperClass()
594 && (*ClassDeclared->ivar_begin()) == IV) {
595 if (RHS) {
596 NamedDecl *ObjectSetClass =
597 S.LookupSingleName(S.TUScope,
598 &S.Context.Idents.get("object_setClass"),
599 SourceLocation(), S.LookupOrdinaryName);
600 if (ObjectSetClass) {
601 SourceLocation RHSLocEnd = S.getLocForEndOfToken(RHS->getEndLoc());
602 S.Diag(OIRE->getExprLoc(), diag::warn_objc_isa_assign)
603 << FixItHint::CreateInsertion(OIRE->getBeginLoc(),
604 "object_setClass(")
605 << FixItHint::CreateReplacement(
606 SourceRange(OIRE->getOpLoc(), AssignLoc), ",")
607 << FixItHint::CreateInsertion(RHSLocEnd, ")");
608 }
609 else
610 S.Diag(OIRE->getLocation(), diag::warn_objc_isa_assign);
611 } else {
612 NamedDecl *ObjectGetClass =
613 S.LookupSingleName(S.TUScope,
614 &S.Context.Idents.get("object_getClass"),
615 SourceLocation(), S.LookupOrdinaryName);
616 if (ObjectGetClass)
617 S.Diag(OIRE->getExprLoc(), diag::warn_objc_isa_use)
618 << FixItHint::CreateInsertion(OIRE->getBeginLoc(),
619 "object_getClass(")
620 << FixItHint::CreateReplacement(
621 SourceRange(OIRE->getOpLoc(), OIRE->getEndLoc()), ")");
622 else
623 S.Diag(OIRE->getLocation(), diag::warn_objc_isa_use);
624 }
625 S.Diag(IV->getLocation(), diag::note_ivar_decl);
626 }
627 }
628}
629
630ExprResult Sema::DefaultLvalueConversion(Expr *E) {
631 // Handle any placeholder expressions which made it here.
632 if (E->hasPlaceholderType()) {
633 ExprResult result = CheckPlaceholderExpr(E);
634 if (result.isInvalid()) return ExprError();
635 E = result.get();
636 }
637
638 // C++ [conv.lval]p1:
639 // A glvalue of a non-function, non-array type T can be
640 // converted to a prvalue.
641 if (!E->isGLValue()) return E;
642
643 QualType T = E->getType();
644 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", 644, __extension__ __PRETTY_FUNCTION__
))
;
645
646 // lvalue-to-rvalue conversion cannot be applied to function or array types.
647 if (T->isFunctionType() || T->isArrayType())
648 return E;
649
650 // We don't want to throw lvalue-to-rvalue casts on top of
651 // expressions of certain types in C++.
652 if (getLangOpts().CPlusPlus &&
653 (E->getType() == Context.OverloadTy ||
654 T->isDependentType() ||
655 T->isRecordType()))
656 return E;
657
658 // The C standard is actually really unclear on this point, and
659 // DR106 tells us what the result should be but not why. It's
660 // generally best to say that void types just doesn't undergo
661 // lvalue-to-rvalue at all. Note that expressions of unqualified
662 // 'void' type are never l-values, but qualified void can be.
663 if (T->isVoidType())
664 return E;
665
666 // OpenCL usually rejects direct accesses to values of 'half' type.
667 if (getLangOpts().OpenCL &&
668 !getOpenCLOptions().isAvailableOption("cl_khr_fp16", getLangOpts()) &&
669 T->isHalfType()) {
670 Diag(E->getExprLoc(), diag::err_opencl_half_load_store)
671 << 0 << T;
672 return ExprError();
673 }
674
675 CheckForNullPointerDereference(*this, E);
676 if (const ObjCIsaExpr *OISA = dyn_cast<ObjCIsaExpr>(E->IgnoreParenCasts())) {
677 NamedDecl *ObjectGetClass = LookupSingleName(TUScope,
678 &Context.Idents.get("object_getClass"),
679 SourceLocation(), LookupOrdinaryName);
680 if (ObjectGetClass)
681 Diag(E->getExprLoc(), diag::warn_objc_isa_use)
682 << FixItHint::CreateInsertion(OISA->getBeginLoc(), "object_getClass(")
683 << FixItHint::CreateReplacement(
684 SourceRange(OISA->getOpLoc(), OISA->getIsaMemberLoc()), ")");
685 else
686 Diag(E->getExprLoc(), diag::warn_objc_isa_use);
687 }
688 else if (const ObjCIvarRefExpr *OIRE =
689 dyn_cast<ObjCIvarRefExpr>(E->IgnoreParenCasts()))
690 DiagnoseDirectIsaAccess(*this, OIRE, SourceLocation(), /* Expr*/nullptr);
691
692 // C++ [conv.lval]p1:
693 // [...] If T is a non-class type, the type of the prvalue is the
694 // cv-unqualified version of T. Otherwise, the type of the
695 // rvalue is T.
696 //
697 // C99 6.3.2.1p2:
698 // If the lvalue has qualified type, the value has the unqualified
699 // version of the type of the lvalue; otherwise, the value has the
700 // type of the lvalue.
701 if (T.hasQualifiers())
702 T = T.getUnqualifiedType();
703
704 // Under the MS ABI, lock down the inheritance model now.
705 if (T->isMemberPointerType() &&
706 Context.getTargetInfo().getCXXABI().isMicrosoft())
707 (void)isCompleteType(E->getExprLoc(), T);
708
709 ExprResult Res = CheckLValueToRValueConversionOperand(E);
710 if (Res.isInvalid())
711 return Res;
712 E = Res.get();
713
714 // Loading a __weak object implicitly retains the value, so we need a cleanup to
715 // balance that.
716 if (E->getType().getObjCLifetime() == Qualifiers::OCL_Weak)
717 Cleanup.setExprNeedsCleanups(true);
718
719 if (E->getType().isDestructedType() == QualType::DK_nontrivial_c_struct)
720 Cleanup.setExprNeedsCleanups(true);
721
722 // C++ [conv.lval]p3:
723 // If T is cv std::nullptr_t, the result is a null pointer constant.
724 CastKind CK = T->isNullPtrType() ? CK_NullToPointer : CK_LValueToRValue;
725 Res = ImplicitCastExpr::Create(Context, T, CK, E, nullptr, VK_PRValue,
726 CurFPFeatureOverrides());
727
728 // C11 6.3.2.1p2:
729 // ... if the lvalue has atomic type, the value has the non-atomic version
730 // of the type of the lvalue ...
731 if (const AtomicType *Atomic = T->getAs<AtomicType>()) {
732 T = Atomic->getValueType().getUnqualifiedType();
733 Res = ImplicitCastExpr::Create(Context, T, CK_AtomicToNonAtomic, Res.get(),
734 nullptr, VK_PRValue, FPOptionsOverride());
735 }
736
737 return Res;
738}
739
740ExprResult Sema::DefaultFunctionArrayLvalueConversion(Expr *E, bool Diagnose) {
741 ExprResult Res = DefaultFunctionArrayConversion(E, Diagnose);
742 if (Res.isInvalid())
743 return ExprError();
744 Res = DefaultLvalueConversion(Res.get());
745 if (Res.isInvalid())
746 return ExprError();
747 return Res;
748}
749
750/// CallExprUnaryConversions - a special case of an unary conversion
751/// performed on a function designator of a call expression.
752ExprResult Sema::CallExprUnaryConversions(Expr *E) {
753 QualType Ty = E->getType();
754 ExprResult Res = E;
755 // Only do implicit cast for a function type, but not for a pointer
756 // to function type.
757 if (Ty->isFunctionType()) {
758 Res = ImpCastExprToType(E, Context.getPointerType(Ty),
759 CK_FunctionToPointerDecay);
760 if (Res.isInvalid())
761 return ExprError();
762 }
763 Res = DefaultLvalueConversion(Res.get());
764 if (Res.isInvalid())
765 return ExprError();
766 return Res.get();
767}
768
769/// UsualUnaryConversions - Performs various conversions that are common to most
770/// operators (C99 6.3). The conversions of array and function types are
771/// sometimes suppressed. For example, the array->pointer conversion doesn't
772/// apply if the array is an argument to the sizeof or address (&) operators.
773/// In these instances, this routine should *not* be called.
774ExprResult Sema::UsualUnaryConversions(Expr *E) {
775 // First, convert to an r-value.
776 ExprResult Res = DefaultFunctionArrayLvalueConversion(E);
777 if (Res.isInvalid())
778 return ExprError();
779 E = Res.get();
780
781 QualType Ty = E->getType();
782 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", 782, __extension__ __PRETTY_FUNCTION__
))
;
783
784 LangOptions::FPEvalMethodKind EvalMethod = CurFPFeatures.getFPEvalMethod();
785 if (EvalMethod != LangOptions::FEM_Source && Ty->isFloatingType() &&
786 (getLangOpts().getFPEvalMethod() !=
787 LangOptions::FPEvalMethodKind::FEM_UnsetOnCommandLine ||
788 PP.getLastFPEvalPragmaLocation().isValid())) {
789 switch (EvalMethod) {
790 default:
791 llvm_unreachable("Unrecognized float evaluation method")::llvm::llvm_unreachable_internal("Unrecognized float evaluation method"
, "clang/lib/Sema/SemaExpr.cpp", 791)
;
792 break;
793 case LangOptions::FEM_UnsetOnCommandLine:
794 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", 794)
;
795 break;
796 case LangOptions::FEM_Double:
797 if (Context.getFloatingTypeOrder(Context.DoubleTy, Ty) > 0)
798 // Widen the expression to double.
799 return Ty->isComplexType()
800 ? ImpCastExprToType(E,
801 Context.getComplexType(Context.DoubleTy),
802 CK_FloatingComplexCast)
803 : ImpCastExprToType(E, Context.DoubleTy, CK_FloatingCast);
804 break;
805 case LangOptions::FEM_Extended:
806 if (Context.getFloatingTypeOrder(Context.LongDoubleTy, Ty) > 0)
807 // Widen the expression to long double.
808 return Ty->isComplexType()
809 ? ImpCastExprToType(
810 E, Context.getComplexType(Context.LongDoubleTy),
811 CK_FloatingComplexCast)
812 : ImpCastExprToType(E, Context.LongDoubleTy,
813 CK_FloatingCast);
814 break;
815 }
816 }
817
818 // Half FP have to be promoted to float unless it is natively supported
819 if (Ty->isHalfType() && !getLangOpts().NativeHalfType)
820 return ImpCastExprToType(Res.get(), Context.FloatTy, CK_FloatingCast);
821
822 // Try to perform integral promotions if the object has a theoretically
823 // promotable type.
824 if (Ty->isIntegralOrUnscopedEnumerationType()) {
825 // C99 6.3.1.1p2:
826 //
827 // The following may be used in an expression wherever an int or
828 // unsigned int may be used:
829 // - an object or expression with an integer type whose integer
830 // conversion rank is less than or equal to the rank of int
831 // and unsigned int.
832 // - A bit-field of type _Bool, int, signed int, or unsigned int.
833 //
834 // If an int can represent all values of the original type, the
835 // value is converted to an int; otherwise, it is converted to an
836 // unsigned int. These are called the integer promotions. All
837 // other types are unchanged by the integer promotions.
838
839 QualType PTy = Context.isPromotableBitField(E);
840 if (!PTy.isNull()) {
841 E = ImpCastExprToType(E, PTy, CK_IntegralCast).get();
842 return E;
843 }
844 if (Context.isPromotableIntegerType(Ty)) {
845 QualType PT = Context.getPromotedIntegerType(Ty);
846 E = ImpCastExprToType(E, PT, CK_IntegralCast).get();
847 return E;
848 }
849 }
850 return E;
851}
852
853/// DefaultArgumentPromotion (C99 6.5.2.2p6). Used for function calls that
854/// do not have a prototype. Arguments that have type float or __fp16
855/// are promoted to double. All other argument types are converted by
856/// UsualUnaryConversions().
857ExprResult Sema::DefaultArgumentPromotion(Expr *E) {
858 QualType Ty = E->getType();
859 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", 859, __extension__ __PRETTY_FUNCTION__
))
;
860
861 ExprResult Res = UsualUnaryConversions(E);
862 if (Res.isInvalid())
863 return ExprError();
864 E = Res.get();
865
866 // If this is a 'float' or '__fp16' (CVR qualified or typedef)
867 // promote to double.
868 // Note that default argument promotion applies only to float (and
869 // half/fp16); it does not apply to _Float16.
870 const BuiltinType *BTy = Ty->getAs<BuiltinType>();
871 if (BTy && (BTy->getKind() == BuiltinType::Half ||
872 BTy->getKind() == BuiltinType::Float)) {
873 if (getLangOpts().OpenCL &&
874 !getOpenCLOptions().isAvailableOption("cl_khr_fp64", getLangOpts())) {
875 if (BTy->getKind() == BuiltinType::Half) {
876 E = ImpCastExprToType(E, Context.FloatTy, CK_FloatingCast).get();
877 }
878 } else {
879 E = ImpCastExprToType(E, Context.DoubleTy, CK_FloatingCast).get();
880 }
881 }
882 if (BTy &&
883 getLangOpts().getExtendIntArgs() ==
884 LangOptions::ExtendArgsKind::ExtendTo64 &&
885 Context.getTargetInfo().supportsExtendIntArgs() && Ty->isIntegerType() &&
886 Context.getTypeSizeInChars(BTy) <
887 Context.getTypeSizeInChars(Context.LongLongTy)) {
888 E = (Ty->isUnsignedIntegerType())
889 ? ImpCastExprToType(E, Context.UnsignedLongLongTy, CK_IntegralCast)
890 .get()
891 : ImpCastExprToType(E, Context.LongLongTy, CK_IntegralCast).get();
892 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", 893, __extension__ __PRETTY_FUNCTION__
))
893 "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", 893, __extension__ __PRETTY_FUNCTION__
))
;
894 }
895
896 // C++ performs lvalue-to-rvalue conversion as a default argument
897 // promotion, even on class types, but note:
898 // C++11 [conv.lval]p2:
899 // When an lvalue-to-rvalue conversion occurs in an unevaluated
900 // operand or a subexpression thereof the value contained in the
901 // referenced object is not accessed. Otherwise, if the glvalue
902 // has a class type, the conversion copy-initializes a temporary
903 // of type T from the glvalue and the result of the conversion
904 // is a prvalue for the temporary.
905 // FIXME: add some way to gate this entire thing for correctness in
906 // potentially potentially evaluated contexts.
907 if (getLangOpts().CPlusPlus && E->isGLValue() && !isUnevaluatedContext()) {
908 ExprResult Temp = PerformCopyInitialization(
909 InitializedEntity::InitializeTemporary(E->getType()),
910 E->getExprLoc(), E);
911 if (Temp.isInvalid())
912 return ExprError();
913 E = Temp.get();
914 }
915
916 return E;
917}
918
919/// Determine the degree of POD-ness for an expression.
920/// Incomplete types are considered POD, since this check can be performed
921/// when we're in an unevaluated context.
922Sema::VarArgKind Sema::isValidVarArgType(const QualType &Ty) {
923 if (Ty->isIncompleteType()) {
924 // C++11 [expr.call]p7:
925 // After these conversions, if the argument does not have arithmetic,
926 // enumeration, pointer, pointer to member, or class type, the program
927 // is ill-formed.
928 //
929 // Since we've already performed array-to-pointer and function-to-pointer
930 // decay, the only such type in C++ is cv void. This also handles
931 // initializer lists as variadic arguments.
932 if (Ty->isVoidType())
933 return VAK_Invalid;
934
935 if (Ty->isObjCObjectType())
936 return VAK_Invalid;
937 return VAK_Valid;
938 }
939
940 if (Ty.isDestructedType() == QualType::DK_nontrivial_c_struct)
941 return VAK_Invalid;
942
943 if (Context.getTargetInfo().getTriple().isWasm() &&
944 Ty->isWebAssemblyReferenceType()) {
945 return VAK_Invalid;
946 }
947
948 if (Ty.isCXX98PODType(Context))
949 return VAK_Valid;
950
951 // C++11 [expr.call]p7:
952 // Passing a potentially-evaluated argument of class type (Clause 9)
953 // having a non-trivial copy constructor, a non-trivial move constructor,
954 // or a non-trivial destructor, with no corresponding parameter,
955 // is conditionally-supported with implementation-defined semantics.
956 if (getLangOpts().CPlusPlus11 && !Ty->isDependentType())
957 if (CXXRecordDecl *Record = Ty->getAsCXXRecordDecl())
958 if (!Record->hasNonTrivialCopyConstructor() &&
959 !Record->hasNonTrivialMoveConstructor() &&
960 !Record->hasNonTrivialDestructor())
961 return VAK_ValidInCXX11;
962
963 if (getLangOpts().ObjCAutoRefCount && Ty->isObjCLifetimeType())
964 return VAK_Valid;
965
966 if (Ty->isObjCObjectType())
967 return VAK_Invalid;
968
969 if (getLangOpts().MSVCCompat)
970 return VAK_MSVCUndefined;
971
972 // FIXME: In C++11, these cases are conditionally-supported, meaning we're
973 // permitted to reject them. We should consider doing so.
974 return VAK_Undefined;
975}
976
977void Sema::checkVariadicArgument(const Expr *E, VariadicCallType CT) {
978 // Don't allow one to pass an Objective-C interface to a vararg.
979 const QualType &Ty = E->getType();
980 VarArgKind VAK = isValidVarArgType(Ty);
981
982 // Complain about passing non-POD types through varargs.
983 switch (VAK) {
984 case VAK_ValidInCXX11:
985 DiagRuntimeBehavior(
986 E->getBeginLoc(), nullptr,
987 PDiag(diag::warn_cxx98_compat_pass_non_pod_arg_to_vararg) << Ty << CT);
988 [[fallthrough]];
989 case VAK_Valid:
990 if (Ty->isRecordType()) {
991 // This is unlikely to be what the user intended. If the class has a
992 // 'c_str' member function, the user probably meant to call that.
993 DiagRuntimeBehavior(E->getBeginLoc(), nullptr,
994 PDiag(diag::warn_pass_class_arg_to_vararg)
995 << Ty << CT << hasCStrMethod(E) << ".c_str()");
996 }
997 break;
998
999 case VAK_Undefined:
1000 case VAK_MSVCUndefined:
1001 DiagRuntimeBehavior(E->getBeginLoc(), nullptr,
1002 PDiag(diag::warn_cannot_pass_non_pod_arg_to_vararg)
1003 << getLangOpts().CPlusPlus11 << Ty << CT);
1004 break;
1005
1006 case VAK_Invalid:
1007 if (Ty.isDestructedType() == QualType::DK_nontrivial_c_struct)
1008 Diag(E->getBeginLoc(),
1009 diag::err_cannot_pass_non_trivial_c_struct_to_vararg)
1010 << Ty << CT;
1011 else if (Ty->isObjCObjectType())
1012 DiagRuntimeBehavior(E->getBeginLoc(), nullptr,
1013 PDiag(diag::err_cannot_pass_objc_interface_to_vararg)
1014 << Ty << CT);
1015 else
1016 Diag(E->getBeginLoc(), diag::err_cannot_pass_to_vararg)
1017 << isa<InitListExpr>(E) << Ty << CT;
1018 break;
1019 }
1020}
1021
1022/// DefaultVariadicArgumentPromotion - Like DefaultArgumentPromotion, but
1023/// will create a trap if the resulting type is not a POD type.
1024ExprResult Sema::DefaultVariadicArgumentPromotion(Expr *E, VariadicCallType CT,
1025 FunctionDecl *FDecl) {
1026 if (const BuiltinType *PlaceholderTy = E->getType()->getAsPlaceholderType()) {
1027 // Strip the unbridged-cast placeholder expression off, if applicable.
1028 if (PlaceholderTy->getKind() == BuiltinType::ARCUnbridgedCast &&
1029 (CT == VariadicMethod ||
1030 (FDecl && FDecl->hasAttr<CFAuditedTransferAttr>()))) {
1031 E = stripARCUnbridgedCast(E);
1032
1033 // Otherwise, do normal placeholder checking.
1034 } else {
1035 ExprResult ExprRes = CheckPlaceholderExpr(E);
1036 if (ExprRes.isInvalid())
1037 return ExprError();
1038 E = ExprRes.get();
1039 }
1040 }
1041
1042 ExprResult ExprRes = DefaultArgumentPromotion(E);
1043 if (ExprRes.isInvalid())
1044 return ExprError();
1045
1046 // Copy blocks to the heap.
1047 if (ExprRes.get()->getType()->isBlockPointerType())
1048 maybeExtendBlockObject(ExprRes);
1049
1050 E = ExprRes.get();
1051
1052 // Diagnostics regarding non-POD argument types are
1053 // emitted along with format string checking in Sema::CheckFunctionCall().
1054 if (isValidVarArgType(E->getType()) == VAK_Undefined) {
1055 // Turn this into a trap.
1056 CXXScopeSpec SS;
1057 SourceLocation TemplateKWLoc;
1058 UnqualifiedId Name;
1059 Name.setIdentifier(PP.getIdentifierInfo("__builtin_trap"),
1060 E->getBeginLoc());
1061 ExprResult TrapFn = ActOnIdExpression(TUScope, SS, TemplateKWLoc, Name,
1062 /*HasTrailingLParen=*/true,
1063 /*IsAddressOfOperand=*/false);
1064 if (TrapFn.isInvalid())
1065 return ExprError();
1066
1067 ExprResult Call = BuildCallExpr(TUScope, TrapFn.get(), E->getBeginLoc(),
1068 std::nullopt, E->getEndLoc());
1069 if (Call.isInvalid())
1070 return ExprError();
1071
1072 ExprResult Comma =
1073 ActOnBinOp(TUScope, E->getBeginLoc(), tok::comma, Call.get(), E);
1074 if (Comma.isInvalid())
1075 return ExprError();
1076 return Comma.get();
1077 }
1078
1079 if (!getLangOpts().CPlusPlus &&
1080 RequireCompleteType(E->getExprLoc(), E->getType(),
1081 diag::err_call_incomplete_argument))
1082 return ExprError();
1083
1084 return E;
1085}
1086
1087/// Converts an integer to complex float type. Helper function of
1088/// UsualArithmeticConversions()
1089///
1090/// \return false if the integer expression is an integer type and is
1091/// successfully converted to the complex type.
1092static bool handleIntegerToComplexFloatConversion(Sema &S, ExprResult &IntExpr,
1093 ExprResult &ComplexExpr,
1094 QualType IntTy,
1095 QualType ComplexTy,
1096 bool SkipCast) {
1097 if (IntTy->isComplexType() || IntTy->isRealFloatingType()) return true;
1098 if (SkipCast) return false;
1099 if (IntTy->isIntegerType()) {
1100 QualType fpTy = ComplexTy->castAs<ComplexType>()->getElementType();
1101 IntExpr = S.ImpCastExprToType(IntExpr.get(), fpTy, CK_IntegralToFloating);
1102 IntExpr = S.ImpCastExprToType(IntExpr.get(), ComplexTy,
1103 CK_FloatingRealToComplex);
1104 } else {
1105 assert(IntTy->isComplexIntegerType())(static_cast <bool> (IntTy->isComplexIntegerType()) ?
void (0) : __assert_fail ("IntTy->isComplexIntegerType()"
, "clang/lib/Sema/SemaExpr.cpp", 1105, __extension__ __PRETTY_FUNCTION__
))
;
1106 IntExpr = S.ImpCastExprToType(IntExpr.get(), ComplexTy,
1107 CK_IntegralComplexToFloatingComplex);
1108 }
1109 return false;
1110}
1111
1112// This handles complex/complex, complex/float, or float/complex.
1113// When both operands are complex, the shorter operand is converted to the
1114// type of the longer, and that is the type of the result. This corresponds
1115// to what is done when combining two real floating-point operands.
1116// The fun begins when size promotion occur across type domains.
1117// From H&S 6.3.4: When one operand is complex and the other is a real
1118// floating-point type, the less precise type is converted, within it's
1119// real or complex domain, to the precision of the other type. For example,
1120// when combining a "long double" with a "double _Complex", the
1121// "double _Complex" is promoted to "long double _Complex".
1122static QualType handleComplexFloatConversion(Sema &S, ExprResult &Shorter,
1123 QualType ShorterType,
1124 QualType LongerType,
1125 bool PromotePrecision) {
1126 bool LongerIsComplex = isa<ComplexType>(LongerType.getCanonicalType());
1127 QualType Result =
1128 LongerIsComplex ? LongerType : S.Context.getComplexType(LongerType);
1129
1130 if (PromotePrecision) {
1131 if (isa<ComplexType>(ShorterType.getCanonicalType())) {
1132 Shorter =
1133 S.ImpCastExprToType(Shorter.get(), Result, CK_FloatingComplexCast);
1134 } else {
1135 if (LongerIsComplex)
1136 LongerType = LongerType->castAs<ComplexType>()->getElementType();
1137 Shorter = S.ImpCastExprToType(Shorter.get(), LongerType, CK_FloatingCast);
1138 }
1139 }
1140 return Result;
1141}
1142
1143/// Handle arithmetic conversion with complex types. Helper function of
1144/// UsualArithmeticConversions()
1145static QualType handleComplexConversion(Sema &S, ExprResult &LHS,
1146 ExprResult &RHS, QualType LHSType,
1147 QualType RHSType, bool IsCompAssign) {
1148 // if we have an integer operand, the result is the complex type.
1149 if (!handleIntegerToComplexFloatConversion(S, RHS, LHS, RHSType, LHSType,
1150 /*SkipCast=*/false))
1151 return LHSType;
1152 if (!handleIntegerToComplexFloatConversion(S, LHS, RHS, LHSType, RHSType,
1153 /*SkipCast=*/IsCompAssign))
1154 return RHSType;
1155
1156 // Compute the rank of the two types, regardless of whether they are complex.
1157 int Order = S.Context.getFloatingTypeOrder(LHSType, RHSType);
1158 if (Order < 0)
1159 // Promote the precision of the LHS if not an assignment.
1160 return handleComplexFloatConversion(S, LHS, LHSType, RHSType,
1161 /*PromotePrecision=*/!IsCompAssign);
1162 // Promote the precision of the RHS unless it is already the same as the LHS.
1163 return handleComplexFloatConversion(S, RHS, RHSType, LHSType,
1164 /*PromotePrecision=*/Order > 0);
1165}
1166
1167/// Handle arithmetic conversion from integer to float. Helper function
1168/// of UsualArithmeticConversions()
1169static QualType handleIntToFloatConversion(Sema &S, ExprResult &FloatExpr,
1170 ExprResult &IntExpr,
1171 QualType FloatTy, QualType IntTy,
1172 bool ConvertFloat, bool ConvertInt) {
1173 if (IntTy->isIntegerType()) {
1174 if (ConvertInt)
1175 // Convert intExpr to the lhs floating point type.
1176 IntExpr = S.ImpCastExprToType(IntExpr.get(), FloatTy,
1177 CK_IntegralToFloating);
1178 return FloatTy;
1179 }
1180
1181 // Convert both sides to the appropriate complex float.
1182 assert(IntTy->isComplexIntegerType())(static_cast <bool> (IntTy->isComplexIntegerType()) ?
void (0) : __assert_fail ("IntTy->isComplexIntegerType()"
, "clang/lib/Sema/SemaExpr.cpp", 1182, __extension__ __PRETTY_FUNCTION__
))
;
1183 QualType result = S.Context.getComplexType(FloatTy);
1184
1185 // _Complex int -> _Complex float
1186 if (ConvertInt)
1187 IntExpr = S.ImpCastExprToType(IntExpr.get(), result,
1188 CK_IntegralComplexToFloatingComplex);
1189
1190 // float -> _Complex float
1191 if (ConvertFloat)
1192 FloatExpr = S.ImpCastExprToType(FloatExpr.get(), result,
1193 CK_FloatingRealToComplex);
1194
1195 return result;
1196}
1197
1198/// Handle arithmethic conversion with floating point types. Helper
1199/// function of UsualArithmeticConversions()
1200static QualType handleFloatConversion(Sema &S, ExprResult &LHS,
1201 ExprResult &RHS, QualType LHSType,
1202 QualType RHSType, bool IsCompAssign) {
1203 bool LHSFloat = LHSType->isRealFloatingType();
1204 bool RHSFloat = RHSType->isRealFloatingType();
1205
1206 // N1169 4.1.4: If one of the operands has a floating type and the other
1207 // operand has a fixed-point type, the fixed-point operand
1208 // is converted to the floating type [...]
1209 if (LHSType->isFixedPointType() || RHSType->isFixedPointType()) {
1210 if (LHSFloat)
1211 RHS = S.ImpCastExprToType(RHS.get(), LHSType, CK_FixedPointToFloating);
1212 else if (!IsCompAssign)
1213 LHS = S.ImpCastExprToType(LHS.get(), RHSType, CK_FixedPointToFloating);
1214 return LHSFloat ? LHSType : RHSType;
1215 }
1216
1217 // If we have two real floating types, convert the smaller operand
1218 // to the bigger result.
1219 if (LHSFloat && RHSFloat) {
1220 int order = S.Context.getFloatingTypeOrder(LHSType, RHSType);
1221 if (order > 0) {
1222 RHS = S.ImpCastExprToType(RHS.get(), LHSType, CK_FloatingCast);
1223 return LHSType;
1224 }
1225
1226 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", 1226, __extension__ __PRETTY_FUNCTION__
))
;
1227 if (!IsCompAssign)
1228 LHS = S.ImpCastExprToType(LHS.get(), RHSType, CK_FloatingCast);
1229 return RHSType;
1230 }
1231
1232 if (LHSFloat) {
1233 // Half FP has to be promoted to float unless it is natively supported
1234 if (LHSType->isHalfType() && !S.getLangOpts().NativeHalfType)
1235 LHSType = S.Context.FloatTy;
1236
1237 return handleIntToFloatConversion(S, LHS, RHS, LHSType, RHSType,
1238 /*ConvertFloat=*/!IsCompAssign,
1239 /*ConvertInt=*/ true);
1240 }
1241 assert(RHSFloat)(static_cast <bool> (RHSFloat) ? void (0) : __assert_fail
("RHSFloat", "clang/lib/Sema/SemaExpr.cpp", 1241, __extension__
__PRETTY_FUNCTION__))
;
1242 return handleIntToFloatConversion(S, RHS, LHS, RHSType, LHSType,
1243 /*ConvertFloat=*/ true,
1244 /*ConvertInt=*/!IsCompAssign);
1245}
1246
1247/// Diagnose attempts to convert between __float128, __ibm128 and
1248/// long double if there is no support for such conversion.
1249/// Helper function of UsualArithmeticConversions().
1250static bool unsupportedTypeConversion(const Sema &S, QualType LHSType,
1251 QualType RHSType) {
1252 // No issue if either is not a floating point type.
1253 if (!LHSType->isFloatingType() || !RHSType->isFloatingType())
1254 return false;
1255
1256 // No issue if both have the same 128-bit float semantics.
1257 auto *LHSComplex = LHSType->getAs<ComplexType>();
1258 auto *RHSComplex = RHSType->getAs<ComplexType>();
1259
1260 QualType LHSElem = LHSComplex ? LHSComplex->getElementType() : LHSType;
1261 QualType RHSElem = RHSComplex ? RHSComplex->getElementType() : RHSType;
1262
1263 const llvm::fltSemantics &LHSSem = S.Context.getFloatTypeSemantics(LHSElem);
1264 const llvm::fltSemantics &RHSSem = S.Context.getFloatTypeSemantics(RHSElem);
1265
1266 if ((&LHSSem != &llvm::APFloat::PPCDoubleDouble() ||
1267 &RHSSem != &llvm::APFloat::IEEEquad()) &&
1268 (&LHSSem != &llvm::APFloat::IEEEquad() ||
1269 &RHSSem != &llvm::APFloat::PPCDoubleDouble()))
1270 return false;
1271
1272 return true;
1273}
1274
1275typedef ExprResult PerformCastFn(Sema &S, Expr *operand, QualType toType);
1276
1277namespace {
1278/// These helper callbacks are placed in an anonymous namespace to
1279/// permit their use as function template parameters.
1280ExprResult doIntegralCast(Sema &S, Expr *op, QualType toType) {
1281 return S.ImpCastExprToType(op, toType, CK_IntegralCast);
1282}
1283
1284ExprResult doComplexIntegralCast(Sema &S, Expr *op, QualType toType) {
1285 return S.ImpCastExprToType(op, S.Context.getComplexType(toType),
1286 CK_IntegralComplexCast);
1287}
1288}
1289
1290/// Handle integer arithmetic conversions. Helper function of
1291/// UsualArithmeticConversions()
1292template <PerformCastFn doLHSCast, PerformCastFn doRHSCast>
1293static QualType handleIntegerConversion(Sema &S, ExprResult &LHS,
1294 ExprResult &RHS, QualType LHSType,
1295 QualType RHSType, bool IsCompAssign) {
1296 // The rules for this case are in C99 6.3.1.8
1297 int order = S.Context.getIntegerTypeOrder(LHSType, RHSType);
1298 bool LHSSigned = LHSType->hasSignedIntegerRepresentation();
1299 bool RHSSigned = RHSType->hasSignedIntegerRepresentation();
1300 if (LHSSigned == RHSSigned) {
1301 // Same signedness; use the higher-ranked type
1302 if (order >= 0) {
1303 RHS = (*doRHSCast)(S, RHS.get(), LHSType);
1304 return LHSType;
1305 } else if (!IsCompAssign)
1306 LHS = (*doLHSCast)(S, LHS.get(), RHSType);
1307 return RHSType;
1308 } else if (order != (LHSSigned ? 1 : -1)) {
1309 // The unsigned type has greater than or equal rank to the
1310 // signed type, so use the unsigned type
1311 if (RHSSigned) {
1312 RHS = (*doRHSCast)(S, RHS.get(), LHSType);
1313 return LHSType;
1314 } else if (!IsCompAssign)
1315 LHS = (*doLHSCast)(S, LHS.get(), RHSType);
1316 return RHSType;
1317 } else if (S.Context.getIntWidth(LHSType) != S.Context.getIntWidth(RHSType)) {
1318 // The two types are different widths; if we are here, that
1319 // means the signed type is larger than the unsigned type, so
1320 // use the signed type.
1321 if (LHSSigned) {
1322 RHS = (*doRHSCast)(S, RHS.get(), LHSType);
1323 return LHSType;
1324 } else if (!IsCompAssign)
1325 LHS = (*doLHSCast)(S, LHS.get(), RHSType);
1326 return RHSType;
1327 } else {
1328 // The signed type is higher-ranked than the unsigned type,
1329 // but isn't actually any bigger (like unsigned int and long
1330 // on most 32-bit systems). Use the unsigned type corresponding
1331 // to the signed type.
1332 QualType result =
1333 S.Context.getCorrespondingUnsignedType(LHSSigned ? LHSType : RHSType);
1334 RHS = (*doRHSCast)(S, RHS.get(), result);
1335 if (!IsCompAssign)
1336 LHS = (*doLHSCast)(S, LHS.get(), result);
1337 return result;
1338 }
1339}
1340
1341/// Handle conversions with GCC complex int extension. Helper function
1342/// of UsualArithmeticConversions()
1343static QualType handleComplexIntConversion(Sema &S, ExprResult &LHS,
1344 ExprResult &RHS, QualType LHSType,
1345 QualType RHSType,
1346 bool IsCompAssign) {
1347 const ComplexType *LHSComplexInt = LHSType->getAsComplexIntegerType();
1348 const ComplexType *RHSComplexInt = RHSType->getAsComplexIntegerType();
1349
1350 if (LHSComplexInt && RHSComplexInt) {
1351 QualType LHSEltType = LHSComplexInt->getElementType();
1352 QualType RHSEltType = RHSComplexInt->getElementType();
1353 QualType ScalarType =
1354 handleIntegerConversion<doComplexIntegralCast, doComplexIntegralCast>
1355 (S, LHS, RHS, LHSEltType, RHSEltType, IsCompAssign);
1356
1357 return S.Context.getComplexType(ScalarType);
1358 }
1359
1360 if (LHSComplexInt) {
1361 QualType LHSEltType = LHSComplexInt->getElementType();
1362 QualType ScalarType =
1363 handleIntegerConversion<doComplexIntegralCast, doIntegralCast>
1364 (S, LHS, RHS, LHSEltType, RHSType, IsCompAssign);
1365 QualType ComplexType = S.Context.getComplexType(ScalarType);
1366 RHS = S.ImpCastExprToType(RHS.get(), ComplexType,
1367 CK_IntegralRealToComplex);
1368
1369 return ComplexType;
1370 }
1371
1372 assert(RHSComplexInt)(static_cast <bool> (RHSComplexInt) ? void (0) : __assert_fail
("RHSComplexInt", "clang/lib/Sema/SemaExpr.cpp", 1372, __extension__
__PRETTY_FUNCTION__))
;
1373
1374 QualType RHSEltType = RHSComplexInt->getElementType();
1375 QualType ScalarType =
1376 handleIntegerConversion<doIntegralCast, doComplexIntegralCast>
1377 (S, LHS, RHS, LHSType, RHSEltType, IsCompAssign);
1378 QualType ComplexType = S.Context.getComplexType(ScalarType);
1379
1380 if (!IsCompAssign)
1381 LHS = S.ImpCastExprToType(LHS.get(), ComplexType,
1382 CK_IntegralRealToComplex);
1383 return ComplexType;
1384}
1385
1386/// Return the rank of a given fixed point or integer type. The value itself
1387/// doesn't matter, but the values must be increasing with proper increasing
1388/// rank as described in N1169 4.1.1.
1389static unsigned GetFixedPointRank(QualType Ty) {
1390 const auto *BTy = Ty->getAs<BuiltinType>();
1391 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", 1391, __extension__ __PRETTY_FUNCTION__
))
;
1392
1393 switch (BTy->getKind()) {
1394 case BuiltinType::ShortFract:
1395 case BuiltinType::UShortFract:
1396 case BuiltinType::SatShortFract:
1397 case BuiltinType::SatUShortFract:
1398 return 1;
1399 case BuiltinType::Fract:
1400 case BuiltinType::UFract:
1401 case BuiltinType::SatFract:
1402 case BuiltinType::SatUFract:
1403 return 2;
1404 case BuiltinType::LongFract:
1405 case BuiltinType::ULongFract:
1406 case BuiltinType::SatLongFract:
1407 case BuiltinType::SatULongFract:
1408 return 3;
1409 case BuiltinType::ShortAccum:
1410 case BuiltinType::UShortAccum:
1411 case BuiltinType::SatShortAccum:
1412 case BuiltinType::SatUShortAccum:
1413 return 4;
1414 case BuiltinType::Accum:
1415 case BuiltinType::UAccum:
1416 case BuiltinType::SatAccum:
1417 case BuiltinType::SatUAccum:
1418 return 5;
1419 case BuiltinType::LongAccum:
1420 case BuiltinType::ULongAccum:
1421 case BuiltinType::SatLongAccum:
1422 case BuiltinType::SatULongAccum:
1423 return 6;
1424 default:
1425 if (BTy->isInteger())
1426 return 0;
1427 llvm_unreachable("Unexpected fixed point or integer type")::llvm::llvm_unreachable_internal("Unexpected fixed point or integer type"
, "clang/lib/Sema/SemaExpr.cpp", 1427)
;
1428 }
1429}
1430
1431/// handleFixedPointConversion - Fixed point operations between fixed
1432/// point types and integers or other fixed point types do not fall under
1433/// usual arithmetic conversion since these conversions could result in loss
1434/// of precsision (N1169 4.1.4). These operations should be calculated with
1435/// the full precision of their result type (N1169 4.1.6.2.1).
1436static QualType handleFixedPointConversion(Sema &S, QualType LHSTy,
1437 QualType RHSTy) {
1438 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", 1439, __extension__ __PRETTY_FUNCTION__
))
1439 "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", 1439, __extension__ __PRETTY_FUNCTION__
))
;
1440 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", 1443, __extension__ __PRETTY_FUNCTION__
))
1441 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", 1443, __extension__ __PRETTY_FUNCTION__
))
1442 "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", 1443, __extension__ __PRETTY_FUNCTION__
))
1443 "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", 1443, __extension__ __PRETTY_FUNCTION__
))
;
1444
1445 // If one operand has signed fixed-point type and the other operand has
1446 // unsigned fixed-point type, then the unsigned fixed-point operand is
1447 // converted to its corresponding signed fixed-point type and the resulting
1448 // type is the type of the converted operand.
1449 if (RHSTy->isSignedFixedPointType() && LHSTy->isUnsignedFixedPointType())
1450 LHSTy = S.Context.getCorrespondingSignedFixedPointType(LHSTy);
1451 else if (RHSTy->isUnsignedFixedPointType() && LHSTy->isSignedFixedPointType())
1452 RHSTy = S.Context.getCorrespondingSignedFixedPointType(RHSTy);
1453
1454 // The result type is the type with the highest rank, whereby a fixed-point
1455 // conversion rank is always greater than an integer conversion rank; if the
1456 // type of either of the operands is a saturating fixedpoint type, the result
1457 // type shall be the saturating fixed-point type corresponding to the type
1458 // with the highest rank; the resulting value is converted (taking into
1459 // account rounding and overflow) to the precision of the resulting type.
1460 // Same ranks between signed and unsigned types are resolved earlier, so both
1461 // types are either signed or both unsigned at this point.
1462 unsigned LHSTyRank = GetFixedPointRank(LHSTy);
1463 unsigned RHSTyRank = GetFixedPointRank(RHSTy);
1464
1465 QualType ResultTy = LHSTyRank > RHSTyRank ? LHSTy : RHSTy;
1466
1467 if (LHSTy->isSaturatedFixedPointType() || RHSTy->isSaturatedFixedPointType())
1468 ResultTy = S.Context.getCorrespondingSaturatedType(ResultTy);
1469
1470 return ResultTy;
1471}
1472
1473/// Check that the usual arithmetic conversions can be performed on this pair of
1474/// expressions that might be of enumeration type.
1475static void checkEnumArithmeticConversions(Sema &S, Expr *LHS, Expr *RHS,
1476 SourceLocation Loc,
1477 Sema::ArithConvKind ACK) {
1478 // C++2a [expr.arith.conv]p1:
1479 // If one operand is of enumeration type and the other operand is of a
1480 // different enumeration type or a floating-point type, this behavior is
1481 // deprecated ([depr.arith.conv.enum]).
1482 //
1483 // Warn on this in all language modes. Produce a deprecation warning in C++20.
1484 // Eventually we will presumably reject these cases (in C++23 onwards?).
1485 QualType L = LHS->getType(), R = RHS->getType();
1486 bool LEnum = L->isUnscopedEnumerationType(),
1487 REnum = R->isUnscopedEnumerationType();
1488 bool IsCompAssign = ACK == Sema::ACK_CompAssign;
1489 if ((!IsCompAssign && LEnum && R->isFloatingType()) ||
1490 (REnum && L->isFloatingType())) {
1491 S.Diag(Loc, S.getLangOpts().CPlusPlus20
1492 ? diag::warn_arith_conv_enum_float_cxx20
1493 : diag::warn_arith_conv_enum_float)
1494 << LHS->getSourceRange() << RHS->getSourceRange()
1495 << (int)ACK << LEnum << L << R;
1496 } else if (!IsCompAssign && LEnum && REnum &&
1497 !S.Context.hasSameUnqualifiedType(L, R)) {
1498 unsigned DiagID;
1499 if (!L->castAs<EnumType>()->getDecl()->hasNameForLinkage() ||
1500 !R->castAs<EnumType>()->getDecl()->hasNameForLinkage()) {
1501 // If either enumeration type is unnamed, it's less likely that the
1502 // user cares about this, but this situation is still deprecated in
1503 // C++2a. Use a different warning group.
1504 DiagID = S.getLangOpts().CPlusPlus20
1505 ? diag::warn_arith_conv_mixed_anon_enum_types_cxx20
1506 : diag::warn_arith_conv_mixed_anon_enum_types;
1507 } else if (ACK == Sema::ACK_Conditional) {
1508 // Conditional expressions are separated out because they have
1509 // historically had a different warning flag.
1510 DiagID = S.getLangOpts().CPlusPlus20
1511 ? diag::warn_conditional_mixed_enum_types_cxx20
1512 : diag::warn_conditional_mixed_enum_types;
1513 } else if (ACK == Sema::ACK_Comparison) {
1514 // Comparison expressions are separated out because they have
1515 // historically had a different warning flag.
1516 DiagID = S.getLangOpts().CPlusPlus20
1517 ? diag::warn_comparison_mixed_enum_types_cxx20
1518 : diag::warn_comparison_mixed_enum_types;
1519 } else {
1520 DiagID = S.getLangOpts().CPlusPlus20
1521 ? diag::warn_arith_conv_mixed_enum_types_cxx20
1522 : diag::warn_arith_conv_mixed_enum_types;
1523 }
1524 S.Diag(Loc, DiagID) << LHS->getSourceRange() << RHS->getSourceRange()
1525 << (int)ACK << L << R;
1526 }
1527}
1528
1529/// UsualArithmeticConversions - Performs various conversions that are common to
1530/// binary operators (C99 6.3.1.8). If both operands aren't arithmetic, this
1531/// routine returns the first non-arithmetic type found. The client is
1532/// responsible for emitting appropriate error diagnostics.
1533QualType Sema::UsualArithmeticConversions(ExprResult &LHS, ExprResult &RHS,
1534 SourceLocation Loc,
1535 ArithConvKind ACK) {
1536 checkEnumArithmeticConversions(*this, LHS.get(), RHS.get(), Loc, ACK);
1537
1538 if (ACK != ACK_CompAssign) {
1539 LHS = UsualUnaryConversions(LHS.get());
1540 if (LHS.isInvalid())
1541 return QualType();
1542 }
1543
1544 RHS = UsualUnaryConversions(RHS.get());
1545 if (RHS.isInvalid())
1546 return QualType();
1547
1548 // For conversion purposes, we ignore any qualifiers.
1549 // For example, "const float" and "float" are equivalent.
1550 QualType LHSType = LHS.get()->getType().getUnqualifiedType();
1551 QualType RHSType = RHS.get()->getType().getUnqualifiedType();
1552
1553 // For conversion purposes, we ignore any atomic qualifier on the LHS.
1554 if (const AtomicType *AtomicLHS = LHSType->getAs<AtomicType>())
1555 LHSType = AtomicLHS->getValueType();
1556
1557 // If both types are identical, no conversion is needed.
1558 if (Context.hasSameType(LHSType, RHSType))
1559 return Context.getCommonSugaredType(LHSType, RHSType);
1560
1561 // If either side is a non-arithmetic type (e.g. a pointer), we are done.
1562 // The caller can deal with this (e.g. pointer + int).
1563 if (!LHSType->isArithmeticType() || !RHSType->isArithmeticType())
1564 return QualType();
1565
1566 // Apply unary and bitfield promotions to the LHS's type.
1567 QualType LHSUnpromotedType = LHSType;
1568 if (Context.isPromotableIntegerType(LHSType))
1569 LHSType = Context.getPromotedIntegerType(LHSType);
1570 QualType LHSBitfieldPromoteTy = Context.isPromotableBitField(LHS.get());
1571 if (!LHSBitfieldPromoteTy.isNull())
1572 LHSType = LHSBitfieldPromoteTy;
1573 if (LHSType != LHSUnpromotedType && ACK != ACK_CompAssign)
1574 LHS = ImpCastExprToType(LHS.get(), LHSType, CK_IntegralCast);
1575
1576 // If both types are identical, no conversion is needed.
1577 if (Context.hasSameType(LHSType, RHSType))
1578 return Context.getCommonSugaredType(LHSType, RHSType);
1579
1580 // At this point, we have two different arithmetic types.
1581
1582 // Diagnose attempts to convert between __ibm128, __float128 and long double
1583 // where such conversions currently can't be handled.
1584 if (unsupportedTypeConversion(*this, LHSType, RHSType))
1585 return QualType();
1586
1587 // Handle complex types first (C99 6.3.1.8p1).
1588 if (LHSType->isComplexType() || RHSType->isComplexType())
1589 return handleComplexConversion(*this, LHS, RHS, LHSType, RHSType,
1590 ACK == ACK_CompAssign);
1591
1592 // Now handle "real" floating types (i.e. float, double, long double).
1593 if (LHSType->isRealFloatingType() || RHSType->isRealFloatingType())
1594 return handleFloatConversion(*this, LHS, RHS, LHSType, RHSType,
1595 ACK == ACK_CompAssign);
1596
1597 // Handle GCC complex int extension.
1598 if (LHSType->isComplexIntegerType() || RHSType->isComplexIntegerType())
1599 return handleComplexIntConversion(*this, LHS, RHS, LHSType, RHSType,
1600 ACK == ACK_CompAssign);
1601
1602 if (LHSType->isFixedPointType() || RHSType->isFixedPointType())
1603 return handleFixedPointConversion(*this, LHSType, RHSType);
1604
1605 // Finally, we have two differing integer types.
1606 return handleIntegerConversion<doIntegralCast, doIntegralCast>
1607 (*this, LHS, RHS, LHSType, RHSType, ACK == ACK_CompAssign);
1608}
1609
1610//===----------------------------------------------------------------------===//
1611// Semantic Analysis for various Expression Types
1612//===----------------------------------------------------------------------===//
1613
1614
1615ExprResult
1616Sema::ActOnGenericSelectionExpr(SourceLocation KeyLoc,
1617 SourceLocation DefaultLoc,
1618 SourceLocation RParenLoc,
1619 Expr *ControllingExpr,
1620 ArrayRef<ParsedType> ArgTypes,
1621 ArrayRef<Expr *> ArgExprs) {
1622 unsigned NumAssocs = ArgTypes.size();
1623 assert(NumAssocs == ArgExprs.size())(static_cast <bool> (NumAssocs == ArgExprs.size()) ? void
(0) : __assert_fail ("NumAssocs == ArgExprs.size()", "clang/lib/Sema/SemaExpr.cpp"
, 1623, __extension__ __PRETTY_FUNCTION__))
;
1624
1625 TypeSourceInfo **Types = new TypeSourceInfo*[NumAssocs];
1626 for (unsigned i = 0; i < NumAssocs; ++i) {
1627 if (ArgTypes[i])
1628 (void) GetTypeFromParser(ArgTypes[i], &Types[i]);
1629 else
1630 Types[i] = nullptr;
1631 }
1632
1633 ExprResult ER =
1634 CreateGenericSelectionExpr(KeyLoc, DefaultLoc, RParenLoc, ControllingExpr,
1635 llvm::ArrayRef(Types, NumAssocs), ArgExprs);
1636 delete [] Types;
1637 return ER;
1638}
1639
1640ExprResult
1641Sema::CreateGenericSelectionExpr(SourceLocation KeyLoc,
1642 SourceLocation DefaultLoc,
1643 SourceLocation RParenLoc,
1644 Expr *ControllingExpr,
1645 ArrayRef<TypeSourceInfo *> Types,
1646 ArrayRef<Expr *> Exprs) {
1647 unsigned NumAssocs = Types.size();
1648 assert(NumAssocs == Exprs.size())(static_cast <bool> (NumAssocs == Exprs.size()) ? void (
0) : __assert_fail ("NumAssocs == Exprs.size()", "clang/lib/Sema/SemaExpr.cpp"
, 1648, __extension__ __PRETTY_FUNCTION__))
;
1649
1650 // Decay and strip qualifiers for the controlling expression type, and handle
1651 // placeholder type replacement. See committee discussion from WG14 DR423.
1652 {
1653 EnterExpressionEvaluationContext Unevaluated(
1654 *this, Sema::ExpressionEvaluationContext::Unevaluated);
1655 ExprResult R = DefaultFunctionArrayLvalueConversion(ControllingExpr);
1656 if (R.isInvalid())
1657 return ExprError();
1658 ControllingExpr = R.get();
1659 }
1660
1661 bool TypeErrorFound = false,
1662 IsResultDependent = ControllingExpr->isTypeDependent(),
1663 ContainsUnexpandedParameterPack
1664 = ControllingExpr->containsUnexpandedParameterPack();
1665
1666 // The controlling expression is an unevaluated operand, so side effects are
1667 // likely unintended.
1668 if (!inTemplateInstantiation() && !IsResultDependent &&
1669 ControllingExpr->HasSideEffects(Context, false))
1670 Diag(ControllingExpr->getExprLoc(),
1671 diag::warn_side_effects_unevaluated_context);
1672
1673 for (unsigned i = 0; i < NumAssocs; ++i) {
1674 if (Exprs[i]->containsUnexpandedParameterPack())
1675 ContainsUnexpandedParameterPack = true;
1676
1677 if (Types[i]) {
1678 if (Types[i]->getType()->containsUnexpandedParameterPack())
1679 ContainsUnexpandedParameterPack = true;
1680
1681 if (Types[i]->getType()->isDependentType()) {
1682 IsResultDependent = true;
1683 } else {
1684 // C11 6.5.1.1p2 "The type name in a generic association shall specify a
1685 // complete object type other than a variably modified type."
1686 unsigned D = 0;
1687 if (Types[i]->getType()->isIncompleteType())
1688 D = diag::err_assoc_type_incomplete;
1689 else if (!Types[i]->getType()->isObjectType())
1690 D = diag::err_assoc_type_nonobject;
1691 else if (Types[i]->getType()->isVariablyModifiedType())
1692 D = diag::err_assoc_type_variably_modified;
1693 else {
1694 // Because the controlling expression undergoes lvalue conversion,
1695 // array conversion, and function conversion, an association which is
1696 // of array type, function type, or is qualified can never be
1697 // reached. We will warn about this so users are less surprised by
1698 // the unreachable association. However, we don't have to handle
1699 // function types; that's not an object type, so it's handled above.
1700 //
1701 // The logic is somewhat different for C++ because C++ has different
1702 // lvalue to rvalue conversion rules than C. [conv.lvalue]p1 says,
1703 // If T is a non-class type, the type of the prvalue is the cv-
1704 // unqualified version of T. Otherwise, the type of the prvalue is T.
1705 // The result of these rules is that all qualified types in an
1706 // association in C are unreachable, and in C++, only qualified non-
1707 // class types are unreachable.
1708 unsigned Reason = 0;
1709 QualType QT = Types[i]->getType();
1710 if (QT->isArrayType())
1711 Reason = 1;
1712 else if (QT.hasQualifiers() &&
1713 (!LangOpts.CPlusPlus || !QT->isRecordType()))
1714 Reason = 2;
1715
1716 if (Reason)
1717 Diag(Types[i]->getTypeLoc().getBeginLoc(),
1718 diag::warn_unreachable_association)
1719 << QT << (Reason - 1);
1720 }
1721
1722 if (D != 0) {
1723 Diag(Types[i]->getTypeLoc().getBeginLoc(), D)
1724 << Types[i]->getTypeLoc().getSourceRange()
1725 << Types[i]->getType();
1726 TypeErrorFound = true;
1727 }
1728
1729 // C11 6.5.1.1p2 "No two generic associations in the same generic
1730 // selection shall specify compatible types."
1731 for (unsigned j = i+1; j < NumAssocs; ++j)
1732 if (Types[j] && !Types[j]->getType()->isDependentType() &&
1733 Context.typesAreCompatible(Types[i]->getType(),
1734 Types[j]->getType())) {
1735 Diag(Types[j]->getTypeLoc().getBeginLoc(),
1736 diag::err_assoc_compatible_types)
1737 << Types[j]->getTypeLoc().getSourceRange()
1738 << Types[j]->getType()
1739 << Types[i]->getType();
1740 Diag(Types[i]->getTypeLoc().getBeginLoc(),
1741 diag::note_compat_assoc)
1742 << Types[i]->getTypeLoc().getSourceRange()
1743 << Types[i]->getType();
1744 TypeErrorFound = true;
1745 }
1746 }
1747 }
1748 }
1749 if (TypeErrorFound)
1750 return ExprError();
1751
1752 // If we determined that the generic selection is result-dependent, don't
1753 // try to compute the result expression.
1754 if (IsResultDependent)
1755 return GenericSelectionExpr::Create(Context, KeyLoc, ControllingExpr, Types,
1756 Exprs, DefaultLoc, RParenLoc,
1757 ContainsUnexpandedParameterPack);
1758
1759 SmallVector<unsigned, 1> CompatIndices;
1760 unsigned DefaultIndex = -1U;
1761 // Look at the canonical type of the controlling expression in case it was a
1762 // deduced type like __auto_type. However, when issuing diagnostics, use the
1763 // type the user wrote in source rather than the canonical one.
1764 for (unsigned i = 0; i < NumAssocs; ++i) {
1765 if (!Types[i])
1766 DefaultIndex = i;
1767 else if (Context.typesAreCompatible(
1768 ControllingExpr->getType().getCanonicalType(),
1769 Types[i]->getType()))
1770 CompatIndices.push_back(i);
1771 }
1772
1773 // C11 6.5.1.1p2 "The controlling expression of a generic selection shall have
1774 // type compatible with at most one of the types named in its generic
1775 // association list."
1776 if (CompatIndices.size() > 1) {
1777 // We strip parens here because the controlling expression is typically
1778 // parenthesized in macro definitions.
1779 ControllingExpr = ControllingExpr->IgnoreParens();
1780 Diag(ControllingExpr->getBeginLoc(), diag::err_generic_sel_multi_match)
1781 << ControllingExpr->getSourceRange() << ControllingExpr->getType()
1782 << (unsigned)CompatIndices.size();
1783 for (unsigned I : CompatIndices) {
1784 Diag(Types[I]->getTypeLoc().getBeginLoc(),
1785 diag::note_compat_assoc)
1786 << Types[I]->getTypeLoc().getSourceRange()
1787 << Types[I]->getType();
1788 }
1789 return ExprError();
1790 }
1791
1792 // C11 6.5.1.1p2 "If a generic selection has no default generic association,
1793 // its controlling expression shall have type compatible with exactly one of
1794 // the types named in its generic association list."
1795 if (DefaultIndex == -1U && CompatIndices.size() == 0) {
1796 // We strip parens here because the controlling expression is typically
1797 // parenthesized in macro definitions.
1798 ControllingExpr = ControllingExpr->IgnoreParens();
1799 Diag(ControllingExpr->getBeginLoc(), diag::err_generic_sel_no_match)
1800 << ControllingExpr->getSourceRange() << ControllingExpr->getType();
1801 return ExprError();
1802 }
1803
1804 // C11 6.5.1.1p3 "If a generic selection has a generic association with a
1805 // type name that is compatible with the type of the controlling expression,
1806 // then the result expression of the generic selection is the expression
1807 // in that generic association. Otherwise, the result expression of the
1808 // generic selection is the expression in the default generic association."
1809 unsigned ResultIndex =
1810 CompatIndices.size() ? CompatIndices[0] : DefaultIndex;
1811
1812 return GenericSelectionExpr::Create(
1813 Context, KeyLoc, ControllingExpr, Types, Exprs, DefaultLoc, RParenLoc,
1814 ContainsUnexpandedParameterPack, ResultIndex);
1815}
1816
1817/// getUDSuffixLoc - Create a SourceLocation for a ud-suffix, given the
1818/// location of the token and the offset of the ud-suffix within it.
1819static SourceLocation getUDSuffixLoc(Sema &S, SourceLocation TokLoc,
1820 unsigned Offset) {
1821 return Lexer::AdvanceToTokenCharacter(TokLoc, Offset, S.getSourceManager(),
1822 S.getLangOpts());
1823}
1824
1825/// BuildCookedLiteralOperatorCall - A user-defined literal was found. Look up
1826/// the corresponding cooked (non-raw) literal operator, and build a call to it.
1827static ExprResult BuildCookedLiteralOperatorCall(Sema &S, Scope *Scope,
1828 IdentifierInfo *UDSuffix,
1829 SourceLocation UDSuffixLoc,
1830 ArrayRef<Expr*> Args,
1831 SourceLocation LitEndLoc) {
1832 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", 1832, __extension__ __PRETTY_FUNCTION__
))
;
1833
1834 QualType ArgTy[2];
1835 for (unsigned ArgIdx = 0; ArgIdx != Args.size(); ++ArgIdx) {
1836 ArgTy[ArgIdx] = Args[ArgIdx]->getType();
1837 if (ArgTy[ArgIdx]->isArrayType())
1838 ArgTy[ArgIdx] = S.Context.getArrayDecayedType(ArgTy[ArgIdx]);
1839 }
1840
1841 DeclarationName OpName =
1842 S.Context.DeclarationNames.getCXXLiteralOperatorName(UDSuffix);
1843 DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc);
1844 OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc);
1845
1846 LookupResult R(S, OpName, UDSuffixLoc, Sema::LookupOrdinaryName);
1847 if (S.LookupLiteralOperator(Scope, R, llvm::ArrayRef(ArgTy, Args.size()),
1848 /*AllowRaw*/ false, /*AllowTemplate*/ false,
1849 /*AllowStringTemplatePack*/ false,
1850 /*DiagnoseMissing*/ true) == Sema::LOLR_Error)
1851 return ExprError();
1852
1853 return S.BuildLiteralOperatorCall(R, OpNameInfo, Args, LitEndLoc);
1854}
1855
1856/// ActOnStringLiteral - The specified tokens were lexed as pasted string
1857/// fragments (e.g. "foo" "bar" L"baz"). The result string has to handle string
1858/// concatenation ([C99 5.1.1.2, translation phase #6]), so it may come from
1859/// multiple tokens. However, the common case is that StringToks points to one
1860/// string.
1861///
1862ExprResult
1863Sema::ActOnStringLiteral(ArrayRef<Token> StringToks, Scope *UDLScope) {
1864 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", 1864, __extension__ __PRETTY_FUNCTION__
))
;
1865
1866 StringLiteralParser Literal(StringToks, PP);
1867 if (Literal.hadError)
1868 return ExprError();
1869
1870 SmallVector<SourceLocation, 4> StringTokLocs;
1871 for (const Token &Tok : StringToks)
1872 StringTokLocs.push_back(Tok.getLocation());
1873
1874 QualType CharTy = Context.CharTy;
1875 StringLiteral::StringKind Kind = StringLiteral::Ordinary;
1876 if (Literal.isWide()) {
1877 CharTy = Context.getWideCharType();
1878 Kind = StringLiteral::Wide;
1879 } else if (Literal.isUTF8()) {
1880 if (getLangOpts().Char8)
1881 CharTy = Context.Char8Ty;
1882 Kind = StringLiteral::UTF8;
1883 } else if (Literal.isUTF16()) {
1884 CharTy = Context.Char16Ty;
1885 Kind = StringLiteral::UTF16;
1886 } else if (Literal.isUTF32()) {
1887 CharTy = Context.Char32Ty;
1888 Kind = StringLiteral::UTF32;
1889 } else if (Literal.isPascal()) {
1890 CharTy = Context.UnsignedCharTy;
1891 }
1892
1893 // Warn on initializing an array of char from a u8 string literal; this
1894 // becomes ill-formed in C++2a.
1895 if (getLangOpts().CPlusPlus && !getLangOpts().CPlusPlus20 &&
1896 !getLangOpts().Char8 && Kind == StringLiteral::UTF8) {
1897 Diag(StringTokLocs.front(), diag::warn_cxx20_compat_utf8_string);
1898
1899 // Create removals for all 'u8' prefixes in the string literal(s). This
1900 // ensures C++2a compatibility (but may change the program behavior when
1901 // built by non-Clang compilers for which the execution character set is
1902 // not always UTF-8).
1903 auto RemovalDiag = PDiag(diag::note_cxx20_compat_utf8_string_remove_u8);
1904 SourceLocation RemovalDiagLoc;
1905 for (const Token &Tok : StringToks) {
1906 if (Tok.getKind() == tok::utf8_string_literal) {
1907 if (RemovalDiagLoc.isInvalid())
1908 RemovalDiagLoc = Tok.getLocation();
1909 RemovalDiag << FixItHint::CreateRemoval(CharSourceRange::getCharRange(
1910 Tok.getLocation(),
1911 Lexer::AdvanceToTokenCharacter(Tok.getLocation(), 2,
1912 getSourceManager(), getLangOpts())));
1913 }
1914 }
1915 Diag(RemovalDiagLoc, RemovalDiag);
1916 }
1917
1918 QualType StrTy =
1919 Context.getStringLiteralArrayType(CharTy, Literal.GetNumStringChars());
1920
1921 // Pass &StringTokLocs[0], StringTokLocs.size() to factory!
1922 StringLiteral *Lit = StringLiteral::Create(Context, Literal.GetString(),
1923 Kind, Literal.Pascal, StrTy,
1924 &StringTokLocs[0],
1925 StringTokLocs.size());
1926 if (Literal.getUDSuffix().empty())
1927 return Lit;
1928
1929 // We're building a user-defined literal.
1930 IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix());
1931 SourceLocation UDSuffixLoc =
1932 getUDSuffixLoc(*this, StringTokLocs[Literal.getUDSuffixToken()],
1933 Literal.getUDSuffixOffset());
1934
1935 // Make sure we're allowed user-defined literals here.
1936 if (!UDLScope)
1937 return ExprError(Diag(UDSuffixLoc, diag::err_invalid_string_udl));
1938
1939 // C++11 [lex.ext]p5: The literal L is treated as a call of the form
1940 // operator "" X (str, len)
1941 QualType SizeType = Context.getSizeType();
1942
1943 DeclarationName OpName =
1944 Context.DeclarationNames.getCXXLiteralOperatorName(UDSuffix);
1945 DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc);
1946 OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc);
1947
1948 QualType ArgTy[] = {
1949 Context.getArrayDecayedType(StrTy), SizeType
1950 };
1951
1952 LookupResult R(*this, OpName, UDSuffixLoc, LookupOrdinaryName);
1953 switch (LookupLiteralOperator(UDLScope, R, ArgTy,
1954 /*AllowRaw*/ false, /*AllowTemplate*/ true,
1955 /*AllowStringTemplatePack*/ true,
1956 /*DiagnoseMissing*/ true, Lit)) {
1957
1958 case LOLR_Cooked: {
1959 llvm::APInt Len(Context.getIntWidth(SizeType), Literal.GetNumStringChars());
1960 IntegerLiteral *LenArg = IntegerLiteral::Create(Context, Len, SizeType,
1961 StringTokLocs[0]);
1962 Expr *Args[] = { Lit, LenArg };
1963
1964 return BuildLiteralOperatorCall(R, OpNameInfo, Args, StringTokLocs.back());
1965 }
1966
1967 case LOLR_Template: {
1968 TemplateArgumentListInfo ExplicitArgs;
1969 TemplateArgument Arg(Lit);
1970 TemplateArgumentLocInfo ArgInfo(Lit);
1971 ExplicitArgs.addArgument(TemplateArgumentLoc(Arg, ArgInfo));
1972 return BuildLiteralOperatorCall(R, OpNameInfo, std::nullopt,
1973 StringTokLocs.back(), &ExplicitArgs);
1974 }
1975
1976 case LOLR_StringTemplatePack: {
1977 TemplateArgumentListInfo ExplicitArgs;
1978
1979 unsigned CharBits = Context.getIntWidth(CharTy);
1980 bool CharIsUnsigned = CharTy->isUnsignedIntegerType();
1981 llvm::APSInt Value(CharBits, CharIsUnsigned);
1982
1983 TemplateArgument TypeArg(CharTy);
1984 TemplateArgumentLocInfo TypeArgInfo(Context.getTrivialTypeSourceInfo(CharTy));
1985 ExplicitArgs.addArgument(TemplateArgumentLoc(TypeArg, TypeArgInfo));
1986
1987 for (unsigned I = 0, N = Lit->getLength(); I != N; ++I) {
1988 Value = Lit->getCodeUnit(I);
1989 TemplateArgument Arg(Context, Value, CharTy);
1990 TemplateArgumentLocInfo ArgInfo;
1991 ExplicitArgs.addArgument(TemplateArgumentLoc(Arg, ArgInfo));
1992 }
1993 return BuildLiteralOperatorCall(R, OpNameInfo, std::nullopt,
1994 StringTokLocs.back(), &ExplicitArgs);
1995 }
1996 case LOLR_Raw:
1997 case LOLR_ErrorNoDiagnostic:
1998 llvm_unreachable("unexpected literal operator lookup result")::llvm::llvm_unreachable_internal("unexpected literal operator lookup result"
, "clang/lib/Sema/SemaExpr.cpp", 1998)
;
1999 case LOLR_Error:
2000 return ExprError();
2001 }
2002 llvm_unreachable("unexpected literal operator lookup result")::llvm::llvm_unreachable_internal("unexpected literal operator lookup result"
, "clang/lib/Sema/SemaExpr.cpp", 2002)
;
2003}
2004
2005DeclRefExpr *
2006Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK,
2007 SourceLocation Loc,
2008 const CXXScopeSpec *SS) {
2009 DeclarationNameInfo NameInfo(D->getDeclName(), Loc);
2010 return BuildDeclRefExpr(D, Ty, VK, NameInfo, SS);
2011}
2012
2013DeclRefExpr *
2014Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK,
2015 const DeclarationNameInfo &NameInfo,
2016 const CXXScopeSpec *SS, NamedDecl *FoundD,
2017 SourceLocation TemplateKWLoc,
2018 const TemplateArgumentListInfo *TemplateArgs) {
2019 NestedNameSpecifierLoc NNS =
2020 SS ? SS->getWithLocInContext(Context) : NestedNameSpecifierLoc();
2021 return BuildDeclRefExpr(D, Ty, VK, NameInfo, NNS, FoundD, TemplateKWLoc,
2022 TemplateArgs);
2023}
2024
2025// CUDA/HIP: Check whether a captured reference variable is referencing a
2026// host variable in a device or host device lambda.
2027static bool isCapturingReferenceToHostVarInCUDADeviceLambda(const Sema &S,
2028 VarDecl *VD) {
2029 if (!S.getLangOpts().CUDA || !VD->hasInit())
2030 return false;
2031 assert(VD->getType()->isReferenceType())(static_cast <bool> (VD->getType()->isReferenceType
()) ? void (0) : __assert_fail ("VD->getType()->isReferenceType()"
, "clang/lib/Sema/SemaExpr.cpp", 2031, __extension__ __PRETTY_FUNCTION__
))
;
2032
2033 // Check whether the reference variable is referencing a host variable.
2034 auto *DRE = dyn_cast<DeclRefExpr>(VD->getInit());
2035 if (!DRE)
2036 return false;
2037 auto *Referee = dyn_cast<VarDecl>(DRE->getDecl());
2038 if (!Referee || !Referee->hasGlobalStorage() ||
2039 Referee->hasAttr<CUDADeviceAttr>())
2040 return false;
2041
2042 // Check whether the current function is a device or host device lambda.
2043 // Check whether the reference variable is a capture by getDeclContext()
2044 // since refersToEnclosingVariableOrCapture() is not ready at this point.
2045 auto *MD = dyn_cast_or_null<CXXMethodDecl>(S.CurContext);
2046 if (MD && MD->getParent()->isLambda() &&
2047 MD->getOverloadedOperator() == OO_Call && MD->hasAttr<CUDADeviceAttr>() &&
2048 VD->getDeclContext() != MD)
2049 return true;
2050
2051 return false;
2052}
2053
2054NonOdrUseReason Sema::getNonOdrUseReasonInCurrentContext(ValueDecl *D) {
2055 // A declaration named in an unevaluated operand never constitutes an odr-use.
2056 if (isUnevaluatedContext())
2057 return NOUR_Unevaluated;
2058
2059 // C++2a [basic.def.odr]p4:
2060 // A variable x whose name appears as a potentially-evaluated expression e
2061 // is odr-used by e unless [...] x is a reference that is usable in
2062 // constant expressions.
2063 // CUDA/HIP:
2064 // If a reference variable referencing a host variable is captured in a
2065 // device or host device lambda, the value of the referee must be copied
2066 // to the capture and the reference variable must be treated as odr-use
2067 // since the value of the referee is not known at compile time and must
2068 // be loaded from the captured.
2069 if (VarDecl *VD = dyn_cast<VarDecl>(D)) {
2070 if (VD->getType()->isReferenceType() &&
2071 !(getLangOpts().OpenMP && isOpenMPCapturedDecl(D)) &&
2072 !isCapturingReferenceToHostVarInCUDADeviceLambda(*this, VD) &&
2073 VD->isUsableInConstantExpressions(Context))
2074 return NOUR_Constant;
2075 }
2076
2077 // All remaining non-variable cases constitute an odr-use. For variables, we
2078 // need to wait and see how the expression is used.
2079 return NOUR_None;
2080}
2081
2082/// BuildDeclRefExpr - Build an expression that references a
2083/// declaration that does not require a closure capture.
2084DeclRefExpr *
2085Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK,
2086 const DeclarationNameInfo &NameInfo,
2087 NestedNameSpecifierLoc NNS, NamedDecl *FoundD,
2088 SourceLocation TemplateKWLoc,
2089 const TemplateArgumentListInfo *TemplateArgs) {
2090 bool RefersToCapturedVariable = isa<VarDecl, BindingDecl>(D) &&
2091 NeedToCaptureVariable(D, NameInfo.getLoc());
2092
2093 DeclRefExpr *E = DeclRefExpr::Create(
2094 Context, NNS, TemplateKWLoc, D, RefersToCapturedVariable, NameInfo, Ty,
2095 VK, FoundD, TemplateArgs, getNonOdrUseReasonInCurrentContext(D));
2096 MarkDeclRefReferenced(E);
2097
2098 // C++ [except.spec]p17:
2099 // An exception-specification is considered to be needed when:
2100 // - in an expression, the function is the unique lookup result or
2101 // the selected member of a set of overloaded functions.
2102 //
2103 // We delay doing this until after we've built the function reference and
2104 // marked it as used so that:
2105 // a) if the function is defaulted, we get errors from defining it before /
2106 // instead of errors from computing its exception specification, and
2107 // b) if the function is a defaulted comparison, we can use the body we
2108 // build when defining it as input to the exception specification
2109 // computation rather than computing a new body.
2110 if (auto *FPT = Ty->getAs<FunctionProtoType>()) {
2111 if (isUnresolvedExceptionSpec(FPT->getExceptionSpecType())) {
2112 if (auto *NewFPT = ResolveExceptionSpec(NameInfo.getLoc(), FPT))
2113 E->setType(Context.getQualifiedType(NewFPT, Ty.getQualifiers()));
2114 }
2115 }
2116
2117 if (getLangOpts().ObjCWeak && isa<VarDecl>(D) &&
2118 Ty.getObjCLifetime() == Qualifiers::OCL_Weak && !isUnevaluatedContext() &&
2119 !Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, E->getBeginLoc()))
2120 getCurFunction()->recordUseOfWeak(E);
2121
2122 FieldDecl *FD = dyn_cast<FieldDecl>(D);
2123 if (IndirectFieldDecl *IFD = dyn_cast<IndirectFieldDecl>(D))
2124 FD = IFD->getAnonField();
2125 if (FD) {
2126 UnusedPrivateFields.remove(FD);
2127 // Just in case we're building an illegal pointer-to-member.
2128 if (FD->isBitField())
2129 E->setObjectKind(OK_BitField);
2130 }
2131
2132 // C++ [expr.prim]/8: The expression [...] is a bit-field if the identifier
2133 // designates a bit-field.
2134 if (auto *BD = dyn_cast<BindingDecl>(D))
2135 if (auto *BE = BD->getBinding())
2136 E->setObjectKind(BE->getObjectKind());
2137
2138 return E;
2139}
2140
2141/// Decomposes the given name into a DeclarationNameInfo, its location, and
2142/// possibly a list of template arguments.
2143///
2144/// If this produces template arguments, it is permitted to call
2145/// DecomposeTemplateName.
2146///
2147/// This actually loses a lot of source location information for
2148/// non-standard name kinds; we should consider preserving that in
2149/// some way.
2150void
2151Sema::DecomposeUnqualifiedId(const UnqualifiedId &Id,
2152 TemplateArgumentListInfo &Buffer,
2153 DeclarationNameInfo &NameInfo,
2154 const TemplateArgumentListInfo *&TemplateArgs) {
2155 if (Id.getKind() == UnqualifiedIdKind::IK_TemplateId) {
2156 Buffer.setLAngleLoc(Id.TemplateId->LAngleLoc);
2157 Buffer.setRAngleLoc(Id.TemplateId->RAngleLoc);
2158
2159 ASTTemplateArgsPtr TemplateArgsPtr(Id.TemplateId->getTemplateArgs(),
2160 Id.TemplateId->NumArgs);
2161 translateTemplateArguments(TemplateArgsPtr, Buffer);
2162
2163 TemplateName TName = Id.TemplateId->Template.get();
2164 SourceLocation TNameLoc = Id.TemplateId->TemplateNameLoc;
2165 NameInfo = Context.getNameForTemplate(TName, TNameLoc);
2166 TemplateArgs = &Buffer;
2167 } else {
2168 NameInfo = GetNameFromUnqualifiedId(Id);
2169 TemplateArgs = nullptr;
2170 }
2171}
2172
2173static void emitEmptyLookupTypoDiagnostic(
2174 const TypoCorrection &TC, Sema &SemaRef, const CXXScopeSpec &SS,
2175 DeclarationName Typo, SourceLocation TypoLoc, ArrayRef<Expr *> Args,
2176 unsigned DiagnosticID, unsigned DiagnosticSuggestID) {
2177 DeclContext *Ctx =
2178 SS.isEmpty() ? nullptr : SemaRef.computeDeclContext(SS, false);
2179 if (!TC) {
2180 // Emit a special diagnostic for failed member lookups.
2181 // FIXME: computing the declaration context might fail here (?)
2182 if (Ctx)
2183 SemaRef.Diag(TypoLoc, diag::err_no_member) << Typo << Ctx
2184 << SS.getRange();
2185 else
2186 SemaRef.Diag(TypoLoc, DiagnosticID) << Typo;
2187 return;
2188 }
2189
2190 std::string CorrectedStr = TC.getAsString(SemaRef.getLangOpts());
2191 bool DroppedSpecifier =
2192 TC.WillReplaceSpecifier() && Typo.getAsString() == CorrectedStr;
2193 unsigned NoteID = TC.getCorrectionDeclAs<ImplicitParamDecl>()
2194 ? diag::note_implicit_param_decl
2195 : diag::note_previous_decl;
2196 if (!Ctx)
2197 SemaRef.diagnoseTypo(TC, SemaRef.PDiag(DiagnosticSuggestID) << Typo,
2198 SemaRef.PDiag(NoteID));
2199 else
2200 SemaRef.diagnoseTypo(TC, SemaRef.PDiag(diag::err_no_member_suggest)
2201 << Typo << Ctx << DroppedSpecifier
2202 << SS.getRange(),
2203 SemaRef.PDiag(NoteID));
2204}
2205
2206/// Diagnose a lookup that found results in an enclosing class during error
2207/// recovery. This usually indicates that the results were found in a dependent
2208/// base class that could not be searched as part of a template definition.
2209/// Always issues a diagnostic (though this may be only a warning in MS
2210/// compatibility mode).
2211///
2212/// Return \c true if the error is unrecoverable, or \c false if the caller
2213/// should attempt to recover using these lookup results.
2214bool Sema::DiagnoseDependentMemberLookup(LookupResult &R) {
2215 // During a default argument instantiation the CurContext points
2216 // to a CXXMethodDecl; but we can't apply a this-> fixit inside a
2217 // function parameter list, hence add an explicit check.
2218 bool isDefaultArgument =
2219 !CodeSynthesisContexts.empty() &&
2220 CodeSynthesisContexts.back().Kind ==
2221 CodeSynthesisContext::DefaultFunctionArgumentInstantiation;
2222 CXXMethodDecl *CurMethod = dyn_cast<CXXMethodDecl>(CurContext);
2223 bool isInstance = CurMethod && CurMethod->isInstance() &&
2224 R.getNamingClass() == CurMethod->getParent() &&
2225 !isDefaultArgument;
2226
2227 // There are two ways we can find a class-scope declaration during template
2228 // instantiation that we did not find in the template definition: if it is a
2229 // member of a dependent base class, or if it is declared after the point of
2230 // use in the same class. Distinguish these by comparing the class in which
2231 // the member was found to the naming class of the lookup.
2232 unsigned DiagID = diag::err_found_in_dependent_base;
2233 unsigned NoteID = diag::note_member_declared_at;
2234 if (R.getRepresentativeDecl()->getDeclContext()->Equals(R.getNamingClass())) {
2235 DiagID = getLangOpts().MSVCCompat ? diag::ext_found_later_in_class
2236 : diag::err_found_later_in_class;
2237 } else if (getLangOpts().MSVCCompat) {
2238 DiagID = diag::ext_found_in_dependent_base;
2239 NoteID = diag::note_dependent_member_use;
2240 }
2241
2242 if (isInstance) {
2243 // Give a code modification hint to insert 'this->'.
2244 Diag(R.getNameLoc(), DiagID)
2245 << R.getLookupName()
2246 << FixItHint::CreateInsertion(R.getNameLoc(), "this->");
2247 CheckCXXThisCapture(R.getNameLoc());
2248 } else {
2249 // FIXME: Add a FixItHint to insert 'Base::' or 'Derived::' (assuming
2250 // they're not shadowed).
2251 Diag(R.getNameLoc(), DiagID) << R.getLookupName();
2252 }
2253
2254 for (NamedDecl *D : R)
2255 Diag(D->getLocation(), NoteID);
2256
2257 // Return true if we are inside a default argument instantiation
2258 // and the found name refers to an instance member function, otherwise
2259 // the caller will try to create an implicit member call and this is wrong
2260 // for default arguments.
2261 //
2262 // FIXME: Is this special case necessary? We could allow the caller to
2263 // diagnose this.
2264 if (isDefaultArgument && ((*R.begin())->isCXXInstanceMember())) {
2265 Diag(R.getNameLoc(), diag::err_member_call_without_object);
2266 return true;
2267 }
2268
2269 // Tell the callee to try to recover.
2270 return false;
2271}
2272
2273/// Diagnose an empty lookup.
2274///
2275/// \return false if new lookup candidates were found
2276bool Sema::DiagnoseEmptyLookup(Scope *S, CXXScopeSpec &SS, LookupResult &R,
2277 CorrectionCandidateCallback &CCC,
2278 TemplateArgumentListInfo *ExplicitTemplateArgs,
2279 ArrayRef<Expr *> Args, TypoExpr **Out) {
2280 DeclarationName Name = R.getLookupName();
2281
2282 unsigned diagnostic = diag::err_undeclared_var_use;
2283 unsigned diagnostic_suggest = diag::err_undeclared_var_use_suggest;
2284 if (Name.getNameKind() == DeclarationName::CXXOperatorName ||
2285 Name.getNameKind() == DeclarationName::CXXLiteralOperatorName ||
2286 Name.getNameKind() == DeclarationName::CXXConversionFunctionName) {
2287 diagnostic = diag::err_undeclared_use;
2288 diagnostic_suggest = diag::err_undeclared_use_suggest;
2289 }
2290
2291 // If the original lookup was an unqualified lookup, fake an
2292 // unqualified lookup. This is useful when (for example) the
2293 // original lookup would not have found something because it was a
2294 // dependent name.
2295 DeclContext *DC = SS.isEmpty() ? CurContext : nullptr;
2296 while (DC) {
2297 if (isa<CXXRecordDecl>(DC)) {
2298 LookupQualifiedName(R, DC);
2299
2300 if (!R.empty()) {
2301 // Don't give errors about ambiguities in this lookup.
2302 R.suppressDiagnostics();
2303
2304 // If there's a best viable function among the results, only mention
2305 // that one in the notes.
2306 OverloadCandidateSet Candidates(R.getNameLoc(),
2307 OverloadCandidateSet::CSK_Normal);
2308 AddOverloadedCallCandidates(R, ExplicitTemplateArgs, Args, Candidates);
2309 OverloadCandidateSet::iterator Best;
2310 if (Candidates.BestViableFunction(*this, R.getNameLoc(), Best) ==
2311 OR_Success) {
2312 R.clear();
2313 R.addDecl(Best->FoundDecl.getDecl(), Best->FoundDecl.getAccess());
2314 R.resolveKind();
2315 }
2316
2317 return DiagnoseDependentMemberLookup(R);
2318 }
2319
2320 R.clear();
2321 }
2322
2323 DC = DC->getLookupParent();
2324 }
2325
2326 // We didn't find anything, so try to correct for a typo.
2327 TypoCorrection Corrected;
2328 if (S && Out) {
2329 SourceLocation TypoLoc = R.getNameLoc();
2330 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", 2331, __extension__ __PRETTY_FUNCTION__
))
2331 "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", 2331, __extension__ __PRETTY_FUNCTION__
))
;
2332 *Out = CorrectTypoDelayed(
2333 R.getLookupNameInfo(), R.getLookupKind(), S, &SS, CCC,
2334 [=](const TypoCorrection &TC) {
2335 emitEmptyLookupTypoDiagnostic(TC, *this, SS, Name, TypoLoc, Args,
2336 diagnostic, diagnostic_suggest);
2337 },
2338 nullptr, CTK_ErrorRecovery);
2339 if (*Out)
2340 return true;
2341 } else if (S &&
2342 (Corrected = CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(),
2343 S, &SS, CCC, CTK_ErrorRecovery))) {
2344 std::string CorrectedStr(Corrected.getAsString(getLangOpts()));
2345 bool DroppedSpecifier =
2346 Corrected.WillReplaceSpecifier() && Name.getAsString() == CorrectedStr;
2347 R.setLookupName(Corrected.getCorrection());
2348
2349 bool AcceptableWithRecovery = false;
2350 bool AcceptableWithoutRecovery = false;
2351 NamedDecl *ND = Corrected.getFoundDecl();
2352 if (ND) {
2353 if (Corrected.isOverloaded()) {
2354 OverloadCandidateSet OCS(R.getNameLoc(),
2355 OverloadCandidateSet::CSK_Normal);
2356 OverloadCandidateSet::iterator Best;
2357 for (NamedDecl *CD : Corrected) {
2358 if (FunctionTemplateDecl *FTD =
2359 dyn_cast<FunctionTemplateDecl>(CD))
2360 AddTemplateOverloadCandidate(
2361 FTD, DeclAccessPair::make(FTD, AS_none), ExplicitTemplateArgs,
2362 Args, OCS);
2363 else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(CD))
2364 if (!ExplicitTemplateArgs || ExplicitTemplateArgs->size() == 0)
2365 AddOverloadCandidate(FD, DeclAccessPair::make(FD, AS_none),
2366 Args, OCS);
2367 }
2368 switch (OCS.BestViableFunction(*this, R.getNameLoc(), Best)) {
2369 case OR_Success:
2370 ND = Best->FoundDecl;
2371 Corrected.setCorrectionDecl(ND);
2372 break;
2373 default:
2374 // FIXME: Arbitrarily pick the first declaration for the note.
2375 Corrected.setCorrectionDecl(ND);
2376 break;
2377 }
2378 }
2379 R.addDecl(ND);
2380 if (getLangOpts().CPlusPlus && ND->isCXXClassMember()) {
2381 CXXRecordDecl *Record = nullptr;
2382 if (Corrected.getCorrectionSpecifier()) {
2383 const Type *Ty = Corrected.getCorrectionSpecifier()->getAsType();
2384 Record = Ty->getAsCXXRecordDecl();
2385 }
2386 if (!Record)
2387 Record = cast<CXXRecordDecl>(
2388 ND->getDeclContext()->getRedeclContext());
2389 R.setNamingClass(Record);
2390 }
2391
2392 auto *UnderlyingND = ND->getUnderlyingDecl();
2393 AcceptableWithRecovery = isa<ValueDecl>(UnderlyingND) ||
2394 isa<FunctionTemplateDecl>(UnderlyingND);
2395 // FIXME: If we ended up with a typo for a type name or
2396 // Objective-C class name, we're in trouble because the parser
2397 // is in the wrong place to recover. Suggest the typo
2398 // correction, but don't make it a fix-it since we're not going
2399 // to recover well anyway.
2400 AcceptableWithoutRecovery = isa<TypeDecl>(UnderlyingND) ||
2401 getAsTypeTemplateDecl(UnderlyingND) ||
2402 isa<ObjCInterfaceDecl>(UnderlyingND);
2403 } else {
2404 // FIXME: We found a keyword. Suggest it, but don't provide a fix-it
2405 // because we aren't able to recover.
2406 AcceptableWithoutRecovery = true;
2407 }
2408
2409 if (AcceptableWithRecovery || AcceptableWithoutRecovery) {
2410 unsigned NoteID = Corrected.getCorrectionDeclAs<ImplicitParamDecl>()
2411 ? diag::note_implicit_param_decl
2412 : diag::note_previous_decl;
2413 if (SS.isEmpty())
2414 diagnoseTypo(Corrected, PDiag(diagnostic_suggest) << Name,
2415 PDiag(NoteID), AcceptableWithRecovery);
2416 else
2417 diagnoseTypo(Corrected, PDiag(diag::err_no_member_suggest)
2418 << Name << computeDeclContext(SS, false)
2419 << DroppedSpecifier << SS.getRange(),
2420 PDiag(NoteID), AcceptableWithRecovery);
2421
2422 // Tell the callee whether to try to recover.
2423 return !AcceptableWithRecovery;
2424 }
2425 }
2426 R.clear();
2427
2428 // Emit a special diagnostic for failed member lookups.
2429 // FIXME: computing the declaration context might fail here (?)
2430 if (!SS.isEmpty()) {
2431 Diag(R.getNameLoc(), diag::err_no_member)
2432 << Name << computeDeclContext(SS, false)
2433 << SS.getRange();
2434 return true;
2435 }
2436
2437 // Give up, we can't recover.
2438 Diag(R.getNameLoc(), diagnostic) << Name;
2439 return true;
2440}
2441
2442/// In Microsoft mode, if we are inside a template class whose parent class has
2443/// dependent base classes, and we can't resolve an unqualified identifier, then
2444/// assume the identifier is a member of a dependent base class. We can only
2445/// recover successfully in static methods, instance methods, and other contexts
2446/// where 'this' is available. This doesn't precisely match MSVC's
2447/// instantiation model, but it's close enough.
2448static Expr *
2449recoverFromMSUnqualifiedLookup(Sema &S, ASTContext &Context,
2450 DeclarationNameInfo &NameInfo,
2451 SourceLocation TemplateKWLoc,
2452 const TemplateArgumentListInfo *TemplateArgs) {
2453 // Only try to recover from lookup into dependent bases in static methods or
2454 // contexts where 'this' is available.
2455 QualType ThisType = S.getCurrentThisType();
2456 const CXXRecordDecl *RD = nullptr;
2457 if (!ThisType.isNull())
2458 RD = ThisType->getPointeeType()->getAsCXXRecordDecl();
2459 else if (auto *MD = dyn_cast<CXXMethodDecl>(S.CurContext))
2460 RD = MD->getParent();
2461 if (!RD || !RD->hasAnyDependentBases())
2462 return nullptr;
2463
2464 // Diagnose this as unqualified lookup into a dependent base class. If 'this'
2465 // is available, suggest inserting 'this->' as a fixit.
2466 SourceLocation Loc = NameInfo.getLoc();
2467 auto DB = S.Diag(Loc, diag::ext_undeclared_unqual_id_with_dependent_base);
2468 DB << NameInfo.getName() << RD;
2469
2470 if (!ThisType.isNull()) {
2471 DB << FixItHint::CreateInsertion(Loc, "this->");
2472 return CXXDependentScopeMemberExpr::Create(
2473 Context, /*This=*/nullptr, ThisType, /*IsArrow=*/true,
2474 /*Op=*/SourceLocation(), NestedNameSpecifierLoc(), TemplateKWLoc,
2475 /*FirstQualifierFoundInScope=*/nullptr, NameInfo, TemplateArgs);
2476 }
2477
2478 // Synthesize a fake NNS that points to the derived class. This will
2479 // perform name lookup during template instantiation.
2480 CXXScopeSpec SS;
2481 auto *NNS =
2482 NestedNameSpecifier::Create(Context, nullptr, true, RD->getTypeForDecl());
2483 SS.MakeTrivial(Context, NNS, SourceRange(Loc, Loc));
2484 return DependentScopeDeclRefExpr::Create(
2485 Context, SS.getWithLocInContext(Context), TemplateKWLoc, NameInfo,
2486 TemplateArgs);
2487}
2488
2489ExprResult
2490Sema::ActOnIdExpression(Scope *S, CXXScopeSpec &SS,
2491 SourceLocation TemplateKWLoc, UnqualifiedId &Id,
2492 bool HasTrailingLParen, bool IsAddressOfOperand,
2493 CorrectionCandidateCallback *CCC,
2494 bool IsInlineAsmIdentifier, Token *KeywordReplacement) {
2495 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", 2496, __extension__ __PRETTY_FUNCTION__
))
2496 "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", 2496, __extension__ __PRETTY_FUNCTION__
))
;
2497 if (SS.isInvalid())
2498 return ExprError();
2499
2500 TemplateArgumentListInfo TemplateArgsBuffer;
2501
2502 // Decompose the UnqualifiedId into the following data.
2503 DeclarationNameInfo NameInfo;
2504 const TemplateArgumentListInfo *TemplateArgs;
2505 DecomposeUnqualifiedId(Id, TemplateArgsBuffer, NameInfo, TemplateArgs);
2506
2507 DeclarationName Name = NameInfo.getName();
2508 IdentifierInfo *II = Name.getAsIdentifierInfo();
2509 SourceLocation NameLoc = NameInfo.getLoc();
2510
2511 if (II && II->isEditorPlaceholder()) {
2512 // FIXME: When typed placeholders are supported we can create a typed
2513 // placeholder expression node.
2514 return ExprError();
2515 }
2516
2517 // C++ [temp.dep.expr]p3:
2518 // An id-expression is type-dependent if it contains:
2519 // -- an identifier that was declared with a dependent type,
2520 // (note: handled after lookup)
2521 // -- a template-id that is dependent,
2522 // (note: handled in BuildTemplateIdExpr)
2523 // -- a conversion-function-id that specifies a dependent type,
2524 // -- a nested-name-specifier that contains a class-name that
2525 // names a dependent type.
2526 // Determine whether this is a member of an unknown specialization;
2527 // we need to handle these differently.
2528 bool DependentID = false;
2529 if (Name.getNameKind() == DeclarationName::CXXConversionFunctionName &&
2530 Name.getCXXNameType()->isDependentType()) {
2531 DependentID = true;
2532 } else if (SS.isSet()) {
2533 if (DeclContext *DC = computeDeclContext(SS, false)) {
2534 if (RequireCompleteDeclContext(SS, DC))
2535 return ExprError();
2536 } else {
2537 DependentID = true;
2538 }
2539 }
2540
2541 if (DependentID)
2542 return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo,
2543 IsAddressOfOperand, TemplateArgs);
2544
2545 // Perform the required lookup.
2546 LookupResult R(*this, NameInfo,
2547 (Id.getKind() == UnqualifiedIdKind::IK_ImplicitSelfParam)
2548 ? LookupObjCImplicitSelfParam
2549 : LookupOrdinaryName);
2550 if (TemplateKWLoc.isValid() || TemplateArgs) {
2551 // Lookup the template name again to correctly establish the context in
2552 // which it was found. This is really unfortunate as we already did the
2553 // lookup to determine that it was a template name in the first place. If
2554 // this becomes a performance hit, we can work harder to preserve those
2555 // results until we get here but it's likely not worth it.
2556 bool MemberOfUnknownSpecialization;
2557 AssumedTemplateKind AssumedTemplate;
2558 if (LookupTemplateName(R, S, SS, QualType(), /*EnteringContext=*/false,
2559 MemberOfUnknownSpecialization, TemplateKWLoc,
2560 &AssumedTemplate))
2561 return ExprError();
2562
2563 if (MemberOfUnknownSpecialization ||
2564 (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation))
2565 return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo,
2566 IsAddressOfOperand, TemplateArgs);
2567 } else {
2568 bool IvarLookupFollowUp = II && !SS.isSet() && getCurMethodDecl();
2569 LookupParsedName(R, S, &SS, !IvarLookupFollowUp);
2570
2571 // If the result might be in a dependent base class, this is a dependent
2572 // id-expression.
2573 if (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation)
2574 return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo,
2575 IsAddressOfOperand, TemplateArgs);
2576
2577 // If this reference is in an Objective-C method, then we need to do
2578 // some special Objective-C lookup, too.
2579 if (IvarLookupFollowUp) {
2580 ExprResult E(LookupInObjCMethod(R, S, II, true));
2581 if (E.isInvalid())
2582 return ExprError();
2583
2584 if (Expr *Ex = E.getAs<Expr>())
2585 return Ex;
2586 }
2587 }
2588
2589 if (R.isAmbiguous())
2590 return ExprError();
2591
2592 // This could be an implicitly declared function reference if the language
2593 // mode allows it as a feature.
2594 if (R.empty() && HasTrailingLParen && II &&
2595 getLangOpts().implicitFunctionsAllowed()) {
2596 NamedDecl *D = ImplicitlyDefineFunction(NameLoc, *II, S);
2597 if (D) R.addDecl(D);
2598 }
2599
2600 // Determine whether this name might be a candidate for
2601 // argument-dependent lookup.
2602 bool ADL = UseArgumentDependentLookup(SS, R, HasTrailingLParen);
2603
2604 if (R.empty() && !ADL) {
2605 if (SS.isEmpty() && getLangOpts().MSVCCompat) {
2606 if (Expr *E = recoverFromMSUnqualifiedLookup(*this, Context, NameInfo,
2607 TemplateKWLoc, TemplateArgs))
2608 return E;
2609 }
2610
2611 // Don't diagnose an empty lookup for inline assembly.
2612 if (IsInlineAsmIdentifier)
2613 return ExprError();
2614
2615 // If this name wasn't predeclared and if this is not a function
2616 // call, diagnose the problem.
2617 TypoExpr *TE = nullptr;
2618 DefaultFilterCCC DefaultValidator(II, SS.isValid() ? SS.getScopeRep()
2619 : nullptr);
2620 DefaultValidator.IsAddressOfOperand = IsAddressOfOperand;
2621 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", 2622, __extension__ __PRETTY_FUNCTION__
))
2622 "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", 2622, __extension__ __PRETTY_FUNCTION__
))
;
2623 if (CCC) {
2624 // Make sure the callback knows what the typo being diagnosed is.
2625 CCC->setTypoName(II);
2626 if (SS.isValid())
2627 CCC->setTypoNNS(SS.getScopeRep());
2628 }
2629 // FIXME: DiagnoseEmptyLookup produces bad diagnostics if we're looking for
2630 // a template name, but we happen to have always already looked up the name
2631 // before we get here if it must be a template name.
2632 if (DiagnoseEmptyLookup(S, SS, R, CCC ? *CCC : DefaultValidator, nullptr,
2633 std::nullopt, &TE)) {
2634 if (TE && KeywordReplacement) {
2635 auto &State = getTypoExprState(TE);
2636 auto BestTC = State.Consumer->getNextCorrection();
2637 if (BestTC.isKeyword()) {
2638 auto *II = BestTC.getCorrectionAsIdentifierInfo();
2639 if (State.DiagHandler)
2640 State.DiagHandler(BestTC);
2641 KeywordReplacement->startToken();
2642 KeywordReplacement->setKind(II->getTokenID());
2643 KeywordReplacement->setIdentifierInfo(II);
2644 KeywordReplacement->setLocation(BestTC.getCorrectionRange().getBegin());
2645 // Clean up the state associated with the TypoExpr, since it has
2646 // now been diagnosed (without a call to CorrectDelayedTyposInExpr).
2647 clearDelayedTypo(TE);
2648 // Signal that a correction to a keyword was performed by returning a
2649 // valid-but-null ExprResult.
2650 return (Expr*)nullptr;
2651 }
2652 State.Consumer->resetCorrectionStream();
2653 }
2654 return TE ? TE : ExprError();
2655 }
2656
2657 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", 2658, __extension__ __PRETTY_FUNCTION__
))
2658 "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", 2658, __extension__ __PRETTY_FUNCTION__
))
;
2659
2660 // If we found an Objective-C instance variable, let
2661 // LookupInObjCMethod build the appropriate expression to
2662 // reference the ivar.
2663 if (ObjCIvarDecl *Ivar = R.getAsSingle<ObjCIvarDecl>()) {
2664 R.clear();
2665 ExprResult E(LookupInObjCMethod(R, S, Ivar->getIdentifier()));
2666 // In a hopelessly buggy code, Objective-C instance variable
2667 // lookup fails and no expression will be built to reference it.
2668 if (!E.isInvalid() && !E.get())
2669 return ExprError();
2670 return E;
2671 }
2672 }
2673
2674 // This is guaranteed from this point on.
2675 assert(!R.empty() || ADL)(static_cast <bool> (!R.empty() || ADL) ? void (0) : __assert_fail
("!R.empty() || ADL", "clang/lib/Sema/SemaExpr.cpp", 2675, __extension__
__PRETTY_FUNCTION__))
;
2676
2677 // Check whether this might be a C++ implicit instance member access.
2678 // C++ [class.mfct.non-static]p3:
2679 // When an id-expression that is not part of a class member access
2680 // syntax and not used to form a pointer to member is used in the
2681 // body of a non-static member function of class X, if name lookup
2682 // resolves the name in the id-expression to a non-static non-type
2683 // member of some class C, the id-expression is transformed into a
2684 // class member access expression using (*this) as the
2685 // postfix-expression to the left of the . operator.
2686 //
2687 // But we don't actually need to do this for '&' operands if R
2688 // resolved to a function or overloaded function set, because the
2689 // expression is ill-formed if it actually works out to be a
2690 // non-static member function:
2691 //
2692 // C++ [expr.ref]p4:
2693 // Otherwise, if E1.E2 refers to a non-static member function. . .
2694 // [t]he expression can be used only as the left-hand operand of a
2695 // member function call.
2696 //
2697 // There are other safeguards against such uses, but it's important
2698 // to get this right here so that we don't end up making a
2699 // spuriously dependent expression if we're inside a dependent
2700 // instance method.
2701 if (!R.empty() && (*R.begin())->isCXXClassMember()) {
2702 bool MightBeImplicitMember;
2703 if (!IsAddressOfOperand)
2704 MightBeImplicitMember = true;
2705 else if (!SS.isEmpty())
2706 MightBeImplicitMember = false;
2707 else if (R.isOverloadedResult())
2708 MightBeImplicitMember = false;
2709 else if (R.isUnresolvableResult())
2710 MightBeImplicitMember = true;
2711 else
2712 MightBeImplicitMember = isa<FieldDecl>(R.getFoundDecl()) ||
2713 isa<IndirectFieldDecl>(R.getFoundDecl()) ||
2714 isa<MSPropertyDecl>(R.getFoundDecl());
2715
2716 if (MightBeImplicitMember)
2717 return BuildPossibleImplicitMemberExpr(SS, TemplateKWLoc,
2718 R, TemplateArgs, S);
2719 }
2720
2721 if (TemplateArgs || TemplateKWLoc.isValid()) {
2722
2723 // In C++1y, if this is a variable template id, then check it
2724 // in BuildTemplateIdExpr().
2725 // The single lookup result must be a variable template declaration.
2726 if (Id.getKind() == UnqualifiedIdKind::IK_TemplateId && Id.TemplateId &&
2727 Id.TemplateId->Kind == TNK_Var_template) {
2728 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", 2729, __extension__ __PRETTY_FUNCTION__
))
2729 "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", 2729, __extension__ __PRETTY_FUNCTION__
))
;
2730 }
2731
2732 return BuildTemplateIdExpr(SS, TemplateKWLoc, R, ADL, TemplateArgs);
2733 }
2734
2735 return BuildDeclarationNameExpr(SS, R, ADL);
2736}
2737
2738/// BuildQualifiedDeclarationNameExpr - Build a C++ qualified
2739/// declaration name, generally during template instantiation.
2740/// There's a large number of things which don't need to be done along
2741/// this path.
2742ExprResult Sema::BuildQualifiedDeclarationNameExpr(
2743 CXXScopeSpec &SS, const DeclarationNameInfo &NameInfo,
2744 bool IsAddressOfOperand, const Scope *S, TypeSourceInfo **RecoveryTSI) {
2745 if (NameInfo.getName().isDependentName())
2746 return BuildDependentDeclRefExpr(SS, /*TemplateKWLoc=*/SourceLocation(),
2747 NameInfo, /*TemplateArgs=*/nullptr);
2748
2749 DeclContext *DC = computeDeclContext(SS, false);
2750 if (!DC)
2751 return BuildDependentDeclRefExpr(SS, /*TemplateKWLoc=*/SourceLocation(),
2752 NameInfo, /*TemplateArgs=*/nullptr);
2753
2754 if (RequireCompleteDeclContext(SS, DC))
2755 return ExprError();
2756
2757 LookupResult R(*this, NameInfo, LookupOrdinaryName);
2758 LookupQualifiedName(R, DC);
2759
2760 if (R.isAmbiguous())
2761 return ExprError();
2762
2763 if (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation)
2764 return BuildDependentDeclRefExpr(SS, /*TemplateKWLoc=*/SourceLocation(),
2765 NameInfo, /*TemplateArgs=*/nullptr);
2766
2767 if (R.empty()) {
2768 // Don't diagnose problems with invalid record decl, the secondary no_member
2769 // diagnostic during template instantiation is likely bogus, e.g. if a class
2770 // is invalid because it's derived from an invalid base class, then missing
2771 // members were likely supposed to be inherited.
2772 if (const auto *CD = dyn_cast<CXXRecordDecl>(DC))
2773 if (CD->isInvalidDecl())
2774 return ExprError();
2775 Diag(NameInfo.getLoc(), diag::err_no_member)
2776 << NameInfo.getName() << DC << SS.getRange();
2777 return ExprError();
2778 }
2779
2780 if (const TypeDecl *TD = R.getAsSingle<TypeDecl>()) {
2781 // Diagnose a missing typename if this resolved unambiguously to a type in
2782 // a dependent context. If we can recover with a type, downgrade this to
2783 // a warning in Microsoft compatibility mode.
2784 unsigned DiagID = diag::err_typename_missing;
2785 if (RecoveryTSI && getLangOpts().MSVCCompat)
2786 DiagID = diag::ext_typename_missing;
2787 SourceLocation Loc = SS.getBeginLoc();
2788 auto D = Diag(Loc, DiagID);
2789 D << SS.getScopeRep() << NameInfo.getName().getAsString()
2790 << SourceRange(Loc, NameInfo.getEndLoc());
2791
2792 // Don't recover if the caller isn't expecting us to or if we're in a SFINAE
2793 // context.
2794 if (!RecoveryTSI)
2795 return ExprError();
2796
2797 // Only issue the fixit if we're prepared to recover.
2798 D << FixItHint::CreateInsertion(Loc, "typename ");
2799
2800 // Recover by pretending this was an elaborated type.
2801 QualType Ty = Context.getTypeDeclType(TD);
2802 TypeLocBuilder TLB;
2803 TLB.pushTypeSpec(Ty).setNameLoc(NameInfo.getLoc());
2804
2805 QualType ET = getElaboratedType(ETK_None, SS, Ty);
2806 ElaboratedTypeLoc QTL = TLB.push<ElaboratedTypeLoc>(ET);
2807 QTL.setElaboratedKeywordLoc(SourceLocation());
2808 QTL.setQualifierLoc(SS.getWithLocInContext(Context));
2809
2810 *RecoveryTSI = TLB.getTypeSourceInfo(Context, ET);
2811
2812 return ExprEmpty();
2813 }
2814
2815 // Defend against this resolving to an implicit member access. We usually
2816 // won't get here if this might be a legitimate a class member (we end up in
2817 // BuildMemberReferenceExpr instead), but this can be valid if we're forming
2818 // a pointer-to-member or in an unevaluated context in C++11.
2819 if (!R.empty() && (*R.begin())->isCXXClassMember() && !IsAddressOfOperand)
2820 return BuildPossibleImplicitMemberExpr(SS,
2821 /*TemplateKWLoc=*/SourceLocation(),
2822 R, /*TemplateArgs=*/nullptr, S);
2823
2824 return BuildDeclarationNameExpr(SS, R, /* ADL */ false);
2825}
2826
2827/// The parser has read a name in, and Sema has detected that we're currently
2828/// inside an ObjC method. Perform some additional checks and determine if we
2829/// should form a reference to an ivar.
2830///
2831/// Ideally, most of this would be done by lookup, but there's
2832/// actually quite a lot of extra work involved.
2833DeclResult Sema::LookupIvarInObjCMethod(LookupResult &Lookup, Scope *S,
2834 IdentifierInfo *II) {
2835 SourceLocation Loc = Lookup.getNameLoc();
2836 ObjCMethodDecl *CurMethod = getCurMethodDecl();
2837
2838 // Check for error condition which is already reported.
2839 if (!CurMethod)
2840 return DeclResult(true);
2841
2842 // There are two cases to handle here. 1) scoped lookup could have failed,
2843 // in which case we should look for an ivar. 2) scoped lookup could have
2844 // found a decl, but that decl is outside the current instance method (i.e.
2845 // a global variable). In these two cases, we do a lookup for an ivar with
2846 // this name, if the lookup sucedes, we replace it our current decl.
2847
2848 // If we're in a class method, we don't normally want to look for
2849 // ivars. But if we don't find anything else, and there's an
2850 // ivar, that's an error.
2851 bool IsClassMethod = CurMethod->isClassMethod();
2852
2853 bool LookForIvars;
2854 if (Lookup.empty())
2855 LookForIvars = true;
2856 else if (IsClassMethod)
2857 LookForIvars = false;
2858 else
2859 LookForIvars = (Lookup.isSingleResult() &&
2860 Lookup.getFoundDecl()->isDefinedOutsideFunctionOrMethod());
2861 ObjCInterfaceDecl *IFace = nullptr;
2862 if (LookForIvars) {
2863 IFace = CurMethod->getClassInterface();
2864 ObjCInterfaceDecl *ClassDeclared;
2865 ObjCIvarDecl *IV = nullptr;
2866 if (IFace && (IV = IFace->lookupInstanceVariable(II, ClassDeclared))) {
2867 // Diagnose using an ivar in a class method.
2868 if (IsClassMethod) {
2869 Diag(Loc, diag::err_ivar_use_in_class_method) << IV->getDeclName();
2870 return DeclResult(true);
2871 }
2872
2873 // Diagnose the use of an ivar outside of the declaring class.
2874 if (IV->getAccessControl() == ObjCIvarDecl::Private &&
2875 !declaresSameEntity(ClassDeclared, IFace) &&
2876 !getLangOpts().DebuggerSupport)
2877 Diag(Loc, diag::err_private_ivar_access) << IV->getDeclName();
2878
2879 // Success.
2880 return IV;
2881 }
2882 } else if (CurMethod->isInstanceMethod()) {
2883 // We should warn if a local variable hides an ivar.
2884 if (ObjCInterfaceDecl *IFace = CurMethod->getClassInterface()) {
2885 ObjCInterfaceDecl *ClassDeclared;
2886 if (ObjCIvarDecl *IV = IFace->lookupInstanceVariable(II, ClassDeclared)) {
2887 if (IV->getAccessControl() != ObjCIvarDecl::Private ||
2888 declaresSameEntity(IFace, ClassDeclared))
2889 Diag(Loc, diag::warn_ivar_use_hidden) << IV->getDeclName();
2890 }
2891 }
2892 } else if (Lookup.isSingleResult() &&
2893 Lookup.getFoundDecl()->isDefinedOutsideFunctionOrMethod()) {
2894 // If accessing a stand-alone ivar in a class method, this is an error.
2895 if (const ObjCIvarDecl *IV =
2896 dyn_cast<ObjCIvarDecl>(Lookup.getFoundDecl())) {
2897 Diag(Loc, diag::err_ivar_use_in_class_method) << IV->getDeclName();
2898 return DeclResult(true);
2899 }
2900 }
2901
2902 // Didn't encounter an error, didn't find an ivar.
2903 return DeclResult(false);
2904}
2905
2906ExprResult Sema::BuildIvarRefExpr(Scope *S, SourceLocation Loc,
2907 ObjCIvarDecl *IV) {
2908 ObjCMethodDecl *CurMethod = getCurMethodDecl();
2909 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", 2910, __extension__ __PRETTY_FUNCTION__
))
2910 "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", 2910, __extension__ __PRETTY_FUNCTION__
))
;
2911
2912 ObjCInterfaceDecl *IFace = CurMethod->getClassInterface();
2913 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", 2913, __extension__ __PRETTY_FUNCTION__
))
;
2914
2915 // If we're referencing an invalid decl, just return this as a silent
2916 // error node. The error diagnostic was already emitted on the decl.
2917 if (IV->isInvalidDecl())
2918 return ExprError();
2919
2920 // Check if referencing a field with __attribute__((deprecated)).
2921 if (DiagnoseUseOfDecl(IV, Loc))
2922 return ExprError();
2923
2924 // FIXME: This should use a new expr for a direct reference, don't
2925 // turn this into Self->ivar, just return a BareIVarExpr or something.
2926 IdentifierInfo &II = Context.Idents.get("self");
2927 UnqualifiedId SelfName;
2928 SelfName.setImplicitSelfParam(&II);
2929 CXXScopeSpec SelfScopeSpec;
2930 SourceLocation TemplateKWLoc;
2931 ExprResult SelfExpr =
2932 ActOnIdExpression(S, SelfScopeSpec, TemplateKWLoc, SelfName,
2933 /*HasTrailingLParen=*/false,
2934 /*IsAddressOfOperand=*/false);
2935 if (SelfExpr.isInvalid())
2936 return ExprError();
2937
2938 SelfExpr = DefaultLvalueConversion(SelfExpr.get());
2939 if (SelfExpr.isInvalid())
2940 return ExprError();
2941
2942 MarkAnyDeclReferenced(Loc, IV, true);
2943
2944 ObjCMethodFamily MF = CurMethod->getMethodFamily();
2945 if (MF != OMF_init && MF != OMF_dealloc && MF != OMF_finalize &&
2946 !IvarBacksCurrentMethodAccessor(IFace, CurMethod, IV))
2947 Diag(Loc, diag::warn_direct_ivar_access) << IV->getDeclName();
2948
2949 ObjCIvarRefExpr *Result = new (Context)
2950 ObjCIvarRefExpr(IV, IV->getUsageType(SelfExpr.get()->getType()), Loc,
2951 IV->getLocation(), SelfExpr.get(), true, true);
2952
2953 if (IV->getType().getObjCLifetime() == Qualifiers::OCL_Weak) {
2954 if (!isUnevaluatedContext() &&
2955 !Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, Loc))
2956 getCurFunction()->recordUseOfWeak(Result);
2957 }
2958 if (getLangOpts().ObjCAutoRefCount && !isUnevaluatedContext())
2959 if (const BlockDecl *BD = CurContext->getInnermostBlockDecl())
2960 ImplicitlyRetainedSelfLocs.push_back({Loc, BD});
2961
2962 return Result;
2963}
2964
2965/// The parser has read a name in, and Sema has detected that we're currently
2966/// inside an ObjC method. Perform some additional checks and determine if we
2967/// should form a reference to an ivar. If so, build an expression referencing
2968/// that ivar.
2969ExprResult
2970Sema::LookupInObjCMethod(LookupResult &Lookup, Scope *S,
2971 IdentifierInfo *II, bool AllowBuiltinCreation) {
2972 // FIXME: Integrate this lookup step into LookupParsedName.
2973 DeclResult Ivar = LookupIvarInObjCMethod(Lookup, S, II);
2974 if (Ivar.isInvalid())
2975 return ExprError();
2976 if (Ivar.isUsable())
2977 return BuildIvarRefExpr(S, Lookup.getNameLoc(),
2978 cast<ObjCIvarDecl>(Ivar.get()));
2979
2980 if (Lookup.empty() && II && AllowBuiltinCreation)
2981 LookupBuiltin(Lookup);
2982
2983 // Sentinel value saying that we didn't do anything special.
2984 return ExprResult(false);
2985}
2986
2987/// Cast a base object to a member's actual type.
2988///
2989/// There are two relevant checks:
2990///
2991/// C++ [class.access.base]p7:
2992///
2993/// If a class member access operator [...] is used to access a non-static
2994/// data member or non-static member function, the reference is ill-formed if
2995/// the left operand [...] cannot be implicitly converted to a pointer to the
2996/// naming class of the right operand.
2997///
2998/// C++ [expr.ref]p7:
2999///
3000/// If E2 is a non-static data member or a non-static member function, the
3001/// program is ill-formed if the class of which E2 is directly a member is an
3002/// ambiguous base (11.8) of the naming class (11.9.3) of E2.
3003///
3004/// Note that the latter check does not consider access; the access of the
3005/// "real" base class is checked as appropriate when checking the access of the
3006/// member name.
3007ExprResult
3008Sema::PerformObjectMemberConversion(Expr *From,
3009 NestedNameSpecifier *Qualifier,
3010 NamedDecl *FoundDecl,
3011 NamedDecl *Member) {
3012 CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Member->getDeclContext());
3013 if (!RD)
3014 return From;
3015
3016 QualType DestRecordType;
3017 QualType DestType;
3018 QualType FromRecordType;
3019 QualType FromType = From->getType();
3020 bool PointerConversions = false;
3021 if (isa<FieldDecl>(Member)) {
3022 DestRecordType = Context.getCanonicalType(Context.getTypeDeclType(RD));
3023 auto FromPtrType = FromType->getAs<PointerType>();
3024 DestRecordType = Context.getAddrSpaceQualType(
3025 DestRecordType, FromPtrType
3026 ? FromType->getPointeeType().getAddressSpace()
3027 : FromType.getAddressSpace());
3028
3029 if (FromPtrType) {
3030 DestType = Context.getPointerType(DestRecordType);
3031 FromRecordType = FromPtrType->getPointeeType();
3032 PointerConversions = true;
3033 } else {
3034 DestType = DestRecordType;
3035 FromRecordType = FromType;
3036 }
3037 } else if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Member)) {
3038 if (Method->isStatic())
3039 return From;
3040
3041 DestType = Method->getThisType();
3042 DestRecordType = DestType->getPointeeType();
3043
3044 if (FromType->getAs<PointerType>()) {
3045 FromRecordType = FromType->getPointeeType();
3046 PointerConversions = true;
3047 } else {
3048 FromRecordType = FromType;
3049 DestType = DestRecordType;
3050 }
3051
3052 LangAS FromAS = FromRecordType.getAddressSpace();
3053 LangAS DestAS = DestRecordType.getAddressSpace();
3054 if (FromAS != DestAS) {
3055 QualType FromRecordTypeWithoutAS =
3056 Context.removeAddrSpaceQualType(FromRecordType);
3057 QualType FromTypeWithDestAS =
3058 Context.getAddrSpaceQualType(FromRecordTypeWithoutAS, DestAS);
3059 if (PointerConversions)
3060 FromTypeWithDestAS = Context.getPointerType(FromTypeWithDestAS);
3061 From = ImpCastExprToType(From, FromTypeWithDestAS,
3062 CK_AddressSpaceConversion, From->getValueKind())
3063 .get();
3064 }
3065 } else {
3066 // No conversion necessary.
3067 return From;
3068 }
3069
3070 if (DestType->isDependentType() || FromType->isDependentType())
3071 return From;
3072
3073 // If the unqualified types are the same, no conversion is necessary.
3074 if (Context.hasSameUnqualifiedType(FromRecordType, DestRecordType))
3075 return From;
3076
3077 SourceRange FromRange = From->getSourceRange();
3078 SourceLocation FromLoc = FromRange.getBegin();
3079
3080 ExprValueKind VK = From->getValueKind();
3081
3082 // C++ [class.member.lookup]p8:
3083 // [...] Ambiguities can often be resolved by qualifying a name with its
3084 // class name.
3085 //
3086 // If the member was a qualified name and the qualified referred to a
3087 // specific base subobject type, we'll cast to that intermediate type
3088 // first and then to the object in which the member is declared. That allows
3089 // one to resolve ambiguities in, e.g., a diamond-shaped hierarchy such as:
3090 //
3091 // class Base { public: int x; };
3092 // class Derived1 : public Base { };
3093 // class Derived2 : public Base { };
3094 // class VeryDerived : public Derived1, public Derived2 { void f(); };
3095 //
3096 // void VeryDerived::f() {
3097 // x = 17; // error: ambiguous base subobjects
3098 // Derived1::x = 17; // okay, pick the Base subobject of Derived1
3099 // }
3100 if (Qualifier && Qualifier->getAsType()) {
3101 QualType QType = QualType(Qualifier->getAsType(), 0);
3102 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", 3102, __extension__ __PRETTY_FUNCTION__
))
;
3103
3104 QualType QRecordType = QualType(QType->castAs<RecordType>(), 0);
3105
3106 // In C++98, the qualifier type doesn't actually have to be a base
3107 // type of the object type, in which case we just ignore it.
3108 // Otherwise build the appropriate casts.
3109 if (IsDerivedFrom(FromLoc, FromRecordType, QRecordType)) {
3110 CXXCastPath BasePath;
3111 if (CheckDerivedToBaseConversion(FromRecordType, QRecordType,
3112 FromLoc, FromRange, &BasePath))
3113 return ExprError();
3114
3115 if (PointerConversions)
3116 QType = Context.getPointerType(QType);
3117 From = ImpCastExprToType(From, QType, CK_UncheckedDerivedToBase,
3118 VK, &BasePath).get();
3119
3120 FromType = QType;
3121 FromRecordType = QRecordType;
3122
3123 // If the qualifier type was the same as the destination type,
3124 // we're done.
3125 if (Context.hasSameUnqualifiedType(FromRecordType, DestRecordType))
3126 return From;
3127 }
3128 }
3129
3130 CXXCastPath BasePath;
3131 if (CheckDerivedToBaseConversion(FromRecordType, DestRecordType,
3132 FromLoc, FromRange, &BasePath,
3133 /*IgnoreAccess=*/true))
3134 return ExprError();
3135
3136 return ImpCastExprToType(From, DestType, CK_UncheckedDerivedToBase,
3137 VK, &BasePath);
3138}
3139
3140bool Sema::UseArgumentDependentLookup(const CXXScopeSpec &SS,
3141 const LookupResult &R,
3142 bool HasTrailingLParen) {
3143 // Only when used directly as the postfix-expression of a call.
3144 if (!HasTrailingLParen)
3145 return false;
3146
3147 // Never if a scope specifier was provided.
3148 if (SS.isSet())
3149 return false;
3150
3151 // Only in C++ or ObjC++.
3152 if (!getLangOpts().CPlusPlus)
3153 return false;
3154
3155 // Turn off ADL when we find certain kinds of declarations during
3156 // normal lookup:
3157 for (NamedDecl *D : R) {
3158 // C++0x [basic.lookup.argdep]p3:
3159 // -- a declaration of a class member
3160 // Since using decls preserve this property, we check this on the
3161 // original decl.
3162 if (D->isCXXClassMember())
3163 return false;
3164
3165 // C++0x [basic.lookup.argdep]p3:
3166 // -- a block-scope function declaration that is not a
3167 // using-declaration
3168 // NOTE: we also trigger this for function templates (in fact, we
3169 // don't check the decl type at all, since all other decl types
3170 // turn off ADL anyway).
3171 if (isa<UsingShadowDecl>(D))
3172 D = cast<UsingShadowDecl>(D)->getTargetDecl();
3173 else if (D->getLexicalDeclContext()->isFunctionOrMethod())
3174 return false;
3175
3176 // C++0x [basic.lookup.argdep]p3:
3177 // -- a declaration that is neither a function or a function
3178 // template
3179 // And also for builtin functions.
3180 if (isa<FunctionDecl>(D)) {
3181 FunctionDecl *FDecl = cast<FunctionDecl>(D);
3182
3183 // But also builtin functions.
3184 if (FDecl->getBuiltinID() && FDecl->isImplicit())
3185 return false;
3186 } else if (!isa<FunctionTemplateDecl>(D))
3187 return false;
3188 }
3189
3190 return true;
3191}
3192
3193
3194/// Diagnoses obvious problems with the use of the given declaration
3195/// as an expression. This is only actually called for lookups that
3196/// were not overloaded, and it doesn't promise that the declaration
3197/// will in fact be used.
3198static bool CheckDeclInExpr(Sema &S, SourceLocation Loc, NamedDecl *D,
3199 bool AcceptInvalid) {
3200 if (D->isInvalidDecl() && !AcceptInvalid)
3201 return true;
3202
3203 if (isa<TypedefNameDecl>(D)) {
3204 S.Diag(Loc, diag::err_unexpected_typedef) << D->getDeclName();
3205 return true;
3206 }
3207
3208 if (isa<ObjCInterfaceDecl>(D)) {
3209 S.Diag(Loc, diag::err_unexpected_interface) << D->getDeclName();
3210 return true;
3211 }
3212
3213 if (isa<NamespaceDecl>(D)) {
3214 S.Diag(Loc, diag::err_unexpected_namespace) << D->getDeclName();
3215 return true;
3216 }
3217
3218 return false;
3219}
3220
3221// Certain multiversion types should be treated as overloaded even when there is
3222// only one result.
3223static bool ShouldLookupResultBeMultiVersionOverload(const LookupResult &R) {
3224 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", 3224, __extension__ __PRETTY_FUNCTION__
))
;
3225 const auto *FD = dyn_cast<FunctionDecl>(R.getFoundDecl());
3226 return FD &&
3227 (FD->isCPUDispatchMultiVersion() || FD->isCPUSpecificMultiVersion());
3228}
3229
3230ExprResult Sema::BuildDeclarationNameExpr(const CXXScopeSpec &SS,
3231 LookupResult &R, bool NeedsADL,
3232 bool AcceptInvalidDecl) {
3233 // If this is a single, fully-resolved result and we don't need ADL,
3234 // just build an ordinary singleton decl ref.
3235 if (!NeedsADL && R.isSingleResult() &&
3236 !R.getAsSingle<FunctionTemplateDecl>() &&
3237 !ShouldLookupResultBeMultiVersionOverload(R))
3238 return BuildDeclarationNameExpr(SS, R.getLookupNameInfo(), R.getFoundDecl(),
3239 R.getRepresentativeDecl(), nullptr,
3240 AcceptInvalidDecl);
3241
3242 // We only need to check the declaration if there's exactly one
3243 // result, because in the overloaded case the results can only be
3244 // functions and function templates.
3245 if (R.isSingleResult() && !ShouldLookupResultBeMultiVersionOverload(R) &&
3246 CheckDeclInExpr(*this, R.getNameLoc(), R.getFoundDecl(),
3247 AcceptInvalidDecl))
3248 return ExprError();
3249
3250 // Otherwise, just build an unresolved lookup expression. Suppress
3251 // any lookup-related diagnostics; we'll hash these out later, when
3252 // we've picked a target.
3253 R.suppressDiagnostics();
3254
3255 UnresolvedLookupExpr *ULE
3256 = UnresolvedLookupExpr::Create(Context, R.getNamingClass(),
3257 SS.getWithLocInContext(Context),
3258 R.getLookupNameInfo(),
3259 NeedsADL, R.isOverloadedResult(),
3260 R.begin(), R.end());
3261
3262 return ULE;
3263}
3264
3265static void diagnoseUncapturableValueReferenceOrBinding(Sema &S,
3266 SourceLocation loc,
3267 ValueDecl *var);
3268
3269/// Complete semantic analysis for a reference to the given declaration.
3270ExprResult Sema::BuildDeclarationNameExpr(
3271 const CXXScopeSpec &SS, const DeclarationNameInfo &NameInfo, NamedDecl *D,
3272 NamedDecl *FoundD, const TemplateArgumentListInfo *TemplateArgs,
3273 bool AcceptInvalidDecl) {
3274 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", 3274, __extension__ __PRETTY_FUNCTION__
))
;
3275 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", 3276, __extension__ __PRETTY_FUNCTION__
))
3276 "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", 3276, __extension__ __PRETTY_FUNCTION__
))
;
3277
3278 SourceLocation Loc = NameInfo.getLoc();
3279 if (CheckDeclInExpr(*this, Loc, D, AcceptInvalidDecl)) {
3280 // Recovery from invalid cases (e.g. D is an invalid Decl).
3281 // We use the dependent type for the RecoveryExpr to prevent bogus follow-up
3282 // diagnostics, as invalid decls use int as a fallback type.
3283 return CreateRecoveryExpr(NameInfo.getBeginLoc(), NameInfo.getEndLoc(), {});
3284 }
3285
3286 if (TemplateDecl *Template = dyn_cast<TemplateDecl>(D)) {
3287 // Specifically diagnose references to class templates that are missing
3288 // a template argument list.
3289 diagnoseMissingTemplateArguments(TemplateName(Template), Loc);
3290 return ExprError();
3291 }
3292
3293 // Make sure that we're referring to a value.
3294 if (!isa<ValueDecl, UnresolvedUsingIfExistsDecl>(D)) {
3295 Diag(Loc, diag::err_ref_non_value) << D << SS.getRange();
3296 Diag(D->getLocation(), diag::note_declared_at);
3297 return ExprError();
3298 }
3299
3300 // Check whether this declaration can be used. Note that we suppress
3301 // this check when we're going to perform argument-dependent lookup
3302 // on this function name, because this might not be the function
3303 // that overload resolution actually selects.
3304 if (DiagnoseUseOfDecl(D, Loc))
3305 return ExprError();
3306
3307 auto *VD = cast<ValueDecl>(D);
3308
3309 // Only create DeclRefExpr's for valid Decl's.
3310 if (VD->isInvalidDecl() && !AcceptInvalidDecl)
3311 return ExprError();
3312
3313 // Handle members of anonymous structs and unions. If we got here,
3314 // and the reference is to a class member indirect field, then this
3315 // must be the subject of a pointer-to-member expression.
3316 if (IndirectFieldDecl *indirectField = dyn_cast<IndirectFieldDecl>(VD))
3317 if (!indirectField->isCXXClassMember())
3318 return BuildAnonymousStructUnionMemberReference(SS, NameInfo.getLoc(),
3319 indirectField);
3320
3321 QualType type = VD->getType();
3322 if (type.isNull())
3323 return ExprError();
3324 ExprValueKind valueKind = VK_PRValue;
3325
3326 // In 'T ...V;', the type of the declaration 'V' is 'T...', but the type of
3327 // a reference to 'V' is simply (unexpanded) 'T'. The type, like the value,
3328 // is expanded by some outer '...' in the context of the use.
3329 type = type.getNonPackExpansionType();
3330
3331 switch (D->getKind()) {
3332 // Ignore all the non-ValueDecl kinds.
3333#define ABSTRACT_DECL(kind)
3334#define VALUE(type, base)
3335#define DECL(type, base) case Decl::type:
3336#include "clang/AST/DeclNodes.inc"
3337 llvm_unreachable("invalid value decl kind")::llvm::llvm_unreachable_internal("invalid value decl kind", "clang/lib/Sema/SemaExpr.cpp"
, 3337)
;
3338
3339 // These shouldn't make it here.
3340 case Decl::ObjCAtDefsField:
3341 llvm_unreachable("forming non-member reference to ivar?")::llvm::llvm_unreachable_internal("forming non-member reference to ivar?"
, "clang/lib/Sema/SemaExpr.cpp", 3341)
;
3342
3343 // Enum constants are always r-values and never references.
3344 // Unresolved using declarations are dependent.
3345 case Decl::EnumConstant:
3346 case Decl::UnresolvedUsingValue:
3347 case Decl::OMPDeclareReduction:
3348 case Decl::OMPDeclareMapper:
3349 valueKind = VK_PRValue;
3350 break;
3351
3352 // Fields and indirect fields that got here must be for
3353 // pointer-to-member expressions; we just call them l-values for
3354 // internal consistency, because this subexpression doesn't really
3355 // exist in the high-level semantics.
3356 case Decl::Field:
3357 case Decl::IndirectField:
3358 case Decl::ObjCIvar:
3359 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", 3359, __extension__ __PRETTY_FUNCTION__
))
;
3360
3361 // These can't have reference type in well-formed programs, but
3362 // for internal consistency we do this anyway.
3363 type = type.getNonReferenceType();
3364 valueKind = VK_LValue;
3365 break;
3366
3367 // Non-type template parameters are either l-values or r-values
3368 // depending on the type.
3369 case Decl::NonTypeTemplateParm: {
3370 if (const ReferenceType *reftype = type->getAs<ReferenceType>()) {
3371 type = reftype->getPointeeType();
3372 valueKind = VK_LValue; // even if the parameter is an r-value reference
3373 break;
3374 }
3375
3376 // [expr.prim.id.unqual]p2:
3377 // If the entity is a template parameter object for a template
3378 // parameter of type T, the type of the expression is const T.
3379 // [...] The expression is an lvalue if the entity is a [...] template
3380 // parameter object.
3381 if (type->isRecordType()) {
3382 type = type.getUnqualifiedType().withConst();
3383 valueKind = VK_LValue;
3384 break;
3385 }
3386
3387 // For non-references, we need to strip qualifiers just in case
3388 // the template parameter was declared as 'const int' or whatever.
3389 valueKind = VK_PRValue;
3390 type = type.getUnqualifiedType();
3391 break;
3392 }
3393
3394 case Decl::Var:
3395 case Decl::VarTemplateSpecialization:
3396 case Decl::VarTemplatePartialSpecialization:
3397 case Decl::Decomposition:
3398 case Decl::OMPCapturedExpr:
3399 // In C, "extern void blah;" is valid and is an r-value.
3400 if (!getLangOpts().CPlusPlus && !type.hasQualifiers() &&
3401 type->isVoidType()) {
3402 valueKind = VK_PRValue;
3403 break;
3404 }
3405 [[fallthrough]];
3406
3407 case Decl::ImplicitParam:
3408 case Decl::ParmVar: {
3409 // These are always l-values.
3410 valueKind = VK_LValue;
3411 type = type.getNonReferenceType();
3412
3413 // FIXME: Does the addition of const really only apply in
3414 // potentially-evaluated contexts? Since the variable isn't actually
3415 // captured in an unevaluated context, it seems that the answer is no.
3416 if (!isUnevaluatedContext()) {
3417 QualType CapturedType = getCapturedDeclRefType(cast<VarDecl>(VD), Loc);
3418 if (!CapturedType.isNull())
3419 type = CapturedType;
3420 }
3421
3422 break;
3423 }
3424
3425 case Decl::Binding:
3426 // These are always lvalues.
3427 valueKind = VK_LValue;
3428 type = type.getNonReferenceType();
3429 break;
3430
3431 case Decl::Function: {
3432 if (unsigned BID = cast<FunctionDecl>(VD)->getBuiltinID()) {
3433 if (!Context.BuiltinInfo.isDirectlyAddressable(BID)) {
3434 type = Context.BuiltinFnTy;
3435 valueKind = VK_PRValue;
3436 break;
3437 }
3438 }
3439
3440 const FunctionType *fty = type->castAs<FunctionType>();
3441
3442 // If we're referring to a function with an __unknown_anytype
3443 // result type, make the entire expression __unknown_anytype.
3444 if (fty->getReturnType() == Context.UnknownAnyTy) {
3445 type = Context.UnknownAnyTy;
3446 valueKind = VK_PRValue;
3447 break;
3448 }
3449
3450 // Functions are l-values in C++.
3451 if (getLangOpts().CPlusPlus) {
3452 valueKind = VK_LValue;
3453 break;
3454 }
3455
3456 // C99 DR 316 says that, if a function type comes from a
3457 // function definition (without a prototype), that type is only
3458 // used for checking compatibility. Therefore, when referencing
3459 // the function, we pretend that we don't have the full function
3460 // type.
3461 if (!cast<FunctionDecl>(VD)->hasPrototype() && isa<FunctionProtoType>(fty))
3462 type = Context.getFunctionNoProtoType(fty->getReturnType(),
3463 fty->getExtInfo());
3464
3465 // Functions are r-values in C.
3466 valueKind = VK_PRValue;
3467 break;
3468 }
3469
3470 case Decl::CXXDeductionGuide:
3471 llvm_unreachable("building reference to deduction guide")::llvm::llvm_unreachable_internal("building reference to deduction guide"
, "clang/lib/Sema/SemaExpr.cpp", 3471)
;
3472
3473 case Decl::MSProperty:
3474 case Decl::MSGuid:
3475 case Decl::TemplateParamObject:
3476 // FIXME: Should MSGuidDecl and template parameter objects be subject to
3477 // capture in OpenMP, or duplicated between host and device?
3478 valueKind = VK_LValue;
3479 break;
3480
3481 case Decl::UnnamedGlobalConstant:
3482 valueKind = VK_LValue;
3483 break;
3484
3485 case Decl::CXXMethod:
3486 // If we're referring to a method with an __unknown_anytype
3487 // result type, make the entire expression __unknown_anytype.
3488 // This should only be possible with a type written directly.
3489 if (const FunctionProtoType *proto =
3490 dyn_cast<FunctionProtoType>(VD->getType()))
3491 if (proto->getReturnType() == Context.UnknownAnyTy) {
3492 type = Context.UnknownAnyTy;
3493 valueKind = VK_PRValue;
3494 break;
3495 }
3496
3497 // C++ methods are l-values if static, r-values if non-static.
3498 if (cast<CXXMethodDecl>(VD)->isStatic()) {
3499 valueKind = VK_LValue;
3500 break;
3501 }
3502 [[fallthrough]];
3503
3504 case Decl::CXXConversion:
3505 case Decl::CXXDestructor:
3506 case Decl::CXXConstructor:
3507 valueKind = VK_PRValue;
3508 break;
3509 }
3510
3511 auto *E =
3512 BuildDeclRefExpr(VD, type, valueKind, NameInfo, &SS, FoundD,
3513 /*FIXME: TemplateKWLoc*/ SourceLocation(), TemplateArgs);
3514 // Clang AST consumers assume a DeclRefExpr refers to a valid decl. We
3515 // wrap a DeclRefExpr referring to an invalid decl with a dependent-type
3516 // RecoveryExpr to avoid follow-up semantic analysis (thus prevent bogus
3517 // diagnostics).
3518 if (VD->isInvalidDecl() && E)
3519 return CreateRecoveryExpr(E->getBeginLoc(), E->getEndLoc(), {E});
3520 return E;
3521}
3522
3523static void ConvertUTF8ToWideString(unsigned CharByteWidth, StringRef Source,
3524 SmallString<32> &Target) {
3525 Target.resize(CharByteWidth * (Source.size() + 1));
3526 char *ResultPtr = &Target[0];
3527 const llvm::UTF8 *ErrorPtr;
3528 bool success =
3529 llvm::ConvertUTF8toWide(CharByteWidth, Source, ResultPtr, ErrorPtr);
3530 (void)success;
3531 assert(success)(static_cast <bool> (success) ? void (0) : __assert_fail
("success", "clang/lib/Sema/SemaExpr.cpp", 3531, __extension__
__PRETTY_FUNCTION__))
;
3532 Target.resize(ResultPtr - &Target[0]);
3533}
3534
3535ExprResult Sema::BuildPredefinedExpr(SourceLocation Loc,
3536 PredefinedExpr::IdentKind IK) {
3537 // Pick the current block, lambda, captured statement or function.
3538 Decl *currentDecl = nullptr;
3539 if (const BlockScopeInfo *BSI = getCurBlock())
3540 currentDecl = BSI->TheDecl;
3541 else if (const LambdaScopeInfo *LSI = getCurLambda())
3542 currentDecl = LSI->CallOperator;
3543 else if (const CapturedRegionScopeInfo *CSI = getCurCapturedRegion())
3544 currentDecl = CSI->TheCapturedDecl;
3545 else
3546 currentDecl = getCurFunctionOrMethodDecl();
3547
3548 if (!currentDecl) {
3549 Diag(Loc, diag::ext_predef_outside_function);
3550 currentDecl = Context.getTranslationUnitDecl();
3551 }
3552
3553 QualType ResTy;
3554 StringLiteral *SL = nullptr;
3555 if (cast<DeclContext>(currentDecl)->isDependentContext())
3556 ResTy = Context.DependentTy;
3557 else {
3558 // Pre-defined identifiers are of type char[x], where x is the length of
3559 // the string.
3560 auto Str = PredefinedExpr::ComputeName(IK, currentDecl);
3561 unsigned Length = Str.length();
3562
3563 llvm::APInt LengthI(32, Length + 1);
3564 if (IK == PredefinedExpr::LFunction || IK == PredefinedExpr::LFuncSig) {
3565 ResTy =
3566 Context.adjustStringLiteralBaseType(Context.WideCharTy.withConst());
3567 SmallString<32> RawChars;
3568 ConvertUTF8ToWideString(Context.getTypeSizeInChars(ResTy).getQuantity(),
3569 Str, RawChars);
3570 ResTy = Context.getConstantArrayType(ResTy, LengthI, nullptr,
3571 ArrayType::Normal,
3572 /*IndexTypeQuals*/ 0);
3573 SL = StringLiteral::Create(Context, RawChars, StringLiteral::Wide,
3574 /*Pascal*/ false, ResTy, Loc);
3575 } else {
3576 ResTy = Context.adjustStringLiteralBaseType(Context.CharTy.withConst());
3577 ResTy = Context.getConstantArrayType(ResTy, LengthI, nullptr,
3578 ArrayType::Normal,
3579 /*IndexTypeQuals*/ 0);
3580 SL = StringLiteral::Create(Context, Str, StringLiteral::Ordinary,
3581 /*Pascal*/ false, ResTy, Loc);
3582 }
3583 }
3584
3585 return PredefinedExpr::Create(Context, Loc, ResTy, IK, SL);
3586}
3587
3588ExprResult Sema::BuildSYCLUniqueStableNameExpr(SourceLocation OpLoc,
3589 SourceLocation LParen,
3590 SourceLocation RParen,
3591 TypeSourceInfo *TSI) {
3592 return SYCLUniqueStableNameExpr::Create(Context, OpLoc, LParen, RParen, TSI);
3593}
3594
3595ExprResult Sema::ActOnSYCLUniqueStableNameExpr(SourceLocation OpLoc,
3596 SourceLocation LParen,
3597 SourceLocation RParen,
3598 ParsedType ParsedTy) {
3599 TypeSourceInfo *TSI = nullptr;
3600 QualType Ty = GetTypeFromParser(ParsedTy, &TSI);
3601
3602 if (Ty.isNull())
3603 return ExprError();
3604 if (!TSI)
3605 TSI = Context.getTrivialTypeSourceInfo(Ty, LParen);
3606
3607 return BuildSYCLUniqueStableNameExpr(OpLoc, LParen, RParen, TSI);
3608}
3609
3610ExprResult Sema::ActOnPredefinedExpr(SourceLocation Loc, tok::TokenKind Kind) {
3611 PredefinedExpr::IdentKind IK;
3612
3613 switch (Kind) {
3614 default: llvm_unreachable("Unknown simple primary expr!")::llvm::llvm_unreachable_internal("Unknown simple primary expr!"
, "clang/lib/Sema/SemaExpr.cpp", 3614)
;
3615 case tok::kw___func__: IK = PredefinedExpr::Func; break; // [C99 6.4.2.2]
3616 case tok::kw___FUNCTION__: IK = PredefinedExpr::Function; break;
3617 case tok::kw___FUNCDNAME__: IK = PredefinedExpr::FuncDName; break; // [MS]
3618 case tok::kw___FUNCSIG__: IK = PredefinedExpr::FuncSig; break; // [MS]
3619 case tok::kw_L__FUNCTION__: IK = PredefinedExpr::LFunction; break; // [MS]
3620 case tok::kw_L__FUNCSIG__: IK = PredefinedExpr::LFuncSig; break; // [MS]
3621 case tok::kw___PRETTY_FUNCTION__: IK = PredefinedExpr::PrettyFunction; break;
3622 }
3623
3624 return BuildPredefinedExpr(Loc, IK);
3625}
3626
3627ExprResult Sema::ActOnCharacterConstant(const Token &Tok, Scope *UDLScope) {
3628 SmallString<16> CharBuffer;
3629 bool Invalid = false;
3630 StringRef ThisTok = PP.getSpelling(Tok, CharBuffer, &Invalid);
3631 if (Invalid)
3632 return ExprError();
3633
3634 CharLiteralParser Literal(ThisTok.begin(), ThisTok.end(), Tok.getLocation(),
3635 PP, Tok.getKind());
3636 if (Literal.hadError())
3637 return ExprError();
3638
3639 QualType Ty;
3640 if (Literal.isWide())
3641 Ty = Context.WideCharTy; // L'x' -> wchar_t in C and C++.
3642 else if (Literal.isUTF8() && getLangOpts().C2x)
3643 Ty = Context.UnsignedCharTy; // u8'x' -> unsigned char in C2x
3644 else if (Literal.isUTF8() && getLangOpts().Char8)
3645 Ty = Context.Char8Ty; // u8'x' -> char8_t when it exists.
3646 else if (Literal.isUTF16())
3647 Ty = Context.Char16Ty; // u'x' -> char16_t in C11 and C++11.
3648 else if (Literal.isUTF32())
3649 Ty = Context.Char32Ty; // U'x' -> char32_t in C11 and C++11.
3650 else if (!getLangOpts().CPlusPlus || Literal.isMultiChar())
3651 Ty = Context.IntTy; // 'x' -> int in C, 'wxyz' -> int in C++.
3652 else
3653 Ty = Context.CharTy; // 'x' -> char in C++;
3654 // u8'x' -> char in C11-C17 and in C++ without char8_t.
3655
3656 CharacterLiteral::CharacterKind Kind = CharacterLiteral::Ascii;
3657 if (Literal.isWide())
3658 Kind = CharacterLiteral::Wide;
3659 else if (Literal.isUTF16())
3660 Kind = CharacterLiteral::UTF16;
3661 else if (Literal.isUTF32())
3662 Kind = CharacterLiteral::UTF32;
3663 else if (Literal.isUTF8())
3664 Kind = CharacterLiteral::UTF8;
3665
3666 Expr *Lit = new (Context) CharacterLiteral(Literal.getValue(), Kind, Ty,
3667 Tok.getLocation());
3668
3669 if (Literal.getUDSuffix().empty())
3670 return Lit;
3671
3672 // We're building a user-defined literal.
3673 IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix());
3674 SourceLocation UDSuffixLoc =
3675 getUDSuffixLoc(*this, Tok.getLocation(), Literal.getUDSuffixOffset());
3676
3677 // Make sure we're allowed user-defined literals here.
3678 if (!UDLScope)
3679 return ExprError(Diag(UDSuffixLoc, diag::err_invalid_character_udl));
3680
3681 // C++11 [lex.ext]p6: The literal L is treated as a call of the form
3682 // operator "" X (ch)
3683 return BuildCookedLiteralOperatorCall(*this, UDLScope, UDSuffix, UDSuffixLoc,
3684 Lit, Tok.getLocation());
3685}
3686
3687ExprResult Sema::ActOnIntegerConstant(SourceLocation Loc, uint64_t Val) {
3688 unsigned IntSize = Context.getTargetInfo().getIntWidth();
3689 return IntegerLiteral::Create(Context, llvm::APInt(IntSize, Val),
3690 Context.IntTy, Loc);
3691}
3692
3693static Expr *BuildFloatingLiteral(Sema &S, NumericLiteralParser &Literal,
3694 QualType Ty, SourceLocation Loc) {
3695 const llvm::fltSemantics &Format = S.Context.getFloatTypeSemantics(Ty);
3696
3697 using llvm::APFloat;
3698 APFloat Val(Format);
3699
3700 APFloat::opStatus result = Literal.GetFloatValue(Val);
3701
3702 // Overflow is always an error, but underflow is only an error if
3703 // we underflowed to zero (APFloat reports denormals as underflow).
3704 if ((result & APFloat::opOverflow) ||
3705 ((result & APFloat::opUnderflow) && Val.isZero())) {
3706 unsigned diagnostic;
3707 SmallString<20> buffer;
3708 if (result & APFloat::opOverflow) {
3709 diagnostic = diag::warn_float_overflow;
3710 APFloat::getLargest(Format).toString(buffer);
3711 } else {
3712 diagnostic = diag::warn_float_underflow;
3713 APFloat::getSmallest(Format).toString(buffer);
3714 }
3715
3716 S.Diag(Loc, diagnostic)
3717 << Ty
3718 << StringRef(buffer.data(), buffer.size());
3719 }
3720
3721 bool isExact = (result == APFloat::opOK);
3722 return FloatingLiteral::Create(S.Context, Val, isExact, Ty, Loc);
3723}
3724
3725bool Sema::CheckLoopHintExpr(Expr *E, SourceLocation Loc) {
3726 assert(E && "Invalid expression")(static_cast <bool> (E && "Invalid expression")
? void (0) : __assert_fail ("E && \"Invalid expression\""
, "clang/lib/Sema/SemaExpr.cpp", 3726, __extension__ __PRETTY_FUNCTION__
))
;
3727
3728 if (E->isValueDependent())
3729 return false;
3730
3731 QualType QT = E->getType();
3732 if (!QT->isIntegerType() || QT->isBooleanType() || QT->isCharType()) {
3733 Diag(E->getExprLoc(), diag::err_pragma_loop_invalid_argument_type) << QT;
3734 return true;
3735 }
3736
3737 llvm::APSInt ValueAPS;
3738 ExprResult R = VerifyIntegerConstantExpression(E, &ValueAPS);
3739
3740 if (R.isInvalid())
3741 return true;
3742
3743 bool ValueIsPositive = ValueAPS.isStrictlyPositive();
3744 if (!ValueIsPositive || ValueAPS.getActiveBits() > 31) {
3745 Diag(E->getExprLoc(), diag::err_pragma_loop_invalid_argument_value)
3746 << toString(ValueAPS, 10) << ValueIsPositive;
3747 return true;
3748 }
3749
3750 return false;
3751}
3752
3753ExprResult Sema::ActOnNumericConstant(const Token &Tok, Scope *UDLScope) {
3754 // Fast path for a single digit (which is quite common). A single digit
3755 // cannot have a trigraph, escaped newline, radix prefix, or suffix.
3756 if (Tok.getLength() == 1) {
3757 const char Val = PP.getSpellingOfSingleCharacterNumericConstant(Tok);
3758 return ActOnIntegerConstant(Tok.getLocation(), Val-'0');
3759 }
3760
3761 SmallString<128> SpellingBuffer;
3762 // NumericLiteralParser wants to overread by one character. Add padding to
3763 // the buffer in case the token is copied to the buffer. If getSpelling()
3764 // returns a StringRef to the memory buffer, it should have a null char at
3765 // the EOF, so it is also safe.
3766 SpellingBuffer.resize(Tok.getLength() + 1);
3767
3768 // Get the spelling of the token, which eliminates trigraphs, etc.
3769 bool Invalid = false;
3770 StringRef TokSpelling = PP.getSpelling(Tok, SpellingBuffer, &Invalid);
3771 if (Invalid)
3772 return ExprError();
3773
3774 NumericLiteralParser Literal(TokSpelling, Tok.getLocation(),
3775 PP.getSourceManager(), PP.getLangOpts(),
3776 PP.getTargetInfo(), PP.getDiagnostics());
3777 if (Literal.hadError)
3778 return ExprError();
3779
3780 if (Literal.hasUDSuffix()) {
3781 // We're building a user-defined literal.
3782 IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix());
3783 SourceLocation UDSuffixLoc =
3784 getUDSuffixLoc(*this, Tok.getLocation(), Literal.getUDSuffixOffset());
3785
3786 // Make sure we're allowed user-defined literals here.
3787 if (!UDLScope)
3788 return ExprError(Diag(UDSuffixLoc, diag::err_invalid_numeric_udl));
3789
3790 QualType CookedTy;
3791 if (Literal.isFloatingLiteral()) {
3792 // C++11 [lex.ext]p4: If S contains a literal operator with parameter type
3793 // long double, the literal is treated as a call of the form
3794 // operator "" X (f L)
3795 CookedTy = Context.LongDoubleTy;
3796 } else {
3797 // C++11 [lex.ext]p3: If S contains a literal operator with parameter type
3798 // unsigned long long, the literal is treated as a call of the form
3799 // operator "" X (n ULL)
3800 CookedTy = Context.UnsignedLongLongTy;
3801 }
3802
3803 DeclarationName OpName =
3804 Context.DeclarationNames.getCXXLiteralOperatorName(UDSuffix);
3805 DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc);
3806 OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc);
3807
3808 SourceLocation TokLoc = Tok.getLocation();
3809
3810 // Perform literal operator lookup to determine if we're building a raw
3811 // literal or a cooked one.
3812 LookupResult R(*this, OpName, UDSuffixLoc, LookupOrdinaryName);
3813 switch (LookupLiteralOperator(UDLScope, R, CookedTy,
3814 /*AllowRaw*/ true, /*AllowTemplate*/ true,
3815 /*AllowStringTemplatePack*/ false,
3816 /*DiagnoseMissing*/ !Literal.isImaginary)) {
3817 case LOLR_ErrorNoDiagnostic:
3818 // Lookup failure for imaginary constants isn't fatal, there's still the
3819 // GNU extension producing _Complex types.
3820 break;
3821 case LOLR_Error:
3822 return ExprError();
3823 case LOLR_Cooked: {
3824 Expr *Lit;
3825 if (Literal.isFloatingLiteral()) {
3826 Lit = BuildFloatingLiteral(*this, Literal, CookedTy, Tok.getLocation());
3827 } else {
3828 llvm::APInt ResultVal(Context.getTargetInfo().getLongLongWidth(), 0);
3829 if (Literal.GetIntegerValue(ResultVal))
3830 Diag(Tok.getLocation(), diag::err_integer_literal_too_large)
3831 << /* Unsigned */ 1;
3832 Lit = IntegerLiteral::Create(Context, ResultVal, CookedTy,
3833 Tok.getLocation());
3834 }
3835 return BuildLiteralOperatorCall(R, OpNameInfo, Lit, TokLoc);
3836 }
3837
3838 case LOLR_Raw: {
3839 // C++11 [lit.ext]p3, p4: If S contains a raw literal operator, the
3840 // literal is treated as a call of the form
3841 // operator "" X ("n")
3842 unsigned Length = Literal.getUDSuffixOffset();
3843 QualType StrTy = Context.getConstantArrayType(
3844 Context.adjustStringLiteralBaseType(Context.CharTy.withConst()),
3845 llvm::APInt(32, Length + 1), nullptr, ArrayType::Normal, 0);
3846 Expr *Lit =
3847 StringLiteral::Create(Context, StringRef(TokSpelling.data(), Length),
3848 StringLiteral::Ordinary,
3849 /*Pascal*/ false, StrTy, &TokLoc, 1);
3850 return BuildLiteralOperatorCall(R, OpNameInfo, Lit, TokLoc);
3851 }
3852
3853 case LOLR_Template: {
3854 // C++11 [lit.ext]p3, p4: Otherwise (S contains a literal operator
3855 // template), L is treated as a call fo the form
3856 // operator "" X <'c1', 'c2', ... 'ck'>()
3857 // where n is the source character sequence c1 c2 ... ck.
3858 TemplateArgumentListInfo ExplicitArgs;
3859 unsigned CharBits = Context.getIntWidth(Context.CharTy);
3860 bool CharIsUnsigned = Context.CharTy->isUnsignedIntegerType();
3861 llvm::APSInt Value(CharBits, CharIsUnsigned);
3862 for (unsigned I = 0, N = Literal.getUDSuffixOffset(); I != N; ++I) {
3863 Value = TokSpelling[I];
3864 TemplateArgument Arg(Context, Value, Context.CharTy);
3865 TemplateArgumentLocInfo ArgInfo;
3866 ExplicitArgs.addArgument(TemplateArgumentLoc(Arg, ArgInfo));
3867 }
3868 return BuildLiteralOperatorCall(R, OpNameInfo, std::nullopt, TokLoc,
3869 &ExplicitArgs);
3870 }
3871 case LOLR_StringTemplatePack:
3872 llvm_unreachable("unexpected literal operator lookup result")::llvm::llvm_unreachable_internal("unexpected literal operator lookup result"
, "clang/lib/Sema/SemaExpr.cpp", 3872)
;
3873 }
3874 }
3875
3876 Expr *Res;
3877
3878 if (Literal.isFixedPointLiteral()) {
3879 QualType Ty;
3880
3881 if (Literal.isAccum) {
3882 if (Literal.isHalf) {
3883 Ty = Context.ShortAccumTy;
3884 } else if (Literal.isLong) {
3885 Ty = Context.LongAccumTy;
3886 } else {
3887 Ty = Context.AccumTy;
3888 }
3889 } else if (Literal.isFract) {
3890 if (Literal.isHalf) {
3891 Ty = Context.ShortFractTy;
3892 } else if (Literal.isLong) {
3893 Ty = Context.LongFractTy;
3894 } else {
3895 Ty = Context.FractTy;
3896 }
3897 }
3898
3899 if (Literal.isUnsigned) Ty = Context.getCorrespondingUnsignedType(Ty);
3900
3901 bool isSigned = !Literal.isUnsigned;
3902 unsigned scale = Context.getFixedPointScale(Ty);
3903 unsigned bit_width = Context.getTypeInfo(Ty).Width;
3904
3905 llvm::APInt Val(bit_width, 0, isSigned);
3906 bool Overflowed = Literal.GetFixedPointValue(Val, scale);
3907 bool ValIsZero = Val.isZero() && !Overflowed;
3908
3909 auto MaxVal = Context.getFixedPointMax(Ty).getValue();
3910 if (Literal.isFract && Val == MaxVal + 1 && !ValIsZero)
3911 // Clause 6.4.4 - The value of a constant shall be in the range of
3912 // representable values for its type, with exception for constants of a
3913 // fract type with a value of exactly 1; such a constant shall denote
3914 // the maximal value for the type.
3915 --Val;
3916 else if (Val.ugt(MaxVal) || Overflowed)
3917 Diag(Tok.getLocation(), diag::err_too_large_for_fixed_point);
3918
3919 Res = FixedPointLiteral::CreateFromRawInt(Context, Val, Ty,
3920 Tok.getLocation(), scale);
3921 } else if (Literal.isFloatingLiteral()) {
3922 QualType Ty;
3923 if (Literal.isHalf){
3924 if (getOpenCLOptions().isAvailableOption("cl_khr_fp16", getLangOpts()))
3925 Ty = Context.HalfTy;
3926 else {
3927 Diag(Tok.getLocation(), diag::err_half_const_requires_fp16);
3928 return ExprError();
3929 }
3930 } else if (Literal.isFloat)
3931 Ty = Context.FloatTy;
3932 else if (Literal.isLong)
3933 Ty = Context.LongDoubleTy;
3934 else if (Literal.isFloat16)
3935 Ty = Context.Float16Ty;
3936 else if (Literal.isFloat128)
3937 Ty = Context.Float128Ty;
3938 else
3939 Ty = Context.DoubleTy;
3940
3941 Res = BuildFloatingLiteral(*this, Literal, Ty, Tok.getLocation());
3942
3943 if (Ty == Context.DoubleTy) {
3944 if (getLangOpts().SinglePrecisionConstants) {
3945 if (Ty->castAs<BuiltinType>()->getKind() != BuiltinType::Float) {
3946 Res = ImpCastExprToType(Res, Context.FloatTy, CK_FloatingCast).get();
3947 }
3948 } else if (getLangOpts().OpenCL && !getOpenCLOptions().isAvailableOption(
3949 "cl_khr_fp64", getLangOpts())) {
3950 // Impose single-precision float type when cl_khr_fp64 is not enabled.
3951 Diag(Tok.getLocation(), diag::warn_double_const_requires_fp64)
3952 << (getLangOpts().getOpenCLCompatibleVersion() >= 300);
3953 Res = ImpCastExprToType(Res, Context.FloatTy, CK_FloatingCast).get();
3954 }
3955 }
3956 } else if (!Literal.isIntegerLiteral()) {
3957 return ExprError();
3958 } else {
3959 QualType Ty;
3960
3961 // 'z/uz' literals are a C++2b feature.
3962 if (Literal.isSizeT)
3963 Diag(Tok.getLocation(), getLangOpts().CPlusPlus
3964 ? getLangOpts().CPlusPlus2b
3965 ? diag::warn_cxx20_compat_size_t_suffix
3966 : diag::ext_cxx2b_size_t_suffix
3967 : diag::err_cxx2b_size_t_suffix);
3968
3969 // 'wb/uwb' literals are a C2x feature. We support _BitInt as a type in C++,
3970 // but we do not currently support the suffix in C++ mode because it's not
3971 // entirely clear whether WG21 will prefer this suffix to return a library
3972 // type such as std::bit_int instead of returning a _BitInt.
3973 if (Literal.isBitInt && !getLangOpts().CPlusPlus)
3974 PP.Diag(Tok.getLocation(), getLangOpts().C2x
3975 ? diag::warn_c2x_compat_bitint_suffix
3976 : diag::ext_c2x_bitint_suffix);
3977
3978 // Get the value in the widest-possible width. What is "widest" depends on
3979 // whether the literal is a bit-precise integer or not. For a bit-precise
3980 // integer type, try to scan the source to determine how many bits are
3981 // needed to represent the value. This may seem a bit expensive, but trying
3982 // to get the integer value from an overly-wide APInt is *extremely*
3983 // expensive, so the naive approach of assuming
3984 // llvm::IntegerType::MAX_INT_BITS is a big performance hit.
3985 unsigned BitsNeeded =
3986 Literal.isBitInt ? llvm::APInt::getSufficientBitsNeeded(
3987 Literal.getLiteralDigits(), Literal.getRadix())
3988 : Context.getTargetInfo().getIntMaxTWidth();
3989 llvm::APInt ResultVal(BitsNeeded, 0);
3990
3991 if (Literal.GetIntegerValue(ResultVal)) {
3992 // If this value didn't fit into uintmax_t, error and force to ull.
3993 Diag(Tok.getLocation(), diag::err_integer_literal_too_large)
3994 << /* Unsigned */ 1;
3995 Ty = Context.UnsignedLongLongTy;
3996 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", 3997, __extension__ __PRETTY_FUNCTION__
))
3997 "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", 3997, __extension__ __PRETTY_FUNCTION__
))
;
3998 } else {
3999 // If this value fits into a ULL, try to figure out what else it fits into
4000 // according to the rules of C99 6.4.4.1p5.
4001
4002 // Octal, Hexadecimal, and integers with a U suffix are allowed to
4003 // be an unsigned int.
4004 bool AllowUnsigned = Literal.isUnsigned || Literal.getRadix() != 10;
4005
4006 // Check from smallest to largest, picking the smallest type we can.
4007 unsigned Width = 0;
4008
4009 // Microsoft specific integer suffixes are explicitly sized.
4010 if (Literal.MicrosoftInteger) {
4011 if (Literal.MicrosoftInteger == 8 && !Literal.isUnsigned) {
4012 Width = 8;
4013 Ty = Context.CharTy;
4014 } else {
4015 Width = Literal.MicrosoftInteger;
4016 Ty = Context.getIntTypeForBitwidth(Width,
4017 /*Signed=*/!Literal.isUnsigned);
4018 }
4019 }
4020
4021 // Bit-precise integer literals are automagically-sized based on the
4022 // width required by the literal.
4023 if (Literal.isBitInt) {
4024 // The signed version has one more bit for the sign value. There are no
4025 // zero-width bit-precise integers, even if the literal value is 0.
4026 Width = std::max(ResultVal.getActiveBits(), 1u) +
4027 (Literal.isUnsigned ? 0u : 1u);
4028
4029 // Diagnose if the width of the constant is larger than BITINT_MAXWIDTH,
4030 // and reset the type to the largest supported width.
4031 unsigned int MaxBitIntWidth =
4032 Context.getTargetInfo().getMaxBitIntWidth();
4033 if (Width > MaxBitIntWidth) {
4034 Diag(Tok.getLocation(), diag::err_integer_literal_too_large)
4035 << Literal.isUnsigned;
4036 Width = MaxBitIntWidth;
4037 }
4038
4039 // Reset the result value to the smaller APInt and select the correct
4040 // type to be used. Note, we zext even for signed values because the
4041 // literal itself is always an unsigned value (a preceeding - is a
4042 // unary operator, not part of the literal).
4043 ResultVal = ResultVal.zextOrTrunc(Width);
4044 Ty = Context.getBitIntType(Literal.isUnsigned, Width);
4045 }
4046
4047 // Check C++2b size_t literals.
4048 if (Literal.isSizeT) {
4049 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", 4050, __extension__ __PRETTY_FUNCTION__
))
4050 "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", 4050, __extension__ __PRETTY_FUNCTION__
))
;
4051 unsigned SizeTSize = Context.getTargetInfo().getTypeWidth(
4052 Context.getTargetInfo().getSizeType());
4053
4054 // Does it fit in size_t?
4055 if (ResultVal.isIntN(SizeTSize)) {
4056 // Does it fit in ssize_t?
4057 if (!Literal.isUnsigned && ResultVal[SizeTSize - 1] == 0)
4058 Ty = Context.getSignedSizeType();
4059 else if (AllowUnsigned)
4060 Ty = Context.getSizeType();
4061 Width = SizeTSize;
4062 }
4063 }
4064
4065 if (Ty.isNull() && !Literal.isLong && !Literal.isLongLong &&
4066 !Literal.isSizeT) {
4067 // Are int/unsigned possibilities?
4068 unsigned IntSize = Context.getTargetInfo().getIntWidth();
4069
4070 // Does it fit in a unsigned int?
4071 if (ResultVal.isIntN(IntSize)) {
4072 // Does it fit in a signed int?
4073 if (!Literal.isUnsigned && ResultVal[IntSize-1] == 0)
4074 Ty = Context.IntTy;
4075 else if (AllowUnsigned)
4076 Ty = Context.UnsignedIntTy;
4077 Width = IntSize;
4078 }
4079 }
4080
4081 // Are long/unsigned long possibilities?
4082 if (Ty.isNull() && !Literal.isLongLong && !Literal.isSizeT) {
4083 unsigned LongSize = Context.getTargetInfo().getLongWidth();
4084
4085 // Does it fit in a unsigned long?
4086 if (ResultVal.isIntN(LongSize)) {
4087 // Does it fit in a signed long?
4088 if (!Literal.isUnsigned && ResultVal[LongSize-1] == 0)
4089 Ty = Context.LongTy;
4090 else if (AllowUnsigned)
4091 Ty = Context.UnsignedLongTy;
4092 // Check according to the rules of C90 6.1.3.2p5. C++03 [lex.icon]p2
4093 // is compatible.
4094 else if (!getLangOpts().C99 && !getLangOpts().CPlusPlus11) {
4095 const unsigned LongLongSize =
4096 Context.getTargetInfo().getLongLongWidth();
4097 Diag(Tok.getLocation(),
4098 getLangOpts().CPlusPlus
4099 ? Literal.isLong
4100 ? diag::warn_old_implicitly_unsigned_long_cxx
4101 : /*C++98 UB*/ diag::
4102 ext_old_implicitly_unsigned_long_cxx
4103 : diag::warn_old_implicitly_unsigned_long)
4104 << (LongLongSize > LongSize ? /*will have type 'long long'*/ 0
4105 : /*will be ill-formed*/ 1);
4106 Ty = Context.UnsignedLongTy;
4107 }
4108 Width = LongSize;
4109 }
4110 }
4111
4112 // Check long long if needed.
4113 if (Ty.isNull() && !Literal.isSizeT) {
4114 unsigned LongLongSize = Context.getTargetInfo().getLongLongWidth();
4115
4116 // Does it fit in a unsigned long long?
4117 if (ResultVal.isIntN(LongLongSize)) {
4118 // Does it fit in a signed long long?
4119 // To be compatible with MSVC, hex integer literals ending with the
4120 // LL or i64 suffix are always signed in Microsoft mode.
4121 if (!Literal.isUnsigned && (ResultVal[LongLongSize-1] == 0 ||
4122 (getLangOpts().MSVCCompat && Literal.isLongLong)))
4123 Ty = Context.LongLongTy;
4124 else if (AllowUnsigned)
4125 Ty = Context.UnsignedLongLongTy;
4126 Width = LongLongSize;
4127
4128 // 'long long' is a C99 or C++11 feature, whether the literal
4129 // explicitly specified 'long long' or we needed the extra width.
4130 if (getLangOpts().CPlusPlus)
4131 Diag(Tok.getLocation(), getLangOpts().CPlusPlus11
4132 ? diag::warn_cxx98_compat_longlong
4133 : diag::ext_cxx11_longlong);
4134 else if (!getLangOpts().C99)
4135 Diag(Tok.getLocation(), diag::ext_c99_longlong);
4136 }
4137 }
4138
4139 // If we still couldn't decide a type, we either have 'size_t' literal
4140 // that is out of range, or a decimal literal that does not fit in a
4141 // signed long long and has no U suffix.
4142 if (Ty.isNull()) {
4143 if (Literal.isSizeT)
4144 Diag(Tok.getLocation(), diag::err_size_t_literal_too_large)
4145 << Literal.isUnsigned;
4146 else
4147 Diag(Tok.getLocation(),
4148 diag::ext_integer_literal_too_large_for_signed);
4149 Ty = Context.UnsignedLongLongTy;
4150 Width = Context.getTargetInfo().getLongLongWidth();
4151 }
4152
4153 if (ResultVal.getBitWidth() != Width)
4154 ResultVal = ResultVal.trunc(Width);
4155 }
4156 Res = IntegerLiteral::Create(Context, ResultVal, Ty, Tok.getLocation());
4157 }
4158
4159 // If this is an imaginary literal, create the ImaginaryLiteral wrapper.
4160 if (Literal.isImaginary) {
4161 Res = new (Context) ImaginaryLiteral(Res,
4162 Context.getComplexType(Res->getType()));
4163
4164 Diag(Tok.getLocation(), diag::ext_imaginary_constant);
4165 }
4166 return Res;
4167}
4168
4169ExprResult Sema::ActOnParenExpr(SourceLocation L, SourceLocation R, Expr *E) {
4170 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", 4170, __extension__ __PRETTY_FUNCTION__
))
;
4171 QualType ExprTy = E->getType();
4172 if (getLangOpts().ProtectParens && CurFPFeatures.getAllowFPReassociate() &&
4173 !E->isLValue() && ExprTy->hasFloatingRepresentation())
4174 return BuildBuiltinCallExpr(R, Builtin::BI__arithmetic_fence, E);
4175 return new (Context) ParenExpr(L, R, E);
4176}
4177
4178static bool CheckVecStepTraitOperandType(Sema &S, QualType T,
4179 SourceLocation Loc,
4180 SourceRange ArgRange) {
4181 // [OpenCL 1.1 6.11.12] "The vec_step built-in function takes a built-in
4182 // scalar or vector data type argument..."
4183 // Every built-in scalar type (OpenCL 1.1 6.1.1) is either an arithmetic
4184 // type (C99 6.2.5p18) or void.
4185 if (!(T->isArithmeticType() || T->isVoidType() || T->isVectorType())) {
4186 S.Diag(Loc, diag::err_vecstep_non_scalar_vector_type)
4187 << T << ArgRange;
4188 return true;
4189 }
4190
4191 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", 4192, __extension__ __PRETTY_FUNCTION__
))
4192 "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", 4192, __extension__ __PRETTY_FUNCTION__
))
;
4193 return false;
4194}
4195
4196static bool CheckExtensionTraitOperandType(Sema &S, QualType T,
4197 SourceLocation Loc,
4198 SourceRange ArgRange,
4199 UnaryExprOrTypeTrait TraitKind) {
4200 // Invalid types must be hard errors for SFINAE in C++.
4201 if (S.LangOpts.CPlusPlus)
4202 return true;
4203
4204 // C99 6.5.3.4p1:
4205 if (T->isFunctionType() &&
4206 (TraitKind == UETT_SizeOf || TraitKind == UETT_AlignOf ||
4207 TraitKind == UETT_PreferredAlignOf)) {
4208 // sizeof(function)/alignof(function) is allowed as an extension.
4209 S.Diag(Loc, diag::ext_sizeof_alignof_function_type)
4210 << getTraitSpelling(TraitKind) << ArgRange;
4211 return false;
4212 }
4213
4214 // Allow sizeof(void)/alignof(void) as an extension, unless in OpenCL where
4215 // this is an error (OpenCL v1.1 s6.3.k)
4216 if (T->isVoidType()) {
4217 unsigned DiagID = S.LangOpts.OpenCL ? diag::err_opencl_sizeof_alignof_type
4218 : diag::ext_sizeof_alignof_void_type;
4219 S.Diag(Loc, DiagID) << getTraitSpelling(TraitKind) << ArgRange;
4220 return false;
4221 }
4222
4223 return true;
4224}
4225
4226static bool CheckObjCTraitOperandConstraints(Sema &S, QualType T,
4227 SourceLocation Loc,
4228 SourceRange ArgRange,
4229 UnaryExprOrTypeTrait TraitKind) {
4230 // Reject sizeof(interface) and sizeof(interface<proto>) if the
4231 // runtime doesn't allow it.
4232 if (!S.LangOpts.ObjCRuntime.allowsSizeofAlignof() && T->isObjCObjectType()) {
4233 S.Diag(Loc, diag::err_sizeof_nonfragile_interface)
4234 << T << (TraitKind == UETT_SizeOf)
4235 << ArgRange;
4236 return true;
4237 }
4238
4239 return false;
4240}
4241
4242/// Check whether E is a pointer from a decayed array type (the decayed
4243/// pointer type is equal to T) and emit a warning if it is.
4244static void warnOnSizeofOnArrayDecay(Sema &S, SourceLocation Loc, QualType T,
4245 Expr *E) {
4246 // Don't warn if the operation changed the type.
4247 if (T != E->getType())
4248 return;
4249
4250 // Now look for array decays.
4251 ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E);
4252 if (!ICE || ICE->getCastKind() != CK_ArrayToPointerDecay)
4253 return;
4254
4255 S.Diag(Loc, diag::warn_sizeof_array_decay) << ICE->getSourceRange()
4256 << ICE->getType()
4257 << ICE->getSubExpr()->getType();
4258}
4259
4260/// Check the constraints on expression operands to unary type expression
4261/// and type traits.
4262///
4263/// Completes any types necessary and validates the constraints on the operand
4264/// expression. The logic mostly mirrors the type-based overload, but may modify
4265/// the expression as it completes the type for that expression through template
4266/// instantiation, etc.
4267bool Sema::CheckUnaryExprOrTypeTraitOperand(Expr *E,
4268 UnaryExprOrTypeTrait ExprKind) {
4269 QualType ExprTy = E->getType();
4270 assert(!ExprTy->isReferenceType())(static_cast <bool> (!ExprTy->isReferenceType()) ? void
(0) : __assert_fail ("!ExprTy->isReferenceType()", "clang/lib/Sema/SemaExpr.cpp"
, 4270, __extension__ __PRETTY_FUNCTION__))
;
4271
4272 bool IsUnevaluatedOperand =
4273 (ExprKind == UETT_SizeOf || ExprKind == UETT_AlignOf ||
4274 ExprKind == UETT_PreferredAlignOf || ExprKind == UETT_VecStep);
4275 if (IsUnevaluatedOperand) {
4276 ExprResult Result = CheckUnevaluatedOperand(E);
4277 if (Result.isInvalid())
4278 return true;
4279 E = Result.get();
4280 }
4281
4282 // The operand for sizeof and alignof is in an unevaluated expression context,
4283 // so side effects could result in unintended consequences.
4284 // Exclude instantiation-dependent expressions, because 'sizeof' is sometimes
4285 // used to build SFINAE gadgets.
4286 // FIXME: Should we consider instantiation-dependent operands to 'alignof'?
4287 if (IsUnevaluatedOperand && !inTemplateInstantiation() &&
4288 !E->isInstantiationDependent() &&
4289 !E->getType()->isVariableArrayType() &&
4290 E->HasSideEffects(Context, false))
4291 Diag(E->getExprLoc(), diag::warn_side_effects_unevaluated_context);
4292
4293 if (ExprKind == UETT_VecStep)
4294 return CheckVecStepTraitOperandType(*this, ExprTy, E->getExprLoc(),
4295 E->getSourceRange());
4296
4297 // Explicitly list some types as extensions.
4298 if (!CheckExtensionTraitOperandType(*this, ExprTy, E->getExprLoc(),
4299 E->getSourceRange(), ExprKind))
4300 return false;
4301
4302 // 'alignof' applied to an expression only requires the base element type of
4303 // the expression to be complete. 'sizeof' requires the expression's type to
4304 // be complete (and will attempt to complete it if it's an array of unknown
4305 // bound).
4306 if (ExprKind == UETT_AlignOf || ExprKind == UETT_PreferredAlignOf) {
4307 if (RequireCompleteSizedType(
4308 E->getExprLoc(), Context.getBaseElementType(E->getType()),
4309 diag::err_sizeof_alignof_incomplete_or_sizeless_type,
4310 getTraitSpelling(ExprKind), E->getSourceRange()))
4311 return true;
4312 } else {
4313 if (RequireCompleteSizedExprType(
4314 E, diag::err_sizeof_alignof_incomplete_or_sizeless_type,
4315 getTraitSpelling(ExprKind), E->getSourceRange()))
4316 return true;
4317 }
4318
4319 // Completing the expression's type may have changed it.
4320 ExprTy = E->getType();
4321 assert(!ExprTy->isReferenceType())(static_cast <bool> (!ExprTy->isReferenceType()) ? void
(0) : __assert_fail ("!ExprTy->isReferenceType()", "clang/lib/Sema/SemaExpr.cpp"
, 4321, __extension__ __PRETTY_FUNCTION__))
;
4322
4323 if (ExprTy->isFunctionType()) {
4324 Diag(E->getExprLoc(), diag::err_sizeof_alignof_function_type)
4325 << getTraitSpelling(ExprKind) << E->getSourceRange();
4326 return true;
4327 }
4328
4329 if (CheckObjCTraitOperandConstraints(*this, ExprTy, E->getExprLoc(),
4330 E->getSourceRange(), ExprKind))
4331 return true;
4332
4333 if (ExprKind == UETT_SizeOf) {
4334 if (DeclRefExpr *DeclRef = dyn_cast<DeclRefExpr>(E->IgnoreParens())) {
4335 if (ParmVarDecl *PVD = dyn_cast<ParmVarDecl>(DeclRef->getFoundDecl())) {
4336 QualType OType = PVD->getOriginalType();
4337 QualType Type = PVD->getType();
4338 if (Type->isPointerType() && OType->isArrayType()) {
4339 Diag(E->getExprLoc(), diag::warn_sizeof_array_param)
4340 << Type << OType;
4341 Diag(PVD->getLocation(), diag::note_declared_at);
4342 }
4343 }
4344 }
4345
4346 // Warn on "sizeof(array op x)" and "sizeof(x op array)", where the array
4347 // decays into a pointer and returns an unintended result. This is most
4348 // likely a typo for "sizeof(array) op x".
4349 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E->IgnoreParens())) {
4350 warnOnSizeofOnArrayDecay(*this, BO->getOperatorLoc(), BO->getType(),
4351 BO->getLHS());
4352 warnOnSizeofOnArrayDecay(*this, BO->getOperatorLoc(), BO->getType(),
4353 BO->getRHS());
4354 }
4355 }
4356
4357 return false;
4358}
4359
4360/// Check the constraints on operands to unary expression and type
4361/// traits.
4362///
4363/// This will complete any types necessary, and validate the various constraints
4364/// on those operands.
4365///
4366/// The UsualUnaryConversions() function is *not* called by this routine.
4367/// C99 6.3.2.1p[2-4] all state:
4368/// Except when it is the operand of the sizeof operator ...
4369///
4370/// C++ [expr.sizeof]p4
4371/// The lvalue-to-rvalue, array-to-pointer, and function-to-pointer
4372/// standard conversions are not applied to the operand of sizeof.
4373///
4374/// This policy is followed for all of the unary trait expressions.
4375bool Sema::CheckUnaryExprOrTypeTraitOperand(QualType ExprType,
4376 SourceLocation OpLoc,
4377 SourceRange ExprRange,
4378 UnaryExprOrTypeTrait ExprKind) {
4379 if (ExprType->isDependentType())
4380 return false;
4381
4382 // C++ [expr.sizeof]p2:
4383 // When applied to a reference or a reference type, the result
4384 // is the size of the referenced type.
4385 // C++11 [expr.alignof]p3:
4386 // When alignof is applied to a reference type, the result
4387 // shall be the alignment of the referenced type.
4388 if (const ReferenceType *Ref = ExprType->getAs<ReferenceType>())
4389 ExprType = Ref->getPointeeType();
4390
4391 // C11 6.5.3.4/3, C++11 [expr.alignof]p3:
4392 // When alignof or _Alignof is applied to an array type, the result
4393 // is the alignment of the element type.
4394 if (ExprKind == UETT_AlignOf || ExprKind == UETT_PreferredAlignOf ||
4395 ExprKind == UETT_OpenMPRequiredSimdAlign)
4396 ExprType = Context.getBaseElementType(ExprType);
4397
4398 if (ExprKind == UETT_VecStep)
4399 return CheckVecStepTraitOperandType(*this, ExprType, OpLoc, ExprRange);
4400
4401 // Explicitly list some types as extensions.
4402 if (!CheckExtensionTraitOperandType(*this, ExprType, OpLoc, ExprRange,
4403 ExprKind))
4404 return false;
4405
4406 if (RequireCompleteSizedType(
4407 OpLoc, ExprType, diag::err_sizeof_alignof_incomplete_or_sizeless_type,
4408 getTraitSpelling(ExprKind), ExprRange))
4409 return true;
4410
4411 if (ExprType->isFunctionType()) {
4412 Diag(OpLoc, diag::err_sizeof_alignof_function_type)
4413 << getTraitSpelling(ExprKind) << ExprRange;
4414 return true;
4415 }
4416
4417 if (CheckObjCTraitOperandConstraints(*this, ExprType, OpLoc, ExprRange,
4418 ExprKind))
4419 return true;
4420
4421 return false;
4422}
4423
4424static bool CheckAlignOfExpr(Sema &S, Expr *E, UnaryExprOrTypeTrait ExprKind) {
4425 // Cannot know anything else if the expression is dependent.
4426 if (E->isTypeDependent())
4427 return false;
4428
4429 if (E->getObjectKind() == OK_BitField) {
4430 S.Diag(E->getExprLoc(), diag::err_sizeof_alignof_typeof_bitfield)
4431 << 1 << E->getSourceRange();
4432 return true;
4433 }
4434
4435 ValueDecl *D = nullptr;
4436 Expr *Inner = E->IgnoreParens();
4437 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Inner)) {
4438 D = DRE->getDecl();
4439 } else if (MemberExpr *ME = dyn_cast<MemberExpr>(Inner)) {
4440 D = ME->getMemberDecl();
4441 }
4442
4443 // If it's a field, require the containing struct to have a
4444 // complete definition so that we can compute the layout.
4445 //
4446 // This can happen in C++11 onwards, either by naming the member
4447 // in a way that is not transformed into a member access expression
4448 // (in an unevaluated operand, for instance), or by naming the member
4449 // in a trailing-return-type.
4450 //
4451 // For the record, since __alignof__ on expressions is a GCC
4452 // extension, GCC seems to permit this but always gives the
4453 // nonsensical answer 0.
4454 //
4455 // We don't really need the layout here --- we could instead just
4456 // directly check for all the appropriate alignment-lowing
4457 // attributes --- but that would require duplicating a lot of
4458 // logic that just isn't worth duplicating for such a marginal
4459 // use-case.
4460 if (FieldDecl *FD = dyn_cast_or_null<FieldDecl>(D)) {
4461 // Fast path this check, since we at least know the record has a
4462 // definition if we can find a member of it.
4463 if (!FD->getParent()->isCompleteDefinition()) {
4464 S.Diag(E->getExprLoc(), diag::err_alignof_member_of_incomplete_type)
4465 << E->getSourceRange();
4466 return true;
4467 }
4468
4469 // Otherwise, if it's a field, and the field doesn't have
4470 // reference type, then it must have a complete type (or be a
4471 // flexible array member, which we explicitly want to
4472 // white-list anyway), which makes the following checks trivial.
4473 if (!FD->getType()->isReferenceType())
4474 return false;
4475 }
4476
4477 return S.CheckUnaryExprOrTypeTraitOperand(E, ExprKind);
4478}
4479
4480bool Sema::CheckVecStepExpr(Expr *E) {
4481 E = E->IgnoreParens();
4482
4483 // Cannot know anything else if the expression is dependent.
4484 if (E->isTypeDependent())
4485 return false;
4486
4487 return CheckUnaryExprOrTypeTraitOperand(E, UETT_VecStep);
4488}
4489
4490static void captureVariablyModifiedType(ASTContext &Context, QualType T,
4491 CapturingScopeInfo *CSI) {
4492 assert(T->isVariablyModifiedType())(static_cast <bool> (T->isVariablyModifiedType()) ? void
(0) : __assert_fail ("T->isVariablyModifiedType()", "clang/lib/Sema/SemaExpr.cpp"
, 4492, __extension__ __PRETTY_FUNCTION__))
;
4493 assert(CSI != nullptr)(static_cast <bool> (CSI != nullptr) ? void (0) : __assert_fail
("CSI != nullptr", "clang/lib/Sema/SemaExpr.cpp", 4493, __extension__
__PRETTY_FUNCTION__))
;
4494
4495 // We're going to walk down into the type and look for VLA expressions.
4496 do {
4497 const Type *Ty = T.getTypePtr();
4498 switch (Ty->getTypeClass()) {
4499#define TYPE(Class, Base)
4500#define ABSTRACT_TYPE(Class, Base)
4501#define NON_CANONICAL_TYPE(Class, Base)
4502#define DEPENDENT_TYPE(Class, Base) case Type::Class:
4503#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base)
4504#include "clang/AST/TypeNodes.inc"
4505 T = QualType();
4506 break;
4507 // These types are never variably-modified.
4508 case Type::Builtin:
4509 case Type::Complex:
4510 case Type::Vector:
4511 case Type::ExtVector:
4512 case Type::ConstantMatrix:
4513 case Type::Record:
4514 case Type::Enum:
4515 case Type::TemplateSpecialization:
4516 case Type::ObjCObject:
4517 case Type::ObjCInterface:
4518 case Type::ObjCObjectPointer:
4519 case Type::ObjCTypeParam:
4520 case Type::Pipe:
4521 case Type::BitInt:
4522 llvm_unreachable("type class is never variably-modified!")::llvm::llvm_unreachable_internal("type class is never variably-modified!"
, "clang/lib/Sema/SemaExpr.cpp", 4522)
;
4523 case Type::Elaborated:
4524 T = cast<ElaboratedType>(Ty)->getNamedType();
4525 break;
4526 case Type::Adjusted:
4527 T = cast<AdjustedType>(Ty)->getOriginalType();
4528 break;
4529 case Type::Decayed:
4530 T = cast<DecayedType>(Ty)->getPointeeType();
4531 break;
4532 case Type::Pointer:
4533 T = cast<PointerType>(Ty)->getPointeeType();
4534 break;
4535 case Type::BlockPointer:
4536 T = cast<BlockPointerType>(Ty)->getPointeeType();
4537 break;
4538 case Type::LValueReference:
4539 case Type::RValueReference:
4540 T = cast<ReferenceType>(Ty)->getPointeeType();
4541 break;
4542 case Type::MemberPointer:
4543 T = cast<MemberPointerType>(Ty)->getPointeeType();
4544 break;
4545 case Type::ConstantArray:
4546 case Type::IncompleteArray:
4547 // Losing element qualification here is fine.
4548 T = cast<ArrayType>(Ty)->getElementType();
4549 break;
4550 case Type::VariableArray: {
4551 // Losing element qualification here is fine.
4552 const VariableArrayType *VAT = cast<VariableArrayType>(Ty);
4553
4554 // Unknown size indication requires no size computation.
4555 // Otherwise, evaluate and record it.
4556 auto Size = VAT->getSizeExpr();
4557 if (Size && !CSI->isVLATypeCaptured(VAT) &&
4558 (isa<CapturedRegionScopeInfo>(CSI) || isa<LambdaScopeInfo>(CSI)))
4559 CSI->addVLATypeCapture(Size->getExprLoc(), VAT, Context.getSizeType());
4560
4561 T = VAT->getElementType();
4562 break;
4563 }
4564 case Type::FunctionProto:
4565 case Type::FunctionNoProto:
4566 T = cast<FunctionType>(Ty)->getReturnType();
4567 break;
4568 case Type::Paren:
4569 case Type::TypeOf:
4570 case Type::UnaryTransform:
4571 case Type::Attributed:
4572 case Type::BTFTagAttributed:
4573 case Type::SubstTemplateTypeParm:
4574 case Type::MacroQualified:
4575 // Keep walking after single level desugaring.
4576 T = T.getSingleStepDesugaredType(Context);
4577 break;
4578 case Type::Typedef:
4579 T = cast<TypedefType>(Ty)->desugar();
4580 break;
4581 case Type::Decltype:
4582 T = cast<DecltypeType>(Ty)->desugar();
4583 break;
4584 case Type::Using:
4585 T = cast<UsingType>(Ty)->desugar();
4586 break;
4587 case Type::Auto:
4588 case Type::DeducedTemplateSpecialization:
4589 T = cast<DeducedType>(Ty)->getDeducedType();
4590 break;
4591 case Type::TypeOfExpr:
4592 T = cast<TypeOfExprType>(Ty)->getUnderlyingExpr()->getType();
4593 break;
4594 case Type::Atomic:
4595 T = cast<AtomicType>(Ty)->getValueType();
4596 break;
4597 }
4598 } while (!T.isNull() && T->isVariablyModifiedType());
4599}
4600
4601/// Build a sizeof or alignof expression given a type operand.
4602ExprResult
4603Sema::CreateUnaryExprOrTypeTraitExpr(TypeSourceInfo *TInfo,
4604 SourceLocation OpLoc,
4605 UnaryExprOrTypeTrait ExprKind,
4606 SourceRange R) {
4607 if (!TInfo)
4608 return ExprError();
4609
4610 QualType T = TInfo->getType();
4611
4612 if (!T->isDependentType() &&
4613 CheckUnaryExprOrTypeTraitOperand(T, OpLoc, R, ExprKind))
4614 return ExprError();
4615
4616 if (T->isVariablyModifiedType() && FunctionScopes.size() > 1) {
4617 if (auto *TT = T->getAs<TypedefType>()) {
4618 for (auto I = FunctionScopes.rbegin(),
4619 E = std::prev(FunctionScopes.rend());
4620 I != E; ++I) {
4621 auto *CSI = dyn_cast<CapturingScopeInfo>(*I);
4622 if (CSI == nullptr)
4623 break;
4624 DeclContext *DC = nullptr;
4625 if (auto *LSI = dyn_cast<LambdaScopeInfo>(CSI))
4626 DC = LSI->CallOperator;
4627 else if (auto *CRSI = dyn_cast<CapturedRegionScopeInfo>(CSI))
4628 DC = CRSI->TheCapturedDecl;
4629 else if (auto *BSI = dyn_cast<BlockScopeInfo>(CSI))
4630 DC = BSI->TheDecl;
4631 if (DC) {
4632 if (DC->containsDecl(TT->getDecl()))
4633 break;
4634 captureVariablyModifiedType(Context, T, CSI);
4635 }
4636 }
4637 }
4638 }
4639
4640 // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t.
4641 if (isUnevaluatedContext() && ExprKind == UETT_SizeOf &&
4642 TInfo->getType()->isVariablyModifiedType())
4643 TInfo = TransformToPotentiallyEvaluated(TInfo);
4644
4645 return new (Context) UnaryExprOrTypeTraitExpr(
4646 ExprKind, TInfo, Context.getSizeType(), OpLoc, R.getEnd());
4647}
4648
4649/// Build a sizeof or alignof expression given an expression
4650/// operand.
4651ExprResult
4652Sema::CreateUnaryExprOrTypeTraitExpr(Expr *E, SourceLocation OpLoc,
4653 UnaryExprOrTypeTrait ExprKind) {
4654 ExprResult PE = CheckPlaceholderExpr(E);
4655 if (PE.isInvalid())
4656 return ExprError();
4657
4658 E = PE.get();
4659
4660 // Verify that the operand is valid.
4661 bool isInvalid = false;
4662 if (E->isTypeDependent()) {
4663 // Delay type-checking for type-dependent expressions.
4664 } else if (ExprKind == UETT_AlignOf || ExprKind == UETT_PreferredAlignOf) {
4665 isInvalid = CheckAlignOfExpr(*this, E, ExprKind);
4666 } else if (ExprKind == UETT_VecStep) {
4667 isInvalid = CheckVecStepExpr(E);
4668 } else if (ExprKind == UETT_OpenMPRequiredSimdAlign) {
4669 Diag(E->getExprLoc(), diag::err_openmp_default_simd_align_expr);
4670 isInvalid = true;
4671 } else if (E->refersToBitField()) { // C99 6.5.3.4p1.
4672 Diag(E->getExprLoc(), diag::err_sizeof_alignof_typeof_bitfield) << 0;
4673 isInvalid = true;
4674 } else {
4675 isInvalid = CheckUnaryExprOrTypeTraitOperand(E, UETT_SizeOf);
4676 }
4677
4678 if (isInvalid)
4679 return ExprError();
4680
4681 if (ExprKind == UETT_SizeOf && E->getType()->isVariableArrayType()) {
4682 PE = TransformToPotentiallyEvaluated(E);
4683 if (PE.isInvalid()) return ExprError();
4684 E = PE.get();
4685 }
4686
4687 // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t.
4688 return new (Context) UnaryExprOrTypeTraitExpr(
4689 ExprKind, E, Context.getSizeType(), OpLoc, E->getSourceRange().getEnd());
4690}
4691
4692/// ActOnUnaryExprOrTypeTraitExpr - Handle @c sizeof(type) and @c sizeof @c
4693/// expr and the same for @c alignof and @c __alignof
4694/// Note that the ArgRange is invalid if isType is false.
4695ExprResult
4696Sema::ActOnUnaryExprOrTypeTraitExpr(SourceLocation OpLoc,
4697 UnaryExprOrTypeTrait ExprKind, bool IsType,
4698 void *TyOrEx, SourceRange ArgRange) {
4699 // If error parsing type, ignore.
4700 if (!TyOrEx) return ExprError();
4701
4702 if (IsType) {
4703 TypeSourceInfo *TInfo;
4704 (void) GetTypeFromParser(ParsedType::getFromOpaquePtr(TyOrEx), &TInfo);
4705 return CreateUnaryExprOrTypeTraitExpr(TInfo, OpLoc, ExprKind, ArgRange);
4706 }
4707
4708 Expr *ArgEx = (Expr *)TyOrEx;
4709 ExprResult Result = CreateUnaryExprOrTypeTraitExpr(ArgEx, OpLoc, ExprKind);
4710 return Result;
4711}
4712
4713static QualType CheckRealImagOperand(Sema &S, ExprResult &V, SourceLocation Loc,
4714 bool IsReal) {
4715 if (V.get()->isTypeDependent())
4716 return S.Context.DependentTy;
4717
4718 // _Real and _Imag are only l-values for normal l-values.
4719 if (V.get()->getObjectKind() != OK_Ordinary) {
4720 V = S.DefaultLvalueConversion(V.get());
4721 if (V.isInvalid())
4722 return QualType();
4723 }
4724
4725 // These operators return the element type of a complex type.
4726 if (const ComplexType *CT = V.get()->getType()->getAs<ComplexType>())
4727 return CT->getElementType();
4728
4729 // Otherwise they pass through real integer and floating point types here.
4730 if (V.get()->getType()->isArithmeticType())
4731 return V.get()->getType();
4732
4733 // Test for placeholders.
4734 ExprResult PR = S.CheckPlaceholderExpr(V.get());
4735 if (PR.isInvalid()) return QualType();
4736 if (PR.get() != V.get()) {
4737 V = PR;
4738 return CheckRealImagOperand(S, V, Loc, IsReal);
4739 }
4740
4741 // Reject anything else.
4742 S.Diag(Loc, diag::err_realimag_invalid_type) << V.get()->getType()
4743 << (IsReal ? "__real" : "__imag");
4744 return QualType();
4745}
4746
4747
4748
4749ExprResult
4750Sema::ActOnPostfixUnaryOp(Scope *S, SourceLocation OpLoc,
4751 tok::TokenKind Kind, Expr *Input) {
4752 UnaryOperatorKind Opc;
4753 switch (Kind) {
4754 default: llvm_unreachable("Unknown unary op!")::llvm::llvm_unreachable_internal("Unknown unary op!", "clang/lib/Sema/SemaExpr.cpp"
, 4754)
;
4755 case tok::plusplus: Opc = UO_PostInc; break;
4756 case tok::minusminus: Opc = UO_PostDec; break;
4757 }
4758
4759 // Since this might is a postfix expression, get rid of ParenListExprs.
4760 ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Input);
4761 if (Result.isInvalid()) return ExprError();
4762 Input = Result.get();
4763
4764 return BuildUnaryOp(S, OpLoc, Opc, Input);
4765}
4766
4767/// Diagnose if arithmetic on the given ObjC pointer is illegal.
4768///
4769/// \return true on error
4770static bool checkArithmeticOnObjCPointer(Sema &S,
4771 SourceLocation opLoc,
4772 Expr *op) {
4773 assert(op->getType()->isObjCObjectPointerType())(static_cast <bool> (op->getType()->isObjCObjectPointerType
()) ? void (0) : __assert_fail ("op->getType()->isObjCObjectPointerType()"
, "clang/lib/Sema/SemaExpr.cpp", 4773, __extension__ __PRETTY_FUNCTION__
))
;
4774 if (S.LangOpts.ObjCRuntime.allowsPointerArithmetic() &&
4775 !S.LangOpts.ObjCSubscriptingLegacyRuntime)
4776 return false;
4777
4778 S.Diag(opLoc, diag::err_arithmetic_nonfragile_interface)
4779 << op->getType()->castAs<ObjCObjectPointerType>()->getPointeeType()
4780 << op->getSourceRange();
4781 return true;
4782}
4783
4784static bool isMSPropertySubscriptExpr(Sema &S, Expr *Base) {
4785 auto *BaseNoParens = Base->IgnoreParens();
4786 if (auto *MSProp = dyn_cast<MSPropertyRefExpr>(BaseNoParens))
4787 return MSProp->getPropertyDecl()->getType()->isArrayType();
4788 return isa<MSPropertySubscriptExpr>(BaseNoParens);
4789}
4790
4791// Returns the type used for LHS[RHS], given one of LHS, RHS is type-dependent.
4792// Typically this is DependentTy, but can sometimes be more precise.
4793//
4794// There are cases when we could determine a non-dependent type:
4795// - LHS and RHS may have non-dependent types despite being type-dependent
4796// (e.g. unbounded array static members of the current instantiation)
4797// - one may be a dependent-sized array with known element type
4798// - one may be a dependent-typed valid index (enum in current instantiation)
4799//
4800// We *always* return a dependent type, in such cases it is DependentTy.
4801// This avoids creating type-dependent expressions with non-dependent types.
4802// FIXME: is this important to avoid? See https://reviews.llvm.org/D107275
4803static QualType getDependentArraySubscriptType(Expr *LHS, Expr *RHS,
4804 const ASTContext &Ctx) {
4805 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", 4805, __extension__ __PRETTY_FUNCTION__
))
;
4806 QualType LTy = LHS->getType(), RTy = RHS->getType();
4807 QualType Result = Ctx.DependentTy;
4808 if (RTy->isIntegralOrUnscopedEnumerationType()) {
4809 if (const PointerType *PT = LTy->getAs<PointerType>())
4810 Result = PT->getPointeeType();
4811 else if (const ArrayType *AT = LTy->getAsArrayTypeUnsafe())
4812 Result = AT->getElementType();
4813 } else if (LTy->isIntegralOrUnscopedEnumerationType()) {
4814 if (const PointerType *PT = RTy->getAs<PointerType>())
4815 Result = PT->getPointeeType();
4816 else if (const ArrayType *AT = RTy->getAsArrayTypeUnsafe())
4817 Result = AT->getElementType();
4818 }
4819 // Ensure we return a dependent type.
4820 return Result->isDependentType() ? Result : Ctx.DependentTy;
4821}
4822
4823static bool checkArgsForPlaceholders(Sema &S, MultiExprArg args);
4824
4825ExprResult Sema::ActOnArraySubscriptExpr(Scope *S, Expr *base,
4826 SourceLocation lbLoc,
4827 MultiExprArg ArgExprs,
4828 SourceLocation rbLoc) {
4829
4830 if (base && !base->getType().isNull() &&
4831 base->hasPlaceholderType(BuiltinType::OMPArraySection))
4832 return ActOnOMPArraySectionExpr(base, lbLoc, ArgExprs.front(), SourceLocation(),
4833 SourceLocation(), /*Length*/ nullptr,
4834 /*Stride=*/nullptr, rbLoc);
4835
4836 // Since this might be a postfix expression, get rid of ParenListExprs.
4837 if (isa<ParenListExpr>(base)) {
4838 ExprResult result = MaybeConvertParenListExprToParenExpr(S, base);
4839 if (result.isInvalid())
4840 return ExprError();
4841 base = result.get();
4842 }
4843
4844 // Check if base and idx form a MatrixSubscriptExpr.
4845 //
4846 // Helper to check for comma expressions, which are not allowed as indices for
4847 // matrix subscript expressions.
4848 auto CheckAndReportCommaError = [this, base, rbLoc](Expr *E) {
4849 if (isa<BinaryOperator>(E) && cast<BinaryOperator>(E)->isCommaOp()) {
4850 Diag(E->getExprLoc(), diag::err_matrix_subscript_comma)
4851 << SourceRange(base->getBeginLoc(), rbLoc);
4852 return true;
4853 }
4854 return false;
4855 };
4856 // The matrix subscript operator ([][])is considered a single operator.
4857 // Separating the index expressions by parenthesis is not allowed.
4858 if (base->hasPlaceholderType(BuiltinType::IncompleteMatrixIdx) &&
4859 !isa<MatrixSubscriptExpr>(base)) {
4860 Diag(base->getExprLoc(), diag::err_matrix_separate_incomplete_index)
4861 << SourceRange(base->getBeginLoc(), rbLoc);
4862 return ExprError();
4863 }
4864 // If the base is a MatrixSubscriptExpr, try to create a new
4865 // MatrixSubscriptExpr.
4866 auto *matSubscriptE = dyn_cast<MatrixSubscriptExpr>(base);
4867 if (matSubscriptE) {
4868 assert(ArgExprs.size() == 1)(static_cast <bool> (ArgExprs.size() == 1) ? void (0) :
__assert_fail ("ArgExprs.size() == 1", "clang/lib/Sema/SemaExpr.cpp"
, 4868, __extension__ __PRETTY_FUNCTION__))
;
4869 if (CheckAndReportCommaError(ArgExprs.front()))
4870 return ExprError();
4871
4872 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", 4873, __extension__ __PRETTY_FUNCTION__
))
4873 "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", 4873, __extension__ __PRETTY_FUNCTION__
))
;
4874 return CreateBuiltinMatrixSubscriptExpr(matSubscriptE->getBase(),
4875 matSubscriptE->getRowIdx(),
4876 ArgExprs.front(), rbLoc);
4877 }
4878
4879 // Handle any non-overload placeholder types in the base and index
4880 // expressions. We can't handle overloads here because the other
4881 // operand might be an overloadable type, in which case the overload
4882 // resolution for the operator overload should get the first crack
4883 // at the overload.
4884 bool IsMSPropertySubscript = false;
4885 if (base->getType()->isNonOverloadPlaceholderType()) {
4886 IsMSPropertySubscript = isMSPropertySubscriptExpr(*this, base);
4887 if (!IsMSPropertySubscript) {
4888 ExprResult result = CheckPlaceholderExpr(base);
4889 if (result.isInvalid())
4890 return ExprError();
4891 base = result.get();
4892 }
4893 }
4894
4895 // If the base is a matrix type, try to create a new MatrixSubscriptExpr.
4896 if (base->getType()->isMatrixType()) {
4897 assert(ArgExprs.size() == 1)(static_cast <bool> (ArgExprs.size() == 1) ? void (0) :
__assert_fail ("ArgExprs.size() == 1", "clang/lib/Sema/SemaExpr.cpp"
, 4897, __extension__ __PRETTY_FUNCTION__))
;
4898 if (CheckAndReportCommaError(ArgExprs.front()))
4899 return ExprError();
4900
4901 return CreateBuiltinMatrixSubscriptExpr(base, ArgExprs.front(), nullptr,
4902 rbLoc);
4903 }
4904
4905 if (ArgExprs.size() == 1 && getLangOpts().CPlusPlus20) {
4906 Expr *idx = ArgExprs[0];
4907 if ((isa<BinaryOperator>(idx) && cast<BinaryOperator>(idx)->isCommaOp()) ||
4908 (isa<CXXOperatorCallExpr>(idx) &&
4909 cast<CXXOperatorCallExpr>(idx)->getOperator() == OO_Comma)) {
4910 Diag(idx->getExprLoc(), diag::warn_deprecated_comma_subscript)
4911 << SourceRange(base->getBeginLoc(), rbLoc);
4912 }
4913 }
4914
4915 if (ArgExprs.size() == 1 &&
4916 ArgExprs[0]->getType()->isNonOverloadPlaceholderType()) {
4917 ExprResult result = CheckPlaceholderExpr(ArgExprs[0]);
4918 if (result.isInvalid())
4919 return ExprError();
4920 ArgExprs[0] = result.get();
4921 } else {
4922 if (checkArgsForPlaceholders(*this, ArgExprs))
4923 return ExprError();
4924 }
4925
4926 // Build an unanalyzed expression if either operand is type-dependent.
4927 if (getLangOpts().CPlusPlus && ArgExprs.size() == 1 &&
4928 (base->isTypeDependent() ||
4929 Expr::hasAnyTypeDependentArguments(ArgExprs))) {
4930 return new (Context) ArraySubscriptExpr(
4931 base, ArgExprs.front(),
4932 getDependentArraySubscriptType(base, ArgExprs.front(), getASTContext()),
4933 VK_LValue, OK_Ordinary, rbLoc);
4934 }
4935
4936 // MSDN, property (C++)
4937 // https://msdn.microsoft.com/en-us/library/yhfk0thd(v=vs.120).aspx
4938 // This attribute can also be used in the declaration of an empty array in a
4939 // class or structure definition. For example:
4940 // __declspec(property(get=GetX, put=PutX)) int x[];
4941 // The above statement indicates that x[] can be used with one or more array
4942 // indices. In this case, i=p->x[a][b] will be turned into i=p->GetX(a, b),
4943 // and p->x[a][b] = i will be turned into p->PutX(a, b, i);
4944 if (IsMSPropertySubscript) {
4945 assert(ArgExprs.size() == 1)(static_cast <bool> (ArgExprs.size() == 1) ? void (0) :
__assert_fail ("ArgExprs.size() == 1", "clang/lib/Sema/SemaExpr.cpp"
, 4945, __extension__ __PRETTY_FUNCTION__))
;
4946 // Build MS property subscript expression if base is MS property reference
4947 // or MS property subscript.
4948 return new (Context)
4949 MSPropertySubscriptExpr(base, ArgExprs.front(), Context.PseudoObjectTy,
4950 VK_LValue, OK_Ordinary, rbLoc);
4951 }
4952
4953 // Use C++ overloaded-operator rules if either operand has record
4954 // type. The spec says to do this if either type is *overloadable*,
4955 // but enum types can't declare subscript operators or conversion
4956 // operators, so there's nothing interesting for overload resolution
4957 // to do if there aren't any record types involved.
4958 //
4959 // ObjC pointers have their own subscripting logic that is not tied
4960 // to overload resolution and so should not take this path.
4961 if (getLangOpts().CPlusPlus && !base->getType()->isObjCObjectPointerType() &&
4962 ((base->getType()->isRecordType() ||
4963 (ArgExprs.size() != 1 || ArgExprs[0]->getType()->isRecordType())))) {
4964 return CreateOverloadedArraySubscriptExpr(lbLoc, rbLoc, base, ArgExprs);
4965 }
4966
4967 ExprResult Res =
4968 CreateBuiltinArraySubscriptExpr(base, lbLoc, ArgExprs.front(), rbLoc);
4969
4970 if (!Res.isInvalid() && isa<ArraySubscriptExpr>(Res.get()))
4971 CheckSubscriptAccessOfNoDeref(cast<ArraySubscriptExpr>(Res.get()));
4972
4973 return Res;
4974}
4975
4976ExprResult Sema::tryConvertExprToType(Expr *E, QualType Ty) {
4977 InitializedEntity Entity = InitializedEntity::InitializeTemporary(Ty);
4978 InitializationKind Kind =
4979 InitializationKind::CreateCopy(E->getBeginLoc(), SourceLocation());
4980 InitializationSequence InitSeq(*this, Entity, Kind, E);
4981 return InitSeq.Perform(*this, Entity, Kind, E);
4982}
4983
4984ExprResult Sema::CreateBuiltinMatrixSubscriptExpr(Expr *Base, Expr *RowIdx,
4985 Expr *ColumnIdx,
4986 SourceLocation RBLoc) {
4987 ExprResult BaseR = CheckPlaceholderExpr(Base);
4988 if (BaseR.isInvalid())
4989 return BaseR;
4990 Base = BaseR.get();
4991
4992 ExprResult RowR = CheckPlaceholderExpr(RowIdx);
4993 if (RowR.isInvalid())
4994 return RowR;
4995 RowIdx = RowR.get();
4996
4997 if (!ColumnIdx)
4998 return new (Context) MatrixSubscriptExpr(
4999 Base, RowIdx, ColumnIdx, Context.IncompleteMatrixIdxTy, RBLoc);
5000
5001 // Build an unanalyzed expression if any of the operands is type-dependent.
5002 if (Base->isTypeDependent() || RowIdx->isTypeDependent() ||
5003 ColumnIdx->isTypeDependent())
5004 return new (Context) MatrixSubscriptExpr(Base, RowIdx, ColumnIdx,
5005 Context.DependentTy, RBLoc);
5006
5007 ExprResult ColumnR = CheckPlaceholderExpr(ColumnIdx);
5008 if (ColumnR.isInvalid())
5009 return ColumnR;
5010 ColumnIdx = ColumnR.get();
5011
5012 // Check that IndexExpr is an integer expression. If it is a constant
5013 // expression, check that it is less than Dim (= the number of elements in the
5014 // corresponding dimension).
5015 auto IsIndexValid = [&](Expr *IndexExpr, unsigned Dim,
5016 bool IsColumnIdx) -> Expr * {
5017 if (!IndexExpr->getType()->isIntegerType() &&
5018 !IndexExpr->isTypeDependent()) {
5019 Diag(IndexExpr->getBeginLoc(), diag::err_matrix_index_not_integer)
5020 << IsColumnIdx;
5021 return nullptr;
5022 }
5023
5024 if (std::optional<llvm::APSInt> Idx =
5025 IndexExpr->getIntegerConstantExpr(Context)) {
5026 if ((*Idx < 0 || *Idx >= Dim)) {
5027 Diag(IndexExpr->getBeginLoc(), diag::err_matrix_index_outside_range)
5028 << IsColumnIdx << Dim;
5029 return nullptr;
5030 }
5031 }
5032
5033 ExprResult ConvExpr =
5034 tryConvertExprToType(IndexExpr, Context.getSizeType());
5035 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", 5036, __extension__ __PRETTY_FUNCTION__
))
5036 "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", 5036, __extension__ __PRETTY_FUNCTION__
))
;
5037 return ConvExpr.get();
5038 };
5039
5040 auto *MTy = Base->getType()->getAs<ConstantMatrixType>();
5041 RowIdx = IsIndexValid(RowIdx, MTy->getNumRows(), false);
5042 ColumnIdx = IsIndexValid(ColumnIdx, MTy->getNumColumns(), true);
5043 if (!RowIdx || !ColumnIdx)
5044 return ExprError();
5045
5046 return new (Context) MatrixSubscriptExpr(Base, RowIdx, ColumnIdx,
5047 MTy->getElementType(), RBLoc);
5048}
5049
5050void Sema::CheckAddressOfNoDeref(const Expr *E) {
5051 ExpressionEvaluationContextRecord &LastRecord = ExprEvalContexts.back();
5052 const Expr *StrippedExpr = E->IgnoreParenImpCasts();
5053
5054 // For expressions like `&(*s).b`, the base is recorded and what should be
5055 // checked.
5056 const MemberExpr *Member = nullptr;
5057 while ((Member = dyn_cast<MemberExpr>(StrippedExpr)) && !Member->isArrow())
5058 StrippedExpr = Member->getBase()->IgnoreParenImpCasts();
5059
5060 LastRecord.PossibleDerefs.erase(StrippedExpr);
5061}
5062
5063void Sema::CheckSubscriptAccessOfNoDeref(const ArraySubscriptExpr *E) {
5064 if (isUnevaluatedContext())
5065 return;
5066
5067 QualType ResultTy = E->getType();
5068 ExpressionEvaluationContextRecord &LastRecord = ExprEvalContexts.back();
5069
5070 // Bail if the element is an array since it is not memory access.
5071 if (isa<ArrayType>(ResultTy))
5072 return;
5073
5074 if (ResultTy->hasAttr(attr::NoDeref)) {
5075 LastRecord.PossibleDerefs.insert(E);
5076 return;
5077 }
5078
5079 // Check if the base type is a pointer to a member access of a struct
5080 // marked with noderef.
5081 const Expr *Base = E->getBase();
5082 QualType BaseTy = Base->getType();
5083 if (!(isa<ArrayType>(BaseTy) || isa<PointerType>(BaseTy)))
5084 // Not a pointer access
5085 return;
5086
5087 const MemberExpr *Member = nullptr;
5088 while ((Member = dyn_cast<MemberExpr>(Base->IgnoreParenCasts())) &&
5089 Member->isArrow())
5090 Base = Member->getBase();
5091
5092 if (const auto *Ptr = dyn_cast<PointerType>(Base->getType())) {
5093 if (Ptr->getPointeeType()->hasAttr(attr::NoDeref))
5094 LastRecord.PossibleDerefs.insert(E);
5095 }
5096}
5097
5098ExprResult Sema::ActOnOMPArraySectionExpr(Expr *Base, SourceLocation LBLoc,
5099 Expr *LowerBound,
5100 SourceLocation ColonLocFirst,
5101 SourceLocation ColonLocSecond,
5102 Expr *Length, Expr *Stride,
5103 SourceLocation RBLoc) {
5104 if (Base->hasPlaceholderType() &&
5105 !Base->hasPlaceholderType(BuiltinType::OMPArraySection)) {
5106 ExprResult Result = CheckPlaceholderExpr(Base);
5107 if (Result.isInvalid())
5108 return ExprError();
5109 Base = Result.get();
5110 }
5111 if (LowerBound && LowerBound->getType()->isNonOverloadPlaceholderType()) {
5112 ExprResult Result = CheckPlaceholderExpr(LowerBound);
5113 if (Result.isInvalid())
5114 return ExprError();
5115 Result = DefaultLvalueConversion(Result.get());
5116 if (Result.isInvalid())
5117 return ExprError();
5118 LowerBound = Result.get();
5119 }
5120 if (Length && Length->getType()->isNonOverloadPlaceholderType()) {
5121 ExprResult Result = CheckPlaceholderExpr(Length);
5122 if (Result.isInvalid())
5123 return ExprError();
5124 Result = DefaultLvalueConversion(Result.get());
5125 if (Result.isInvalid())
5126 return ExprError();
5127 Length = Result.get();
5128 }
5129 if (Stride && Stride->getType()->isNonOverloadPlaceholderType()) {
5130 ExprResult Result = CheckPlaceholderExpr(Stride);
5131 if (Result.isInvalid())
5132 return ExprError();
5133 Result = DefaultLvalueConversion(Result.get());
5134 if (Result.isInvalid())
5135 return ExprError();
5136 Stride = Result.get();
5137 }
5138
5139 // Build an unanalyzed expression if either operand is type-dependent.
5140 if (Base->isTypeDependent() ||
5141 (LowerBound &&
5142 (LowerBound->isTypeDependent() || LowerBound->isValueDependent())) ||
5143 (Length && (Length->isTypeDependent() || Length->isValueDependent())) ||
5144 (Stride && (Stride->isTypeDependent() || Stride->isValueDependent()))) {
5145 return new (Context) OMPArraySectionExpr(
5146 Base, LowerBound, Length, Stride, Context.DependentTy, VK_LValue,
5147 OK_Ordinary, ColonLocFirst, ColonLocSecond, RBLoc);
5148 }
5149
5150 // Perform default conversions.
5151 QualType OriginalTy = OMPArraySectionExpr::getBaseOriginalType(Base);
5152 QualType ResultTy;
5153 if (OriginalTy->isAnyPointerType()) {
5154 ResultTy = OriginalTy->getPointeeType();
5155 } else if (OriginalTy->isArrayType()) {
5156 ResultTy = OriginalTy->getAsArrayTypeUnsafe()->getElementType();
5157 } else {
5158 return ExprError(
5159 Diag(Base->getExprLoc(), diag::err_omp_typecheck_section_value)
5160 << Base->getSourceRange());
5161 }
5162 // C99 6.5.2.1p1
5163 if (LowerBound) {
5164 auto Res = PerformOpenMPImplicitIntegerConversion(LowerBound->getExprLoc(),
5165 LowerBound);
5166 if (Res.isInvalid())
5167 return ExprError(Diag(LowerBound->getExprLoc(),
5168 diag::err_omp_typecheck_section_not_integer)
5169 << 0 << LowerBound->getSourceRange());
5170 LowerBound = Res.get();
5171
5172 if (LowerBound->getType()->isSpecificBuiltinType(BuiltinType::Char_S) ||
5173 LowerBound->getType()->isSpecificBuiltinType(BuiltinType::Char_U))
5174 Diag(LowerBound->getExprLoc(), diag::warn_omp_section_is_char)
5175 << 0 << LowerBound->getSourceRange();
5176 }
5177 if (Length) {
5178 auto Res =
5179 PerformOpenMPImplicitIntegerConversion(Length->getExprLoc(), Length);
5180 if (Res.isInvalid())
5181 return ExprError(Diag(Length->getExprLoc(),
5182 diag::err_omp_typecheck_section_not_integer)
5183 << 1 << Length->getSourceRange());
5184 Length = Res.get();
5185
5186 if (Length->getType()->isSpecificBuiltinType(BuiltinType::Char_S) ||
5187 Length->getType()->isSpecificBuiltinType(BuiltinType::Char_U))
5188 Diag(Length->getExprLoc(), diag::warn_omp_section_is_char)
5189 << 1 << Length->getSourceRange();
5190 }
5191 if (Stride) {
5192 ExprResult Res =
5193 PerformOpenMPImplicitIntegerConversion(Stride->getExprLoc(), Stride);
5194 if (Res.isInvalid())
5195 return ExprError(Diag(Stride->getExprLoc(),
5196 diag::err_omp_typecheck_section_not_integer)
5197 << 1 << Stride->getSourceRange());
5198 Stride = Res.get();
5199
5200 if (Stride->getType()->isSpecificBuiltinType(BuiltinType::Char_S) ||
5201 Stride->getType()->isSpecificBuiltinType(BuiltinType::Char_U))
5202 Diag(Stride->getExprLoc(), diag::warn_omp_section_is_char)
5203 << 1 << Stride->getSourceRange();
5204 }
5205
5206 // C99 6.5.2.1p1: "shall have type "pointer to *object* type". Similarly,
5207 // C++ [expr.sub]p1: The type "T" shall be a completely-defined object
5208 // type. Note that functions are not objects, and that (in C99 parlance)
5209 // incomplete types are not object types.
5210 if (ResultTy->isFunctionType()) {
5211 Diag(Base->getExprLoc(), diag::err_omp_section_function_type)
5212 << ResultTy << Base->getSourceRange();
5213 return ExprError();
5214 }
5215
5216 if (RequireCompleteType(Base->getExprLoc(), ResultTy,
5217 diag::err_omp_section_incomplete_type, Base))
5218 return ExprError();
5219
5220 if (LowerBound && !OriginalTy->isAnyPointerType()) {
5221 Expr::EvalResult Result;
5222 if (LowerBound->EvaluateAsInt(Result, Context)) {
5223 // OpenMP 5.0, [2.1.5 Array Sections]
5224 // The array section must be a subset of the original array.
5225 llvm::APSInt LowerBoundValue = Result.Val.getInt();
5226 if (LowerBoundValue.isNegative()) {
5227 Diag(LowerBound->getExprLoc(), diag::err_omp_section_not_subset_of_array)
5228 << LowerBound->getSourceRange();
5229 return ExprError();
5230 }
5231 }
5232 }
5233
5234 if (Length) {
5235 Expr::EvalResult Result;
5236 if (Length->EvaluateAsInt(Result, Context)) {
5237 // OpenMP 5.0, [2.1.5 Array Sections]
5238 // The length must evaluate to non-negative integers.
5239 llvm::APSInt LengthValue = Result.Val.getInt();
5240 if (LengthValue.isNegative()) {
5241 Diag(Length->getExprLoc(), diag::err_omp_section_length_negative)
5242 << toString(LengthValue, /*Radix=*/10, /*Signed=*/true)
5243 << Length->getSourceRange();
5244 return ExprError();
5245 }
5246 }
5247 } else if (ColonLocFirst.isValid() &&
5248 (OriginalTy.isNull() || (!OriginalTy->isConstantArrayType() &&
5249 !OriginalTy->isVariableArrayType()))) {
5250 // OpenMP 5.0, [2.1.5 Array Sections]
5251 // When the size of the array dimension is not known, the length must be
5252 // specified explicitly.
5253 Diag(ColonLocFirst, diag::err_omp_section_length_undefined)
5254 << (!OriginalTy.isNull() && OriginalTy->isArrayType());
5255 return ExprError();
5256 }
5257
5258 if (Stride) {
5259 Expr::EvalResult Result;
5260 if (Stride->EvaluateAsInt(Result, Context)) {
5261 // OpenMP 5.0, [2.1.5 Array Sections]
5262 // The stride must evaluate to a positive integer.
5263 llvm::APSInt StrideValue = Result.Val.getInt();
5264 if (!StrideValue.isStrictlyPositive()) {
5265 Diag(Stride->getExprLoc(), diag::err_omp_section_stride_non_positive)
5266 << toString(StrideValue, /*Radix=*/10, /*Signed=*/true)
5267 << Stride->getSourceRange();
5268 return ExprError();
5269 }
5270 }
5271 }
5272
5273 if (!Base->hasPlaceholderType(BuiltinType::OMPArraySection)) {
5274 ExprResult Result = DefaultFunctionArrayLvalueConversion(Base);
5275 if (Result.isInvalid())
5276 return ExprError();
5277 Base = Result.get();
5278 }
5279 return new (Context) OMPArraySectionExpr(
5280 Base, LowerBound, Length, Stride, Context.OMPArraySectionTy, VK_LValue,
5281 OK_Ordinary, ColonLocFirst, ColonLocSecond, RBLoc);
5282}
5283
5284ExprResult Sema::ActOnOMPArrayShapingExpr(Expr *Base, SourceLocation LParenLoc,
5285 SourceLocation RParenLoc,
5286 ArrayRef<Expr *> Dims,
5287 ArrayRef<SourceRange> Brackets) {
5288 if (Base->hasPlaceholderType()) {
5289 ExprResult Result = CheckPlaceholderExpr(Base);
5290 if (Result.isInvalid())
5291 return ExprError();
5292 Result = DefaultLvalueConversion(Result.get());
5293 if (Result.isInvalid())
5294 return ExprError();
5295 Base = Result.get();
5296 }
5297 QualType BaseTy = Base->getType();
5298 // Delay analysis of the types/expressions if instantiation/specialization is
5299 // required.
5300 if (!BaseTy->isPointerType() && Base->isTypeDependent())
5301 return OMPArrayShapingExpr::Create(Context, Context.DependentTy, Base,
5302 LParenLoc, RParenLoc, Dims, Brackets);
5303 if (!BaseTy->isPointerType() ||
5304 (!Base->isTypeDependent() &&
5305 BaseTy->getPointeeType()->isIncompleteType()))
5306 return ExprError(Diag(Base->getExprLoc(),
5307 diag::err_omp_non_pointer_type_array_shaping_base)
5308 << Base->getSourceRange());
5309
5310 SmallVector<Expr *, 4> NewDims;
5311 bool ErrorFound = false;
5312 for (Expr *Dim : Dims) {
5313 if (Dim->hasPlaceholderType()) {
5314 ExprResult Result = CheckPlaceholderExpr(Dim);
5315 if (Result.isInvalid()) {
5316 ErrorFound = true;
5317 continue;
5318 }
5319 Result = DefaultLvalueConversion(Result.get());
5320 if (Result.isInvalid()) {
5321 ErrorFound = true;
5322 continue;
5323 }
5324 Dim = Result.get();
5325 }
5326 if (!Dim->isTypeDependent()) {
5327 ExprResult Result =
5328 PerformOpenMPImplicitIntegerConversion(Dim->getExprLoc(), Dim);
5329 if (Result.isInvalid()) {
5330 ErrorFound = true;
5331 Diag(Dim->getExprLoc(), diag::err_omp_typecheck_shaping_not_integer)
5332 << Dim->getSourceRange();
5333 continue;
5334 }
5335 Dim = Result.get();
5336 Expr::EvalResult EvResult;
5337 if (!Dim->isValueDependent() && Dim->EvaluateAsInt(EvResult, Context)) {
5338 // OpenMP 5.0, [2.1.4 Array Shaping]
5339 // Each si is an integral type expression that must evaluate to a
5340 // positive integer.
5341 llvm::APSInt Value = EvResult.Val.getInt();
5342 if (!Value.isStrictlyPositive()) {
5343 Diag(Dim->getExprLoc(), diag::err_omp_shaping_dimension_not_positive)
5344 << toString(Value, /*Radix=*/10, /*Signed=*/true)
5345 << Dim->getSourceRange();
5346 ErrorFound = true;
5347 continue;
5348 }
5349 }
5350 }
5351 NewDims.push_back(Dim);
5352 }
5353 if (ErrorFound)
5354 return ExprError();
5355 return OMPArrayShapingExpr::Create(Context, Context.OMPArrayShapingTy, Base,
5356 LParenLoc, RParenLoc, NewDims, Brackets);
5357}
5358
5359ExprResult Sema::ActOnOMPIteratorExpr(Scope *S, SourceLocation IteratorKwLoc,
5360 SourceLocation LLoc, SourceLocation RLoc,
5361 ArrayRef<OMPIteratorData> Data) {
5362 SmallVector<OMPIteratorExpr::IteratorDefinition, 4> ID;
5363 bool IsCorrect = true;
5364 for (const OMPIteratorData &D : Data) {
5365 TypeSourceInfo *TInfo = nullptr;
5366 SourceLocation StartLoc;
5367 QualType DeclTy;
5368 if (!D.Type.getAsOpaquePtr()) {
5369 // OpenMP 5.0, 2.1.6 Iterators
5370 // In an iterator-specifier, if the iterator-type is not specified then
5371 // the type of that iterator is of int type.
5372 DeclTy = Context.IntTy;
5373 StartLoc = D.DeclIdentLoc;
5374 } else {
5375 DeclTy = GetTypeFromParser(D.Type, &TInfo);
5376 StartLoc = TInfo->getTypeLoc().getBeginLoc();
5377 }
5378
5379 bool IsDeclTyDependent = DeclTy->isDependentType() ||
5380 DeclTy->containsUnexpandedParameterPack() ||
5381 DeclTy->isInstantiationDependentType();
5382 if (!IsDeclTyDependent) {
5383 if (!DeclTy->isIntegralType(Context) && !DeclTy->isAnyPointerType()) {
5384 // OpenMP 5.0, 2.1.6 Iterators, Restrictions, C/C++
5385 // The iterator-type must be an integral or pointer type.
5386 Diag(StartLoc, diag::err_omp_iterator_not_integral_or_pointer)
5387 << DeclTy;
5388 IsCorrect = false;
5389 continue;
5390 }
5391 if (DeclTy.isConstant(Context)) {
5392 // OpenMP 5.0, 2.1.6 Iterators, Restrictions, C/C++
5393 // The iterator-type must not be const qualified.
5394 Diag(StartLoc, diag::err_omp_iterator_not_integral_or_pointer)
5395 << DeclTy;
5396 IsCorrect = false;
5397 continue;
5398 }
5399 }
5400
5401 // Iterator declaration.
5402 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", 5402, __extension__ __PRETTY_FUNCTION__
))
;
5403 // Always try to create iterator declarator to avoid extra error messages
5404 // about unknown declarations use.
5405 auto *VD = VarDecl::Create(Context, CurContext, StartLoc, D.DeclIdentLoc,
5406 D.DeclIdent, DeclTy, TInfo, SC_None);
5407 VD->setImplicit();
5408 if (S) {
5409 // Check for conflicting previous declaration.
5410 DeclarationNameInfo NameInfo(VD->getDeclName(), D.DeclIdentLoc);
5411 LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
5412 ForVisibleRedeclaration);
5413 Previous.suppressDiagnostics();
5414 LookupName(Previous, S);
5415
5416 FilterLookupForScope(Previous, CurContext, S, /*ConsiderLinkage=*/false,
5417 /*AllowInlineNamespace=*/false);
5418 if (!Previous.empty()) {
5419 NamedDecl *Old = Previous.getRepresentativeDecl();
5420 Diag(D.DeclIdentLoc, diag::err_redefinition) << VD->getDeclName();
5421 Diag(Old->getLocation(), diag::note_previous_definition);
5422 } else {
5423 PushOnScopeChains(VD, S);
5424 }
5425 } else {
5426 CurContext->addDecl(VD);
5427 }
5428
5429 /// Act on the iterator variable declaration.
5430 ActOnOpenMPIteratorVarDecl(VD);
5431
5432 Expr *Begin = D.Range.Begin;
5433 if (!IsDeclTyDependent && Begin && !Begin->isTypeDependent()) {
5434 ExprResult BeginRes =
5435 PerformImplicitConversion(Begin, DeclTy, AA_Converting);
5436 Begin = BeginRes.get();
5437 }
5438 Expr *End = D.Range.End;
5439 if (!IsDeclTyDependent && End && !End->isTypeDependent()) {
5440 ExprResult EndRes = PerformImplicitConversion(End, DeclTy, AA_Converting);
5441 End = EndRes.get();
5442 }
5443 Expr *Step = D.Range.Step;
5444 if (!IsDeclTyDependent && Step && !Step->isTypeDependent()) {
5445 if (!Step->getType()->isIntegralType(Context)) {
5446 Diag(Step->getExprLoc(), diag::err_omp_iterator_step_not_integral)
5447 << Step << Step->getSourceRange();
5448 IsCorrect = false;
5449 continue;
5450 }
5451 std::optional<llvm::APSInt> Result =
5452 Step->getIntegerConstantExpr(Context);
5453 // OpenMP 5.0, 2.1.6 Iterators, Restrictions
5454 // If the step expression of a range-specification equals zero, the
5455 // behavior is unspecified.
5456 if (Result && Result->isZero()) {
5457 Diag(Step->getExprLoc(), diag::err_omp_iterator_step_constant_zero)
5458 << Step << Step->getSourceRange();
5459 IsCorrect = false;
5460 continue;
5461 }
5462 }
5463 if (!Begin || !End || !IsCorrect) {
5464 IsCorrect = false;
5465 continue;
5466 }
5467 OMPIteratorExpr::IteratorDefinition &IDElem = ID.emplace_back();
5468 IDElem.IteratorDecl = VD;
5469 IDElem.AssignmentLoc = D.AssignLoc;
5470 IDElem.Range.Begin = Begin;
5471 IDElem.Range.End = End;
5472 IDElem.Range.Step = Step;
5473 IDElem.ColonLoc = D.ColonLoc;
5474 IDElem.SecondColonLoc = D.SecColonLoc;
5475 }
5476 if (!IsCorrect) {
5477 // Invalidate all created iterator declarations if error is found.
5478 for (const OMPIteratorExpr::IteratorDefinition &D : ID) {
5479 if (Decl *ID = D.IteratorDecl)
5480 ID->setInvalidDecl();
5481 }
5482 return ExprError();
5483 }
5484 SmallVector<OMPIteratorHelperData, 4> Helpers;
5485 if (!CurContext->isDependentContext()) {
5486 // Build number of ityeration for each iteration range.
5487 // Ni = ((Stepi > 0) ? ((Endi + Stepi -1 - Begini)/Stepi) :
5488 // ((Begini-Stepi-1-Endi) / -Stepi);
5489 for (OMPIteratorExpr::IteratorDefinition &D : ID) {
5490 // (Endi - Begini)
5491 ExprResult Res = CreateBuiltinBinOp(D.AssignmentLoc, BO_Sub, D.Range.End,
5492 D.Range.Begin);
5493 if(!Res.isUsable()) {
5494 IsCorrect = false;
5495 continue;
5496 }
5497 ExprResult St, St1;
5498 if (D.Range.Step) {
5499 St = D.Range.Step;
5500 // (Endi - Begini) + Stepi
5501 Res = CreateBuiltinBinOp(D.AssignmentLoc, BO_Add, Res.get(), St.get());
5502 if (!Res.isUsable()) {
5503 IsCorrect = false;
5504 continue;
5505 }
5506 // (Endi - Begini) + Stepi - 1
5507 Res =
5508 CreateBuiltinBinOp(D.AssignmentLoc, BO_Sub, Res.get(),
5509 ActOnIntegerConstant(D.AssignmentLoc, 1).get());
5510 if (!Res.isUsable()) {
5511 IsCorrect = false;
5512 continue;
5513 }
5514 // ((Endi - Begini) + Stepi - 1) / Stepi
5515 Res = CreateBuiltinBinOp(D.AssignmentLoc, BO_Div, Res.get(), St.get());
5516 if (!Res.isUsable()) {
5517 IsCorrect = false;
5518 continue;
5519 }
5520 St1 = CreateBuiltinUnaryOp(D.AssignmentLoc, UO_Minus, D.Range.Step);
5521 // (Begini - Endi)
5522 ExprResult Res1 = CreateBuiltinBinOp(D.AssignmentLoc, BO_Sub,
5523 D.Range.Begin, D.Range.End);
5524 if (!Res1.isUsable()) {
5525 IsCorrect = false;
5526 continue;
5527 }
5528 // (Begini - Endi) - Stepi
5529 Res1 =
5530 CreateBuiltinBinOp(D.AssignmentLoc, BO_Add, Res1.get(), St1.get());
5531 if (!Res1.isUsable()) {
5532 IsCorrect = false;
5533 continue;
5534 }
5535 // (Begini - Endi) - Stepi - 1
5536 Res1 =
5537 CreateBuiltinBinOp(D.AssignmentLoc, BO_Sub, Res1.get(),
5538 ActOnIntegerConstant(D.AssignmentLoc, 1).get());
5539 if (!Res1.isUsable()) {
5540 IsCorrect = false;
5541 continue;
5542 }
5543 // ((Begini - Endi) - Stepi - 1) / (-Stepi)
5544 Res1 =
5545 CreateBuiltinBinOp(D.AssignmentLoc, BO_Div, Res1.get(), St1.get());
5546 if (!Res1.isUsable()) {
5547 IsCorrect = false;
5548 continue;
5549 }
5550 // Stepi > 0.
5551 ExprResult CmpRes =
5552 CreateBuiltinBinOp(D.AssignmentLoc, BO_GT, D.Range.Step,
5553 ActOnIntegerConstant(D.AssignmentLoc, 0).get());
5554 if (!CmpRes.isUsable()) {
5555 IsCorrect = false;
5556 continue;
5557 }
5558 Res = ActOnConditionalOp(D.AssignmentLoc, D.AssignmentLoc, CmpRes.get(),
5559 Res.get(), Res1.get());
5560 if (!Res.isUsable()) {
5561 IsCorrect = false;
5562 continue;
5563 }
5564 }
5565 Res = ActOnFinishFullExpr(Res.get(), /*DiscardedValue=*/false);
5566 if (!Res.isUsable()) {
5567 IsCorrect = false;
5568 continue;
5569 }
5570
5571 // Build counter update.
5572 // Build counter.
5573 auto *CounterVD =
5574 VarDecl::Create(Context, CurContext, D.IteratorDecl->getBeginLoc(),
5575 D.IteratorDecl->getBeginLoc(), nullptr,
5576 Res.get()->getType(), nullptr, SC_None);
5577 CounterVD->setImplicit();
5578 ExprResult RefRes =
5579 BuildDeclRefExpr(CounterVD, CounterVD->getType(), VK_LValue,
5580 D.IteratorDecl->getBeginLoc());
5581 // Build counter update.
5582 // I = Begini + counter * Stepi;
5583 ExprResult UpdateRes;
5584 if (D.Range.Step) {
5585 UpdateRes = CreateBuiltinBinOp(
5586 D.AssignmentLoc, BO_Mul,
5587 DefaultLvalueConversion(RefRes.get()).get(), St.get());
5588 } else {
5589 UpdateRes = DefaultLvalueConversion(RefRes.get());
5590 }
5591 if (!UpdateRes.isUsable()) {
5592 IsCorrect = false;
5593 continue;
5594 }
5595 UpdateRes = CreateBuiltinBinOp(D.AssignmentLoc, BO_Add, D.Range.Begin,
5596 UpdateRes.get());
5597 if (!UpdateRes.isUsable()) {
5598 IsCorrect = false;
5599 continue;
5600 }
5601 ExprResult VDRes =
5602 BuildDeclRefExpr(cast<VarDecl>(D.IteratorDecl),
5603 cast<VarDecl>(D.IteratorDecl)->getType(), VK_LValue,
5604 D.IteratorDecl->getBeginLoc());
5605 UpdateRes = CreateBuiltinBinOp(D.AssignmentLoc, BO_Assign, VDRes.get(),
5606 UpdateRes.get());
5607 if (!UpdateRes.isUsable()) {
5608 IsCorrect = false;
5609 continue;
5610 }
5611 UpdateRes =
5612 ActOnFinishFullExpr(UpdateRes.get(), /*DiscardedValue=*/true);
5613 if (!UpdateRes.isUsable()) {
5614 IsCorrect = false;
5615 continue;
5616 }
5617 ExprResult CounterUpdateRes =
5618 CreateBuiltinUnaryOp(D.AssignmentLoc, UO_PreInc, RefRes.get());
5619 if (!CounterUpdateRes.isUsable()) {
5620 IsCorrect = false;
5621 continue;
5622 }
5623 CounterUpdateRes =
5624 ActOnFinishFullExpr(CounterUpdateRes.get(), /*DiscardedValue=*/true);
5625 if (!CounterUpdateRes.isUsable()) {
5626 IsCorrect = false;
5627 continue;
5628 }
5629 OMPIteratorHelperData &HD = Helpers.emplace_back();
5630 HD.CounterVD = CounterVD;
5631 HD.Upper = Res.get();
5632 HD.Update = UpdateRes.get();
5633 HD.CounterUpdate = CounterUpdateRes.get();
5634 }
5635 } else {
5636 Helpers.assign(ID.size(), {});
5637 }
5638 if (!IsCorrect) {
5639 // Invalidate all created iterator declarations if error is found.
5640 for (const OMPIteratorExpr::IteratorDefinition &D : ID) {
5641 if (Decl *ID = D.IteratorDecl)
5642 ID->setInvalidDecl();
5643 }
5644 return ExprError();
5645 }
5646 return OMPIteratorExpr::Create(Context, Context.OMPIteratorTy, IteratorKwLoc,
5647 LLoc, RLoc, ID, Helpers);
5648}
5649
5650ExprResult
5651Sema::CreateBuiltinArraySubscriptExpr(Expr *Base, SourceLocation LLoc,
5652 Expr *Idx, SourceLocation RLoc) {
5653 Expr *LHSExp = Base;
5654 Expr *RHSExp = Idx;
5655
5656 ExprValueKind VK = VK_LValue;
5657 ExprObjectKind OK = OK_Ordinary;
5658
5659 // Per C++ core issue 1213, the result is an xvalue if either operand is
5660 // a non-lvalue array, and an lvalue otherwise.
5661 if (getLangOpts().CPlusPlus11) {
5662 for (auto *Op : {LHSExp, RHSExp}) {
5663 Op = Op->IgnoreImplicit();
5664 if (Op->getType()->isArrayType() && !Op->isLValue())
5665 VK = VK_XValue;
5666 }
5667 }
5668
5669 // Perform default conversions.
5670 if (!LHSExp->getType()->getAs<VectorType>()) {
5671 ExprResult Result = DefaultFunctionArrayLvalueConversion(LHSExp);
5672 if (Result.isInvalid())
5673 return ExprError();
5674 LHSExp = Result.get();
5675 }
5676 ExprResult Result = DefaultFunctionArrayLvalueConversion(RHSExp);
5677 if (Result.isInvalid())
5678 return ExprError();
5679 RHSExp = Result.get();
5680
5681 QualType LHSTy = LHSExp->getType(), RHSTy = RHSExp->getType();
5682
5683 // C99 6.5.2.1p2: the expression e1[e2] is by definition precisely equivalent
5684 // to the expression *((e1)+(e2)). This means the array "Base" may actually be
5685 // in the subscript position. As a result, we need to derive the array base
5686 // and index from the expression types.
5687 Expr *BaseExpr, *IndexExpr;
5688 QualType ResultType;
5689 if (LHSTy->isDependentType() || RHSTy->isDependentType()) {
5690 BaseExpr = LHSExp;
5691 IndexExpr = RHSExp;
5692 ResultType =
5693 getDependentArraySubscriptType(LHSExp, RHSExp, getASTContext());
5694 } else if (const PointerType *PTy = LHSTy->getAs<PointerType>()) {
5695 BaseExpr = LHSExp;
5696 IndexExpr = RHSExp;
5697 ResultType = PTy->getPointeeType();
5698 } else if (const ObjCObjectPointerType *PTy =
5699 LHSTy->getAs<ObjCObjectPointerType>()) {
5700 BaseExpr = LHSExp;
5701 IndexExpr = RHSExp;
5702
5703 // Use custom logic if this should be the pseudo-object subscript
5704 // expression.
5705 if (!LangOpts.isSubscriptPointerArithmetic())
5706 return BuildObjCSubscriptExpression(RLoc, BaseExpr, IndexExpr, nullptr,
5707 nullptr);
5708
5709 ResultType = PTy->getPointeeType();
5710 } else if (const PointerType *PTy = RHSTy->getAs<PointerType>()) {
5711 // Handle the uncommon case of "123[Ptr]".
5712 BaseExpr = RHSExp;
5713 IndexExpr = LHSExp;
5714 ResultType = PTy->getPointeeType();
5715 } else if (const ObjCObjectPointerType *PTy =
5716 RHSTy->getAs<ObjCObjectPointerType>()) {
5717 // Handle the uncommon case of "123[Ptr]".
5718 BaseExpr = RHSExp;
5719 IndexExpr = LHSExp;
5720 ResultType = PTy->getPointeeType();
5721 if (!LangOpts.isSubscriptPointerArithmetic()) {
5722 Diag(LLoc, diag::err_subscript_nonfragile_interface)
5723 << ResultType << BaseExpr->getSourceRange();
5724 return ExprError();
5725 }
5726 } else if (const VectorType *VTy = LHSTy->getAs<VectorType>()) {
5727 BaseExpr = LHSExp; // vectors: V[123]
5728 IndexExpr = RHSExp;
5729 // We apply C++ DR1213 to vector subscripting too.
5730 if (getLangOpts().CPlusPlus11 && LHSExp->isPRValue()) {
5731 ExprResult Materialized = TemporaryMaterializationConversion(LHSExp);
5732 if (Materialized.isInvalid())
5733 return ExprError();
5734 LHSExp = Materialized.get();
5735 }
5736 VK = LHSExp->getValueKind();
5737 if (VK != VK_PRValue)
5738 OK = OK_VectorComponent;
5739
5740 ResultType = VTy->getElementType();
5741 QualType BaseType = BaseExpr->getType();
5742 Qualifiers BaseQuals = BaseType.getQualifiers();
5743 Qualifiers MemberQuals = ResultType.getQualifiers();
5744 Qualifiers Combined = BaseQuals + MemberQuals;
5745 if (Combined != MemberQuals)
5746 ResultType = Context.getQualifiedType(ResultType, Combined);
5747 } else if (LHSTy->isBuiltinType() &&
5748 LHSTy->getAs<BuiltinType>()->isVLSTBuiltinType()) {
5749 const BuiltinType *BTy = LHSTy->getAs<BuiltinType>();
5750 if (BTy->isSVEBool())
5751 return ExprError(Diag(LLoc, diag::err_subscript_svbool_t)
5752 << LHSExp->getSourceRange() << RHSExp->getSourceRange());
5753
5754 BaseExpr = LHSExp;
5755 IndexExpr = RHSExp;
5756 if (getLangOpts().CPlusPlus11 && LHSExp->isPRValue()) {
5757 ExprResult Materialized = TemporaryMaterializationConversion(LHSExp);
5758 if (Materialized.isInvalid())
5759 return ExprError();
5760 LHSExp = Materialized.get();
5761 }
5762 VK = LHSExp->getValueKind();
5763 if (VK != VK_PRValue)
5764 OK = OK_VectorComponent;
5765
5766 ResultType = BTy->getSveEltType(Context);
5767
5768 QualType BaseType = BaseExpr->getType();
5769 Qualifiers BaseQuals = BaseType.getQualifiers();
5770 Qualifiers MemberQuals = ResultType.getQualifiers();
5771 Qualifiers Combined = BaseQuals + MemberQuals;
5772 if (Combined != MemberQuals)
5773 ResultType = Context.getQualifiedType(ResultType, Combined);
5774 } else if (LHSTy->isArrayType()) {
5775 // If we see an array that wasn't promoted by
5776 // DefaultFunctionArrayLvalueConversion, it must be an array that
5777 // wasn't promoted because of the C90 rule that doesn't
5778 // allow promoting non-lvalue arrays. Warn, then
5779 // force the promotion here.
5780 Diag(LHSExp->getBeginLoc(), diag::ext_subscript_non_lvalue)
5781 << LHSExp->getSourceRange();
5782 LHSExp = ImpCastExprToType(LHSExp, Context.getArrayDecayedType(LHSTy),
5783 CK_ArrayToPointerDecay).get();
5784 LHSTy = LHSExp->getType();
5785
5786 BaseExpr = LHSExp;
5787 IndexExpr = RHSExp;
5788 ResultType = LHSTy->castAs<PointerType>()->getPointeeType();
5789 } else if (RHSTy->isArrayType()) {
5790 // Same as previous, except for 123[f().a] case
5791 Diag(RHSExp->getBeginLoc(), diag::ext_subscript_non_lvalue)
5792 << RHSExp->getSourceRange();
5793 RHSExp = ImpCastExprToType(RHSExp, Context.getArrayDecayedType(RHSTy),
5794 CK_ArrayToPointerDecay).get();
5795 RHSTy = RHSExp->getType();
5796
5797 BaseExpr = RHSExp;
5798 IndexExpr = LHSExp;
5799 ResultType = RHSTy->castAs<PointerType>()->getPointeeType();
5800 } else {
5801 return ExprError(Diag(LLoc, diag::err_typecheck_subscript_value)
5802 << LHSExp->getSourceRange() << RHSExp->getSourceRange());
5803 }
5804 // C99 6.5.2.1p1
5805 if (!IndexExpr->getType()->isIntegerType() && !IndexExpr->isTypeDependent())
5806 return ExprError(Diag(LLoc, diag::err_typecheck_subscript_not_integer)
5807 << IndexExpr->getSourceRange());
5808
5809 if ((IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_S) ||
5810 IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_U))
5811 && !IndexExpr->isTypeDependent())
5812 Diag(LLoc, diag::warn_subscript_is_char) << IndexExpr->getSourceRange();
5813
5814 // C99 6.5.2.1p1: "shall have type "pointer to *object* type". Similarly,
5815 // C++ [expr.sub]p1: The type "T" shall be a completely-defined object
5816 // type. Note that Functions are not objects, and that (in C99 parlance)
5817 // incomplete types are not object types.
5818 if (ResultType->isFunctionType()) {
5819 Diag(BaseExpr->getBeginLoc(), diag::err_subscript_function_type)
5820 << ResultType << BaseExpr->getSourceRange();
5821 return ExprError();
5822 }
5823
5824 if (ResultType->isVoidType() && !getLangOpts().CPlusPlus) {
5825 // GNU extension: subscripting on pointer to void
5826 Diag(LLoc, diag::ext_gnu_subscript_void_type)
5827 << BaseExpr->getSourceRange();
5828
5829 // C forbids expressions of unqualified void type from being l-values.
5830 // See IsCForbiddenLValueType.
5831 if (!ResultType.hasQualifiers())
5832 VK = VK_PRValue;
5833 } else if (!ResultType->isDependentType() &&
5834 RequireCompleteSizedType(
5835 LLoc, ResultType,
5836 diag::err_subscript_incomplete_or_sizeless_type, BaseExpr))
5837 return ExprError();
5838
5839 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", 5840, __extension__ __PRETTY_FUNCTION__
))
5840 !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", 5840, __extension__ __PRETTY_FUNCTION__
))
;
5841
5842 if (LHSExp->IgnoreParenImpCasts()->getType()->isVariablyModifiedType() &&
5843 FunctionScopes.size() > 1) {
5844 if (auto *TT =
5845 LHSExp->IgnoreParenImpCasts()->getType()->getAs<TypedefType>()) {
5846 for (auto I = FunctionScopes.rbegin(),
5847 E = std::prev(FunctionScopes.rend());
5848 I != E; ++I) {
5849 auto *CSI = dyn_cast<CapturingScopeInfo>(*I);
5850 if (CSI == nullptr)
5851 break;
5852 DeclContext *DC = nullptr;
5853 if (auto *LSI = dyn_cast<LambdaScopeInfo>(CSI))
5854 DC = LSI->CallOperator;
5855 else if (auto *CRSI = dyn_cast<CapturedRegionScopeInfo>(CSI))
5856 DC = CRSI->TheCapturedDecl;
5857 else if (auto *BSI = dyn_cast<BlockScopeInfo>(CSI))
5858 DC = BSI->TheDecl;
5859 if (DC) {
5860 if (DC->containsDecl(TT->getDecl()))
5861 break;
5862 captureVariablyModifiedType(
5863 Context, LHSExp->IgnoreParenImpCasts()->getType(), CSI);
5864 }
5865 }
5866 }
5867 }
5868
5869 return new (Context)
5870 ArraySubscriptExpr(LHSExp, RHSExp, ResultType, VK, OK, RLoc);
5871}
5872
5873bool Sema::CheckCXXDefaultArgExpr(SourceLocation CallLoc, FunctionDecl *FD,
5874 ParmVarDecl *Param, Expr *RewrittenInit,
5875 bool SkipImmediateInvocations) {
5876 if (Param->hasUnparsedDefaultArg()) {
5877 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", 5877, __extension__ __PRETTY_FUNCTION__
))
;
5878 // If we've already cleared out the location for the default argument,
5879 // that means we're parsing it right now.
5880 if (!UnparsedDefaultArgLocs.count(Param)) {
5881 Diag(Param->getBeginLoc(), diag::err_recursive_default_argument) << FD;
5882 Diag(CallLoc, diag::note_recursive_default_argument_used_here);
5883 Param->setInvalidDecl();
5884 return true;
5885 }
5886
5887 Diag(CallLoc, diag::err_use_of_default_argument_to_function_declared_later)
5888 << FD << cast<CXXRecordDecl>(FD->getDeclContext());
5889 Diag(UnparsedDefaultArgLocs[Param],
5890 diag::note_default_argument_declared_here);
5891 return true;
5892 }
5893
5894 if (Param->hasUninstantiatedDefaultArg()) {
5895 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", 5895, __extension__ __PRETTY_FUNCTION__
))
;
5896 if (InstantiateDefaultArgument(CallLoc, FD, Param))
5897 return true;
5898 }
5899
5900 Expr *Init = RewrittenInit ? RewrittenInit : Param->getInit();
5901 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", 5901, __extension__ __PRETTY_FUNCTION__
))
;
5902
5903 // If the default expression creates temporaries, we need to
5904 // push them to the current stack of expression temporaries so they'll
5905 // be properly destroyed.
5906 // FIXME: We should really be rebuilding the default argument with new
5907 // bound temporaries; see the comment in PR5810.
5908 // We don't need to do that with block decls, though, because
5909 // blocks in default argument expression can never capture anything.
5910 if (auto *InitWithCleanup = dyn_cast<ExprWithCleanups>(Init)) {
5911 // Set the "needs cleanups" bit regardless of whether there are
5912 // any explicit objects.
5913 Cleanup.setExprNeedsCleanups(InitWithCleanup->cleanupsHaveSideEffects());
5914 // Append all the objects to the cleanup list. Right now, this
5915 // should always be a no-op, because blocks in default argument
5916 // expressions should never be able to capture anything.
5917 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", 5918, __extension__ __PRETTY_FUNCTION__
))
5918 "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", 5918, __extension__ __PRETTY_FUNCTION__
))
;
5919 }
5920 // C++ [expr.const]p15.1:
5921 // An expression or conversion is in an immediate function context if it is
5922 // potentially evaluated and [...] its innermost enclosing non-block scope
5923 // is a function parameter scope of an immediate function.
5924 EnterExpressionEvaluationContext EvalContext(
5925 *this,
5926 FD->isConsteval() ? ExpressionEvaluationContext::ImmediateFunctionContext
5927 : ExpressionEvaluationContext::PotentiallyEvaluated,
5928 Param);
5929 ExprEvalContexts.back().IsCurrentlyCheckingDefaultArgumentOrInitializer =
5930 SkipImmediateInvocations;
5931 MarkDeclarationsReferencedInExpr(Init, /*SkipLocalVariables*/ true);
5932 return false;
5933}
5934
5935struct ImmediateCallVisitor : public RecursiveASTVisitor<ImmediateCallVisitor> {
5936 bool HasImmediateCalls = false;
5937
5938 bool shouldVisitImplicitCode() const { return true; }
5939
5940 bool VisitCallExpr(CallExpr *E) {
5941 if (const FunctionDecl *FD = E->getDirectCallee())
5942 HasImmediateCalls |= FD->isConsteval();
5943 return RecursiveASTVisitor<ImmediateCallVisitor>::VisitStmt(E);
5944 }
5945
5946 // SourceLocExpr are not immediate invocations
5947 // but CXXDefaultInitExpr/CXXDefaultArgExpr containing a SourceLocExpr
5948 // need to be rebuilt so that they refer to the correct SourceLocation and
5949 // DeclContext.
5950 bool VisitSourceLocExpr(SourceLocExpr *E) {
5951 HasImmediateCalls = true;
5952 return RecursiveASTVisitor<ImmediateCallVisitor>::VisitStmt(E);
5953 }
5954
5955 // A nested lambda might have parameters with immediate invocations
5956 // in their default arguments.
5957 // The compound statement is not visited (as it does not constitute a
5958 // subexpression).
5959 // FIXME: We should consider visiting and transforming captures
5960 // with init expressions.
5961 bool VisitLambdaExpr(LambdaExpr *E) {
5962 return VisitCXXMethodDecl(E->getCallOperator());
5963 }
5964
5965 // Blocks don't support default parameters, and, as for lambdas,
5966 // we don't consider their body a subexpression.
5967 bool VisitBlockDecl(BlockDecl *B) { return false; }
5968
5969 bool VisitCompoundStmt(CompoundStmt *B) { return false; }
5970
5971 bool VisitCXXDefaultArgExpr(CXXDefaultArgExpr *E) {
5972 return TraverseStmt(E->getExpr());
5973 }
5974
5975 bool VisitCXXDefaultInitExpr(CXXDefaultInitExpr *E) {
5976 return TraverseStmt(E->getExpr());
5977 }
5978};
5979
5980struct EnsureImmediateInvocationInDefaultArgs
5981 : TreeTransform<EnsureImmediateInvocationInDefaultArgs> {
5982 EnsureImmediateInvocationInDefaultArgs(Sema &SemaRef)
5983 : TreeTransform(SemaRef) {}
5984
5985 // Lambda can only have immediate invocations in the default
5986 // args of their parameters, which is transformed upon calling the closure.
5987 // The body is not a subexpression, so we have nothing to do.
5988 // FIXME: Immediate calls in capture initializers should be transformed.
5989 ExprResult TransformLambdaExpr(LambdaExpr *E) { return E; }
5990 ExprResult TransformBlockExpr(BlockExpr *E) { return E; }
5991
5992 // Make sure we don't rebuild the this pointer as it would
5993 // cause it to incorrectly point it to the outermost class
5994 // in the case of nested struct initialization.
5995 ExprResult TransformCXXThisExpr(CXXThisExpr *E) { return E; }
5996};
5997
5998ExprResult Sema::BuildCXXDefaultArgExpr(SourceLocation CallLoc,
5999 FunctionDecl *FD, ParmVarDecl *Param,
6000 Expr *Init) {
6001 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", 6001, __extension__ __PRETTY_FUNCTION__
))
;
6002
6003 bool NestedDefaultChecking = isCheckingDefaultArgumentOrInitializer();
6004
6005 std::optional<ExpressionEvaluationContextRecord::InitializationContext>
6006 InitializationContext =
6007 OutermostDeclarationWithDelayedImmediateInvocations();
6008 if (!InitializationContext.has_value())
6009 InitializationContext.emplace(CallLoc, Param, CurContext);
6010
6011 if (!Init && !Param->hasUnparsedDefaultArg()) {
6012 // Mark that we are replacing a default argument first.
6013 // If we are instantiating a template we won't have to
6014 // retransform immediate calls.
6015 // C++ [expr.const]p15.1:
6016 // An expression or conversion is in an immediate function context if it
6017 // is potentially evaluated and [...] its innermost enclosing non-block
6018 // scope is a function parameter scope of an immediate function.
6019 EnterExpressionEvaluationContext EvalContext(
6020 *this,
6021 FD->isConsteval()
6022 ? ExpressionEvaluationContext::ImmediateFunctionContext
6023 : ExpressionEvaluationContext::PotentiallyEvaluated,
6024 Param);
6025
6026 if (Param->hasUninstantiatedDefaultArg()) {
6027 if (InstantiateDefaultArgument(CallLoc, FD, Param))
6028 return ExprError();
6029 }
6030 // CWG2631
6031 // An immediate invocation that is not evaluated where it appears is
6032 // evaluated and checked for whether it is a constant expression at the
6033 // point where the enclosing initializer is used in a function call.
6034 ImmediateCallVisitor V;
6035 if (!NestedDefaultChecking)
6036 V.TraverseDecl(Param);
6037 if (V.HasImmediateCalls) {
6038 ExprEvalContexts.back().DelayedDefaultInitializationContext = {
6039 CallLoc, Param, CurContext};
6040 EnsureImmediateInvocationInDefaultArgs Immediate(*this);
6041 ExprResult Res = Immediate.TransformInitializer(Param->getInit(),
6042 /*NotCopy=*/false);
6043 if (Res.isInvalid())
6044 return ExprError();
6045 Res = ConvertParamDefaultArgument(Param, Res.get(),
6046 Res.get()->getBeginLoc());
6047 if (Res.isInvalid())
6048 return ExprError();
6049 Init = Res.get();
6050 }
6051 }
6052
6053 if (CheckCXXDefaultArgExpr(
6054 CallLoc, FD, Param, Init,
6055 /*SkipImmediateInvocations=*/NestedDefaultChecking))
6056 return ExprError();
6057
6058 return CXXDefaultArgExpr::Create(Context, InitializationContext->Loc, Param,
6059 Init, InitializationContext->Context);
6060}
6061
6062ExprResult Sema::BuildCXXDefaultInitExpr(SourceLocation Loc, FieldDecl *Field) {
6063 assert(Field->hasInClassInitializer())(static_cast <bool> (Field->hasInClassInitializer())
? void (0) : __assert_fail ("Field->hasInClassInitializer()"
, "clang/lib/Sema/SemaExpr.cpp", 6063, __extension__ __PRETTY_FUNCTION__
))
;
6064
6065 // If we might have already tried and failed to instantiate, don't try again.
6066 if (Field->isInvalidDecl())
6067 return ExprError();
6068
6069 auto *ParentRD = cast<CXXRecordDecl>(Field->getParent());
6070
6071 std::optional<ExpressionEvaluationContextRecord::InitializationContext>
6072 InitializationContext =
6073 OutermostDeclarationWithDelayedImmediateInvocations();
6074 if (!InitializationContext.has_value())
6075 InitializationContext.emplace(Loc, Field, CurContext);
6076
6077 Expr *Init = nullptr;
6078
6079 bool NestedDefaultChecking = isCheckingDefaultArgumentOrInitializer();
6080
6081 EnterExpressionEvaluationContext EvalContext(
6082 *this, ExpressionEvaluationContext::PotentiallyEvaluated, Field);
6083
6084 if (!Field->getInClassInitializer()) {
6085 // Maybe we haven't instantiated the in-class initializer. Go check the
6086 // pattern FieldDecl to see if it has one.
6087 if (isTemplateInstantiation(ParentRD->getTemplateSpecializationKind())) {
6088 CXXRecordDecl *ClassPattern = ParentRD->getTemplateInstantiationPattern();
6089 DeclContext::lookup_result Lookup =
6090 ClassPattern->lookup(Field->getDeclName());
6091
6092 FieldDecl *Pattern = nullptr;
6093 for (auto *L : Lookup) {
6094 if ((Pattern = dyn_cast<FieldDecl>(L)))
6095 break;
6096 }
6097 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", 6097, __extension__ __PRETTY_FUNCTION__
))
;
6098 if (!Pattern->hasInClassInitializer() ||
6099 InstantiateInClassInitializer(Loc, Field, Pattern,
6100 getTemplateInstantiationArgs(Field))) {
6101 Field->setInvalidDecl();
6102 return ExprError();
6103 }
6104 }
6105 }
6106
6107 // CWG2631
6108 // An immediate invocation that is not evaluated where it appears is
6109 // evaluated and checked for whether it is a constant expression at the
6110 // point where the enclosing initializer is used in a [...] a constructor
6111 // definition, or an aggregate initialization.
6112 ImmediateCallVisitor V;
6113 if (!NestedDefaultChecking)
6114 V.TraverseDecl(Field);
6115 if (V.HasImmediateCalls) {
6116 ExprEvalContexts.back().DelayedDefaultInitializationContext = {Loc, Field,
6117 CurContext};
6118 ExprEvalContexts.back().IsCurrentlyCheckingDefaultArgumentOrInitializer =
6119 NestedDefaultChecking;
6120
6121 EnsureImmediateInvocationInDefaultArgs Immediate(*this);
6122
6123 ExprResult Res =
6124 Immediate.TransformInitializer(Field->getInClassInitializer(),
6125 /*CXXDirectInit=*/false);
6126 if (!Res.isInvalid())
6127 Res = ConvertMemberDefaultInitExpression(Field, Res.get(), Loc);
6128 if (Res.isInvalid()) {
6129 Field->setInvalidDecl();
6130 return ExprError();
6131 }
6132 Init = Res.get();
6133 }
6134
6135 if (Field->getInClassInitializer()) {
6136 Expr *E = Init ? Init : Field->getInClassInitializer();
6137 if (!NestedDefaultChecking)
6138 MarkDeclarationsReferencedInExpr(E, /*SkipLocalVariables=*/false);
6139 // C++11 [class.base.init]p7:
6140 // The initialization of each base and member constitutes a
6141 // full-expression.
6142 ExprResult Res = ActOnFinishFullExpr(E, /*DiscardedValue=*/false);
6143 if (Res.isInvalid()) {
6144 Field->setInvalidDecl();
6145 return ExprError();
6146 }
6147 Init = Res.get();
6148
6149 return CXXDefaultInitExpr::Create(Context, InitializationContext->Loc,
6150 Field, InitializationContext->Context,
6151 Init);
6152 }
6153
6154 // DR1351:
6155 // If the brace-or-equal-initializer of a non-static data member
6156 // invokes a defaulted default constructor of its class or of an
6157 // enclosing class in a potentially evaluated subexpression, the
6158 // program is ill-formed.
6159 //
6160 // This resolution is unworkable: the exception specification of the
6161 // default constructor can be needed in an unevaluated context, in
6162 // particular, in the operand of a noexcept-expression, and we can be
6163 // unable to compute an exception specification for an enclosed class.
6164 //
6165 // Any attempt to resolve the exception specification of a defaulted default
6166 // constructor before the initializer is lexically complete will ultimately
6167 // come here at which point we can diagnose it.
6168 RecordDecl *OutermostClass = ParentRD->getOuterLexicalRecordContext();
6169 Diag(Loc, diag::err_default_member_initializer_not_yet_parsed)
6170 << OutermostClass << Field;
6171 Diag(Field->getEndLoc(),
6172 diag::note_default_member_initializer_not_yet_parsed);
6173 // Recover by marking the field invalid, unless we're in a SFINAE context.
6174 if (!isSFINAEContext())
6175 Field->setInvalidDecl();
6176 return ExprError();
6177}
6178
6179Sema::VariadicCallType
6180Sema::getVariadicCallType(FunctionDecl *FDecl, const FunctionProtoType *Proto,
6181 Expr *Fn) {
6182 if (Proto && Proto->isVariadic()) {
6183 if (isa_and_nonnull<CXXConstructorDecl>(FDecl))
6184 return VariadicConstructor;
6185 else if (Fn && Fn->getType()->isBlockPointerType())
6186 return VariadicBlock;
6187 else if (FDecl) {
6188 if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(FDecl))
6189 if (Method->isInstance())
6190 return VariadicMethod;
6191 } else if (Fn && Fn->getType() == Context.BoundMemberTy)
6192 return VariadicMethod;
6193 return VariadicFunction;
6194 }
6195 return VariadicDoesNotApply;
6196}
6197
6198namespace {
6199class FunctionCallCCC final : public FunctionCallFilterCCC {
6200public:
6201 FunctionCallCCC(Sema &SemaRef, const IdentifierInfo *FuncName,
6202 unsigned NumArgs, MemberExpr *ME)
6203 : FunctionCallFilterCCC(SemaRef, NumArgs, false, ME),
6204 FunctionName(FuncName) {}
6205
6206 bool ValidateCandidate(const TypoCorrection &candidate) override {
6207 if (!candidate.getCorrectionSpecifier() ||
6208 candidate.getCorrectionAsIdentifierInfo() != FunctionName) {
6209 return false;
6210 }
6211
6212 return FunctionCallFilterCCC::ValidateCandidate(candidate);
6213 }
6214
6215 std::unique_ptr<CorrectionCandidateCallback> clone() override {
6216 return std::make_unique<FunctionCallCCC>(*this);
6217 }
6218
6219private:
6220 const IdentifierInfo *const FunctionName;
6221};
6222}
6223
6224static TypoCorrection TryTypoCorrectionForCall(Sema &S, Expr *Fn,
6225 FunctionDecl *FDecl,
6226 ArrayRef<Expr *> Args) {
6227 MemberExpr *ME = dyn_cast<MemberExpr>(Fn);
6228 DeclarationName FuncName = FDecl->getDeclName();
6229 SourceLocation NameLoc = ME ? ME->getMemberLoc() : Fn->getBeginLoc();
6230
6231 FunctionCallCCC CCC(S, FuncName.getAsIdentifierInfo(), Args.size(), ME);
6232 if (TypoCorrection Corrected = S.CorrectTypo(
6233 DeclarationNameInfo(FuncName, NameLoc), Sema::LookupOrdinaryName,
6234 S.getScopeForContext(S.CurContext), nullptr, CCC,
6235 Sema::CTK_ErrorRecovery)) {
6236 if (NamedDecl *ND = Corrected.getFoundDecl()) {
6237 if (Corrected.isOverloaded()) {
6238 OverloadCandidateSet OCS(NameLoc, OverloadCandidateSet::CSK_Normal);
6239 OverloadCandidateSet::iterator Best;
6240 for (NamedDecl *CD : Corrected) {
6241 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(CD))
6242 S.AddOverloadCandidate(FD, DeclAccessPair::make(FD, AS_none), Args,
6243 OCS);
6244 }
6245 switch (OCS.BestViableFunction(S, NameLoc, Best)) {
6246 case OR_Success:
6247 ND = Best->FoundDecl;
6248 Corrected.setCorrectionDecl(ND);
6249 break;
6250 default:
6251 break;
6252 }
6253 }
6254 ND = ND->getUnderlyingDecl();
6255 if (isa<ValueDecl>(ND) || isa<FunctionTemplateDecl>(ND))
6256 return Corrected;
6257 }
6258 }
6259 return TypoCorrection();
6260}
6261
6262/// ConvertArgumentsForCall - Converts the arguments specified in
6263/// Args/NumArgs to the parameter types of the function FDecl with
6264/// function prototype Proto. Call is the call expression itself, and
6265/// Fn is the function expression. For a C++ member function, this
6266/// routine does not attempt to convert the object argument. Returns
6267/// true if the call is ill-formed.
6268bool
6269Sema::ConvertArgumentsForCall(CallExpr *Call, Expr *Fn,
6270 FunctionDecl *FDecl,
6271 const FunctionProtoType *Proto,
6272 ArrayRef<Expr *> Args,
6273 SourceLocation RParenLoc,
6274 bool IsExecConfig) {
6275 // Bail out early if calling a builtin with custom typechecking.
6276 if (FDecl)
6277 if (unsigned ID = FDecl->getBuiltinID())
6278 if (Context.BuiltinInfo.hasCustomTypechecking(ID))
6279 return false;
6280
6281 // C99 6.5.2.2p7 - the arguments are implicitly converted, as if by
6282 // assignment, to the types of the corresponding parameter, ...
6283 unsigned NumParams = Proto->getNumParams();
6284 bool Invalid = false;
6285 unsigned MinArgs = FDecl ? FDecl->getMinRequiredArguments() : NumParams;
6286 unsigned FnKind = Fn->getType()->isBlockPointerType()
6287 ? 1 /* block */
6288 : (IsExecConfig ? 3 /* kernel function (exec config) */
6289 : 0 /* function */);
6290
6291 // If too few arguments are available (and we don't have default
6292 // arguments for the remaining parameters), don't make the call.
6293 if (Args.size() < NumParams) {
6294 if (Args.size() < MinArgs) {
6295 TypoCorrection TC;
6296 if (FDecl && (TC = TryTypoCorrectionForCall(*this, Fn, FDecl, Args))) {
6297 unsigned diag_id =
6298 MinArgs == NumParams && !Proto->isVariadic()
6299 ? diag::err_typecheck_call_too_few_args_suggest
6300 : diag::err_typecheck_call_too_few_args_at_least_suggest;
6301 diagnoseTypo(TC, PDiag(diag_id) << FnKind << MinArgs
6302 << static_cast<unsigned>(Args.size())
6303 << TC.getCorrectionRange());
6304 } else if (MinArgs == 1 && FDecl && FDecl->getParamDecl(0)->getDeclName())
6305 Diag(RParenLoc,
6306 MinArgs == NumParams && !Proto->isVariadic()
6307 ? diag::err_typecheck_call_too_few_args_one
6308 : diag::err_typecheck_call_too_few_args_at_least_one)
6309 << FnKind << FDecl->getParamDecl(0) << Fn->getSourceRange();
6310 else
6311 Diag(RParenLoc, MinArgs == NumParams && !Proto->isVariadic()
6312 ? diag::err_typecheck_call_too_few_args
6313 : diag::err_typecheck_call_too_few_args_at_least)
6314 << FnKind << MinArgs << static_cast<unsigned>(Args.size())
6315 << Fn->getSourceRange();
6316
6317 // Emit the location of the prototype.
6318 if (!TC && FDecl && !FDecl->getBuiltinID() && !IsExecConfig)
6319 Diag(FDecl->getLocation(), diag::note_callee_decl) << FDecl;
6320
6321 return true;
6322 }
6323 // We reserve space for the default arguments when we create
6324 // the call expression, before calling ConvertArgumentsForCall.
6325 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", 6326, __extension__ __PRETTY_FUNCTION__
))
6326 "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", 6326, __extension__ __PRETTY_FUNCTION__
))
;
6327 }
6328
6329 // If too many are passed and not variadic, error on the extras and drop
6330 // them.
6331 if (Args.size() > NumParams) {
6332 if (!Proto->isVariadic()) {
6333 TypoCorrection TC;
6334 if (FDecl && (TC = TryTypoCorrectionForCall(*this, Fn, FDecl, Args))) {
6335 unsigned diag_id =
6336 MinArgs == NumParams && !Proto->isVariadic()
6337 ? diag::err_typecheck_call_too_many_args_suggest
6338 : diag::err_typecheck_call_too_many_args_at_most_suggest;
6339 diagnoseTypo(TC, PDiag(diag_id) << FnKind << NumParams
6340 << static_cast<unsigned>(Args.size())
6341 << TC.getCorrectionRange());
6342 } else if (NumParams == 1 && FDecl &&
6343 FDecl->getParamDecl(0)->getDeclName())
6344 Diag(Args[NumParams]->getBeginLoc(),
6345 MinArgs == NumParams
6346 ? diag::err_typecheck_call_too_many_args_one
6347 : diag::err_typecheck_call_too_many_args_at_most_one)
6348 << FnKind << FDecl->getParamDecl(0)
6349 << static_cast<unsigned>(Args.size()) << Fn->getSourceRange()
6350 << SourceRange(Args[NumParams]->getBeginLoc(),
6351 Args.back()->getEndLoc());
6352 else
6353 Diag(Args[NumParams]->getBeginLoc(),
6354 MinArgs == NumParams
6355 ? diag::err_typecheck_call_too_many_args
6356 : diag::err_typecheck_call_too_many_args_at_most)
6357 << FnKind << NumParams << static_cast<unsigned>(Args.size())
6358 << Fn->getSourceRange()
6359 << SourceRange(Args[NumParams]->getBeginLoc(),
6360 Args.back()->getEndLoc());
6361
6362 // Emit the location of the prototype.
6363 if (!TC && FDecl && !FDecl->getBuiltinID() && !IsExecConfig)
6364 Diag(FDecl->getLocation(), diag::note_callee_decl) << FDecl;
6365
6366 // This deletes the extra arguments.
6367 Call->shrinkNumArgs(NumParams);
6368 return true;
6369 }
6370 }
6371 SmallVector<Expr *, 8> AllArgs;
6372 VariadicCallType CallType = getVariadicCallType(FDecl, Proto, Fn);
6373
6374 Invalid = GatherArgumentsForCall(Call->getBeginLoc(), FDecl, Proto, 0, Args,
6375 AllArgs, CallType);
6376 if (Invalid)
6377 return true;
6378 unsigned TotalNumArgs = AllArgs.size();
6379 for (unsigned i = 0; i < TotalNumArgs; ++i)
6380 Call->setArg(i, AllArgs[i]);
6381
6382 Call->computeDependence();
6383 return false;
6384}
6385
6386bool Sema::GatherArgumentsForCall(SourceLocation CallLoc, FunctionDecl *FDecl,
6387 const FunctionProtoType *Proto,
6388 unsigned FirstParam, ArrayRef<Expr *> Args,
6389 SmallVectorImpl<Expr *> &AllArgs,
6390 VariadicCallType CallType, bool AllowExplicit,
6391 bool IsListInitialization) {
6392 unsigned NumParams = Proto->getNumParams();
6393 bool Invalid = false;
6394 size_t ArgIx = 0;
6395 // Continue to check argument types (even if we have too few/many args).
6396 for (unsigned i = FirstParam; i < NumParams; i++) {
6397 QualType ProtoArgType = Proto->getParamType(i);
6398
6399 Expr *Arg;
6400 ParmVarDecl *Param = FDecl ? FDecl->getParamDecl(i) : nullptr;
6401 if (ArgIx < Args.size()) {
6402 Arg = Args[ArgIx++];
6403
6404 if (RequireCompleteType(Arg->getBeginLoc(), ProtoArgType,
6405 diag::err_call_incomplete_argument, Arg))
6406 return true;
6407
6408 // Strip the unbridged-cast placeholder expression off, if applicable.
6409 bool CFAudited = false;
6410 if (Arg->getType() == Context.ARCUnbridgedCastTy &&
6411 FDecl && FDecl->hasAttr<CFAuditedTransferAttr>() &&
6412 (!Param || !Param->hasAttr<CFConsumedAttr>()))
6413 Arg = stripARCUnbridgedCast(Arg);
6414 else if (getLangOpts().ObjCAutoRefCount &&
6415 FDecl && FDecl->hasAttr<CFAuditedTransferAttr>() &&
6416 (!Param || !Param->hasAttr<CFConsumedAttr>()))
6417 CFAudited = true;
6418
6419 if (Proto->getExtParameterInfo(i).isNoEscape() &&
6420 ProtoArgType->isBlockPointerType())
6421 if (auto *BE = dyn_cast<BlockExpr>(Arg->IgnoreParenNoopCasts(Context)))
6422 BE->getBlockDecl()->setDoesNotEscape();
6423
6424 InitializedEntity Entity =
6425 Param ? InitializedEntity::InitializeParameter(Context, Param,
6426 ProtoArgType)
6427 : InitializedEntity::InitializeParameter(
6428 Context, ProtoArgType, Proto->isParamConsumed(i));
6429
6430 // Remember that parameter belongs to a CF audited API.
6431 if (CFAudited)
6432 Entity.setParameterCFAudited();
6433
6434 ExprResult ArgE = PerformCopyInitialization(
6435 Entity, SourceLocation(), Arg, IsListInitialization, AllowExplicit);
6436 if (ArgE.isInvalid())
6437 return true;
6438
6439 Arg = ArgE.getAs<Expr>();
6440 } else {
6441 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", 6441, __extension__ __PRETTY_FUNCTION__
))
;
6442
6443 ExprResult ArgExpr = BuildCXXDefaultArgExpr(CallLoc, FDecl, Param);
6444 if (ArgExpr.isInvalid())
6445 return true;
6446
6447 Arg = ArgExpr.getAs<Expr>();
6448 }
6449
6450 // Check for array bounds violations for each argument to the call. This
6451 // check only triggers warnings when the argument isn't a more complex Expr
6452 // with its own checking, such as a BinaryOperator.
6453 CheckArrayAccess(Arg);
6454
6455 // Check for violations of C99 static array rules (C99 6.7.5.3p7).
6456 CheckStaticArrayArgument(CallLoc, Param, Arg);
6457
6458 AllArgs.push_back(Arg);
6459 }
6460
6461 // If this is a variadic call, handle args passed through "...".
6462 if (CallType != VariadicDoesNotApply) {
6463 // Assume that extern "C" functions with variadic arguments that
6464 // return __unknown_anytype aren't *really* variadic.
6465 if (Proto->getReturnType() == Context.UnknownAnyTy && FDecl &&
6466 FDecl->isExternC()) {
6467 for (Expr *A : Args.slice(ArgIx)) {
6468 QualType paramType; // ignored
6469 ExprResult arg = checkUnknownAnyArg(CallLoc, A, paramType);
6470 Invalid |= arg.isInvalid();
6471 AllArgs.push_back(arg.get());
6472 }
6473
6474 // Otherwise do argument promotion, (C99 6.5.2.2p7).
6475 } else {
6476 for (Expr *A : Args.slice(ArgIx)) {
6477 ExprResult Arg = DefaultVariadicArgumentPromotion(A, CallType, FDecl);
6478 Invalid |= Arg.isInvalid();
6479 AllArgs.push_back(Arg.get());
6480 }
6481 }
6482
6483 // Check for array bounds violations.
6484 for (Expr *A : Args.slice(ArgIx))
6485 CheckArrayAccess(A);
6486 }
6487 return Invalid;
6488}
6489
6490static void DiagnoseCalleeStaticArrayParam(Sema &S, ParmVarDecl *PVD) {
6491 TypeLoc TL = PVD->getTypeSourceInfo()->getTypeLoc();
6492 if (DecayedTypeLoc DTL = TL.getAs<DecayedTypeLoc>())
6493 TL = DTL.getOriginalLoc();
6494 if (ArrayTypeLoc ATL = TL.getAs<ArrayTypeLoc>())
6495 S.Diag(PVD->getLocation(), diag::note_callee_static_array)
6496 << ATL.getLocalSourceRange();
6497}
6498
6499/// CheckStaticArrayArgument - If the given argument corresponds to a static
6500/// array parameter, check that it is non-null, and that if it is formed by
6501/// array-to-pointer decay, the underlying array is sufficiently large.
6502///
6503/// C99 6.7.5.3p7: If the keyword static also appears within the [ and ] of the
6504/// array type derivation, then for each call to the function, the value of the
6505/// corresponding actual argument shall provide access to the first element of
6506/// an array with at least as many elements as specified by the size expression.
6507void
6508Sema::CheckStaticArrayArgument(SourceLocation CallLoc,
6509 ParmVarDecl *Param,
6510 const Expr *ArgExpr) {
6511 // Static array parameters are not supported in C++.
6512 if (!Param || getLangOpts().CPlusPlus)
6513 return;
6514
6515 QualType OrigTy = Param->getOriginalType();
6516
6517 const ArrayType *AT = Context.getAsArrayType(OrigTy);
6518 if (!AT || AT->getSizeModifier() != ArrayType::Static)
6519 return;
6520
6521 if (ArgExpr->isNullPointerConstant(Context,
6522 Expr::NPC_NeverValueDependent)) {
6523 Diag(CallLoc, diag::warn_null_arg) << ArgExpr->getSourceRange();
6524 DiagnoseCalleeStaticArrayParam(*this, Param);
6525 return;
6526 }
6527
6528 const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT);
6529 if (!CAT)
6530 return;
6531
6532 const ConstantArrayType *ArgCAT =
6533 Context.getAsConstantArrayType(ArgExpr->IgnoreParenCasts()->getType());
6534 if (!ArgCAT)
6535 return;
6536
6537 if (getASTContext().hasSameUnqualifiedType(CAT->getElementType(),
6538 ArgCAT->getElementType())) {
6539 if (ArgCAT->getSize().ult(CAT->getSize())) {
6540 Diag(CallLoc, diag::warn_static_array_too_small)
6541 << ArgExpr->getSourceRange()
6542 << (unsigned)ArgCAT->getSize().getZExtValue()
6543 << (unsigned)CAT->getSize().getZExtValue() << 0;
6544 DiagnoseCalleeStaticArrayParam(*this, Param);
6545 }
6546 return;
6547 }
6548
6549 std::optional<CharUnits> ArgSize =
6550 getASTContext().getTypeSizeInCharsIfKnown(ArgCAT);
6551 std::optional<CharUnits> ParmSize =
6552 getASTContext().getTypeSizeInCharsIfKnown(CAT);
6553 if (ArgSize && ParmSize && *ArgSize < *ParmSize) {
6554 Diag(CallLoc, diag::warn_static_array_too_small)
6555 << ArgExpr->getSourceRange() << (unsigned)ArgSize->getQuantity()
6556 << (unsigned)ParmSize->getQuantity() << 1;
6557 DiagnoseCalleeStaticArrayParam(*this, Param);
6558 }
6559}
6560
6561/// Given a function expression of unknown-any type, try to rebuild it
6562/// to have a function type.
6563static ExprResult rebuildUnknownAnyFunction(Sema &S, Expr *fn);
6564
6565/// Is the given type a placeholder that we need to lower out
6566/// immediately during argument processing?
6567static bool isPlaceholderToRemoveAsArg(QualType type) {
6568 // Placeholders are never sugared.
6569 const BuiltinType *placeholder = dyn_cast<BuiltinType>(type);
6570 if (!placeholder) return false;
6571
6572 switch (placeholder->getKind()) {
6573 // Ignore all the non-placeholder types.
6574#define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
6575 case BuiltinType::Id:
6576#include "clang/Basic/OpenCLImageTypes.def"
6577#define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \
6578 case BuiltinType::Id:
6579#include "clang/Basic/OpenCLExtensionTypes.def"
6580 // In practice we'll never use this, since all SVE types are sugared
6581 // via TypedefTypes rather than exposed directly as BuiltinTypes.
6582#define SVE_TYPE(Name, Id, SingletonId) \
6583 case BuiltinType::Id:
6584#include "clang/Basic/AArch64SVEACLETypes.def"
6585#define PPC_VECTOR_TYPE(Name, Id, Size) \
6586 case BuiltinType::Id:
6587#include "clang/Basic/PPCTypes.def"
6588#define RVV_TYPE(Name, Id, SingletonId) case BuiltinType::Id:
6589#include "clang/Basic/RISCVVTypes.def"
6590#define WASM_TYPE(Name, Id, SingletonId) case BuiltinType::Id:
6591#include "clang/Basic/WebAssemblyReferenceTypes.def"
6592#define PLACEHOLDER_TYPE(ID, SINGLETON_ID)
6593#define BUILTIN_TYPE(ID, SINGLETON_ID) case BuiltinType::ID:
6594#include "clang/AST/BuiltinTypes.def"
6595 return false;
6596
6597 // We cannot lower out overload sets; they might validly be resolved
6598 // by the call machinery.
6599 case BuiltinType::Overload:
6600 return false;
6601
6602 // Unbridged casts in ARC can be handled in some call positions and
6603 // should be left in place.
6604 case BuiltinType::ARCUnbridgedCast:
6605 return false;
6606
6607 // Pseudo-objects should be converted as soon as possible.
6608 case BuiltinType::PseudoObject:
6609 return true;
6610
6611 // The debugger mode could theoretically but currently does not try
6612 // to resolve unknown-typed arguments based on known parameter types.
6613 case BuiltinType::UnknownAny:
6614 return true;
6615
6616 // These are always invalid as call arguments and should be reported.
6617 case BuiltinType::BoundMember:
6618 case BuiltinType::BuiltinFn:
6619 case BuiltinType::IncompleteMatrixIdx:
6620 case BuiltinType::OMPArraySection:
6621 case BuiltinType::OMPArrayShaping:
6622 case BuiltinType::OMPIterator:
6623 return true;
6624
6625 }
6626 llvm_unreachable("bad builtin type kind")::llvm::llvm_unreachable_internal("bad builtin type kind", "clang/lib/Sema/SemaExpr.cpp"
, 6626)
;
6627}
6628
6629/// Check an argument list for placeholders that we won't try to
6630/// handle later.
6631static bool checkArgsForPlaceholders(Sema &S, MultiExprArg args) {
6632 // Apply this processing to all the arguments at once instead of
6633 // dying at the first failure.
6634 bool hasInvalid = false;
6635 for (size_t i = 0, e = args.size(); i != e; i++) {
6636 if (isPlaceholderToRemoveAsArg(args[i]->getType())) {
6637 ExprResult result = S.CheckPlaceholderExpr(args[i]);
6638 if (result.isInvalid()) hasInvalid = true;
6639 else args[i] = result.get();
6640 }
6641 }
6642 return hasInvalid;
6643}
6644
6645/// If a builtin function has a pointer argument with no explicit address
6646/// space, then it should be able to accept a pointer to any address
6647/// space as input. In order to do this, we need to replace the
6648/// standard builtin declaration with one that uses the same address space
6649/// as the call.
6650///
6651/// \returns nullptr If this builtin is not a candidate for a rewrite i.e.
6652/// it does not contain any pointer arguments without
6653/// an address space qualifer. Otherwise the rewritten
6654/// FunctionDecl is returned.
6655/// TODO: Handle pointer return types.
6656static FunctionDecl *rewriteBuiltinFunctionDecl(Sema *Sema, ASTContext &Context,
6657 FunctionDecl *FDecl,
6658 MultiExprArg ArgExprs) {
6659
6660 QualType DeclType = FDecl->getType();
6661 const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(DeclType);
6662
6663 if (!Context.BuiltinInfo.hasPtrArgsOrResult(FDecl->getBuiltinID()) || !FT ||
6664 ArgExprs.size() < FT->getNumParams())
6665 return nullptr;
6666
6667 bool NeedsNewDecl = false;
6668 unsigned i = 0;
6669 SmallVector<QualType, 8> OverloadParams;
6670
6671 for (QualType ParamType : FT->param_types()) {
6672
6673 // Convert array arguments to pointer to simplify type lookup.
6674 ExprResult ArgRes =
6675 Sema->DefaultFunctionArrayLvalueConversion(ArgExprs[i++]);
6676 if (ArgRes.isInvalid())
6677 return nullptr;
6678 Expr *Arg = ArgRes.get();
6679 QualType ArgType = Arg->getType();
6680 if (!ParamType->isPointerType() || ParamType.hasAddressSpace() ||
6681 !ArgType->isPointerType() ||
6682 !ArgType->getPointeeType().hasAddressSpace() ||
6683 isPtrSizeAddressSpace(ArgType->getPointeeType().getAddressSpace())) {
6684 OverloadParams.push_back(ParamType);
6685 continue;
6686 }
6687
6688 QualType PointeeType = ParamType->getPointeeType();
6689 if (PointeeType.hasAddressSpace())
6690 continue;
6691
6692 NeedsNewDecl = true;
6693 LangAS AS = ArgType->getPointeeType().getAddressSpace();
6694
6695 PointeeType = Context.getAddrSpaceQualType(PointeeType, AS);
6696 OverloadParams.push_back(Context.getPointerType(PointeeType));
6697 }
6698
6699 if (!NeedsNewDecl)
6700 return nullptr;
6701
6702 FunctionProtoType::ExtProtoInfo EPI;
6703 EPI.Variadic = FT->isVariadic();
6704 QualType OverloadTy = Context.getFunctionType(FT->getReturnType(),
6705 OverloadParams, EPI);
6706 DeclContext *Parent = FDecl->getParent();
6707 FunctionDecl *OverloadDecl = FunctionDecl::Create(
6708 Context, Parent, FDecl->getLocation(), FDecl->getLocation(),
6709 FDecl->getIdentifier(), OverloadTy,
6710 /*TInfo=*/nullptr, SC_Extern, Sema->getCurFPFeatures().isFPConstrained(),
6711 false,
6712 /*hasPrototype=*/true);
6713 SmallVector<ParmVarDecl*, 16> Params;
6714 FT = cast<FunctionProtoType>(OverloadTy);
6715 for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i) {
6716 QualType ParamType = FT->getParamType(i);
6717 ParmVarDecl *Parm =
6718 ParmVarDecl::Create(Context, OverloadDecl, SourceLocation(),
6719 SourceLocation(), nullptr, ParamType,
6720 /*TInfo=*/nullptr, SC_None, nullptr);
6721 Parm->setScopeInfo(0, i);
6722 Params.push_back(Parm);
6723 }
6724 OverloadDecl->setParams(Params);
6725 Sema->mergeDeclAttributes(OverloadDecl, FDecl);
6726 return OverloadDecl;
6727}
6728
6729static void checkDirectCallValidity(Sema &S, const Expr *Fn,
6730 FunctionDecl *Callee,
6731 MultiExprArg ArgExprs) {
6732 // `Callee` (when called with ArgExprs) may be ill-formed. enable_if (and
6733 // similar attributes) really don't like it when functions are called with an
6734 // invalid number of args.
6735 if (S.TooManyArguments(Callee->getNumParams(), ArgExprs.size(),
6736 /*PartialOverloading=*/false) &&
6737 !Callee->isVariadic())
6738 return;
6739 if (Callee->getMinRequiredArguments() > ArgExprs.size())
6740 return;
6741
6742 if (const EnableIfAttr *Attr =
6743 S.CheckEnableIf(Callee, Fn->getBeginLoc(), ArgExprs, true)) {
6744 S.Diag(Fn->getBeginLoc(),
6745 isa<CXXMethodDecl>(Callee)
6746 ? diag::err_ovl_no_viable_member_function_in_call
6747 : diag::err_ovl_no_viable_function_in_call)
6748 << Callee << Callee->getSourceRange();
6749 S.Diag(Callee->getLocation(),
6750 diag::note_ovl_candidate_disabled_by_function_cond_attr)
6751 << Attr->getCond()->getSourceRange() << Attr->getMessage();
6752 return;
6753 }
6754}
6755
6756static bool enclosingClassIsRelatedToClassInWhichMembersWereFound(
6757 const UnresolvedMemberExpr *const UME, Sema &S) {
6758
6759 const auto GetFunctionLevelDCIfCXXClass =
6760 [](Sema &S) -> const CXXRecordDecl * {
6761 const DeclContext *const DC = S.getFunctionLevelDeclContext();
6762 if (!DC || !DC->getParent())
6763 return nullptr;
6764
6765 // If the call to some member function was made from within a member
6766 // function body 'M' return return 'M's parent.
6767 if (const auto *MD = dyn_cast<CXXMethodDecl>(DC))
6768 return MD->getParent()->getCanonicalDecl();
6769 // else the call was made from within a default member initializer of a
6770 // class, so return the class.
6771 if (const auto *RD = dyn_cast<CXXRecordDecl>(DC))
6772 return RD->getCanonicalDecl();
6773 return nullptr;
6774 };
6775 // If our DeclContext is neither a member function nor a class (in the
6776 // case of a lambda in a default member initializer), we can't have an
6777 // enclosing 'this'.
6778
6779 const CXXRecordDecl *const CurParentClass = GetFunctionLevelDCIfCXXClass(S);
6780 if (!CurParentClass)
6781 return false;
6782
6783 // The naming class for implicit member functions call is the class in which
6784 // name lookup starts.
6785 const CXXRecordDecl *const NamingClass =
6786 UME->getNamingClass()->getCanonicalDecl();
6787 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", 6787, __extension__ __PRETTY_FUNCTION__
))
;
6788
6789 // If the unresolved member functions were found in a 'naming class' that is
6790 // related (either the same or derived from) to the class that contains the
6791 // member function that itself contained the implicit member access.
6792
6793 return CurParentClass == NamingClass ||
6794 CurParentClass->isDerivedFrom(NamingClass);
6795}
6796
6797static void
6798tryImplicitlyCaptureThisIfImplicitMemberFunctionAccessWithDependentArgs(
6799 Sema &S, const UnresolvedMemberExpr *const UME, SourceLocation CallLoc) {
6800
6801 if (!UME)
6802 return;
6803
6804 LambdaScopeInfo *const CurLSI = S.getCurLambda();
6805 // Only try and implicitly capture 'this' within a C++ Lambda if it hasn't
6806 // already been captured, or if this is an implicit member function call (if
6807 // it isn't, an attempt to capture 'this' should already have been made).
6808 if (!CurLSI || CurLSI->ImpCaptureStyle == CurLSI->ImpCap_None ||
6809 !UME->isImplicitAccess() || CurLSI->isCXXThisCaptured())
6810 return;
6811
6812 // Check if the naming class in which the unresolved members were found is
6813 // related (same as or is a base of) to the enclosing class.
6814
6815 if (!enclosingClassIsRelatedToClassInWhichMembersWereFound(UME, S))
6816 return;
6817
6818
6819 DeclContext *EnclosingFunctionCtx = S.CurContext->getParent()->getParent();
6820 // If the enclosing function is not dependent, then this lambda is
6821 // capture ready, so if we can capture this, do so.
6822 if (!EnclosingFunctionCtx->isDependentContext()) {
6823 // If the current lambda and all enclosing lambdas can capture 'this' -
6824 // then go ahead and capture 'this' (since our unresolved overload set
6825 // contains at least one non-static member function).
6826 if (!S.CheckCXXThisCapture(CallLoc, /*Explcit*/ false, /*Diagnose*/ false))
6827 S.CheckCXXThisCapture(CallLoc);
6828 } else if (S.CurContext->isDependentContext()) {
6829 // ... since this is an implicit member reference, that might potentially
6830 // involve a 'this' capture, mark 'this' for potential capture in
6831 // enclosing lambdas.
6832 if (CurLSI->ImpCaptureStyle != CurLSI->ImpCap_None)
6833 CurLSI->addPotentialThisCapture(CallLoc);
6834 }
6835}
6836
6837// Once a call is fully resolved, warn for unqualified calls to specific
6838// C++ standard functions, like move and forward.
6839static void DiagnosedUnqualifiedCallsToStdFunctions(Sema &S, CallExpr *Call) {
6840 // We are only checking unary move and forward so exit early here.
6841 if (Call->getNumArgs() != 1)
6842 return;
6843
6844 Expr *E = Call->getCallee()->IgnoreParenImpCasts();
6845 if (!E || isa<UnresolvedLookupExpr>(E))
6846 return;
6847 DeclRefExpr *DRE = dyn_cast_or_null<DeclRefExpr>(E);
6848 if (!DRE || !DRE->getLocation().isValid())
6849 return;
6850
6851 if (DRE->getQualifier())
6852 return;
6853
6854 const FunctionDecl *FD = Call->getDirectCallee();
6855 if (!FD)
6856 return;
6857
6858 // Only warn for some functions deemed more frequent or problematic.
6859 unsigned BuiltinID = FD->getBuiltinID();
6860 if (BuiltinID != Builtin::BImove && BuiltinID != Builtin::BIforward)
6861 return;
6862
6863 S.Diag(DRE->getLocation(), diag::warn_unqualified_call_to_std_cast_function)
6864 << FD->getQualifiedNameAsString()
6865 << FixItHint::CreateInsertion(DRE->getLocation(), "std::");
6866}
6867
6868ExprResult Sema::ActOnCallExpr(Scope *Scope, Expr *Fn, SourceLocation LParenLoc,
6869 MultiExprArg ArgExprs, SourceLocation RParenLoc,
6870 Expr *ExecConfig) {
6871 ExprResult Call =
6872 BuildCallExpr(Scope, Fn, LParenLoc, ArgExprs, RParenLoc, ExecConfig,
6873 /*IsExecConfig=*/false, /*AllowRecovery=*/true);
6874 if (Call.isInvalid())
6875 return Call;
6876
6877 // Diagnose uses of the C++20 "ADL-only template-id call" feature in earlier
6878 // language modes.
6879 if (auto *ULE = dyn_cast<UnresolvedLookupExpr>(Fn)) {
6880 if (ULE->hasExplicitTemplateArgs() &&
6881 ULE->decls_begin() == ULE->decls_end()) {
6882 Diag(Fn->getExprLoc(), getLangOpts().CPlusPlus20
6883 ? diag::warn_cxx17_compat_adl_only_template_id
6884 : diag::ext_adl_only_template_id)
6885 << ULE->getName();
6886 }
6887 }
6888
6889 if (LangOpts.OpenMP)
6890 Call = ActOnOpenMPCall(Call, Scope, LParenLoc, ArgExprs, RParenLoc,
6891 ExecConfig);
6892 if (LangOpts.CPlusPlus) {
6893 CallExpr *CE = dyn_cast<CallExpr>(Call.get());
6894 if (CE)
6895 DiagnosedUnqualifiedCallsToStdFunctions(*this, CE);
6896 }
6897 return Call;
6898}
6899
6900/// BuildCallExpr - Handle a call to Fn with the specified array of arguments.
6901/// This provides the location of the left/right parens and a list of comma
6902/// locations.
6903ExprResult Sema::BuildCallExpr(Scope *Scope, Expr *Fn, SourceLocation LParenLoc,
6904 MultiExprArg ArgExprs, SourceLocation RParenLoc,
6905 Expr *ExecConfig, bool IsExecConfig,
6906 bool AllowRecovery) {
6907 // Since this might be a postfix expression, get rid of ParenListExprs.
6908 ExprResult Result = MaybeConvertParenListExprToParenExpr(Scope, Fn);
6909 if (Result.isInvalid()) return ExprError();
6910 Fn = Result.get();
6911
6912 if (checkArgsForPlaceholders(*this, ArgExprs))
6913 return ExprError();
6914
6915 if (getLangOpts().CPlusPlus) {
6916 // If this is a pseudo-destructor expression, build the call immediately.
6917 if (isa<CXXPseudoDestructorExpr>(Fn)) {
6918 if (!ArgExprs.empty()) {
6919 // Pseudo-destructor calls should not have any arguments.
6920 Diag(Fn->getBeginLoc(), diag::err_pseudo_dtor_call_with_args)
6921 << FixItHint::CreateRemoval(
6922 SourceRange(ArgExprs.front()->getBeginLoc(),
6923 ArgExprs.back()->getEndLoc()));
6924 }
6925
6926 return CallExpr::Create(Context, Fn, /*Args=*/{}, Context.VoidTy,
6927 VK_PRValue, RParenLoc, CurFPFeatureOverrides());
6928 }
6929 if (Fn->getType() == Context.PseudoObjectTy) {
6930 ExprResult result = CheckPlaceholderExpr(Fn);
6931 if (result.isInvalid()) return ExprError();
6932 Fn = result.get();
6933 }
6934
6935 // Determine whether this is a dependent call inside a C++ template,
6936 // in which case we won't do any semantic analysis now.
6937 if (Fn->isTypeDependent() || Expr::hasAnyTypeDependentArguments(ArgExprs)) {
6938 if (ExecConfig) {
6939 return CUDAKernelCallExpr::Create(Context, Fn,
6940 cast<CallExpr>(ExecConfig), ArgExprs,
6941 Context.DependentTy, VK_PRValue,
6942 RParenLoc, CurFPFeatureOverrides());
6943 } else {
6944
6945 tryImplicitlyCaptureThisIfImplicitMemberFunctionAccessWithDependentArgs(
6946 *this, dyn_cast<UnresolvedMemberExpr>(Fn->IgnoreParens()),
6947 Fn->getBeginLoc());
6948
6949 return CallExpr::Create(Context, Fn, ArgExprs, Context.DependentTy,
6950 VK_PRValue, RParenLoc, CurFPFeatureOverrides());
6951 }
6952 }
6953
6954 // Determine whether this is a call to an object (C++ [over.call.object]).
6955 if (Fn->getType()->isRecordType())
6956 return BuildCallToObjectOfClassType(Scope, Fn, LParenLoc, ArgExprs,
6957 RParenLoc);
6958
6959 if (Fn->getType() == Context.UnknownAnyTy) {
6960 ExprResult result = rebuildUnknownAnyFunction(*this, Fn);
6961 if (result.isInvalid()) return ExprError();
6962 Fn = result.get();
6963 }
6964
6965 if (Fn->getType() == Context.BoundMemberTy) {
6966 return BuildCallToMemberFunction(Scope, Fn, LParenLoc, ArgExprs,
6967 RParenLoc, ExecConfig, IsExecConfig,
6968 AllowRecovery);
6969 }
6970 }
6971
6972 // Check for overloaded calls. This can happen even in C due to extensions.
6973 if (Fn->getType() == Context.OverloadTy) {
6974 OverloadExpr::FindResult find = OverloadExpr::find(Fn);
6975
6976 // We aren't supposed to apply this logic if there's an '&' involved.
6977 if (!find.HasFormOfMemberPointer) {
6978 if (Expr::hasAnyTypeDependentArguments(ArgExprs))
6979 return CallExpr::Create(Context, Fn, ArgExprs, Context.DependentTy,
6980 VK_PRValue, RParenLoc, CurFPFeatureOverrides());
6981 OverloadExpr *ovl = find.Expression;
6982 if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(ovl))
6983 return BuildOverloadedCallExpr(
6984 Scope, Fn, ULE, LParenLoc, ArgExprs, RParenLoc, ExecConfig,
6985 /*AllowTypoCorrection=*/true, find.IsAddressOfOperand);
6986 return BuildCallToMemberFunction(Scope, Fn, LParenLoc, ArgExprs,
6987 RParenLoc, ExecConfig, IsExecConfig,
6988 AllowRecovery);
6989 }
6990 }
6991
6992 // If we're directly calling a function, get the appropriate declaration.
6993 if (Fn->getType() == Context.UnknownAnyTy) {
6994 ExprResult result = rebuildUnknownAnyFunction(*this, Fn);
6995 if (result.isInvalid()) return ExprError();
6996 Fn = result.get();
6997 }
6998
6999 Expr *NakedFn = Fn->IgnoreParens();
7000
7001 bool CallingNDeclIndirectly = false;
7002 NamedDecl *NDecl = nullptr;
7003 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(NakedFn)) {
7004 if (UnOp->getOpcode() == UO_AddrOf) {
7005 CallingNDeclIndirectly = true;
7006 NakedFn = UnOp->getSubExpr()->IgnoreParens();
7007 }
7008 }
7009
7010 if (auto *DRE = dyn_cast<DeclRefExpr>(NakedFn)) {
7011 NDecl = DRE->getDecl();
7012
7013 FunctionDecl *FDecl = dyn_cast<FunctionDecl>(NDecl);
7014 if (FDecl && FDecl->getBuiltinID()) {
7015 // Rewrite the function decl for this builtin by replacing parameters
7016 // with no explicit address space with the address space of the arguments
7017 // in ArgExprs.
7018 if ((FDecl =
7019 rewriteBuiltinFunctionDecl(this, Context, FDecl, ArgExprs))) {
7020 NDecl = FDecl;
7021 Fn = DeclRefExpr::Create(
7022 Context, FDecl->getQualifierLoc(), SourceLocation(), FDecl, false,
7023 SourceLocation(), FDecl->getType(), Fn->getValueKind(), FDecl,
7024 nullptr, DRE->isNonOdrUse());
7025 }
7026 }
7027 } else if (auto *ME = dyn_cast<MemberExpr>(NakedFn))
7028 NDecl = ME->getMemberDecl();
7029
7030 if (FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(NDecl)) {
7031 if (CallingNDeclIndirectly && !checkAddressOfFunctionIsAvailable(
7032 FD, /*Complain=*/true, Fn->getBeginLoc()))
7033 return ExprError();
7034
7035 checkDirectCallValidity(*this, Fn, FD, ArgExprs);
7036
7037 // If this expression is a call to a builtin function in HIP device
7038 // compilation, allow a pointer-type argument to default address space to be
7039 // passed as a pointer-type parameter to a non-default address space.
7040 // If Arg is declared in the default address space and Param is declared
7041 // in a non-default address space, perform an implicit address space cast to
7042 // the parameter type.
7043 if (getLangOpts().HIP && getLangOpts().CUDAIsDevice && FD &&
7044 FD->getBuiltinID()) {
7045 for (unsigned Idx = 0; Idx < FD->param_size(); ++Idx) {
7046 ParmVarDecl *Param = FD->getParamDecl(Idx);
7047 if (!ArgExprs[Idx] || !Param || !Param->getType()->isPointerType() ||
7048 !ArgExprs[Idx]->getType()->isPointerType())
7049 continue;
7050
7051 auto ParamAS = Param->getType()->getPointeeType().getAddressSpace();
7052 auto ArgTy = ArgExprs[Idx]->getType();
7053 auto ArgPtTy = ArgTy->getPointeeType();
7054 auto ArgAS = ArgPtTy.getAddressSpace();
7055
7056 // Add address space cast if target address spaces are different
7057 bool NeedImplicitASC =
7058 ParamAS != LangAS::Default && // Pointer params in generic AS don't need special handling.
7059 ( ArgAS == LangAS::Default || // We do allow implicit conversion from generic AS
7060 // or from specific AS which has target AS matching that of Param.
7061 getASTContext().getTargetAddressSpace(ArgAS) == getASTContext().getTargetAddressSpace(ParamAS));
7062 if (!NeedImplicitASC)
7063 continue;
7064
7065 // First, ensure that the Arg is an RValue.
7066 if (ArgExprs[Idx]->isGLValue()) {
7067 ArgExprs[Idx] = ImplicitCastExpr::Create(
7068 Context, ArgExprs[Idx]->getType(), CK_NoOp, ArgExprs[Idx],
7069 nullptr, VK_PRValue, FPOptionsOverride());
7070 }
7071
7072 // Construct a new arg type with address space of Param
7073 Qualifiers ArgPtQuals = ArgPtTy.getQualifiers();
7074 ArgPtQuals.setAddressSpace(ParamAS);
7075 auto NewArgPtTy =
7076 Context.getQualifiedType(ArgPtTy.getUnqualifiedType(), ArgPtQuals);
7077 auto NewArgTy =
7078 Context.getQualifiedType(Context.getPointerType(NewArgPtTy),
7079 ArgTy.getQualifiers());
7080
7081 // Finally perform an implicit address space cast
7082 ArgExprs[Idx] = ImpCastExprToType(ArgExprs[Idx], NewArgTy,
7083 CK_AddressSpaceConversion)
7084 .get();
7085 }
7086 }
7087 }
7088
7089 if (Context.isDependenceAllowed() &&
7090 (Fn->isTypeDependent() || Expr::hasAnyTypeDependentArguments(ArgExprs))) {
7091 assert(!getLangOpts().CPlusPlus)(static_cast <bool> (!getLangOpts().CPlusPlus) ? void (
0) : __assert_fail ("!getLangOpts().CPlusPlus", "clang/lib/Sema/SemaExpr.cpp"
, 7091, __extension__ __PRETTY_FUNCTION__))
;
7092 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", 7095, __extension__ __PRETTY_FUNCTION__
))
7093 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", 7095, __extension__ __PRETTY_FUNCTION__
))
7094 [](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", 7095, __extension__ __PRETTY_FUNCTION__
))
7095 "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", 7095, __extension__ __PRETTY_FUNCTION__
))
;
7096 QualType ReturnType =
7097 llvm::isa_and_nonnull<FunctionDecl>(NDecl)
7098 ? cast<FunctionDecl>(NDecl)->getCallResultType()
7099 : Context.DependentTy;
7100 return CallExpr::Create(Context, Fn, ArgExprs, ReturnType,
7101 Expr::getValueKindForType(ReturnType), RParenLoc,
7102 CurFPFeatureOverrides());
7103 }
7104 return BuildResolvedCallExpr(Fn, NDecl, LParenLoc, ArgExprs, RParenLoc,
7105 ExecConfig, IsExecConfig);
7106}
7107
7108/// BuildBuiltinCallExpr - Create a call to a builtin function specified by Id
7109// with the specified CallArgs
7110Expr *Sema::BuildBuiltinCallExpr(SourceLocation Loc, Builtin::ID Id,
7111 MultiExprArg CallArgs) {
7112 StringRef Name = Context.BuiltinInfo.getName(Id);
7113 LookupResult R(*this, &Context.Idents.get(Name), Loc,
7114 Sema::LookupOrdinaryName);
7115 LookupName(R, TUScope, /*AllowBuiltinCreation=*/true);
7116
7117 auto *BuiltInDecl = R.getAsSingle<FunctionDecl>();
7118 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", 7118, __extension__ __PRETTY_FUNCTION__
))
;
7119
7120 ExprResult DeclRef =
7121 BuildDeclRefExpr(BuiltInDecl, BuiltInDecl->getType(), VK_LValue, Loc);
7122 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", 7122, __extension__ __PRETTY_FUNCTION__
))
;
7123
7124 ExprResult Call =
7125 BuildCallExpr(/*Scope=*/nullptr, DeclRef.get(), Loc, CallArgs, Loc);
7126
7127 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", 7127, __extension__ __PRETTY_FUNCTION__
))
;
7128 return Call.get();
7129}
7130
7131/// Parse a __builtin_astype expression.
7132///
7133/// __builtin_astype( value, dst type )
7134///
7135ExprResult Sema::ActOnAsTypeExpr(Expr *E, ParsedType ParsedDestTy,
7136 SourceLocation BuiltinLoc,
7137 SourceLocation RParenLoc) {
7138 QualType DstTy = GetTypeFromParser(ParsedDestTy);
7139 return BuildAsTypeExpr(E, DstTy, BuiltinLoc, RParenLoc);
7140}
7141
7142/// Create a new AsTypeExpr node (bitcast) from the arguments.
7143ExprResult Sema::BuildAsTypeExpr(Expr *E, QualType DestTy,
7144 SourceLocation BuiltinLoc,
7145 SourceLocation RParenLoc) {
7146 ExprValueKind VK = VK_PRValue;
7147 ExprObjectKind OK = OK_Ordinary;
7148 QualType SrcTy = E->getType();
7149 if (!SrcTy->isDependentType() &&
7150 Context.getTypeSize(DestTy) != Context.getTypeSize(SrcTy))
7151 return ExprError(
7152 Diag(BuiltinLoc, diag::err_invalid_astype_of_different_size)
7153 << DestTy << SrcTy << E->getSourceRange());
7154 return new (Context) AsTypeExpr(E, DestTy, VK, OK, BuiltinLoc, RParenLoc);
7155}
7156
7157/// ActOnConvertVectorExpr - create a new convert-vector expression from the
7158/// provided arguments.
7159///
7160/// __builtin_convertvector( value, dst type )
7161///
7162ExprResult Sema::ActOnConvertVectorExpr(Expr *E, ParsedType ParsedDestTy,
7163 SourceLocation BuiltinLoc,
7164 SourceLocation RParenLoc) {
7165 TypeSourceInfo *TInfo;
7166 GetTypeFromParser(ParsedDestTy, &TInfo);
7167 return SemaConvertVectorExpr(E, TInfo, BuiltinLoc, RParenLoc);
7168}
7169
7170/// BuildResolvedCallExpr - Build a call to a resolved expression,
7171/// i.e. an expression not of \p OverloadTy. The expression should
7172/// unary-convert to an expression of function-pointer or
7173/// block-pointer type.
7174///
7175/// \param NDecl the declaration being called, if available
7176ExprResult Sema::BuildResolvedCallExpr(Expr *Fn, NamedDecl *NDecl,
7177 SourceLocation LParenLoc,
7178 ArrayRef<Expr *> Args,
7179 SourceLocation RParenLoc, Expr *Config,
7180 bool IsExecConfig, ADLCallKind UsesADL) {
7181 FunctionDecl *FDecl = dyn_cast_or_null<FunctionDecl>(NDecl);
7182 unsigned BuiltinID = (FDecl ? FDecl->getBuiltinID() : 0);
7183
7184 // Functions with 'interrupt' attribute cannot be called directly.
7185 if (FDecl && FDecl->hasAttr<AnyX86InterruptAttr>()) {
7186 Diag(Fn->getExprLoc(), diag::err_anyx86_interrupt_called);
7187 return ExprError();
7188 }
7189
7190 // Interrupt handlers don't save off the VFP regs automatically on ARM,
7191 // so there's some risk when calling out to non-interrupt handler functions
7192 // that the callee might not preserve them. This is easy to diagnose here,
7193 // but can be very challenging to debug.
7194 // Likewise, X86 interrupt handlers may only call routines with attribute
7195 // no_caller_saved_registers since there is no efficient way to
7196 // save and restore the non-GPR state.
7197 if (auto *Caller = getCurFunctionDecl()) {
7198 if (Caller->hasAttr<ARMInterruptAttr>()) {
7199 bool VFP = Context.getTargetInfo().hasFeature("vfp");
7200 if (VFP && (!FDecl || !FDecl->hasAttr<ARMInterruptAttr>())) {
7201 Diag(Fn->getExprLoc(), diag::warn_arm_interrupt_calling_convention);
7202 if (FDecl)
7203 Diag(FDecl->getLocation(), diag::note_callee_decl) << FDecl;
7204 }
7205 }
7206 if (Caller->hasAttr<AnyX86InterruptAttr>() &&
7207 ((!FDecl || !FDecl->hasAttr<AnyX86NoCallerSavedRegistersAttr>()))) {
7208 Diag(Fn->getExprLoc(), diag::warn_anyx86_interrupt_regsave);
7209 if (FDecl)
7210 Diag(FDecl->getLocation(), diag::note_callee_decl) << FDecl;
7211 }
7212 }
7213
7214 // Promote the function operand.
7215 // We special-case function promotion here because we only allow promoting
7216 // builtin functions to function pointers in the callee of a call.
7217 ExprResult Result;
7218 QualType ResultTy;
7219 if (BuiltinID &&
7220 Fn->getType()->isSpecificBuiltinType(BuiltinType::BuiltinFn)) {
7221 // Extract the return type from the (builtin) function pointer type.
7222 // FIXME Several builtins still have setType in
7223 // Sema::CheckBuiltinFunctionCall. One should review their definitions in
7224 // Builtins.def to ensure they are correct before removing setType calls.
7225 QualType FnPtrTy = Context.getPointerType(FDecl->getType());
7226 Result = ImpCastExprToType(Fn, FnPtrTy, CK_BuiltinFnToFnPtr).get();
7227 ResultTy = FDecl->getCallResultType();
7228 } else {
7229 Result = CallExprUnaryConversions(Fn);
7230 ResultTy = Context.BoolTy;
7231 }
7232 if (Result.isInvalid())
7233 return ExprError();
7234 Fn = Result.get();
7235
7236 // Check for a valid function type, but only if it is not a builtin which
7237 // requires custom type checking. These will be handled by
7238 // CheckBuiltinFunctionCall below just after creation of the call expression.
7239 const FunctionType *FuncT = nullptr;
7240 if (!BuiltinID || !Context.BuiltinInfo.hasCustomTypechecking(BuiltinID)) {
7241 retry:
7242 if (const PointerType *PT = Fn->getType()->getAs<PointerType>()) {
7243 // C99 6.5.2.2p1 - "The expression that denotes the called function shall
7244 // have type pointer to function".
7245 FuncT = PT->getPointeeType()->getAs<FunctionType>();
7246 if (!FuncT)
7247 return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function)
7248 << Fn->getType() << Fn->getSourceRange());
7249 } else if (const BlockPointerType *BPT =
7250 Fn->getType()->getAs<BlockPointerType>()) {
7251 FuncT = BPT->getPointeeType()->castAs<FunctionType>();
7252 } else {
7253 // Handle calls to expressions of unknown-any type.
7254 if (Fn->getType() == Context.UnknownAnyTy) {
7255 ExprResult rewrite = rebuildUnknownAnyFunction(*this, Fn);
7256 if (rewrite.isInvalid())
7257 return ExprError();
7258 Fn = rewrite.get();
7259 goto retry;
7260 }
7261
7262 return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function)
7263 << Fn->getType() << Fn->getSourceRange());
7264 }
7265 }
7266
7267 // Get the number of parameters in the function prototype, if any.
7268 // We will allocate space for max(Args.size(), NumParams) arguments
7269 // in the call expression.
7270 const auto *Proto = dyn_cast_or_null<FunctionProtoType>(FuncT);
7271 unsigned NumParams = Proto ? Proto->getNumParams() : 0;
7272
7273 CallExpr *TheCall;
7274 if (Config) {
7275 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", 7276, __extension__ __PRETTY_FUNCTION__
))
7276 "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", 7276, __extension__ __PRETTY_FUNCTION__
))
;
7277 TheCall = CUDAKernelCallExpr::Create(Context, Fn, cast<CallExpr>(Config),
7278 Args, ResultTy, VK_PRValue, RParenLoc,
7279 CurFPFeatureOverrides(), NumParams);
7280 } else {
7281 TheCall =
7282 CallExpr::Create(Context, Fn, Args, ResultTy, VK_PRValue, RParenLoc,
7283 CurFPFeatureOverrides(), NumParams, UsesADL);
7284 }
7285
7286 if (!Context.isDependenceAllowed()) {
7287 // Forget about the nulled arguments since typo correction
7288 // do not handle them well.
7289 TheCall->shrinkNumArgs(Args.size());
7290 // C cannot always handle TypoExpr nodes in builtin calls and direct
7291 // function calls as their argument checking don't necessarily handle
7292 // dependent types properly, so make sure any TypoExprs have been
7293 // dealt with.
7294 ExprResult Result = CorrectDelayedTyposInExpr(TheCall);
7295 if (!Result.isUsable()) return ExprError();
7296 CallExpr *TheOldCall = TheCall;
7297 TheCall = dyn_cast<CallExpr>(Result.get());
7298 bool CorrectedTypos = TheCall != TheOldCall;
7299 if (!TheCall) return Result;
7300 Args = llvm::ArrayRef(TheCall->getArgs(), TheCall->getNumArgs());
7301
7302 // A new call expression node was created if some typos were corrected.
7303 // However it may not have been constructed with enough storage. In this
7304 // case, rebuild the node with enough storage. The waste of space is
7305 // immaterial since this only happens when some typos were corrected.
7306 if (CorrectedTypos && Args.size() < NumParams) {
7307 if (Config)
7308 TheCall = CUDAKernelCallExpr::Create(
7309 Context, Fn, cast<CallExpr>(Config), Args, ResultTy, VK_PRValue,
7310 RParenLoc, CurFPFeatureOverrides(), NumParams);
7311 else
7312 TheCall =
7313 CallExpr::Create(Context, Fn, Args, ResultTy, VK_PRValue, RParenLoc,
7314 CurFPFeatureOverrides(), NumParams, UsesADL);
7315 }
7316 // We can now handle the nulled arguments for the default arguments.
7317 TheCall->setNumArgsUnsafe(std::max<unsigned>(Args.size(), NumParams));
7318 }
7319
7320 // Bail out early if calling a builtin with custom type checking.
7321 if (BuiltinID && Context.BuiltinInfo.hasCustomTypechecking(BuiltinID))
7322 return CheckBuiltinFunctionCall(FDecl, BuiltinID, TheCall);
7323
7324 if (getLangOpts().CUDA) {
7325 if (Config) {
7326 // CUDA: Kernel calls must be to global functions
7327 if (FDecl && !FDecl->hasAttr<CUDAGlobalAttr>())
7328 return ExprError(Diag(LParenLoc,diag::err_kern_call_not_global_function)
7329 << FDecl << Fn->getSourceRange());
7330
7331 // CUDA: Kernel function must have 'void' return type
7332 if (!FuncT->getReturnType()->isVoidType() &&
7333 !FuncT->getReturnType()->getAs<AutoType>() &&
7334 !FuncT->getReturnType()->isInstantiationDependentType())
7335 return ExprError(Diag(LParenLoc, diag::err_kern_type_not_void_return)
7336 << Fn->getType() << Fn->getSourceRange());
7337 } else {
7338 // CUDA: Calls to global functions must be configured
7339 if (FDecl && FDecl->hasAttr<CUDAGlobalAttr>())
7340 return ExprError(Diag(LParenLoc, diag::err_global_call_not_config)
7341 << FDecl << Fn->getSourceRange());
7342 }
7343 }
7344
7345 // Check for a valid return type
7346 if (CheckCallReturnType(FuncT->getReturnType(), Fn->getBeginLoc(), TheCall,
7347 FDecl))
7348 return ExprError();
7349
7350 // We know the result type of the call, set it.
7351 TheCall->setType(FuncT->getCallResultType(Context));
7352 TheCall->setValueKind(Expr::getValueKindForType(FuncT->getReturnType()));
7353
7354 if (Proto) {
7355 if (ConvertArgumentsForCall(TheCall, Fn, FDecl, Proto, Args, RParenLoc,
7356 IsExecConfig))
7357 return ExprError();
7358 } else {
7359 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", 7359, __extension__ __PRETTY_FUNCTION__
))
;
7360
7361 if (FDecl) {
7362 // Check if we have too few/too many template arguments, based
7363 // on our knowledge of the function definition.
7364 const FunctionDecl *Def = nullptr;
7365 if (FDecl->hasBody(Def) && Args.size() != Def->param_size()) {
7366 Proto = Def->getType()->getAs<FunctionProtoType>();
7367 if (!Proto || !(Proto->isVariadic() && Args.size() >= Def->param_size()))
7368 Diag(RParenLoc, diag::warn_call_wrong_number_of_arguments)
7369 << (Args.size() > Def->param_size()) << FDecl << Fn->getSourceRange();
7370 }
7371
7372 // If the function we're calling isn't a function prototype, but we have
7373 // a function prototype from a prior declaratiom, use that prototype.
7374 if (!FDecl->hasPrototype())
7375 Proto = FDecl->getType()->getAs<FunctionProtoType>();
7376 }
7377
7378 // If we still haven't found a prototype to use but there are arguments to
7379 // the call, diagnose this as calling a function without a prototype.
7380 // However, if we found a function declaration, check to see if
7381 // -Wdeprecated-non-prototype was disabled where the function was declared.
7382 // If so, we will silence the diagnostic here on the assumption that this
7383 // interface is intentional and the user knows what they're doing. We will
7384 // also silence the diagnostic if there is a function declaration but it
7385 // was implicitly defined (the user already gets diagnostics about the
7386 // creation of the implicit function declaration, so the additional warning
7387 // is not helpful).
7388 if (!Proto && !Args.empty() &&
7389 (!FDecl || (!FDecl->isImplicit() &&
7390 !Diags.isIgnored(diag::warn_strict_uses_without_prototype,
7391 FDecl->getLocation()))))
7392 Diag(LParenLoc, diag::warn_strict_uses_without_prototype)
7393 << (FDecl != nullptr) << FDecl;
7394
7395 // Promote the arguments (C99 6.5.2.2p6).
7396 for (unsigned i = 0, e = Args.size(); i != e; i++) {
7397 Expr *Arg = Args[i];
7398
7399 if (Proto && i < Proto->getNumParams()) {
7400 InitializedEntity Entity = InitializedEntity::InitializeParameter(
7401 Context, Proto->getParamType(i), Proto->isParamConsumed(i));
7402 ExprResult ArgE =
7403 PerformCopyInitialization(Entity, SourceLocation(), Arg);
7404 if (ArgE.isInvalid())
7405 return true;
7406
7407 Arg = ArgE.getAs<Expr>();
7408
7409 } else {
7410 ExprResult ArgE = DefaultArgumentPromotion(Arg);
7411
7412 if (ArgE.isInvalid())
7413 return true;
7414
7415 Arg = ArgE.getAs<Expr>();
7416 }
7417
7418 if (RequireCompleteType(Arg->getBeginLoc(), Arg->getType(),
7419 diag::err_call_incomplete_argument, Arg))
7420 return ExprError();
7421
7422 TheCall->setArg(i, Arg);
7423 }
7424 TheCall->computeDependence();
7425 }
7426
7427 if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(FDecl))
7428 if (!Method->isStatic())
7429 return ExprError(Diag(LParenLoc, diag::err_member_call_without_object)
7430 << Fn->getSourceRange());
7431
7432 // Check for sentinels
7433 if (NDecl)
7434 DiagnoseSentinelCalls(NDecl, LParenLoc, Args);
7435
7436 // Warn for unions passing across security boundary (CMSE).
7437 if (FuncT != nullptr && FuncT->getCmseNSCallAttr()) {
7438 for (unsigned i = 0, e = Args.size(); i != e; i++) {
7439 if (const auto *RT =
7440 dyn_cast<RecordType>(Args[i]->getType().getCanonicalType())) {
7441 if (RT->getDecl()->isOrContainsUnion())
7442 Diag(Args[i]->getBeginLoc(), diag::warn_cmse_nonsecure_union)
7443 << 0 << i;
7444 }
7445 }
7446 }
7447
7448 // Do special checking on direct calls to functions.
7449 if (FDecl) {
7450 if (CheckFunctionCall(FDecl, TheCall, Proto))
7451 return ExprError();
7452
7453 checkFortifiedBuiltinMemoryFunction(FDecl, TheCall);
7454
7455 if (BuiltinID)
7456 return CheckBuiltinFunctionCall(FDecl, BuiltinID, TheCall);
7457 } else if (NDecl) {
7458 if (CheckPointerCall(NDecl, TheCall, Proto))
7459 return ExprError();
7460 } else {
7461 if (CheckOtherCall(TheCall, Proto))
7462 return ExprError();
7463 }
7464
7465 return CheckForImmediateInvocation(MaybeBindToTemporary(TheCall), FDecl);
7466}
7467
7468ExprResult
7469Sema::ActOnCompoundLiteral(SourceLocation LParenLoc, ParsedType Ty,
7470 SourceLocation RParenLoc, Expr *InitExpr) {
7471 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", 7471, __extension__ __PRETTY_FUNCTION__
))
;
7472 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", 7472, __extension__ __PRETTY_FUNCTION__
))
;
7473
7474 TypeSourceInfo *TInfo;
7475 QualType literalType = GetTypeFromParser(Ty, &TInfo);
7476 if (!TInfo)
7477 TInfo = Context.getTrivialTypeSourceInfo(literalType);
7478
7479 return BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc, InitExpr);
7480}
7481
7482ExprResult
7483Sema::BuildCompoundLiteralExpr(SourceLocation LParenLoc, TypeSourceInfo *TInfo,
7484 SourceLocation RParenLoc, Expr *LiteralExpr) {
7485 QualType literalType = TInfo->getType();
7486
7487 if (literalType->isArrayType()) {
7488 if (RequireCompleteSizedType(
7489 LParenLoc, Context.getBaseElementType(literalType),
7490 diag::err_array_incomplete_or_sizeless_type,
7491 SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd())))
7492 return ExprError();
7493 if (literalType->isVariableArrayType()) {
7494 if (!tryToFixVariablyModifiedVarType(TInfo, literalType, LParenLoc,
7495 diag::err_variable_object_no_init)) {
7496 return ExprError();
7497 }
7498 }
7499 } else if (!literalType->isDependentType() &&
7500 RequireCompleteType(LParenLoc, literalType,
7501 diag::err_typecheck_decl_incomplete_type,
7502 SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd())))
7503 return ExprError();
7504
7505 InitializedEntity Entity
7506 = InitializedEntity::InitializeCompoundLiteralInit(TInfo);
7507 InitializationKind Kind
7508 = InitializationKind::CreateCStyleCast(LParenLoc,
7509 SourceRange(LParenLoc, RParenLoc),
7510 /*InitList=*/true);
7511 InitializationSequence InitSeq(*this, Entity, Kind, LiteralExpr);
7512 ExprResult Result = InitSeq.Perform(*this, Entity, Kind, LiteralExpr,
7513 &literalType);
7514 if (Result.isInvalid())
7515 return ExprError();
7516 LiteralExpr = Result.get();
7517
7518 bool isFileScope = !CurContext->isFunctionOrMethod();
7519
7520 // In C, compound literals are l-values for some reason.
7521 // For GCC compatibility, in C++, file-scope array compound literals with
7522 // constant initializers are also l-values, and compound literals are
7523 // otherwise prvalues.
7524 //
7525 // (GCC also treats C++ list-initialized file-scope array prvalues with
7526 // constant initializers as l-values, but that's non-conforming, so we don't
7527 // follow it there.)
7528 //
7529 // FIXME: It would be better to handle the lvalue cases as materializing and
7530 // lifetime-extending a temporary object, but our materialized temporaries
7531 // representation only supports lifetime extension from a variable, not "out
7532 // of thin air".
7533 // FIXME: For C++, we might want to instead lifetime-extend only if a pointer
7534 // is bound to the result of applying array-to-pointer decay to the compound
7535 // literal.
7536 // FIXME: GCC supports compound literals of reference type, which should
7537 // obviously have a value kind derived from the kind of reference involved.
7538 ExprValueKind VK =
7539 (getLangOpts().CPlusPlus && !(isFileScope && literalType->isArrayType()))
7540 ? VK_PRValue
7541 : VK_LValue;
7542
7543 if (isFileScope)
7544 if (auto ILE = dyn_cast<InitListExpr>(LiteralExpr))
7545 for (unsigned i = 0, j = ILE->getNumInits(); i != j; i++) {
7546 Expr *Init = ILE->getInit(i);
7547 ILE->setInit(i, ConstantExpr::Create(Context, Init));
7548 }
7549
7550 auto *E = new (Context) CompoundLiteralExpr(LParenLoc, TInfo, literalType,
7551 VK, LiteralExpr, isFileScope);
7552 if (isFileScope) {
7553 if (!LiteralExpr->isTypeDependent() &&
7554 !LiteralExpr->isValueDependent() &&
7555 !literalType->isDependentType()) // C99 6.5.2.5p3
7556 if (CheckForConstantInitializer(LiteralExpr, literalType))
7557 return ExprError();
7558 } else if (literalType.getAddressSpace() != LangAS::opencl_private &&
7559 literalType.getAddressSpace() != LangAS::Default) {
7560 // Embedded-C extensions to C99 6.5.2.5:
7561 // "If the compound literal occurs inside the body of a function, the
7562 // type name shall not be qualified by an address-space qualifier."
7563 Diag(LParenLoc, diag::err_compound_literal_with_address_space)
7564 << SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd());
7565 return ExprError();
7566 }
7567
7568 if (!isFileScope && !getLangOpts().CPlusPlus) {
7569 // Compound literals that have automatic storage duration are destroyed at
7570 // the end of the scope in C; in C++, they're just temporaries.
7571
7572 // Emit diagnostics if it is or contains a C union type that is non-trivial
7573 // to destruct.
7574 if (E->getType().hasNonTrivialToPrimitiveDestructCUnion())
7575 checkNonTrivialCUnion(E->getType(), E->getExprLoc(),
7576 NTCUC_CompoundLiteral, NTCUK_Destruct);
7577
7578 // Diagnose jumps that enter or exit the lifetime of the compound literal.
7579 if (literalType.isDestructedType()) {
7580 Cleanup.setExprNeedsCleanups(true);
7581 ExprCleanupObjects.push_back(E);
7582 getCurFunction()->setHasBranchProtectedScope();
7583 }
7584 }
7585
7586 if (E->getType().hasNonTrivialToPrimitiveDefaultInitializeCUnion() ||
7587 E->getType().hasNonTrivialToPrimitiveCopyCUnion())
7588 checkNonTrivialCUnionInInitializer(E->getInitializer(),
7589 E->getInitializer()->getExprLoc());
7590
7591 return MaybeBindToTemporary(E);
7592}
7593
7594ExprResult
7595Sema::ActOnInitList(SourceLocation LBraceLoc, MultiExprArg InitArgList,
7596 SourceLocation RBraceLoc) {
7597 // Only produce each kind of designated initialization diagnostic once.
7598 SourceLocation FirstDesignator;
7599 bool DiagnosedArrayDesignator = false;
7600 bool DiagnosedNestedDesignator = false;
7601 bool DiagnosedMixedDesignator = false;
7602
7603 // Check that any designated initializers are syntactically valid in the
7604 // current language mode.
7605 for (unsigned I = 0, E = InitArgList.size(); I != E; ++I) {
7606 if (auto *DIE = dyn_cast<DesignatedInitExpr>(InitArgList[I])) {
7607 if (FirstDesignator.isInvalid())
7608 FirstDesignator = DIE->getBeginLoc();
7609
7610 if (!getLangOpts().CPlusPlus)
7611 break;
7612
7613 if (!DiagnosedNestedDesignator && DIE->size() > 1) {
7614 DiagnosedNestedDesignator = true;
7615 Diag(DIE->getBeginLoc(), diag::ext_designated_init_nested)
7616 << DIE->getDesignatorsSourceRange();
7617 }
7618
7619 for (auto &Desig : DIE->designators()) {
7620 if (!Desig.isFieldDesignator() && !DiagnosedArrayDesignator) {
7621 DiagnosedArrayDesignator = true;
7622 Diag(Desig.getBeginLoc(), diag::ext_designated_init_array)
7623 << Desig.getSourceRange();
7624 }
7625 }
7626
7627 if (!DiagnosedMixedDesignator &&
7628 !isa<DesignatedInitExpr>(InitArgList[0])) {
7629 DiagnosedMixedDesignator = true;
7630 Diag(DIE->getBeginLoc(), diag::ext_designated_init_mixed)
7631 << DIE->getSourceRange();
7632 Diag(InitArgList[0]->getBeginLoc(), diag::note_designated_init_mixed)
7633 << InitArgList[0]->getSourceRange();
7634 }
7635 } else if (getLangOpts().CPlusPlus && !DiagnosedMixedDesignator &&
7636 isa<DesignatedInitExpr>(InitArgList[0])) {
7637 DiagnosedMixedDesignator = true;
7638 auto *DIE = cast<DesignatedInitExpr>(InitArgList[0]);
7639 Diag(DIE->getBeginLoc(), diag::ext_designated_init_mixed)
7640 << DIE->getSourceRange();
7641 Diag(InitArgList[I]->getBeginLoc(), diag::note_designated_init_mixed)
7642 << InitArgList[I]->getSourceRange();
7643 }
7644 }
7645
7646 if (FirstDesignator.isValid()) {
7647 // Only diagnose designated initiaization as a C++20 extension if we didn't
7648 // already diagnose use of (non-C++20) C99 designator syntax.
7649 if (getLangOpts().CPlusPlus && !DiagnosedArrayDesignator &&
7650 !DiagnosedNestedDesignator && !DiagnosedMixedDesignator) {
7651 Diag(FirstDesignator, getLangOpts().CPlusPlus20
7652 ? diag::warn_cxx17_compat_designated_init
7653 : diag::ext_cxx_designated_init);
7654 } else if (!getLangOpts().CPlusPlus && !getLangOpts().C99) {
7655 Diag(FirstDesignator, diag::ext_designated_init);
7656 }
7657 }
7658
7659 return BuildInitList(LBraceLoc, InitArgList, RBraceLoc);
7660}
7661
7662ExprResult
7663Sema::BuildInitList(SourceLocation LBraceLoc, MultiExprArg InitArgList,
7664 SourceLocation RBraceLoc) {
7665 // Semantic analysis for initializers is done by ActOnDeclarator() and
7666 // CheckInitializer() - it requires knowledge of the object being initialized.
7667
7668 // Immediately handle non-overload placeholders. Overloads can be
7669 // resolved contextually, but everything else here can't.
7670 for (unsigned I = 0, E = InitArgList.size(); I != E; ++I) {
7671 if (InitArgList[I]->getType()->isNonOverloadPlaceholderType()) {
7672 ExprResult result = CheckPlaceholderExpr(InitArgList[I]);
7673
7674 // Ignore failures; dropping the entire initializer list because
7675 // of one failure would be terrible for indexing/etc.
7676 if (result.isInvalid()) continue;
7677
7678 InitArgList[I] = result.get();
7679 }
7680 }
7681
7682 InitListExpr *E = new (Context) InitListExpr(Context, LBraceLoc, InitArgList,
7683 RBraceLoc);
7684 E->setType(Context.VoidTy); // FIXME: just a place holder for now.
7685 return E;
7686}
7687
7688/// Do an explicit extend of the given block pointer if we're in ARC.
7689void Sema::maybeExtendBlockObject(ExprResult &E) {
7690 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", 7690, __extension__ __PRETTY_FUNCTION__
))
;
7691 assert(E.get()->isPRValue())(static_cast <bool> (E.get()->isPRValue()) ? void (0
) : __assert_fail ("E.get()->isPRValue()", "clang/lib/Sema/SemaExpr.cpp"
, 7691, __extension__ __PRETTY_FUNCTION__))
;
7692
7693 // Only do this in an r-value context.
7694 if (!getLangOpts().ObjCAutoRefCount) return;
7695
7696 E = ImplicitCastExpr::Create(
7697 Context, E.get()->getType(), CK_ARCExtendBlockObject, E.get(),
7698 /*base path*/ nullptr, VK_PRValue, FPOptionsOverride());
7699 Cleanup.setExprNeedsCleanups(true);
7700}
7701
7702/// Prepare a conversion of the given expression to an ObjC object
7703/// pointer type.
7704CastKind Sema::PrepareCastToObjCObjectPointer(ExprResult &E) {
7705 QualType type = E.get()->getType();
7706 if (type->isObjCObjectPointerType()) {
7707 return CK_BitCast;
7708 } else if (type->isBlockPointerType()) {
7709 maybeExtendBlockObject(E);
7710 return CK_BlockPointerToObjCPointerCast;
7711 } else {
7712 assert(type->isPointerType())(static_cast <bool> (type->isPointerType()) ? void (
0) : __assert_fail ("type->isPointerType()", "clang/lib/Sema/SemaExpr.cpp"
, 7712, __extension__ __PRETTY_FUNCTION__))
;
7713 return CK_CPointerToObjCPointerCast;
7714 }
7715}
7716
7717/// Prepares for a scalar cast, performing all the necessary stages
7718/// except the final cast and returning the kind required.
7719CastKind Sema::PrepareScalarCast(ExprResult &Src, QualType DestTy) {
7720 // Both Src and Dest are scalar types, i.e. arithmetic or pointer.
7721 // Also, callers should have filtered out the invalid cases with
7722 // pointers. Everything else should be possible.
7723
7724 QualType SrcTy = Src.get()->getType();
7725 if (Context.hasSameUnqualifiedType(SrcTy, DestTy))
7726 return CK_NoOp;
7727
7728 switch (Type::ScalarTypeKind SrcKind = SrcTy->getScalarTypeKind()) {
7729 case Type::STK_MemberPointer:
7730 llvm_unreachable("member pointer type in C")::llvm::llvm_unreachable_internal("member pointer type in C",
"clang/lib/Sema/SemaExpr.cpp", 7730)
;
7731
7732 case Type::STK_CPointer:
7733 case Type::STK_BlockPointer:
7734 case Type::STK_ObjCObjectPointer:
7735 switch (DestTy->getScalarTypeKind()) {
7736 case Type::STK_CPointer: {
7737 LangAS SrcAS = SrcTy->getPointeeType().getAddressSpace();
7738 LangAS DestAS = DestTy->getPointeeType().getAddressSpace();
7739 if (SrcAS != DestAS)
7740 return CK_AddressSpaceConversion;
7741 if (Context.hasCvrSimilarType(SrcTy, DestTy))
7742 return CK_NoOp;
7743 return CK_BitCast;
7744 }
7745 case Type::STK_BlockPointer:
7746 return (SrcKind == Type::STK_BlockPointer
7747 ? CK_BitCast : CK_AnyPointerToBlockPointerCast);
7748 case Type::STK_ObjCObjectPointer:
7749 if (SrcKind == Type::STK_ObjCObjectPointer)
7750 return CK_BitCast;
7751 if (SrcKind == Type::STK_CPointer)
7752 return CK_CPointerToObjCPointerCast;
7753 maybeExtendBlockObject(Src);
7754 return CK_BlockPointerToObjCPointerCast;
7755 case Type::STK_Bool:
7756 return CK_PointerToBoolean;
7757 case Type::STK_Integral:
7758 return CK_PointerToIntegral;
7759 case Type::STK_Floating:
7760 case Type::STK_FloatingComplex:
7761 case Type::STK_IntegralComplex:
7762 case Type::STK_MemberPointer:
7763 case Type::STK_FixedPoint:
7764 llvm_unreachable("illegal cast from pointer")::llvm::llvm_unreachable_internal("illegal cast from pointer"
, "clang/lib/Sema/SemaExpr.cpp", 7764)
;
7765 }
7766 llvm_unreachable("Should have returned before this")::llvm::llvm_unreachable_internal("Should have returned before this"
, "clang/lib/Sema/SemaExpr.cpp", 7766)
;
7767
7768 case Type::STK_FixedPoint:
7769 switch (DestTy->getScalarTypeKind()) {
7770 case Type::STK_FixedPoint:
7771 return CK_FixedPointCast;
7772 case Type::STK_Bool:
7773 return CK_FixedPointToBoolean;
7774 case Type::STK_Integral:
7775 return CK_FixedPointToIntegral;
7776 case Type::STK_Floating:
7777 return CK_FixedPointToFloating;
7778 case Type::STK_IntegralComplex:
7779 case Type::STK_FloatingComplex:
7780 Diag(Src.get()->getExprLoc(),
7781 diag::err_unimplemented_conversion_with_fixed_point_type)
7782 << DestTy;
7783 return CK_IntegralCast;
7784 case Type::STK_CPointer:
7785 case Type::STK_ObjCObjectPointer:
7786 case Type::STK_BlockPointer:
7787 case Type::STK_MemberPointer:
7788 llvm_unreachable("illegal cast to pointer type")::llvm::llvm_unreachable_internal("illegal cast to pointer type"
, "clang/lib/Sema/SemaExpr.cpp", 7788)
;
7789 }
7790 llvm_unreachable("Should have returned before this")::llvm::llvm_unreachable_internal("Should have returned before this"
, "clang/lib/Sema/SemaExpr.cpp", 7790)
;
7791
7792 case Type::STK_Bool: // casting from bool is like casting from an integer
7793 case Type::STK_Integral:
7794 switch (DestTy->getScalarTypeKind()) {
7795 case Type::STK_CPointer:
7796 case Type::STK_ObjCObjectPointer:
7797 case Type::STK_BlockPointer:
7798 if (Src.get()->isNullPointerConstant(Context,
7799 Expr::NPC_ValueDependentIsNull))
7800 return CK_NullToPointer;
7801 return CK_IntegralToPointer;
7802 case Type::STK_Bool:
7803 return CK_IntegralToBoolean;
7804 case Type::STK_Integral:
7805 return CK_IntegralCast;
7806 case Type::STK_Floating:
7807 return CK_IntegralToFloating;
7808 case Type::STK_IntegralComplex:
7809 Src = ImpCastExprToType(Src.get(),
7810 DestTy->castAs<ComplexType>()->getElementType(),
7811 CK_IntegralCast);
7812 return CK_IntegralRealToComplex;
7813 case Type::STK_FloatingComplex:
7814 Src = ImpCastExprToType(Src.get(),
7815 DestTy->castAs<ComplexType>()->getElementType(),
7816 CK_IntegralToFloating);
7817 return CK_FloatingRealToComplex;
7818 case Type::STK_MemberPointer:
7819 llvm_unreachable("member pointer type in C")::llvm::llvm_unreachable_internal("member pointer type in C",
"clang/lib/Sema/SemaExpr.cpp", 7819)
;
7820 case Type::STK_FixedPoint:
7821 return CK_IntegralToFixedPoint;
7822 }
7823 llvm_unreachable("Should have returned before this")::llvm::llvm_unreachable_internal("Should have returned before this"
, "clang/lib/Sema/SemaExpr.cpp", 7823)
;
7824
7825 case Type::STK_Floating:
7826 switch (DestTy->getScalarTypeKind()) {
7827 case Type::STK_Floating:
7828 return CK_FloatingCast;
7829 case Type::STK_Bool:
7830 return CK_FloatingToBoolean;
7831 case Type::STK_Integral:
7832 return CK_FloatingToIntegral;
7833 case Type::STK_FloatingComplex:
7834 Src = ImpCastExprToType(Src.get(),
7835 DestTy->castAs<ComplexType>()->getElementType(),
7836 CK_FloatingCast);
7837 return CK_FloatingRealToComplex;
7838 case Type::STK_IntegralComplex:
7839 Src = ImpCastExprToType(Src.get(),
7840 DestTy->castAs<ComplexType>()->getElementType(),
7841 CK_FloatingToIntegral);
7842 return CK_IntegralRealToComplex;
7843 case Type::STK_CPointer:
7844 case Type::STK_ObjCObjectPointer:
7845 case Type::STK_BlockPointer:
7846 llvm_unreachable("valid float->pointer cast?")::llvm::llvm_unreachable_internal("valid float->pointer cast?"
, "clang/lib/Sema/SemaExpr.cpp", 7846)
;
7847 case Type::STK_MemberPointer:
7848 llvm_unreachable("member pointer type in C")::llvm::llvm_unreachable_internal("member pointer type in C",
"clang/lib/Sema/SemaExpr.cpp", 7848)
;
7849 case Type::STK_FixedPoint:
7850 return CK_FloatingToFixedPoint;
7851 }
7852 llvm_unreachable("Should have returned before this")::llvm::llvm_unreachable_internal("Should have returned before this"
, "clang/lib/Sema/SemaExpr.cpp", 7852)
;
7853
7854 case Type::STK_FloatingComplex:
7855 switch (DestTy->getScalarTypeKind()) {
7856 case Type::STK_FloatingComplex:
7857 return CK_FloatingComplexCast;
7858 case Type::STK_IntegralComplex:
7859 return CK_FloatingComplexToIntegralComplex;
7860 case Type::STK_Floating: {
7861 QualType ET = SrcTy->castAs<ComplexType>()->getElementType();
7862 if (Context.hasSameType(ET, DestTy))
7863 return CK_FloatingComplexToReal;
7864 Src = ImpCastExprToType(Src.get(), ET, CK_FloatingComplexToReal);
7865 return CK_FloatingCast;
7866 }
7867 case Type::STK_Bool:
7868 return CK_FloatingComplexToBoolean;
7869 case Type::STK_Integral:
7870 Src = ImpCastExprToType(Src.get(),
7871 SrcTy->castAs<ComplexType>()->getElementType(),
7872 CK_FloatingComplexToReal);
7873 return CK_FloatingToIntegral;
7874 case Type::STK_CPointer:
7875 case Type::STK_ObjCObjectPointer:
7876 case Type::STK_BlockPointer:
7877 llvm_unreachable("valid complex float->pointer cast?")::llvm::llvm_unreachable_internal("valid complex float->pointer cast?"
, "clang/lib/Sema/SemaExpr.cpp", 7877)
;
7878 case Type::STK_MemberPointer:
7879 llvm_unreachable("member pointer type in C")::llvm::llvm_unreachable_internal("member pointer type in C",
"clang/lib/Sema/SemaExpr.cpp", 7879)
;
7880 case Type::STK_FixedPoint:
7881 Diag(Src.get()->getExprLoc(),
7882 diag::err_unimplemented_conversion_with_fixed_point_type)
7883 << SrcTy;
7884 return CK_IntegralCast;
7885 }
7886 llvm_unreachable("Should have returned before this")::llvm::llvm_unreachable_internal("Should have returned before this"
, "clang/lib/Sema/SemaExpr.cpp", 7886)
;
7887
7888 case Type::STK_IntegralComplex:
7889 switch (DestTy->getScalarTypeKind()) {
7890 case Type::STK_FloatingComplex:
7891 return CK_IntegralComplexToFloatingComplex;
7892 case Type::STK_IntegralComplex:
7893 return CK_IntegralComplexCast;
7894 case Type::STK_Integral: {
7895 QualType ET = SrcTy->castAs<ComplexType>()->getElementType();
7896 if (Context.hasSameType(ET, DestTy))
7897 return CK_IntegralComplexToReal;
7898 Src = ImpCastExprToType(Src.get(), ET, CK_IntegralComplexToReal);
7899 return CK_IntegralCast;
7900 }
7901 case Type::STK_Bool:
7902 return CK_IntegralComplexToBoolean;
7903 case Type::STK_Floating:
7904 Src = ImpCastExprToType(Src.get(),
7905 SrcTy->castAs<ComplexType>()->getElementType(),
7906 CK_IntegralComplexToReal);
7907 return CK_IntegralToFloating;
7908 case Type::STK_CPointer:
7909 case Type::STK_ObjCObjectPointer:
7910 case Type::STK_BlockPointer:
7911 llvm_unreachable("valid complex int->pointer cast?")::llvm::llvm_unreachable_internal("valid complex int->pointer cast?"
, "clang/lib/Sema/SemaExpr.cpp", 7911)
;
7912 case Type::STK_MemberPointer:
7913 llvm_unreachable("member pointer type in C")::llvm::llvm_unreachable_internal("member pointer type in C",
"clang/lib/Sema/SemaExpr.cpp", 7913)
;
7914 case Type::STK_FixedPoint:
7915 Diag(Src.get()->getExprLoc(),
7916 diag::err_unimplemented_conversion_with_fixed_point_type)
7917 << SrcTy;
7918 return CK_IntegralCast;
7919 }
7920 llvm_unreachable("Should have returned before this")::llvm::llvm_unreachable_internal("Should have returned before this"
, "clang/lib/Sema/SemaExpr.cpp", 7920)
;
7921 }
7922
7923 llvm_unreachable("Unhandled scalar cast")::llvm::llvm_unreachable_internal("Unhandled scalar cast", "clang/lib/Sema/SemaExpr.cpp"
, 7923)
;
7924}
7925
7926static bool breakDownVectorType(QualType type, uint64_t &len,
7927 QualType &eltType) {
7928 // Vectors are simple.
7929 if (const VectorType *vecType = type->getAs<VectorType>()) {
7930 len = vecType->getNumElements();
7931 eltType = vecType->getElementType();
7932 assert(eltType->isScalarType())(static_cast <bool> (eltType->isScalarType()) ? void
(0) : __assert_fail ("eltType->isScalarType()", "clang/lib/Sema/SemaExpr.cpp"
, 7932, __extension__ __PRETTY_FUNCTION__))
;
7933 return true;
7934 }
7935
7936 // We allow lax conversion to and from non-vector types, but only if
7937 // they're real types (i.e. non-complex, non-pointer scalar types).
7938 if (!type->isRealType()) return false;
7939
7940 len = 1;
7941 eltType = type;
7942 return true;
7943}
7944
7945/// Are the two types SVE-bitcast-compatible types? I.e. is bitcasting from the
7946/// first SVE type (e.g. an SVE VLAT) to the second type (e.g. an SVE VLST)
7947/// allowed?
7948///
7949/// This will also return false if the two given types do not make sense from
7950/// the perspective of SVE bitcasts.
7951bool Sema::isValidSveBitcast(QualType srcTy, QualType destTy) {
7952 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", 7952, __extension__ __PRETTY_FUNCTION__
))
;
7953
7954 auto ValidScalableConversion = [](QualType FirstType, QualType SecondType) {
7955 if (!FirstType->isSVESizelessBuiltinType())
7956 return false;
7957
7958 const auto *VecTy = SecondType->getAs<VectorType>();
7959 return VecTy &&
7960 VecTy->getVectorKind() == VectorType::SveFixedLengthDataVector;
7961 };
7962
7963 return ValidScalableConversion(srcTy, destTy) ||
7964 ValidScalableConversion(destTy, srcTy);
7965}
7966
7967/// Are the two types matrix types and do they have the same dimensions i.e.
7968/// do they have the same number of rows and the same number of columns?
7969bool Sema::areMatrixTypesOfTheSameDimension(QualType srcTy, QualType destTy) {
7970 if (!destTy->isMatrixType() || !srcTy->isMatrixType())
7971 return false;
7972
7973 const ConstantMatrixType *matSrcType = srcTy->getAs<ConstantMatrixType>();
7974 const ConstantMatrixType *matDestType = destTy->getAs<ConstantMatrixType>();
7975
7976 return matSrcType->getNumRows() == matDestType->getNumRows() &&
7977 matSrcType->getNumColumns() == matDestType->getNumColumns();
7978}
7979
7980bool Sema::areVectorTypesSameSize(QualType SrcTy, QualType DestTy) {
7981 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", 7981, __extension__ __PRETTY_FUNCTION__
))
;
7982
7983 uint64_t SrcLen, DestLen;
7984 QualType SrcEltTy, DestEltTy;
7985 if (!breakDownVectorType(SrcTy, SrcLen, SrcEltTy))
7986 return false;
7987 if (!breakDownVectorType(DestTy, DestLen, DestEltTy))
7988 return false;
7989
7990 // ASTContext::getTypeSize will return the size rounded up to a
7991 // power of 2, so instead of using that, we need to use the raw
7992 // element size multiplied by the element count.
7993 uint64_t SrcEltSize = Context.getTypeSize(SrcEltTy);
7994 uint64_t DestEltSize = Context.getTypeSize(DestEltTy);
7995
7996 return (SrcLen * SrcEltSize == DestLen * DestEltSize);
7997}
7998
7999// This returns true if at least one of the types is an altivec vector.
8000bool Sema::anyAltivecTypes(QualType SrcTy, QualType DestTy) {
8001 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", 8002, __extension__ __PRETTY_FUNCTION__
))
8002 "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", 8002, __extension__ __PRETTY_FUNCTION__
))
;
8003
8004 bool IsSrcTyAltivec =
8005 SrcTy->isVectorType() && ((SrcTy->castAs<VectorType>()->getVectorKind() ==
8006 VectorType::AltiVecVector) ||
8007 (SrcTy->castAs<VectorType>()->getVectorKind() ==
8008 VectorType::AltiVecBool) ||
8009 (SrcTy->castAs<VectorType>()->getVectorKind() ==
8010 VectorType::AltiVecPixel));
8011
8012 bool IsDestTyAltivec = DestTy->isVectorType() &&
8013 ((DestTy->castAs<VectorType>()->getVectorKind() ==
8014 VectorType::AltiVecVector) ||
8015 (DestTy->castAs<VectorType>()->getVectorKind() ==
8016 VectorType::AltiVecBool) ||
8017 (DestTy->castAs<VectorType>()->getVectorKind() ==
8018 VectorType::AltiVecPixel));
8019
8020 return (IsSrcTyAltivec || IsDestTyAltivec);
8021}
8022
8023/// Are the two types lax-compatible vector types? That is, given
8024/// that one of them is a vector, do they have equal storage sizes,
8025/// where the storage size is the number of elements times the element
8026/// size?
8027///
8028/// This will also return false if either of the types is neither a
8029/// vector nor a real type.
8030bool Sema::areLaxCompatibleVectorTypes(QualType srcTy, QualType destTy) {
8031 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", 8031, __extension__ __PRETTY_FUNCTION__
))
;
8032
8033 // Disallow lax conversions between scalars and ExtVectors (these
8034 // conversions are allowed for other vector types because common headers
8035 // depend on them). Most scalar OP ExtVector cases are handled by the
8036 // splat path anyway, which does what we want (convert, not bitcast).
8037 // What this rules out for ExtVectors is crazy things like char4*float.
8038 if (srcTy->isScalarType() && destTy->isExtVectorType()) return false;
8039 if (destTy->isScalarType() && srcTy->isExtVectorType()) return false;
8040
8041 return areVectorTypesSameSize(srcTy, destTy);
8042}
8043
8044/// Is this a legal conversion between two types, one of which is
8045/// known to be a vector type?
8046bool Sema::isLaxVectorConversion(QualType srcTy, QualType destTy) {
8047 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", 8047, __extension__ __PRETTY_FUNCTION__
))
;
8048
8049 switch (Context.getLangOpts().getLaxVectorConversions()) {
8050 case LangOptions::LaxVectorConversionKind::None:
8051 return false;
8052
8053 case LangOptions::LaxVectorConversionKind::Integer:
8054 if (!srcTy->isIntegralOrEnumerationType()) {
8055 auto *Vec = srcTy->getAs<VectorType>();
8056 if (!Vec || !Vec->getElementType()->isIntegralOrEnumerationType())
8057 return false;
8058 }
8059 if (!destTy->isIntegralOrEnumerationType()) {
8060 auto *Vec = destTy->getAs<VectorType>();
8061 if (!Vec || !Vec->getElementType()->isIntegralOrEnumerationType())
8062 return false;
8063 }
8064 // OK, integer (vector) -> integer (vector) bitcast.
8065 break;
8066
8067 case LangOptions::LaxVectorConversionKind::All:
8068 break;
8069 }
8070
8071 return areLaxCompatibleVectorTypes(srcTy, destTy);
8072}
8073
8074bool Sema::CheckMatrixCast(SourceRange R, QualType DestTy, QualType SrcTy,
8075 CastKind &Kind) {
8076 if (SrcTy->isMatrixType() && DestTy->isMatrixType()) {
8077 if (!areMatrixTypesOfTheSameDimension(SrcTy, DestTy)) {
8078 return Diag(R.getBegin(), diag::err_invalid_conversion_between_matrixes)
8079 << DestTy << SrcTy << R;
8080 }
8081 } else if (SrcTy->isMatrixType()) {
8082 return Diag(R.getBegin(),
8083 diag::err_invalid_conversion_between_matrix_and_type)
8084 << SrcTy << DestTy << R;
8085 } else if (DestTy->isMatrixType()) {
8086 return Diag(R.getBegin(),
8087 diag::err_invalid_conversion_between_matrix_and_type)
8088 << DestTy << SrcTy << R;
8089 }
8090
8091 Kind = CK_MatrixCast;
8092 return false;
8093}
8094
8095bool Sema::CheckVectorCast(SourceRange R, QualType VectorTy, QualType Ty,
8096 CastKind &Kind) {
8097 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", 8097, __extension__ __PRETTY_FUNCTION__
))
;
8098
8099 if (Ty->isVectorType() || Ty->isIntegralType(Context)) {
8100 if (!areLaxCompatibleVectorTypes(Ty, VectorTy))
8101 return Diag(R.getBegin(),
8102 Ty->isVectorType() ?
8103 diag::err_invalid_conversion_between_vectors :
8104 diag::err_invalid_conversion_between_vector_and_integer)
8105 << VectorTy << Ty << R;
8106 } else
8107 return Diag(R.getBegin(),
8108 diag::err_invalid_conversion_between_vector_and_scalar)
8109 << VectorTy << Ty << R;
8110
8111 Kind = CK_BitCast;
8112 return false;
8113}
8114
8115ExprResult Sema::prepareVectorSplat(QualType VectorTy, Expr *SplattedExpr) {
8116 QualType DestElemTy = VectorTy->castAs<VectorType>()->getElementType();
8117
8118 if (DestElemTy == SplattedExpr->getType())
8119 return SplattedExpr;
8120
8121 assert(DestElemTy->isFloatingType() ||(static_cast <bool> (DestElemTy->isFloatingType() ||
DestElemTy->isIntegralOrEnumerationType()) ? void (0) : __assert_fail
("DestElemTy->isFloatingType() || DestElemTy->isIntegralOrEnumerationType()"
, "clang/lib/Sema/SemaExpr.cpp", 8122, __extension__ __PRETTY_FUNCTION__
))
8122 DestElemTy->isIntegralOrEnumerationType())(static_cast <bool> (DestElemTy->isFloatingType() ||
DestElemTy->isIntegralOrEnumerationType()) ? void (0) : __assert_fail
("DestElemTy->isFloatingType() || DestElemTy->isIntegralOrEnumerationType()"
, "clang/lib/Sema/SemaExpr.cpp", 8122, __extension__ __PRETTY_FUNCTION__
))
;
8123
8124 CastKind CK;
8125 if (VectorTy->isExtVectorType() && SplattedExpr->getType()->isBooleanType()) {
8126 // OpenCL requires that we convert `true` boolean expressions to -1, but
8127 // only when splatting vectors.
8128 if (DestElemTy->isFloatingType()) {
8129 // To avoid having to have a CK_BooleanToSignedFloating cast kind, we cast
8130 // in two steps: boolean to signed integral, then to floating.
8131 ExprResult CastExprRes = ImpCastExprToType(SplattedExpr, Context.IntTy,
8132 CK_BooleanToSignedIntegral);
8133 SplattedExpr = CastExprRes.get();
8134 CK = CK_IntegralToFloating;
8135 } else {
8136 CK = CK_BooleanToSignedIntegral;
8137 }
8138 } else {
8139 ExprResult CastExprRes = SplattedExpr;
8140 CK = PrepareScalarCast(CastExprRes, DestElemTy);
8141 if (CastExprRes.isInvalid())
8142 return ExprError();
8143 SplattedExpr = CastExprRes.get();
8144 }
8145 return ImpCastExprToType(SplattedExpr, DestElemTy, CK);
8146}
8147
8148ExprResult Sema::CheckExtVectorCast(SourceRange R, QualType DestTy,
8149 Expr *CastExpr, CastKind &Kind) {
8150 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", 8150, __extension__ __PRETTY_FUNCTION__
))
;
8151
8152 QualType SrcTy = CastExpr->getType();
8153
8154 // If SrcTy is a VectorType, the total size must match to explicitly cast to
8155 // an ExtVectorType.
8156 // In OpenCL, casts between vectors of different types are not allowed.
8157 // (See OpenCL 6.2).
8158 if (SrcTy->isVectorType()) {
8159 if (!areLaxCompatibleVectorTypes(SrcTy, DestTy) ||
8160 (getLangOpts().OpenCL &&
8161 !Context.hasSameUnqualifiedType(DestTy, SrcTy))) {
8162 Diag(R.getBegin(),diag::err_invalid_conversion_between_ext_vectors)
8163 << DestTy << SrcTy << R;
8164 return ExprError();
8165 }
8166 Kind = CK_BitCast;
8167 return CastExpr;
8168 }
8169
8170 // All non-pointer scalars can be cast to ExtVector type. The appropriate
8171 // conversion will take place first from scalar to elt type, and then
8172 // splat from elt type to vector.
8173 if (SrcTy->isPointerType())
8174 return Diag(R.getBegin(),
8175 diag::err_invalid_conversion_between_vector_and_scalar)
8176 << DestTy << SrcTy << R;
8177
8178 Kind = CK_VectorSplat;
8179 return prepareVectorSplat(DestTy, CastExpr);
8180}
8181
8182ExprResult
8183Sema::ActOnCastExpr(Scope *S, SourceLocation LParenLoc,
8184 Declarator &D, ParsedType &Ty,
8185 SourceLocation RParenLoc, Expr *CastExpr) {
8186 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", 8187, __extension__ __PRETTY_FUNCTION__
))
8187 "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", 8187, __extension__ __PRETTY_FUNCTION__
))
;
8188
8189 TypeSourceInfo *castTInfo = GetTypeForDeclaratorCast(D, CastExpr->getType());
8190 if (D.isInvalidType())
8191 return ExprError();
8192
8193 if (getLangOpts().CPlusPlus) {
8194 // Check that there are no default arguments (C++ only).
8195 CheckExtraCXXDefaultArguments(D);
8196 } else {
8197 // Make sure any TypoExprs have been dealt with.
8198 ExprResult Res = CorrectDelayedTyposInExpr(CastExpr);
8199 if (!Res.isUsable())
8200 return ExprError();
8201 CastExpr = Res.get();
8202 }
8203
8204 checkUnusedDeclAttributes(D);
8205
8206 QualType castType = castTInfo->getType();
8207 Ty = CreateParsedType(castType, castTInfo);
8208
8209 bool isVectorLiteral = false;
8210
8211 // Check for an altivec or OpenCL literal,
8212 // i.e. all the elements are integer constants.
8213 ParenExpr *PE = dyn_cast<ParenExpr>(CastExpr);
8214 ParenListExpr *PLE = dyn_cast<ParenListExpr>(CastExpr);
8215 if ((getLangOpts().AltiVec || getLangOpts().ZVector || getLangOpts().OpenCL)
8216 && castType->isVectorType() && (PE || PLE)) {
8217 if (PLE && PLE->getNumExprs() == 0) {
8218 Diag(PLE->getExprLoc(), diag::err_altivec_empty_initializer);
8219 return ExprError();
8220 }
8221 if (PE || PLE->getNumExprs() == 1) {
8222 Expr *E = (PE ? PE->getSubExpr() : PLE->getExpr(0));
8223 if (!E->isTypeDependent() && !E->getType()->isVectorType())
8224 isVectorLiteral = true;
8225 }
8226 else
8227 isVectorLiteral = true;
8228 }
8229
8230 // If this is a vector initializer, '(' type ')' '(' init, ..., init ')'
8231 // then handle it as such.
8232 if (isVectorLiteral)
8233 return BuildVectorLiteral(LParenLoc, RParenLoc, CastExpr, castTInfo);
8234
8235 // If the Expr being casted is a ParenListExpr, handle it specially.
8236 // This is not an AltiVec-style cast, so turn the ParenListExpr into a
8237 // sequence of BinOp comma operators.
8238 if (isa<ParenListExpr>(CastExpr)) {
8239 ExprResult Result = MaybeConvertParenListExprToParenExpr(S, CastExpr);
8240 if (Result.isInvalid()) return ExprError();
8241 CastExpr = Result.get();
8242 }
8243
8244 if (getLangOpts().CPlusPlus && !castType->isVoidType())
8245 Diag(LParenLoc, diag::warn_old_style_cast) << CastExpr->getSourceRange();
8246
8247 CheckTollFreeBridgeCast(castType, CastExpr);
8248
8249 CheckObjCBridgeRelatedCast(castType, CastExpr);
8250
8251 DiscardMisalignedMemberAddress(castType.getTypePtr(), CastExpr);
8252
8253 return BuildCStyleCastExpr(LParenLoc, castTInfo, RParenLoc, CastExpr);
8254}
8255
8256ExprResult Sema::BuildVectorLiteral(SourceLocation LParenLoc,
8257 SourceLocation RParenLoc, Expr *E,
8258 TypeSourceInfo *TInfo) {
8259 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", 8260, __extension__ __PRETTY_FUNCTION__
))
8260 "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", 8260, __extension__ __PRETTY_FUNCTION__
))
;
8261
8262 Expr **exprs;
8263 unsigned numExprs;
8264 Expr *subExpr;
8265 SourceLocation LiteralLParenLoc, LiteralRParenLoc;
8266 if (ParenListExpr *PE = dyn_cast<ParenListExpr>(E)) {
8267 LiteralLParenLoc = PE->getLParenLoc();
8268 LiteralRParenLoc = PE->getRParenLoc();
8269 exprs = PE->getExprs();
8270 numExprs = PE->getNumExprs();
8271 } else { // isa<ParenExpr> by assertion at function entrance
8272 LiteralLParenLoc = cast<ParenExpr>(E)->getLParen();
8273 LiteralRParenLoc = cast<ParenExpr>(E)->getRParen();
8274 subExpr = cast<ParenExpr>(E)->getSubExpr();
8275 exprs = &subExpr;
8276 numExprs = 1;
8277 }
8278
8279 QualType Ty = TInfo->getType();
8280 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", 8280, __extension__ __PRETTY_FUNCTION__
))
;
8281
8282 SmallVector<Expr *, 8> initExprs;
8283 const VectorType *VTy = Ty->castAs<VectorType>();
8284 unsigned numElems = VTy->getNumElements();
8285
8286 // '(...)' form of vector initialization in AltiVec: the number of
8287 // initializers must be one or must match the size of the vector.
8288 // If a single value is specified in the initializer then it will be
8289 // replicated to all the components of the vector
8290 if (CheckAltivecInitFromScalar(E->getSourceRange(), Ty,
8291 VTy->getElementType()))
8292 return ExprError();
8293 if (ShouldSplatAltivecScalarInCast(VTy)) {
8294 // The number of initializers must be one or must match the size of the
8295 // vector. If a single value is specified in the initializer then it will
8296 // be replicated to all the components of the vector
8297 if (numExprs == 1) {
8298 QualType ElemTy = VTy->getElementType();
8299 ExprResult Literal = DefaultLvalueConversion(exprs[0]);
8300 if (Literal.isInvalid())
8301 return ExprError();
8302 Literal = ImpCastExprToType(Literal.get(), ElemTy,
8303 PrepareScalarCast(Literal, ElemTy));
8304 return BuildCStyleCastExpr(LParenLoc, TInfo, RParenLoc, Literal.get());
8305 }
8306 else if (numExprs < numElems) {
8307 Diag(E->getExprLoc(),
8308 diag::err_incorrect_number_of_vector_initializers);
8309 return ExprError();
8310 }
8311 else
8312 initExprs.append(exprs, exprs + numExprs);
8313 }
8314 else {
8315 // For OpenCL, when the number of initializers is a single value,
8316 // it will be replicated to all components of the vector.
8317 if (getLangOpts().OpenCL &&
8318 VTy->getVectorKind() == VectorType::GenericVector &&
8319 numExprs == 1) {
8320 QualType ElemTy = VTy->getElementType();
8321 ExprResult Literal = DefaultLvalueConversion(exprs[0]);
8322 if (Literal.isInvalid())
8323 return ExprError();
8324 Literal = ImpCastExprToType(Literal.get(), ElemTy,
8325 PrepareScalarCast(Literal, ElemTy));
8326 return BuildCStyleCastExpr(LParenLoc, TInfo, RParenLoc, Literal.get());
8327 }
8328
8329 initExprs.append(exprs, exprs + numExprs);
8330 }
8331 // FIXME: This means that pretty-printing the final AST will produce curly
8332 // braces instead of the original commas.
8333 InitListExpr *initE = new (Context) InitListExpr(Context, LiteralLParenLoc,
8334 initExprs, LiteralRParenLoc);
8335 initE->setType(Ty);
8336 return BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc, initE);
8337}
8338
8339/// This is not an AltiVec-style cast or or C++ direct-initialization, so turn
8340/// the ParenListExpr into a sequence of comma binary operators.
8341ExprResult
8342Sema::MaybeConvertParenListExprToParenExpr(Scope *S, Expr *OrigExpr) {
8343 ParenListExpr *E = dyn_cast<ParenListExpr>(OrigExpr);
8344 if (!E)
8345 return OrigExpr;
8346
8347 ExprResult Result(E->getExpr(0));
8348
8349 for (unsigned i = 1, e = E->getNumExprs(); i != e && !Result.isInvalid(); ++i)
8350 Result = ActOnBinOp(S, E->getExprLoc(), tok::comma, Result.get(),
8351 E->getExpr(i));
8352
8353 if (Result.isInvalid()) return ExprError();
8354
8355 return ActOnParenExpr(E->getLParenLoc(), E->getRParenLoc(), Result.get());
8356}
8357
8358ExprResult Sema::ActOnParenListExpr(SourceLocation L,
8359 SourceLocation R,
8360 MultiExprArg Val) {
8361 return ParenListExpr::Create(Context, L, Val, R);
8362}
8363
8364/// Emit a specialized diagnostic when one expression is a null pointer
8365/// constant and the other is not a pointer. Returns true if a diagnostic is
8366/// emitted.
8367bool Sema::DiagnoseConditionalForNull(Expr *LHSExpr, Expr *RHSExpr,
8368 SourceLocation QuestionLoc) {
8369 Expr *NullExpr = LHSExpr;
8370 Expr *NonPointerExpr = RHSExpr;
8371 Expr::NullPointerConstantKind NullKind =
8372 NullExpr->isNullPointerConstant(Context,
8373 Expr::NPC_ValueDependentIsNotNull);
8374
8375 if (NullKind == Expr::NPCK_NotNull) {
8376 NullExpr = RHSExpr;
8377 NonPointerExpr = LHSExpr;
8378 NullKind =
8379 NullExpr->isNullPointerConstant(Context,
8380 Expr::NPC_ValueDependentIsNotNull);
8381 }
8382
8383 if (NullKind == Expr::NPCK_NotNull)
8384 return false;
8385
8386 if (NullKind == Expr::NPCK_ZeroExpression)
8387 return false;
8388
8389 if (NullKind == Expr::NPCK_ZeroLiteral) {
8390 // In this case, check to make sure that we got here from a "NULL"
8391 // string in the source code.
8392 NullExpr = NullExpr->IgnoreParenImpCasts();
8393 SourceLocation loc = NullExpr->getExprLoc();
8394 if (!findMacroSpelling(loc, "NULL"))
8395 return false;
8396 }
8397
8398 int DiagType = (NullKind == Expr::NPCK_CXX11_nullptr);
8399 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands_null)
8400 << NonPointerExpr->getType() << DiagType
8401 << NonPointerExpr->getSourceRange();
8402 return true;
8403}
8404
8405/// Return false if the condition expression is valid, true otherwise.
8406static bool checkCondition(Sema &S, Expr *Cond, SourceLocation QuestionLoc) {
8407 QualType CondTy = Cond->getType();
8408
8409 // OpenCL v1.1 s6.3.i says the condition cannot be a floating point type.
8410 if (S.getLangOpts().OpenCL && CondTy->isFloatingType()) {
8411 S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_nonfloat)
8412 << CondTy << Cond->getSourceRange();
8413 return true;
8414 }
8415
8416 // C99 6.5.15p2
8417 if (CondTy->isScalarType()) return false;
8418
8419 S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_scalar)
8420 << CondTy << Cond->getSourceRange();
8421 return true;
8422}
8423
8424/// Return false if the NullExpr can be promoted to PointerTy,
8425/// true otherwise.
8426static bool checkConditionalNullPointer(Sema &S, ExprResult &NullExpr,
8427 QualType PointerTy) {
8428 if ((!PointerTy->isAnyPointerType() && !PointerTy->isBlockPointerType()) ||
8429 !NullExpr.get()->isNullPointerConstant(S.Context,
8430 Expr::NPC_ValueDependentIsNull))
8431 return true;
8432
8433 NullExpr = S.ImpCastExprToType(NullExpr.get(), PointerTy, CK_NullToPointer);
8434 return false;
8435}
8436
8437/// Checks compatibility between two pointers and return the resulting
8438/// type.
8439static QualType checkConditionalPointerCompatibility(Sema &S, ExprResult &LHS,
8440 ExprResult &RHS,
8441 SourceLocation Loc) {
8442 QualType LHSTy = LHS.get()->getType();
8443 QualType RHSTy = RHS.get()->getType();
8444
8445 if (S.Context.hasSameType(LHSTy, RHSTy)) {
8446 // Two identical pointers types are always compatible.
8447 return S.Context.getCommonSugaredType(LHSTy, RHSTy);
8448 }
8449
8450 QualType lhptee, rhptee;
8451
8452 // Get the pointee types.
8453 bool IsBlockPointer = false;
8454 if (const BlockPointerType *LHSBTy = LHSTy->getAs<BlockPointerType>()) {
8455 lhptee = LHSBTy->getPointeeType();
8456 rhptee = RHSTy->castAs<BlockPointerType>()->getPointeeType();
8457 IsBlockPointer = true;
8458 } else {
8459 lhptee = LHSTy->castAs<PointerType>()->getPointeeType();
8460 rhptee = RHSTy->castAs<PointerType>()->getPointeeType();
8461 }
8462
8463 // C99 6.5.15p6: If both operands are pointers to compatible types or to
8464 // differently qualified versions of compatible types, the result type is
8465 // a pointer to an appropriately qualified version of the composite
8466 // type.
8467
8468 // Only CVR-qualifiers exist in the standard, and the differently-qualified
8469 // clause doesn't make sense for our extensions. E.g. address space 2 should
8470 // be incompatible with address space 3: they may live on different devices or
8471 // anything.
8472 Qualifiers lhQual = lhptee.getQualifiers();
8473 Qualifiers rhQual = rhptee.getQualifiers();
8474
8475 LangAS ResultAddrSpace = LangAS::Default;
8476 LangAS LAddrSpace = lhQual.getAddressSpace();
8477 LangAS RAddrSpace = rhQual.getAddressSpace();
8478
8479 // OpenCL v1.1 s6.5 - Conversion between pointers to distinct address
8480 // spaces is disallowed.
8481 if (lhQual.isAddressSpaceSupersetOf(rhQual))
8482 ResultAddrSpace = LAddrSpace;
8483 else if (rhQual.isAddressSpaceSupersetOf(lhQual))
8484 ResultAddrSpace = RAddrSpace;
8485 else {
8486 S.Diag(Loc, diag::err_typecheck_op_on_nonoverlapping_address_space_pointers)
8487 << LHSTy << RHSTy << 2 << LHS.get()->getSourceRange()
8488 << RHS.get()->getSourceRange();
8489 return QualType();
8490 }
8491
8492 unsigned MergedCVRQual = lhQual.getCVRQualifiers() | rhQual.getCVRQualifiers();
8493 auto LHSCastKind = CK_BitCast, RHSCastKind = CK_BitCast;
8494 lhQual.removeCVRQualifiers();
8495 rhQual.removeCVRQualifiers();
8496
8497 // OpenCL v2.0 specification doesn't extend compatibility of type qualifiers
8498 // (C99 6.7.3) for address spaces. We assume that the check should behave in
8499 // the same manner as it's defined for CVR qualifiers, so for OpenCL two
8500 // qual types are compatible iff
8501 // * corresponded types are compatible
8502 // * CVR qualifiers are equal
8503 // * address spaces are equal
8504 // Thus for conditional operator we merge CVR and address space unqualified
8505 // pointees and if there is a composite type we return a pointer to it with
8506 // merged qualifiers.
8507 LHSCastKind =
8508 LAddrSpace == ResultAddrSpace ? CK_BitCast : CK_AddressSpaceConversion;
8509 RHSCastKind =
8510 RAddrSpace == ResultAddrSpace ? CK_BitCast : CK_AddressSpaceConversion;
8511 lhQual.removeAddressSpace();
8512 rhQual.removeAddressSpace();
8513
8514 lhptee = S.Context.getQualifiedType(lhptee.getUnqualifiedType(), lhQual);
8515 rhptee = S.Context.getQualifiedType(rhptee.getUnqualifiedType(), rhQual);
8516
8517 QualType CompositeTy = S.Context.mergeTypes(
8518 lhptee, rhptee, /*OfBlockPointer=*/false, /*Unqualified=*/false,
8519 /*BlockReturnType=*/false, /*IsConditionalOperator=*/true);
8520
8521 if (CompositeTy.isNull()) {
8522 // In this situation, we assume void* type. No especially good
8523 // reason, but this is what gcc does, and we do have to pick
8524 // to get a consistent AST.
8525 QualType incompatTy;
8526 incompatTy = S.Context.getPointerType(
8527 S.Context.getAddrSpaceQualType(S.Context.VoidTy, ResultAddrSpace));
8528 LHS = S.ImpCastExprToType(LHS.get(), incompatTy, LHSCastKind);
8529 RHS = S.ImpCastExprToType(RHS.get(), incompatTy, RHSCastKind);
8530
8531 // FIXME: For OpenCL the warning emission and cast to void* leaves a room
8532 // for casts between types with incompatible address space qualifiers.
8533 // For the following code the compiler produces casts between global and
8534 // local address spaces of the corresponded innermost pointees:
8535 // local int *global *a;
8536 // global int *global *b;
8537 // a = (0 ? a : b); // see C99 6.5.16.1.p1.
8538 S.Diag(Loc, diag::ext_typecheck_cond_incompatible_pointers)
8539 << LHSTy << RHSTy << LHS.get()->getSourceRange()
8540 << RHS.get()->getSourceRange();
8541
8542 return incompatTy;
8543 }
8544
8545 // The pointer types are compatible.
8546 // In case of OpenCL ResultTy should have the address space qualifier
8547 // which is a superset of address spaces of both the 2nd and the 3rd
8548 // operands of the conditional operator.
8549 QualType ResultTy = [&, ResultAddrSpace]() {
8550 if (S.getLangOpts().OpenCL) {
8551 Qualifiers CompositeQuals = CompositeTy.getQualifiers();
8552 CompositeQuals.setAddressSpace(ResultAddrSpace);
8553 return S.Context
8554 .getQualifiedType(CompositeTy.getUnqualifiedType(), CompositeQuals)
8555 .withCVRQualifiers(MergedCVRQual);
8556 }
8557 return CompositeTy.withCVRQualifiers(MergedCVRQual);
8558 }();
8559 if (IsBlockPointer)
8560 ResultTy = S.Context.getBlockPointerType(ResultTy);
8561 else
8562 ResultTy = S.Context.getPointerType(ResultTy);
8563
8564 LHS = S.ImpCastExprToType(LHS.get(), ResultTy, LHSCastKind);
8565 RHS = S.ImpCastExprToType(RHS.get(), ResultTy, RHSCastKind);
8566 return ResultTy;
8567}
8568
8569/// Return the resulting type when the operands are both block pointers.
8570static QualType checkConditionalBlockPointerCompatibility(Sema &S,
8571 ExprResult &LHS,
8572 ExprResult &RHS,
8573 SourceLocation Loc) {
8574 QualType LHSTy = LHS.get()->getType();
8575 QualType RHSTy = RHS.get()->getType();
8576
8577 if (!LHSTy->isBlockPointerType() || !RHSTy->isBlockPointerType()) {
8578 if (LHSTy->isVoidPointerType() || RHSTy->isVoidPointerType()) {
8579 QualType destType = S.Context.getPointerType(S.Context.VoidTy);
8580 LHS = S.ImpCastExprToType(LHS.get(), destType, CK_BitCast);
8581 RHS = S.ImpCastExprToType(RHS.get(), destType, CK_BitCast);
8582 return destType;
8583 }
8584 S.Diag(Loc, diag::err_typecheck_cond_incompatible_operands)
8585 << LHSTy << RHSTy << LHS.get()->getSourceRange()
8586 << RHS.get()->getSourceRange();
8587 return QualType();
8588 }
8589
8590 // We have 2 block pointer types.
8591 return checkConditionalPointerCompatibility(S, LHS, RHS, Loc);
8592}
8593
8594/// Return the resulting type when the operands are both pointers.
8595static QualType
8596checkConditionalObjectPointersCompatibility(Sema &S, ExprResult &LHS,
8597 ExprResult &RHS,
8598 SourceLocation Loc) {
8599 // get the pointer types
8600 QualType LHSTy = LHS.get()->getType();
8601 QualType RHSTy = RHS.get()->getType();
8602
8603 // get the "pointed to" types
8604 QualType lhptee = LHSTy->castAs<PointerType>()->getPointeeType();
8605 QualType rhptee = RHSTy->castAs<PointerType>()->getPointeeType();
8606
8607 // ignore qualifiers on void (C99 6.5.15p3, clause 6)
8608 if (lhptee->isVoidType() && rhptee->isIncompleteOrObjectType()) {
8609 // Figure out necessary qualifiers (C99 6.5.15p6)
8610 QualType destPointee
8611 = S.Context.getQualifiedType(lhptee, rhptee.getQualifiers());
8612 QualType destType = S.Context.getPointerType(destPointee);
8613 // Add qualifiers if necessary.
8614 LHS = S.ImpCastExprToType(LHS.get(), destType, CK_NoOp);
8615 // Promote to void*.
8616 RHS = S.ImpCastExprToType(RHS.get(), destType, CK_BitCast);
8617 return destType;
8618 }
8619 if (rhptee->isVoidType() && lhptee->isIncompleteOrObjectType()) {
8620 QualType destPointee
8621 = S.Context.getQualifiedType(rhptee, lhptee.getQualifiers());
8622 QualType destType = S.Context.getPointerType(destPointee);
8623 // Add qualifiers if necessary.
8624 RHS = S.ImpCastExprToType(RHS.get(), destType, CK_NoOp);
8625 // Promote to void*.
8626 LHS = S.ImpCastExprToType(LHS.get(), destType, CK_BitCast);
8627 return destType;
8628 }
8629
8630 return checkConditionalPointerCompatibility(S, LHS, RHS, Loc);
8631}
8632
8633/// Return false if the first expression is not an integer and the second
8634/// expression is not a pointer, true otherwise.
8635static bool checkPointerIntegerMismatch(Sema &S, ExprResult &Int,
8636 Expr* PointerExpr, SourceLocation Loc,
8637 bool IsIntFirstExpr) {
8638 if (!PointerExpr->getType()->isPointerType() ||
8639 !Int.get()->getType()->isIntegerType())
8640 return false;
8641
8642 Expr *Expr1 = IsIntFirstExpr ? Int.get() : PointerExpr;
8643 Expr *Expr2 = IsIntFirstExpr ? PointerExpr : Int.get();
8644
8645 S.Diag(Loc, diag::ext_typecheck_cond_pointer_integer_mismatch)
8646 << Expr1->getType() << Expr2->getType()
8647 << Expr1->getSourceRange() << Expr2->getSourceRange();
8648 Int = S.ImpCastExprToType(Int.get(), PointerExpr->getType(),
8649 CK_IntegralToPointer);
8650 return true;
8651}
8652
8653/// Simple conversion between integer and floating point types.
8654///
8655/// Used when handling the OpenCL conditional operator where the
8656/// condition is a vector while the other operands are scalar.
8657///
8658/// OpenCL v1.1 s6.3.i and s6.11.6 together require that the scalar
8659/// types are either integer or floating type. Between the two
8660/// operands, the type with the higher rank is defined as the "result
8661/// type". The other operand needs to be promoted to the same type. No
8662/// other type promotion is allowed. We cannot use
8663/// UsualArithmeticConversions() for this purpose, since it always
8664/// promotes promotable types.
8665static QualType OpenCLArithmeticConversions(Sema &S, ExprResult &LHS,
8666 ExprResult &RHS,
8667 SourceLocation QuestionLoc) {
8668 LHS = S.DefaultFunctionArrayLvalueConversion(LHS.get());
8669 if (LHS.isInvalid())
8670 return QualType();
8671 RHS = S.DefaultFunctionArrayLvalueConversion(RHS.get());
8672 if (RHS.isInvalid())
8673 return QualType();
8674
8675 // For conversion purposes, we ignore any qualifiers.
8676 // For example, "const float" and "float" are equivalent.
8677 QualType LHSType =
8678 S.Context.getCanonicalType(LHS.get()->getType()).getUnqualifiedType();
8679 QualType RHSType =
8680 S.Context.getCanonicalType(RHS.get()->getType()).getUnqualifiedType();
8681
8682 if (!LHSType->isIntegerType() && !LHSType->isRealFloatingType()) {
8683 S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_int_float)
8684 << LHSType << LHS.get()->getSourceRange();
8685 return QualType();
8686 }
8687
8688 if (!RHSType->isIntegerType() && !RHSType->isRealFloatingType()) {
8689 S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_int_float)
8690 << RHSType << RHS.get()->getSourceRange();
8691 return QualType();
8692 }
8693
8694 // If both types are identical, no conversion is needed.
8695 if (LHSType == RHSType)
8696 return LHSType;
8697
8698 // Now handle "real" floating types (i.e. float, double, long double).
8699 if (LHSType->isRealFloatingType() || RHSType->isRealFloatingType())
8700 return handleFloatConversion(S, LHS, RHS, LHSType, RHSType,
8701 /*IsCompAssign = */ false);
8702
8703 // Finally, we have two differing integer types.
8704 return handleIntegerConversion<doIntegralCast, doIntegralCast>
8705 (S, LHS, RHS, LHSType, RHSType, /*IsCompAssign = */ false);
8706}
8707
8708/// Convert scalar operands to a vector that matches the
8709/// condition in length.
8710///
8711/// Used when handling the OpenCL conditional operator where the
8712/// condition is a vector while the other operands are scalar.
8713///
8714/// We first compute the "result type" for the scalar operands
8715/// according to OpenCL v1.1 s6.3.i. Both operands are then converted
8716/// into a vector of that type where the length matches the condition
8717/// vector type. s6.11.6 requires that the element types of the result
8718/// and the condition must have the same number of bits.
8719static QualType
8720OpenCLConvertScalarsToVectors(Sema &S, ExprResult &LHS, ExprResult &RHS,
8721 QualType CondTy, SourceLocation QuestionLoc) {
8722 QualType ResTy = OpenCLArithmeticConversions(S, LHS, RHS, QuestionLoc);
8723 if (ResTy.isNull()) return QualType();
8724
8725 const VectorType *CV = CondTy->getAs<VectorType>();
8726 assert(CV)(static_cast <bool> (CV) ? void (0) : __assert_fail ("CV"
, "clang/lib/Sema/SemaExpr.cpp", 8726, __extension__ __PRETTY_FUNCTION__
))
;
8727
8728 // Determine the vector result type
8729 unsigned NumElements = CV->getNumElements();
8730 QualType VectorTy = S.Context.getExtVectorType(ResTy, NumElements);
8731
8732 // Ensure that all types have the same number of bits
8733 if (S.Context.getTypeSize(CV->getElementType())
8734 != S.Context.getTypeSize(ResTy)) {
8735 // Since VectorTy is created internally, it does not pretty print
8736 // with an OpenCL name. Instead, we just print a description.
8737 std::string EleTyName = ResTy.getUnqualifiedType().getAsString();
8738 SmallString<64> Str;
8739 llvm::raw_svector_ostream OS(Str);
8740 OS << "(vector of " << NumElements << " '" << EleTyName << "' values)";
8741 S.Diag(QuestionLoc, diag::err_conditional_vector_element_size)
8742 << CondTy << OS.str();
8743 return QualType();
8744 }
8745
8746 // Convert operands to the vector result type
8747 LHS = S.ImpCastExprToType(LHS.get(), VectorTy, CK_VectorSplat);
8748 RHS = S.ImpCastExprToType(RHS.get(), VectorTy, CK_VectorSplat);
8749
8750 return VectorTy;
8751}
8752
8753/// Return false if this is a valid OpenCL condition vector
8754static bool checkOpenCLConditionVector(Sema &S, Expr *Cond,
8755 SourceLocation QuestionLoc) {
8756 // OpenCL v1.1 s6.11.6 says the elements of the vector must be of
8757 // integral type.
8758 const VectorType *CondTy = Cond->getType()->getAs<VectorType>();
8759 assert(CondTy)(static_cast <bool> (CondTy) ? void (0) : __assert_fail
("CondTy", "clang/lib/Sema/SemaExpr.cpp", 8759, __extension__
__PRETTY_FUNCTION__))
;
8760 QualType EleTy = CondTy->getElementType();
8761 if (EleTy->isIntegerType()) return false;
8762
8763 S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_nonfloat)
8764 << Cond->getType() << Cond->getSourceRange();
8765 return true;
8766}
8767
8768/// Return false if the vector condition type and the vector
8769/// result type are compatible.
8770///
8771/// OpenCL v1.1 s6.11.6 requires that both vector types have the same
8772/// number of elements, and their element types have the same number
8773/// of bits.
8774static bool checkVectorResult(Sema &S, QualType CondTy, QualType VecResTy,
8775 SourceLocation QuestionLoc) {
8776 const VectorType *CV = CondTy->getAs<VectorType>();
8777 const VectorType *RV = VecResTy->getAs<VectorType>();
8778 assert(CV && RV)(static_cast <bool> (CV && RV) ? void (0) : __assert_fail
("CV && RV", "clang/lib/Sema/SemaExpr.cpp", 8778, __extension__
__PRETTY_FUNCTION__))
;
8779
8780 if (CV->getNumElements() != RV->getNumElements()) {
8781 S.Diag(QuestionLoc, diag::err_conditional_vector_size)
8782 << CondTy << VecResTy;
8783 return true;
8784 }
8785
8786 QualType CVE = CV->getElementType();
8787 QualType RVE = RV->getElementType();
8788
8789 if (S.Context.getTypeSize(CVE) != S.Context.getTypeSize(RVE)) {
8790 S.Diag(QuestionLoc, diag::err_conditional_vector_element_size)
8791 << CondTy << VecResTy;
8792 return true;
8793 }
8794
8795 return false;
8796}
8797
8798/// Return the resulting type for the conditional operator in
8799/// OpenCL (aka "ternary selection operator", OpenCL v1.1
8800/// s6.3.i) when the condition is a vector type.
8801static QualType
8802OpenCLCheckVectorConditional(Sema &S, ExprResult &Cond,
8803 ExprResult &LHS, ExprResult &RHS,
8804 SourceLocation QuestionLoc) {
8805 Cond = S.DefaultFunctionArrayLvalueConversion(Cond.get());
8806 if (Cond.isInvalid())
8807 return QualType();
8808 QualType CondTy = Cond.get()->getType();
8809
8810 if (checkOpenCLConditionVector(S, Cond.get(), QuestionLoc))
8811 return QualType();
8812
8813 // If either operand is a vector then find the vector type of the
8814 // result as specified in OpenCL v1.1 s6.3.i.
8815 if (LHS.get()->getType()->isVectorType() ||
8816 RHS.get()->getType()->isVectorType()) {
8817 bool IsBoolVecLang =
8818 !S.getLangOpts().OpenCL && !S.getLangOpts().OpenCLCPlusPlus;
8819 QualType VecResTy =
8820 S.CheckVectorOperands(LHS, RHS, QuestionLoc,
8821 /*isCompAssign*/ false,
8822 /*AllowBothBool*/ true,
8823 /*AllowBoolConversions*/ false,
8824 /*AllowBooleanOperation*/ IsBoolVecLang,
8825 /*ReportInvalid*/ true);
8826 if (VecResTy.isNull())
8827 return QualType();
8828 // The result type must match the condition type as specified in
8829 // OpenCL v1.1 s6.11.6.
8830 if (checkVectorResult(S, CondTy, VecResTy, QuestionLoc))
8831 return QualType();
8832 return VecResTy;
8833 }
8834
8835 // Both operands are scalar.
8836 return OpenCLConvertScalarsToVectors(S, LHS, RHS, CondTy, QuestionLoc);
8837}
8838
8839/// Return true if the Expr is block type
8840static bool checkBlockType(Sema &S, const Expr *E) {
8841 if (const CallExpr *CE = dyn_cast<CallExpr>(E)) {
8842 QualType Ty = CE->getCallee()->getType();
8843 if (Ty->isBlockPointerType()) {
8844 S.Diag(E->getExprLoc(), diag::err_opencl_ternary_with_block);
8845 return true;
8846 }
8847 }
8848 return false;
8849}
8850
8851/// Note that LHS is not null here, even if this is the gnu "x ?: y" extension.
8852/// In that case, LHS = cond.
8853/// C99 6.5.15
8854QualType Sema::CheckConditionalOperands(ExprResult &Cond, ExprResult &LHS,
8855 ExprResult &RHS, ExprValueKind &VK,
8856 ExprObjectKind &OK,
8857 SourceLocation QuestionLoc) {
8858
8859 ExprResult LHSResult = CheckPlaceholderExpr(LHS.get());
8860 if (!LHSResult.isUsable()) return QualType();
8861 LHS = LHSResult;
8862
8863 ExprResult RHSResult = CheckPlaceholderExpr(RHS.get());
8864 if (!RHSResult.isUsable()) return QualType();
8865 RHS = RHSResult;
8866
8867 // C++ is sufficiently different to merit its own checker.
8868 if (getLangOpts().CPlusPlus)
8869 return CXXCheckConditionalOperands(Cond, LHS, RHS, VK, OK, QuestionLoc);
8870
8871 VK = VK_PRValue;
8872 OK = OK_Ordinary;
8873
8874 if (Context.isDependenceAllowed() &&
8875 (Cond.get()->isTypeDependent() || LHS.get()->isTypeDependent() ||
8876 RHS.get()->isTypeDependent())) {
8877 assert(!getLangOpts().CPlusPlus)(static_cast <bool> (!getLangOpts().CPlusPlus) ? void (
0) : __assert_fail ("!getLangOpts().CPlusPlus", "clang/lib/Sema/SemaExpr.cpp"
, 8877, __extension__ __PRETTY_FUNCTION__))
;
8878 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", 8880, __extension__ __PRETTY_FUNCTION__
))
8879 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", 8880, __extension__ __PRETTY_FUNCTION__
))
8880 "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", 8880, __extension__ __PRETTY_FUNCTION__
))
;
8881 return Context.DependentTy;
8882 }
8883
8884 // The OpenCL operator with a vector condition is sufficiently
8885 // different to merit its own checker.
8886 if ((getLangOpts().OpenCL && Cond.get()->getType()->isVectorType()) ||
8887 Cond.get()->getType()->isExtVectorType())
8888 return OpenCLCheckVectorConditional(*this, Cond, LHS, RHS, QuestionLoc);
8889
8890 // First, check the condition.
8891 Cond = UsualUnaryConversions(Cond.get());
8892 if (Cond.isInvalid())
8893 return QualType();
8894 if (checkCondition(*this, Cond.get(), QuestionLoc))
8895 return QualType();
8896
8897 // Now check the two expressions.
8898 if (LHS.get()->getType()->isVectorType() ||
8899 RHS.get()->getType()->isVectorType())
8900 return CheckVectorOperands(LHS, RHS, QuestionLoc, /*isCompAssign*/ false,
8901 /*AllowBothBool*/ true,
8902 /*AllowBoolConversions*/ false,
8903 /*AllowBooleanOperation*/ false,
8904 /*ReportInvalid*/ true);
8905
8906 QualType ResTy =
8907 UsualArithmeticConversions(LHS, RHS, QuestionLoc, ACK_Conditional);
8908 if (LHS.isInvalid() || RHS.isInvalid())
8909 return QualType();
8910
8911 QualType LHSTy = LHS.get()->getType();
8912 QualType RHSTy = RHS.get()->getType();
8913
8914 // Diagnose attempts to convert between __ibm128, __float128 and long double
8915 // where such conversions currently can't be handled.
8916 if (unsupportedTypeConversion(*this, LHSTy, RHSTy)) {
8917 Diag(QuestionLoc,
8918 diag::err_typecheck_cond_incompatible_operands) << LHSTy << RHSTy
8919 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
8920 return QualType();
8921 }
8922
8923 // OpenCL v2.0 s6.12.5 - Blocks cannot be used as expressions of the ternary
8924 // selection operator (?:).
8925 if (getLangOpts().OpenCL &&
8926 ((int)checkBlockType(*this, LHS.get()) | (int)checkBlockType(*this, RHS.get()))) {
8927 return QualType();
8928 }
8929
8930 // If both operands have arithmetic type, do the usual arithmetic conversions
8931 // to find a common type: C99 6.5.15p3,5.
8932 if (LHSTy->isArithmeticType() && RHSTy->isArithmeticType()) {
8933 // Disallow invalid arithmetic conversions, such as those between bit-
8934 // precise integers types of different sizes, or between a bit-precise
8935 // integer and another type.
8936 if (ResTy.isNull() && (LHSTy->isBitIntType() || RHSTy->isBitIntType())) {
8937 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands)
8938 << LHSTy << RHSTy << LHS.get()->getSourceRange()
8939 << RHS.get()->getSourceRange();
8940 return QualType();
8941 }
8942
8943 LHS = ImpCastExprToType(LHS.get(), ResTy, PrepareScalarCast(LHS, ResTy));
8944 RHS = ImpCastExprToType(RHS.get(), ResTy, PrepareScalarCast(RHS, ResTy));
8945
8946 return ResTy;
8947 }
8948
8949 // And if they're both bfloat (which isn't arithmetic), that's fine too.
8950 if (LHSTy->isBFloat16Type() && RHSTy->isBFloat16Type()) {
8951 return Context.getCommonSugaredType(LHSTy, RHSTy);
8952 }
8953
8954 // If both operands are the same structure or union type, the result is that
8955 // type.
8956 if (const RecordType *LHSRT = LHSTy->getAs<RecordType>()) { // C99 6.5.15p3
8957 if (const RecordType *RHSRT = RHSTy->getAs<RecordType>())
8958 if (LHSRT->getDecl() == RHSRT->getDecl())
8959 // "If both the operands have structure or union type, the result has
8960 // that type." This implies that CV qualifiers are dropped.
8961 return Context.getCommonSugaredType(LHSTy.getUnqualifiedType(),
8962 RHSTy.getUnqualifiedType());
8963 // FIXME: Type of conditional expression must be complete in C mode.
8964 }
8965
8966 // C99 6.5.15p5: "If both operands have void type, the result has void type."
8967 // The following || allows only one side to be void (a GCC-ism).
8968 if (LHSTy->isVoidType() || RHSTy->isVoidType()) {
8969 QualType ResTy;
8970 if (LHSTy->isVoidType() && RHSTy->isVoidType()) {
8971 ResTy = Context.getCommonSugaredType(LHSTy, RHSTy);
8972 } else if (RHSTy->isVoidType()) {
8973 ResTy = RHSTy;
8974 Diag(RHS.get()->getBeginLoc(), diag::ext_typecheck_cond_one_void)
8975 << RHS.get()->getSourceRange();
8976 } else {
8977 ResTy = LHSTy;
8978 Diag(LHS.get()->getBeginLoc(), diag::ext_typecheck_cond_one_void)
8979 << LHS.get()->getSourceRange();
8980 }
8981 LHS = ImpCastExprToType(LHS.get(), ResTy, CK_ToVoid);
8982 RHS = ImpCastExprToType(RHS.get(), ResTy, CK_ToVoid);
8983 return ResTy;
8984 }
8985
8986 // C2x 6.5.15p7:
8987 // ... if both the second and third operands have nullptr_t type, the
8988 // result also has that type.
8989 if (LHSTy->isNullPtrType() && Context.hasSameType(LHSTy, RHSTy))
8990 return ResTy;
8991
8992 // C99 6.5.15p6 - "if one operand is a null pointer constant, the result has
8993 // the type of the other operand."
8994 if (!checkConditionalNullPointer(*this, RHS, LHSTy)) return LHSTy;
8995 if (!checkConditionalNullPointer(*this, LHS, RHSTy)) return RHSTy;
8996
8997 // All objective-c pointer type analysis is done here.
8998 QualType compositeType = FindCompositeObjCPointerType(LHS, RHS,
8999 QuestionLoc);
9000 if (LHS.isInvalid() || RHS.isInvalid())
9001 return QualType();
9002 if (!compositeType.isNull())
9003 return compositeType;
9004
9005
9006 // Handle block pointer types.
9007 if (LHSTy->isBlockPointerType() || RHSTy->isBlockPointerType())
9008 return checkConditionalBlockPointerCompatibility(*this, LHS, RHS,
9009 QuestionLoc);
9010
9011 // Check constraints for C object pointers types (C99 6.5.15p3,6).
9012 if (LHSTy->isPointerType() && RHSTy->isPointerType())
9013 return checkConditionalObjectPointersCompatibility(*this, LHS, RHS,
9014 QuestionLoc);
9015
9016 // GCC compatibility: soften pointer/integer mismatch. Note that
9017 // null pointers have been filtered out by this point.
9018 if (checkPointerIntegerMismatch(*this, LHS, RHS.get(), QuestionLoc,
9019 /*IsIntFirstExpr=*/true))
9020 return RHSTy;
9021 if (checkPointerIntegerMismatch(*this, RHS, LHS.get(), QuestionLoc,
9022 /*IsIntFirstExpr=*/false))
9023 return LHSTy;
9024
9025 // Allow ?: operations in which both operands have the same
9026 // built-in sizeless type.
9027 if (LHSTy->isSizelessBuiltinType() && Context.hasSameType(LHSTy, RHSTy))
9028 return Context.getCommonSugaredType(LHSTy, RHSTy);
9029
9030 // Emit a better diagnostic if one of the expressions is a null pointer
9031 // constant and the other is not a pointer type. In this case, the user most
9032 // likely forgot to take the address of the other expression.
9033 if (DiagnoseConditionalForNull(LHS.get(), RHS.get(), QuestionLoc))
9034 return QualType();
9035
9036 // Otherwise, the operands are not compatible.
9037 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands)
9038 << LHSTy << RHSTy << LHS.get()->getSourceRange()
9039 << RHS.get()->getSourceRange();
9040 return QualType();
9041}
9042
9043/// FindCompositeObjCPointerType - Helper method to find composite type of
9044/// two objective-c pointer types of the two input expressions.
9045QualType Sema::FindCompositeObjCPointerType(ExprResult &LHS, ExprResult &RHS,
9046 SourceLocation QuestionLoc) {
9047 QualType LHSTy = LHS.get()->getType();
9048 QualType RHSTy = RHS.get()->getType();
9049
9050 // Handle things like Class and struct objc_class*. Here we case the result
9051 // to the pseudo-builtin, because that will be implicitly cast back to the
9052 // redefinition type if an attempt is made to access its fields.
9053 if (LHSTy->isObjCClassType() &&
9054 (Context.hasSameType(RHSTy, Context.getObjCClassRedefinitionType()))) {
9055 RHS = ImpCastExprToType(RHS.get(), LHSTy, CK_CPointerToObjCPointerCast);
9056 return LHSTy;
9057 }
9058 if (RHSTy->isObjCClassType() &&
9059 (Context.hasSameType(LHSTy, Context.getObjCClassRedefinitionType()))) {
9060 LHS = ImpCastExprToType(LHS.get(), RHSTy, CK_CPointerToObjCPointerCast);
9061 return RHSTy;
9062 }
9063 // And the same for struct objc_object* / id
9064 if (LHSTy->isObjCIdType() &&
9065 (Context.hasSameType(RHSTy, Context.getObjCIdRedefinitionType()))) {
9066 RHS = ImpCastExprToType(RHS.get(), LHSTy, CK_CPointerToObjCPointerCast);
9067 return LHSTy;
9068 }
9069 if (RHSTy->isObjCIdType() &&
9070 (Context.hasSameType(LHSTy, Context.getObjCIdRedefinitionType()))) {
9071 LHS = ImpCastExprToType(LHS.get(), RHSTy, CK_CPointerToObjCPointerCast);
9072 return RHSTy;
9073 }
9074 // And the same for struct objc_selector* / SEL
9075 if (Context.isObjCSelType(LHSTy) &&
9076 (Context.hasSameType(RHSTy, Context.getObjCSelRedefinitionType()))) {
9077 RHS = ImpCastExprToType(RHS.get(), LHSTy, CK_BitCast);
9078 return LHSTy;
9079 }
9080 if (Context.isObjCSelType(RHSTy) &&
9081 (Context.hasSameType(LHSTy, Context.getObjCSelRedefinitionType()))) {
9082 LHS = ImpCastExprToType(LHS.get(), RHSTy, CK_BitCast);
9083 return RHSTy;
9084 }
9085 // Check constraints for Objective-C object pointers types.
9086 if (LHSTy->isObjCObjectPointerType() && RHSTy->isObjCObjectPointerType()) {
9087
9088 if (Context.getCanonicalType(LHSTy) == Context.getCanonicalType(RHSTy)) {
9089 // Two identical object pointer types are always compatible.
9090 return LHSTy;
9091 }
9092 const ObjCObjectPointerType *LHSOPT = LHSTy->castAs<ObjCObjectPointerType>();
9093 const ObjCObjectPointerType *RHSOPT = RHSTy->castAs<ObjCObjectPointerType>();
9094 QualType compositeType = LHSTy;
9095
9096 // If both operands are interfaces and either operand can be
9097 // assigned to the other, use that type as the composite
9098 // type. This allows
9099 // xxx ? (A*) a : (B*) b
9100 // where B is a subclass of A.
9101 //
9102 // Additionally, as for assignment, if either type is 'id'
9103 // allow silent coercion. Finally, if the types are
9104 // incompatible then make sure to use 'id' as the composite
9105 // type so the result is acceptable for sending messages to.
9106
9107 // FIXME: Consider unifying with 'areComparableObjCPointerTypes'.
9108 // It could return the composite type.
9109 if (!(compositeType =
9110 Context.areCommonBaseCompatible(LHSOPT, RHSOPT)).isNull()) {
9111 // Nothing more to do.
9112 } else if (Context.canAssignObjCInterfaces(LHSOPT, RHSOPT)) {
9113 compositeType = RHSOPT->isObjCBuiltinType() ? RHSTy : LHSTy;
9114 } else if (Context.canAssignObjCInterfaces(RHSOPT, LHSOPT)) {
9115 compositeType = LHSOPT->isObjCBuiltinType() ? LHSTy : RHSTy;
9116 } else if ((LHSOPT->isObjCQualifiedIdType() ||
9117 RHSOPT->isObjCQualifiedIdType()) &&
9118 Context.ObjCQualifiedIdTypesAreCompatible(LHSOPT, RHSOPT,
9119 true)) {
9120 // Need to handle "id<xx>" explicitly.
9121 // GCC allows qualified id and any Objective-C type to devolve to
9122 // id. Currently localizing to here until clear this should be
9123 // part of ObjCQualifiedIdTypesAreCompatible.
9124 compositeType = Context.getObjCIdType();
9125 } else if (LHSTy->isObjCIdType() || RHSTy->isObjCIdType()) {
9126 compositeType = Context.getObjCIdType();
9127 } else {
9128 Diag(QuestionLoc, diag::ext_typecheck_cond_incompatible_operands)
9129 << LHSTy << RHSTy
9130 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
9131 QualType incompatTy = Context.getObjCIdType();
9132 LHS = ImpCastExprToType(LHS.get(), incompatTy, CK_BitCast);
9133 RHS = ImpCastExprToType(RHS.get(), incompatTy, CK_BitCast);
9134 return incompatTy;
9135 }
9136 // The object pointer types are compatible.
9137 LHS = ImpCastExprToType(LHS.get(), compositeType, CK_BitCast);
9138 RHS = ImpCastExprToType(RHS.get(), compositeType, CK_BitCast);
9139 return compositeType;
9140 }
9141 // Check Objective-C object pointer types and 'void *'
9142 if (LHSTy->isVoidPointerType() && RHSTy->isObjCObjectPointerType()) {
9143 if (getLangOpts().ObjCAutoRefCount) {
9144 // ARC forbids the implicit conversion of object pointers to 'void *',
9145 // so these types are not compatible.
9146 Diag(QuestionLoc, diag::err_cond_voidptr_arc) << LHSTy << RHSTy
9147 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
9148 LHS = RHS = true;
9149 return QualType();
9150 }
9151 QualType lhptee = LHSTy->castAs<PointerType>()->getPointeeType();
9152 QualType rhptee = RHSTy->castAs<ObjCObjectPointerType>()->getPointeeType();
9153 QualType destPointee
9154 = Context.getQualifiedType(lhptee, rhptee.getQualifiers());
9155 QualType destType = Context.getPointerType(destPointee);
9156 // Add qualifiers if necessary.
9157 LHS = ImpCastExprToType(LHS.get(), destType, CK_NoOp);
9158 // Promote to void*.
9159 RHS = ImpCastExprToType(RHS.get(), destType, CK_BitCast);
9160 return destType;
9161 }
9162 if (LHSTy->isObjCObjectPointerType() && RHSTy->isVoidPointerType()) {
9163 if (getLangOpts().ObjCAutoRefCount) {
9164 // ARC forbids the implicit conversion of object pointers to 'void *',
9165 // so these types are not compatible.
9166 Diag(QuestionLoc, diag::err_cond_voidptr_arc) << LHSTy << RHSTy
9167 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
9168 LHS = RHS = true;
9169 return QualType();
9170 }
9171 QualType lhptee = LHSTy->castAs<ObjCObjectPointerType>()->getPointeeType();
9172 QualType rhptee = RHSTy->castAs<PointerType>()->getPointeeType();
9173 QualType destPointee
9174 = Context.getQualifiedType(rhptee, lhptee.getQualifiers());
9175 QualType destType = Context.getPointerType(destPointee);
9176 // Add qualifiers if necessary.
9177 RHS = ImpCastExprToType(RHS.get(), destType, CK_NoOp);
9178 // Promote to void*.
9179 LHS = ImpCastExprToType(LHS.get(), destType, CK_BitCast);
9180 return destType;
9181 }
9182 return QualType();
9183}
9184
9185/// SuggestParentheses - Emit a note with a fixit hint that wraps
9186/// ParenRange in parentheses.
9187static void SuggestParentheses(Sema &Self, SourceLocation Loc,
9188 const PartialDiagnostic &Note,
9189 SourceRange ParenRange) {
9190 SourceLocation EndLoc = Self.getLocForEndOfToken(ParenRange.getEnd());
9191 if (ParenRange.getBegin().isFileID() && ParenRange.getEnd().isFileID() &&
9192 EndLoc.isValid()) {
9193 Self.Diag(Loc, Note)
9194 << FixItHint::CreateInsertion(ParenRange.getBegin(), "(")
9195 << FixItHint::CreateInsertion(EndLoc, ")");
9196 } else {
9197 // We can't display the parentheses, so just show the bare note.
9198 Self.Diag(Loc, Note) << ParenRange;
9199 }
9200}
9201
9202static bool IsArithmeticOp(BinaryOperatorKind Opc) {
9203 return BinaryOperator::isAdditiveOp(Opc) ||
9204 BinaryOperator::isMultiplicativeOp(Opc) ||
9205 BinaryOperator::isShiftOp(Opc) || Opc == BO_And || Opc == BO_Or;
9206 // This only checks for bitwise-or and bitwise-and, but not bitwise-xor and
9207 // not any of the logical operators. Bitwise-xor is commonly used as a
9208 // logical-xor because there is no logical-xor operator. The logical
9209 // operators, including uses of xor, have a high false positive rate for
9210 // precedence warnings.
9211}
9212
9213/// IsArithmeticBinaryExpr - Returns true if E is an arithmetic binary
9214/// expression, either using a built-in or overloaded operator,
9215/// and sets *OpCode to the opcode and *RHSExprs to the right-hand side
9216/// expression.
9217static bool IsArithmeticBinaryExpr(Expr *E, BinaryOperatorKind *Opcode,
9218 Expr **RHSExprs) {
9219 // Don't strip parenthesis: we should not warn if E is in parenthesis.
9220 E = E->IgnoreImpCasts();
9221 E = E->IgnoreConversionOperatorSingleStep();
9222 E = E->IgnoreImpCasts();
9223 if (auto *MTE = dyn_cast<MaterializeTemporaryExpr>(E)) {
9224 E = MTE->getSubExpr();
9225 E = E->IgnoreImpCasts();
9226 }
9227
9228 // Built-in binary operator.
9229 if (BinaryOperator *OP = dyn_cast<BinaryOperator>(E)) {
9230 if (IsArithmeticOp(OP->getOpcode())) {
9231 *Opcode = OP->getOpcode();
9232 *RHSExprs = OP->getRHS();
9233 return true;
9234 }
9235 }
9236
9237 // Overloaded operator.
9238 if (CXXOperatorCallExpr *Call = dyn_cast<CXXOperatorCallExpr>(E)) {
9239 if (Call->getNumArgs() != 2)
9240 return false;
9241
9242 // Make sure this is really a binary operator that is safe to pass into
9243 // BinaryOperator::getOverloadedOpcode(), e.g. it's not a subscript op.
9244 OverloadedOperatorKind OO = Call->getOperator();
9245 if (OO < OO_Plus || OO > OO_Arrow ||
9246 OO == OO_PlusPlus || OO == OO_MinusMinus)
9247 return false;
9248
9249 BinaryOperatorKind OpKind = BinaryOperator::getOverloadedOpcode(OO);
9250 if (IsArithmeticOp(OpKind)) {
9251 *Opcode = OpKind;
9252 *RHSExprs = Call->getArg(1);
9253 return true;
9254 }
9255 }
9256
9257 return false;
9258}
9259
9260/// ExprLooksBoolean - Returns true if E looks boolean, i.e. it has boolean type
9261/// or is a logical expression such as (x==y) which has int type, but is
9262/// commonly interpreted as boolean.
9263static bool ExprLooksBoolean(Expr *E) {
9264 E = E->IgnoreParenImpCasts();
9265
9266 if (E->getType()->isBooleanType())
9267 return true;
9268 if (BinaryOperator *OP = dyn_cast<BinaryOperator>(E))
9269 return OP->isComparisonOp() || OP->isLogicalOp();
9270 if (UnaryOperator *OP = dyn_cast<UnaryOperator>(E))
9271 return OP->getOpcode() == UO_LNot;
9272 if (E->getType()->isPointerType())
9273 return true;
9274 // FIXME: What about overloaded operator calls returning "unspecified boolean
9275 // type"s (commonly pointer-to-members)?
9276
9277 return false;
9278}
9279
9280/// DiagnoseConditionalPrecedence - Emit a warning when a conditional operator
9281/// and binary operator are mixed in a way that suggests the programmer assumed
9282/// the conditional operator has higher precedence, for example:
9283/// "int x = a + someBinaryCondition ? 1 : 2".
9284static void DiagnoseConditionalPrecedence(Sema &Self,
9285 SourceLocation OpLoc,
9286 Expr *Condition,
9287 Expr *LHSExpr,
9288 Expr *RHSExpr) {
9289 BinaryOperatorKind CondOpcode;
9290 Expr *CondRHS;
9291
9292 if (!IsArithmeticBinaryExpr(Condition, &CondOpcode, &CondRHS))
9293 return;
9294 if (!ExprLooksBoolean(CondRHS))
9295 return;
9296
9297 // The condition is an arithmetic binary expression, with a right-
9298 // hand side that looks boolean, so warn.
9299
9300 unsigned DiagID = BinaryOperator::isBitwiseOp(CondOpcode)
9301 ? diag::warn_precedence_bitwise_conditional
9302 : diag::warn_precedence_conditional;
9303
9304 Self.Diag(OpLoc, DiagID)
9305 << Condition->getSourceRange()
9306 << BinaryOperator::getOpcodeStr(CondOpcode);
9307
9308 SuggestParentheses(
9309 Self, OpLoc,
9310 Self.PDiag(diag::note_precedence_silence)
9311 << BinaryOperator::getOpcodeStr(CondOpcode),
9312 SourceRange(Condition->getBeginLoc(), Condition->getEndLoc()));
9313
9314 SuggestParentheses(Self, OpLoc,
9315 Self.PDiag(diag::note_precedence_conditional_first),
9316 SourceRange(CondRHS->getBeginLoc(), RHSExpr->getEndLoc()));
9317}
9318
9319/// Compute the nullability of a conditional expression.
9320static QualType computeConditionalNullability(QualType ResTy, bool IsBin,
9321 QualType LHSTy, QualType RHSTy,
9322 ASTContext &Ctx) {
9323 if (!ResTy->isAnyPointerType())
9324 return ResTy;
9325
9326 auto GetNullability = [](QualType Ty) {
9327 std::optional<NullabilityKind> Kind = Ty->getNullability();
9328 if (Kind) {
9329 // For our purposes, treat _Nullable_result as _Nullable.
9330 if (*Kind == NullabilityKind::NullableResult)
9331 return NullabilityKind::Nullable;
9332 return *Kind;
9333 }
9334 return NullabilityKind::Unspecified;
9335 };
9336
9337 auto LHSKind = GetNullability(LHSTy), RHSKind = GetNullability(RHSTy);
9338 NullabilityKind MergedKind;
9339
9340 // Compute nullability of a binary conditional expression.
9341 if (IsBin) {
9342 if (LHSKind == NullabilityKind::NonNull)
9343 MergedKind = NullabilityKind::NonNull;
9344 else
9345 MergedKind = RHSKind;
9346 // Compute nullability of a normal conditional expression.
9347 } else {
9348 if (LHSKind == NullabilityKind::Nullable ||
9349 RHSKind == NullabilityKind::Nullable)
9350 MergedKind = NullabilityKind::Nullable;
9351 else if (LHSKind == NullabilityKind::NonNull)
9352 MergedKind = RHSKind;
9353 else if (RHSKind == NullabilityKind::NonNull)
9354 MergedKind = LHSKind;
9355 else
9356 MergedKind = NullabilityKind::Unspecified;
9357 }
9358
9359 // Return if ResTy already has the correct nullability.
9360 if (GetNullability(ResTy) == MergedKind)
9361 return ResTy;
9362
9363 // Strip all nullability from ResTy.
9364 while (ResTy->getNullability())
9365 ResTy = ResTy.getSingleStepDesugaredType(Ctx);
9366
9367 // Create a new AttributedType with the new nullability kind.
9368 auto NewAttr = AttributedType::getNullabilityAttrKind(MergedKind);
9369 return Ctx.getAttributedType(NewAttr, ResTy, ResTy);
9370}
9371
9372/// ActOnConditionalOp - Parse a ?: operation. Note that 'LHS' may be null
9373/// in the case of a the GNU conditional expr extension.
9374ExprResult Sema::ActOnConditionalOp(SourceLocation QuestionLoc,
9375 SourceLocation ColonLoc,
9376 Expr *CondExpr, Expr *LHSExpr,
9377 Expr *RHSExpr) {
9378 if (!Context.isDependenceAllowed()) {
9379 // C cannot handle TypoExpr nodes in the condition because it
9380 // doesn't handle dependent types properly, so make sure any TypoExprs have
9381 // been dealt with before checking the operands.
9382 ExprResult CondResult = CorrectDelayedTyposInExpr(CondExpr);
9383 ExprResult LHSResult = CorrectDelayedTyposInExpr(LHSExpr);
9384 ExprResult RHSResult = CorrectDelayedTyposInExpr(RHSExpr);
9385
9386 if (!CondResult.isUsable())
9387 return ExprError();
9388
9389 if (LHSExpr) {
9390 if (!LHSResult.isUsable())
9391 return ExprError();
9392 }
9393
9394 if (!RHSResult.isUsable())
9395 return ExprError();
9396
9397 CondExpr = CondResult.get();
9398 LHSExpr = LHSResult.get();
9399 RHSExpr = RHSResult.get();
9400 }
9401
9402 // If this is the gnu "x ?: y" extension, analyze the types as though the LHS
9403 // was the condition.
9404 OpaqueValueExpr *opaqueValue = nullptr;
9405 Expr *commonExpr = nullptr;
9406 if (!LHSExpr) {
9407 commonExpr = CondExpr;
9408 // Lower out placeholder types first. This is important so that we don't
9409 // try to capture a placeholder. This happens in few cases in C++; such
9410 // as Objective-C++'s dictionary subscripting syntax.
9411 if (commonExpr->hasPlaceholderType()) {
9412 ExprResult result = CheckPlaceholderExpr(commonExpr);
9413 if (!result.isUsable()) return ExprError();
9414 commonExpr = result.get();
9415 }
9416 // We usually want to apply unary conversions *before* saving, except
9417 // in the special case of a C++ l-value conditional.
9418 if (!(getLangOpts().CPlusPlus
9419 && !commonExpr->isTypeDependent()
9420 && commonExpr->getValueKind() == RHSExpr->getValueKind()
9421 && commonExpr->isGLValue()
9422 && commonExpr->isOrdinaryOrBitFieldObject()
9423 && RHSExpr->isOrdinaryOrBitFieldObject()
9424 && Context.hasSameType(commonExpr->getType(), RHSExpr->getType()))) {
9425 ExprResult commonRes = UsualUnaryConversions(commonExpr);
9426 if (commonRes.isInvalid())
9427 return ExprError();
9428 commonExpr = commonRes.get();
9429 }
9430
9431 // If the common expression is a class or array prvalue, materialize it
9432 // so that we can safely refer to it multiple times.
9433 if (commonExpr->isPRValue() && (commonExpr->getType()->isRecordType() ||
9434 commonExpr->getType()->isArrayType())) {
9435 ExprResult MatExpr = TemporaryMaterializationConversion(commonExpr);
9436 if (MatExpr.isInvalid())
9437 return ExprError();
9438 commonExpr = MatExpr.get();
9439 }
9440
9441 opaqueValue = new (Context) OpaqueValueExpr(commonExpr->getExprLoc(),
9442 commonExpr->getType(),
9443 commonExpr->getValueKind(),
9444 commonExpr->getObjectKind(),
9445 commonExpr);
9446 LHSExpr = CondExpr = opaqueValue;
9447 }
9448
9449 QualType LHSTy = LHSExpr->getType(), RHSTy = RHSExpr->getType();
9450 ExprValueKind VK = VK_PRValue;
9451 ExprObjectKind OK = OK_Ordinary;
9452 ExprResult Cond = CondExpr, LHS = LHSExpr, RHS = RHSExpr;
9453 QualType result = CheckConditionalOperands(Cond, LHS, RHS,
9454 VK, OK, QuestionLoc);
9455 if (result.isNull() || Cond.isInvalid() || LHS.isInvalid() ||
9456 RHS.isInvalid())
9457 return ExprError();
9458
9459 DiagnoseConditionalPrecedence(*this, QuestionLoc, Cond.get(), LHS.get(),
9460 RHS.get());
9461
9462 CheckBoolLikeConversion(Cond.get(), QuestionLoc);
9463
9464 result = computeConditionalNullability(result, commonExpr, LHSTy, RHSTy,
9465 Context);
9466
9467 if (!commonExpr)
9468 return new (Context)
9469 ConditionalOperator(Cond.get(), QuestionLoc, LHS.get(), ColonLoc,
9470 RHS.get(), result, VK, OK);
9471
9472 return new (Context) BinaryConditionalOperator(
9473 commonExpr, opaqueValue, Cond.get(), LHS.get(), RHS.get(), QuestionLoc,
9474 ColonLoc, result, VK, OK);
9475}
9476
9477// Check if we have a conversion between incompatible cmse function pointer
9478// types, that is, a conversion between a function pointer with the
9479// cmse_nonsecure_call attribute and one without.
9480static bool IsInvalidCmseNSCallConversion(Sema &S, QualType FromType,
9481 QualType ToType) {
9482 if (const auto *ToFn =
9483 dyn_cast<FunctionType>(S.Context.getCanonicalType(ToType))) {
9484 if (const auto *FromFn =
9485 dyn_cast<FunctionType>(S.Context.getCanonicalType(FromType))) {
9486 FunctionType::ExtInfo ToEInfo = ToFn->getExtInfo();
9487 FunctionType::ExtInfo FromEInfo = FromFn->getExtInfo();
9488
9489 return ToEInfo.getCmseNSCall() != FromEInfo.getCmseNSCall();
9490 }
9491 }
9492 return false;
9493}
9494
9495// checkPointerTypesForAssignment - This is a very tricky routine (despite
9496// being closely modeled after the C99 spec:-). The odd characteristic of this
9497// routine is it effectively iqnores the qualifiers on the top level pointee.
9498// This circumvents the usual type rules specified in 6.2.7p1 & 6.7.5.[1-3].
9499// FIXME: add a couple examples in this comment.
9500static Sema::AssignConvertType
9501checkPointerTypesForAssignment(Sema &S, QualType LHSType, QualType RHSType,
9502 SourceLocation Loc) {
9503 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", 9503, __extension__ __PRETTY_FUNCTION__
))
;
9504 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", 9504, __extension__ __PRETTY_FUNCTION__
))
;
9505
9506 // get the "pointed to" type (ignoring qualifiers at the top level)
9507 const Type *lhptee, *rhptee;
9508 Qualifiers lhq, rhq;
9509 std::tie(lhptee, lhq) =
9510 cast<PointerType>(LHSType)->getPointeeType().split().asPair();
9511 std::tie(rhptee, rhq) =
9512 cast<PointerType>(RHSType)->getPointeeType().split().asPair();
9513
9514 Sema::AssignConvertType ConvTy = Sema::Compatible;
9515
9516 // C99 6.5.16.1p1: This following citation is common to constraints
9517 // 3 & 4 (below). ...and the type *pointed to* by the left has all the
9518 // qualifiers of the type *pointed to* by the right;
9519
9520 // As a special case, 'non-__weak A *' -> 'non-__weak const *' is okay.
9521 if (lhq.getObjCLifetime() != rhq.getObjCLifetime() &&
9522 lhq.compatiblyIncludesObjCLifetime(rhq)) {
9523 // Ignore lifetime for further calculation.
9524 lhq.removeObjCLifetime();
9525 rhq.removeObjCLifetime();
9526 }
9527
9528 if (!lhq.compatiblyIncludes(rhq)) {
9529 // Treat address-space mismatches as fatal.
9530 if (!lhq.isAddressSpaceSupersetOf(rhq))
9531 return Sema::IncompatiblePointerDiscardsQualifiers;
9532
9533 // It's okay to add or remove GC or lifetime qualifiers when converting to
9534 // and from void*.
9535 else if (lhq.withoutObjCGCAttr().withoutObjCLifetime()
9536 .compatiblyIncludes(
9537 rhq.withoutObjCGCAttr().withoutObjCLifetime())
9538 && (lhptee->isVoidType() || rhptee->isVoidType()))
9539 ; // keep old
9540
9541 // Treat lifetime mismatches as fatal.
9542 else if (lhq.getObjCLifetime() != rhq.getObjCLifetime())
9543 ConvTy = Sema::IncompatiblePointerDiscardsQualifiers;
9544
9545 // For GCC/MS compatibility, other qualifier mismatches are treated
9546 // as still compatible in C.
9547 else ConvTy = Sema::CompatiblePointerDiscardsQualifiers;
9548 }
9549
9550 // C99 6.5.16.1p1 (constraint 4): If one operand is a pointer to an object or
9551 // incomplete type and the other is a pointer to a qualified or unqualified
9552 // version of void...
9553 if (lhptee->isVoidType()) {
9554 if (rhptee->isIncompleteOrObjectType())
9555 return ConvTy;
9556
9557 // As an extension, we allow cast to/from void* to function pointer.
9558 assert(rhptee->isFunctionType())(static_cast <bool> (rhptee->isFunctionType()) ? void
(0) : __assert_fail ("rhptee->isFunctionType()", "clang/lib/Sema/SemaExpr.cpp"
, 9558, __extension__ __PRETTY_FUNCTION__))
;
9559 return Sema::FunctionVoidPointer;
9560 }
9561
9562 if (rhptee->isVoidType()) {
9563 if (lhptee->isIncompleteOrObjectType())
9564 return ConvTy;
9565
9566 // As an extension, we allow cast to/from void* to function pointer.
9567 assert(lhptee->isFunctionType())(static_cast <bool> (lhptee->isFunctionType()) ? void
(0) : __assert_fail ("lhptee->isFunctionType()", "clang/lib/Sema/SemaExpr.cpp"
, 9567, __extension__ __PRETTY_FUNCTION__))
;
9568 return Sema::FunctionVoidPointer;
9569 }
9570
9571 if (!S.Diags.isIgnored(
9572 diag::warn_typecheck_convert_incompatible_function_pointer_strict,
9573 Loc) &&
9574 RHSType->isFunctionPointerType() && LHSType->isFunctionPointerType() &&
9575 !S.IsFunctionConversion(RHSType, LHSType, RHSType))
9576 return Sema::IncompatibleFunctionPointerStrict;
9577
9578 // C99 6.5.16.1p1 (constraint 3): both operands are pointers to qualified or
9579 // unqualified versions of compatible types, ...
9580 QualType ltrans = QualType(lhptee, 0), rtrans = QualType(rhptee, 0);
9581 if (!S.Context.typesAreCompatible(ltrans, rtrans)) {
9582 // Check if the pointee types are compatible ignoring the sign.
9583 // We explicitly check for char so that we catch "char" vs
9584 // "unsigned char" on systems where "char" is unsigned.
9585 if (lhptee->isCharType())
9586 ltrans = S.Context.UnsignedCharTy;
9587 else if (lhptee->hasSignedIntegerRepresentation())
9588 ltrans = S.Context.getCorrespondingUnsignedType(ltrans);
9589
9590 if (rhptee->isCharType())
9591 rtrans = S.Context.UnsignedCharTy;
9592 else if (rhptee->hasSignedIntegerRepresentation())
9593 rtrans = S.Context.getCorrespondingUnsignedType(rtrans);
9594
9595 if (ltrans == rtrans) {
9596 // Types are compatible ignoring the sign. Qualifier incompatibility
9597 // takes priority over sign incompatibility because the sign
9598 // warning can be disabled.
9599 if (ConvTy != Sema::Compatible)
9600 return ConvTy;
9601
9602 return Sema::IncompatiblePointerSign;
9603 }
9604
9605 // If we are a multi-level pointer, it's possible that our issue is simply
9606 // one of qualification - e.g. char ** -> const char ** is not allowed. If
9607 // the eventual target type is the same and the pointers have the same
9608 // level of indirection, this must be the issue.
9609 if (isa<PointerType>(lhptee) && isa<PointerType>(rhptee)) {
9610 do {
9611 std::tie(lhptee, lhq) =
9612 cast<PointerType>(lhptee)->getPointeeType().split().asPair();
9613 std::tie(rhptee, rhq) =
9614 cast<PointerType>(rhptee)->getPointeeType().split().asPair();
9615
9616 // Inconsistent address spaces at this point is invalid, even if the
9617 // address spaces would be compatible.
9618 // FIXME: This doesn't catch address space mismatches for pointers of
9619 // different nesting levels, like:
9620 // __local int *** a;
9621 // int ** b = a;
9622 // It's not clear how to actually determine when such pointers are
9623 // invalidly incompatible.
9624 if (lhq.getAddressSpace() != rhq.getAddressSpace())
9625 return Sema::IncompatibleNestedPointerAddressSpaceMismatch;
9626
9627 } while (isa<PointerType>(lhptee) && isa<PointerType>(rhptee));
9628
9629 if (lhptee == rhptee)
9630 return Sema::IncompatibleNestedPointerQualifiers;
9631 }
9632
9633 // General pointer incompatibility takes priority over qualifiers.
9634 if (RHSType->isFunctionPointerType() && LHSType->isFunctionPointerType())
9635 return Sema::IncompatibleFunctionPointer;
9636 return Sema::IncompatiblePointer;
9637 }
9638 if (!S.getLangOpts().CPlusPlus &&
9639 S.IsFunctionConversion(ltrans, rtrans, ltrans))
9640 return Sema::IncompatibleFunctionPointer;
9641 if (IsInvalidCmseNSCallConversion(S, ltrans, rtrans))
9642 return Sema::IncompatibleFunctionPointer;
9643 return ConvTy;
9644}
9645
9646/// checkBlockPointerTypesForAssignment - This routine determines whether two
9647/// block pointer types are compatible or whether a block and normal pointer
9648/// are compatible. It is more restrict than comparing two function pointer
9649// types.
9650static Sema::AssignConvertType
9651checkBlockPointerTypesForAssignment(Sema &S, QualType LHSType,
9652 QualType RHSType) {
9653 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", 9653, __extension__ __PRETTY_FUNCTION__
))
;
9654 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", 9654, __extension__ __PRETTY_FUNCTION__
))
;
9655
9656 QualType lhptee, rhptee;
9657
9658 // get the "pointed to" type (ignoring qualifiers at the top level)
9659 lhptee = cast<BlockPointerType>(LHSType)->getPointeeType();
9660 rhptee = cast<BlockPointerType>(RHSType)->getPointeeType();
9661
9662 // In C++, the types have to match exactly.
9663 if (S.getLangOpts().CPlusPlus)
9664 return Sema::IncompatibleBlockPointer;
9665
9666 Sema::AssignConvertType ConvTy = Sema::Compatible;
9667
9668 // For blocks we enforce that qualifiers are identical.
9669 Qualifiers LQuals = lhptee.getLocalQualifiers();
9670 Qualifiers RQuals = rhptee.getLocalQualifiers();
9671 if (S.getLangOpts().OpenCL) {
9672 LQuals.removeAddressSpace();
9673 RQuals.removeAddressSpace();
9674 }
9675 if (LQuals != RQuals)
9676 ConvTy = Sema::CompatiblePointerDiscardsQualifiers;
9677
9678 // FIXME: OpenCL doesn't define the exact compile time semantics for a block
9679 // assignment.
9680 // The current behavior is similar to C++ lambdas. A block might be
9681 // assigned to a variable iff its return type and parameters are compatible
9682 // (C99 6.2.7) with the corresponding return type and parameters of the LHS of
9683 // an assignment. Presumably it should behave in way that a function pointer
9684 // assignment does in C, so for each parameter and return type:
9685 // * CVR and address space of LHS should be a superset of CVR and address
9686 // space of RHS.
9687 // * unqualified types should be compatible.
9688 if (S.getLangOpts().OpenCL) {
9689 if (!S.Context.typesAreBlockPointerCompatible(
9690 S.Context.getQualifiedType(LHSType.getUnqualifiedType(), LQuals),
9691 S.Context.getQualifiedType(RHSType.getUnqualifiedType(), RQuals)))
9692 return Sema::IncompatibleBlockPointer;
9693 } else if (!S.Context.typesAreBlockPointerCompatible(LHSType, RHSType))
9694 return Sema::IncompatibleBlockPointer;
9695
9696 return ConvTy;
9697}
9698
9699/// checkObjCPointerTypesForAssignment - Compares two objective-c pointer types
9700/// for assignment compatibility.
9701static Sema::AssignConvertType
9702checkObjCPointerTypesForAssignment(Sema &S, QualType LHSType,
9703 QualType RHSType) {
9704 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", 9704, __extension__ __PRETTY_FUNCTION__
))
;
9705 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", 9705, __extension__ __PRETTY_FUNCTION__
))
;
9706
9707 if (LHSType->isObjCBuiltinType()) {
9708 // Class is not compatible with ObjC object pointers.
9709 if (LHSType->isObjCClassType() && !RHSType->isObjCBuiltinType() &&
9710 !RHSType->isObjCQualifiedClassType())
9711 return Sema::IncompatiblePointer;
9712 return Sema::Compatible;
9713 }
9714 if (RHSType->isObjCBuiltinType()) {
9715 if (RHSType->isObjCClassType() && !LHSType->isObjCBuiltinType() &&
9716 !LHSType->isObjCQualifiedClassType())
9717 return Sema::IncompatiblePointer;
9718 return Sema::Compatible;
9719 }
9720 QualType lhptee = LHSType->castAs<ObjCObjectPointerType>()->getPointeeType();
9721 QualType rhptee = RHSType->castAs<ObjCObjectPointerType>()->getPointeeType();
9722
9723 if (!lhptee.isAtLeastAsQualifiedAs(rhptee) &&
9724 // make an exception for id<P>
9725 !LHSType->isObjCQualifiedIdType())
9726 return Sema::CompatiblePointerDiscardsQualifiers;
9727
9728 if (S.Context.typesAreCompatible(LHSType, RHSType))
9729 return Sema::Compatible;
9730 if (LHSType->isObjCQualifiedIdType() || RHSType->isObjCQualifiedIdType())
9731 return Sema::IncompatibleObjCQualifiedId;
9732 return Sema::IncompatiblePointer;
9733}
9734
9735Sema::AssignConvertType
9736Sema::CheckAssignmentConstraints(SourceLocation Loc,
9737 QualType LHSType, QualType RHSType) {
9738 // Fake up an opaque expression. We don't actually care about what
9739 // cast operations are required, so if CheckAssignmentConstraints
9740 // adds casts to this they'll be wasted, but fortunately that doesn't
9741 // usually happen on valid code.
9742 OpaqueValueExpr RHSExpr(Loc, RHSType, VK_PRValue);
9743 ExprResult RHSPtr = &RHSExpr;
9744 CastKind K;
9745
9746 return CheckAssignmentConstraints(LHSType, RHSPtr, K, /*ConvertRHS=*/false);
9747}
9748
9749/// This helper function returns true if QT is a vector type that has element
9750/// type ElementType.
9751static bool isVector(QualType QT, QualType ElementType) {
9752 if (const VectorType *VT = QT->getAs<VectorType>())
9753 return VT->getElementType().getCanonicalType() == ElementType;
9754 return false;
9755}
9756
9757/// CheckAssignmentConstraints (C99 6.5.16) - This routine currently
9758/// has code to accommodate several GCC extensions when type checking
9759/// pointers. Here are some objectionable examples that GCC considers warnings:
9760///
9761/// int a, *pint;
9762/// short *pshort;
9763/// struct foo *pfoo;
9764///
9765/// pint = pshort; // warning: assignment from incompatible pointer type
9766/// a = pint; // warning: assignment makes integer from pointer without a cast
9767/// pint = a; // warning: assignment makes pointer from integer without a cast
9768/// pint = pfoo; // warning: assignment from incompatible pointer type
9769///
9770/// As a result, the code for dealing with pointers is more complex than the
9771/// C99 spec dictates.
9772///
9773/// Sets 'Kind' for any result kind except Incompatible.
9774Sema::AssignConvertType
9775Sema::CheckAssignmentConstraints(QualType LHSType, ExprResult &RHS,
9776 CastKind &Kind, bool ConvertRHS) {
9777 QualType RHSType = RHS.get()->getType();
9778 QualType OrigLHSType = LHSType;
9779
9780 // Get canonical types. We're not formatting these types, just comparing
9781 // them.
9782 LHSType = Context.getCanonicalType(LHSType).getUnqualifiedType();
9783 RHSType = Context.getCanonicalType(RHSType).getUnqualifiedType();
9784
9785 // Common case: no conversion required.
9786 if (LHSType == RHSType) {
1
Taking false branch
9787 Kind = CK_NoOp;
9788 return Compatible;
9789 }
9790
9791 // If the LHS has an __auto_type, there are no additional type constraints
9792 // to be worried about.
9793 if (const auto *AT
15.1
'AT' is null
15.1
'AT' is null
= dyn_cast<AutoType>(LHSType)) {
2
Calling 'dyn_cast<clang::AutoType, clang::QualType>'
15
Returning from 'dyn_cast<clang::AutoType, clang::QualType>'
16
Taking false branch
9794 if (AT->isGNUAutoType()) {
9795 Kind = CK_NoOp;
9796 return Compatible;
9797 }
9798 }
9799
9800 // If we have an atomic type, try a non-atomic assignment, then just add an
9801 // atomic qualification step.
9802 if (const AtomicType *AtomicTy
30.1
'AtomicTy' is null
30.1
'AtomicTy' is null
= dyn_cast<AtomicType>(LHSType)) {
17
Calling 'dyn_cast<clang::AtomicType, clang::QualType>'
30
Returning from 'dyn_cast<clang::AtomicType, clang::QualType>'
31
Taking false branch
9803 Sema::AssignConvertType result =
9804 CheckAssignmentConstraints(AtomicTy->getValueType(), RHS, Kind);
9805 if (result != Compatible)
9806 return result;
9807 if (Kind != CK_NoOp && ConvertRHS)
9808 RHS = ImpCastExprToType(RHS.get(), AtomicTy->getValueType(), Kind);
9809 Kind = CK_NonAtomicToAtomic;
9810 return Compatible;
9811 }
9812
9813 // If the left-hand side is a reference type, then we are in a
9814 // (rare!) case where we've allowed the use of references in C,
9815 // e.g., as a parameter type in a built-in function. In this case,
9816 // just make sure that the type referenced is compatible with the
9817 // right-hand side type. The caller is responsible for adjusting
9818 // LHSType so that the resulting expression does not have reference
9819 // type.
9820 if (const ReferenceType *LHSTypeRef
32.1
'LHSTypeRef' is null
32.1
'LHSTypeRef' is null
= LHSType->getAs<ReferenceType>()) {
32
Assuming the object is not a 'const class clang::ReferenceType *'
33
Taking false branch
9821 if (Context.typesAreCompatible(LHSTypeRef->getPointeeType(), RHSType)) {
9822 Kind = CK_LValueBitCast;
9823 return Compatible;
9824 }
9825 return Incompatible;
9826 }
9827
9828 // Allow scalar to ExtVector assignments, and assignments of an ExtVector type
9829 // to the same ExtVector type.
9830 if (LHSType->isExtVectorType()) {
9831 if (RHSType->isExtVectorType())
9832 return Incompatible;
9833 if (RHSType->isArithmeticType()) {
9834 // CK_VectorSplat does T -> vector T, so first cast to the element type.
9835 if (ConvertRHS)
9836 RHS = prepareVectorSplat(LHSType, RHS.get());
9837 Kind = CK_VectorSplat;
9838 return Compatible;
9839 }
9840 }
9841
9842 // Conversions to or from vector type.
9843 if (LHSType->isVectorType() || RHSType->isVectorType()) {
34
Taking false branch
9844 if (LHSType->isVectorType() && RHSType->isVectorType()) {
9845 // Allow assignments of an AltiVec vector type to an equivalent GCC
9846 // vector type and vice versa
9847 if (Context.areCompatibleVectorTypes(LHSType, RHSType)) {
9848 Kind = CK_BitCast;
9849 return Compatible;
9850 }
9851
9852 // If we are allowing lax vector conversions, and LHS and RHS are both
9853 // vectors, the total size only needs to be the same. This is a bitcast;
9854 // no bits are changed but the result type is different.
9855 if (isLaxVectorConversion(RHSType, LHSType)) {
9856 // The default for lax vector conversions with Altivec vectors will
9857 // change, so if we are converting between vector types where
9858 // at least one is an Altivec vector, emit a warning.
9859 if (anyAltivecTypes(RHSType, LHSType) &&
9860 !Context.areCompatibleVectorTypes(RHSType, LHSType))
9861 Diag(RHS.get()->getExprLoc(), diag::warn_deprecated_lax_vec_conv_all)
9862 << RHSType << LHSType;
9863 Kind = CK_BitCast;
9864 return IncompatibleVectors;
9865 }
9866 }
9867
9868 // When the RHS comes from another lax conversion (e.g. binops between
9869 // scalars and vectors) the result is canonicalized as a vector. When the
9870 // LHS is also a vector, the lax is allowed by the condition above. Handle
9871 // the case where LHS is a scalar.
9872 if (LHSType->isScalarType()) {
9873 const VectorType *VecType = RHSType->getAs<VectorType>();
9874 if (VecType && VecType->getNumElements() == 1 &&
9875 isLaxVectorConversion(RHSType, LHSType)) {
9876 if (VecType->getVectorKind() == VectorType::AltiVecVector ||
9877 VecType->getVectorKind() == VectorType::AltiVecBool ||
9878 VecType->getVectorKind() == VectorType::AltiVecPixel)
9879 Diag(RHS.get()->getExprLoc(), diag::warn_deprecated_lax_vec_conv_all)
9880 << RHSType << LHSType;
9881 ExprResult *VecExpr = &RHS;
9882 *VecExpr = ImpCastExprToType(VecExpr->get(), LHSType, CK_BitCast);
9883 Kind = CK_BitCast;
9884 return Compatible;
9885 }
9886 }
9887
9888 // Allow assignments between fixed-length and sizeless SVE vectors.
9889 if ((LHSType->isSVESizelessBuiltinType() && RHSType->isVectorType()) ||
9890 (LHSType->isVectorType() && RHSType->isSVESizelessBuiltinType()))
9891 if (Context.areCompatibleSveTypes(LHSType, RHSType) ||
9892 Context.areLaxCompatibleSveTypes(LHSType, RHSType)) {
9893 Kind = CK_BitCast;
9894 return Compatible;
9895 }
9896
9897 return Incompatible;
9898 }
9899
9900 // Diagnose attempts to convert between __ibm128, __float128 and long double
9901 // where such conversions currently can't be handled.
9902 if (unsupportedTypeConversion(*this, LHSType, RHSType))
9903 return Incompatible;
9904
9905 // Disallow assigning a _Complex to a real type in C++ mode since it simply
9906 // discards the imaginary part.
9907 if (getLangOpts().CPlusPlus && RHSType->getAs<ComplexType>() &&
35
Assuming field 'CPlusPlus' is 0
9908 !LHSType->getAs<ComplexType>())
9909 return Incompatible;
9910
9911 // Arithmetic conversions.
9912 if (LHSType->isArithmeticType() && RHSType->isArithmeticType() &&
36
Assuming the condition is false
9913 !(getLangOpts().CPlusPlus && LHSType->isEnumeralType())) {
9914 if (ConvertRHS)
9915 Kind = PrepareScalarCast(RHS, LHSType);
9916 return Compatible;
9917 }
9918
9919 // Conversions to normal pointers.
9920 if (const PointerType *LHSPointer
62.1
'LHSPointer' is non-null
62.1
'LHSPointer' is non-null
= dyn_cast<PointerType>(LHSType)) {
37
Calling 'dyn_cast<clang::PointerType, clang::QualType>'
62
Returning from 'dyn_cast<clang::PointerType, clang::QualType>'
63
Taking true branch
9921 // U* -> T*
9922 if (isa<PointerType>(RHSType)) {
64
Assuming 'RHSType' is not a 'PointerType'
65
Taking false branch
9923 LangAS AddrSpaceL = LHSPointer->getPointeeType().getAddressSpace();
9924 LangAS AddrSpaceR = RHSType->getPointeeType().getAddressSpace();
9925 if (AddrSpaceL != AddrSpaceR)
9926 Kind = CK_AddressSpaceConversion;
9927 else if (Context.hasCvrSimilarType(RHSType, LHSType))
9928 Kind = CK_NoOp;
9929 else
9930 Kind = CK_BitCast;
9931 return checkPointerTypesForAssignment(*this, LHSType, RHSType,
9932 RHS.get()->getBeginLoc());
9933 }
9934
9935 // int -> T*
9936 if (RHSType->isIntegerType()) {
66
Taking false branch
9937 Kind = CK_IntegralToPointer; // FIXME: null?
9938 return IntToPointer;
9939 }
9940
9941 // C pointers are not compatible with ObjC object pointers,
9942 // with two exceptions:
9943 if (isa<ObjCObjectPointerType>(RHSType)) {
67
Assuming 'RHSType' is not a 'ObjCObjectPointerType'
68
Taking false branch
9944 // - conversions to void*
9945 if (LHSPointer->getPointeeType()->isVoidType()) {
9946 Kind = CK_BitCast;
9947 return Compatible;
9948 }
9949
9950 // - conversions from 'Class' to the redefinition type
9951 if (RHSType->isObjCClassType() &&
9952 Context.hasSameType(LHSType,
9953 Context.getObjCClassRedefinitionType())) {
9954 Kind = CK_BitCast;
9955 return Compatible;
9956 }
9957
9958 Kind = CK_BitCast;
9959 return IncompatiblePointer;
9960 }
9961
9962 // U^ -> void*
9963 if (RHSType->getAs<BlockPointerType>()) {
69
Assuming the object is a 'const class clang::BlockPointerType *'
70
Assuming the condition is true
71
Taking true branch
9964 if (LHSPointer->getPointeeType()->isVoidType()) {
72
Taking true branch
9965 LangAS AddrSpaceL = LHSPointer->getPointeeType().getAddressSpace();
9966 LangAS AddrSpaceR = RHSType->getAs<BlockPointerType>()
73
Assuming the object is not a 'const class clang::BlockPointerType *'
74
Called C++ object pointer is null
9967 ->getPointeeType()
9968 .getAddressSpace();
9969 Kind =
9970 AddrSpaceL != AddrSpaceR ? CK_AddressSpaceConversion : CK_BitCast;
9971 return Compatible;
9972 }
9973 }
9974
9975 return Incompatible;
9976 }
9977
9978 // Conversions to block pointers.
9979 if (isa<BlockPointerType>(LHSType)) {
9980 // U^ -> T^
9981 if (RHSType->isBlockPointerType()) {
9982 LangAS AddrSpaceL = LHSType->getAs<BlockPointerType>()
9983 ->getPointeeType()
9984 .getAddressSpace();
9985 LangAS AddrSpaceR = RHSType->getAs<BlockPointerType>()
9986 ->getPointeeType()
9987 .getAddressSpace();
9988 Kind = AddrSpaceL != AddrSpaceR ? CK_AddressSpaceConversion : CK_BitCast;
9989 return checkBlockPointerTypesForAssignment(*this, LHSType, RHSType);
9990 }
9991
9992 // int or null -> T^
9993 if (RHSType->isIntegerType()) {
9994 Kind = CK_IntegralToPointer; // FIXME: null
9995 return IntToBlockPointer;
9996 }
9997
9998 // id -> T^
9999 if (getLangOpts().ObjC && RHSType->isObjCIdType()) {
10000 Kind = CK_AnyPointerToBlockPointerCast;
10001 return Compatible;
10002 }
10003
10004 // void* -> T^
10005 if (const PointerType *RHSPT = RHSType->getAs<PointerType>())
10006 if (RHSPT->getPointeeType()->isVoidType()) {
10007 Kind = CK_AnyPointerToBlockPointerCast;
10008 return Compatible;
10009 }
10010
10011 return Incompatible;
10012 }
10013
10014 // Conversions to Objective-C pointers.
10015 if (isa<ObjCObjectPointerType>(LHSType)) {
10016 // A* -> B*
10017 if (RHSType->isObjCObjectPointerType()) {
10018 Kind = CK_BitCast;
10019 Sema::AssignConvertType result =
10020 checkObjCPointerTypesForAssignment(*this, LHSType, RHSType);
10021 if (getLangOpts().allowsNonTrivialObjCLifetimeQualifiers() &&
10022 result == Compatible &&
10023 !CheckObjCARCUnavailableWeakConversion(OrigLHSType, RHSType))
10024 result = IncompatibleObjCWeakRef;
10025 return result;
10026 }
10027
10028 // int or null -> A*
10029 if (RHSType->isIntegerType()) {
10030 Kind = CK_IntegralToPointer; // FIXME: null
10031 return IntToPointer;
10032 }
10033
10034 // In general, C pointers are not compatible with ObjC object pointers,
10035 // with two exceptions:
10036 if (isa<PointerType>(RHSType)) {
10037 Kind = CK_CPointerToObjCPointerCast;
10038
10039 // - conversions from 'void*'
10040 if (RHSType->isVoidPointerType()) {
10041 return Compatible;
10042 }
10043
10044 // - conversions to 'Class' from its redefinition type
10045 if (LHSType->isObjCClassType() &&
10046 Context.hasSameType(RHSType,
10047 Context.getObjCClassRedefinitionType())) {
10048 return Compatible;
10049 }
10050
10051 return IncompatiblePointer;
10052 }
10053
10054 // Only under strict condition T^ is compatible with an Objective-C pointer.
10055 if (RHSType->isBlockPointerType() &&
10056 LHSType->isBlockCompatibleObjCPointerType(Context)) {
10057 if (ConvertRHS)
10058 maybeExtendBlockObject(RHS);
10059 Kind = CK_BlockPointerToObjCPointerCast;
10060 return Compatible;
10061 }
10062
10063 return Incompatible;
10064 }
10065
10066 // Conversions from pointers that are not covered by the above.
10067 if (isa<PointerType>(RHSType)) {
10068 // T* -> _Bool
10069 if (LHSType == Context.BoolTy) {
10070 Kind = CK_PointerToBoolean;
10071 return Compatible;
10072 }
10073
10074 // T* -> int
10075 if (LHSType->isIntegerType()) {
10076 Kind = CK_PointerToIntegral;
10077 return PointerToInt;
10078 }
10079
10080 return Incompatible;
10081 }
10082
10083 // Conversions from Objective-C pointers that are not covered by the above.
10084 if (isa<ObjCObjectPointerType>(RHSType)) {
10085 // T* -> _Bool
10086 if (LHSType == Context.BoolTy) {
10087 Kind = CK_PointerToBoolean;
10088 return Compatible;
10089 }
10090
10091 // T* -> int
10092 if (LHSType->isIntegerType()) {
10093 Kind = CK_PointerToIntegral;
10094 return PointerToInt;
10095 }
10096
10097 return Incompatible;
10098 }
10099
10100 // struct A -> struct B
10101 if (isa<TagType>(LHSType) && isa<TagType>(RHSType)) {
10102 if (Context.typesAreCompatible(LHSType, RHSType)) {
10103 Kind = CK_NoOp;
10104 return Compatible;
10105 }
10106 }
10107
10108 if (LHSType->isSamplerT() && RHSType->isIntegerType()) {
10109 Kind = CK_IntToOCLSampler;
10110 return Compatible;
10111 }
10112
10113 return Incompatible;
10114}
10115
10116/// Constructs a transparent union from an expression that is
10117/// used to initialize the transparent union.
10118static void ConstructTransparentUnion(Sema &S, ASTContext &C,
10119 ExprResult &EResult, QualType UnionType,
10120 FieldDecl *Field) {
10121 // Build an initializer list that designates the appropriate member
10122 // of the transparent union.
10123 Expr *E = EResult.get();
10124 InitListExpr *Initializer = new (C) InitListExpr(C, SourceLocation(),
10125 E, SourceLocation());
10126 Initializer->setType(UnionType);
10127 Initializer->setInitializedFieldInUnion(Field);
10128
10129 // Build a compound literal constructing a value of the transparent
10130 // union type from this initializer list.
10131 TypeSourceInfo *unionTInfo = C.getTrivialTypeSourceInfo(UnionType);
10132 EResult = new (C) CompoundLiteralExpr(SourceLocation(), unionTInfo, UnionType,
10133 VK_PRValue, Initializer, false);
10134}
10135
10136Sema::AssignConvertType
10137Sema::CheckTransparentUnionArgumentConstraints(QualType ArgType,
10138 ExprResult &RHS) {
10139 QualType RHSType = RHS.get()->getType();
10140
10141 // If the ArgType is a Union type, we want to handle a potential
10142 // transparent_union GCC extension.
10143 const RecordType *UT = ArgType->getAsUnionType();
10144 if (!UT || !UT->getDecl()->hasAttr<TransparentUnionAttr>())
10145 return Incompatible;
10146
10147 // The field to initialize within the transparent union.
10148 RecordDecl *UD = UT->getDecl();
10149 FieldDecl *InitField = nullptr;
10150 // It's compatible if the expression matches any of the fields.
10151 for (auto *it : UD->fields()) {
10152 if (it->getType()->isPointerType()) {
10153 // If the transparent union contains a pointer type, we allow:
10154 // 1) void pointer
10155 // 2) null pointer constant
10156 if (RHSType->isPointerType())
10157 if (RHSType->castAs<PointerType>()->getPointeeType()->isVoidType()) {
10158 RHS = ImpCastExprToType(RHS.get(), it->getType(), CK_BitCast);
10159 InitField = it;
10160 break;
10161 }
10162
10163 if (RHS.get()->isNullPointerConstant(Context,
10164 Expr::NPC_ValueDependentIsNull)) {
10165 RHS = ImpCastExprToType(RHS.get(), it->getType(),
10166 CK_NullToPointer);
10167 InitField = it;
10168 break;
10169 }
10170 }
10171
10172 CastKind Kind;
10173 if (CheckAssignmentConstraints(it->getType(), RHS, Kind)
10174 == Compatible) {
10175 RHS = ImpCastExprToType(RHS.get(), it->getType(), Kind);
10176 InitField = it;
10177 break;
10178 }
10179 }
10180
10181 if (!InitField)
10182 return Incompatible;
10183
10184 ConstructTransparentUnion(*this, Context, RHS, ArgType, InitField);
10185 return Compatible;
10186}
10187
10188Sema::AssignConvertType
10189Sema::CheckSingleAssignmentConstraints(QualType LHSType, ExprResult &CallerRHS,
10190 bool Diagnose,
10191 bool DiagnoseCFAudited,
10192 bool ConvertRHS) {
10193 // We need to be able to tell the caller whether we diagnosed a problem, if
10194 // they ask us to issue diagnostics.
10195 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", 10195, __extension__ __PRETTY_FUNCTION__
))
;
10196
10197 // If ConvertRHS is false, we want to leave the caller's RHS untouched. Sadly,
10198 // we can't avoid *all* modifications at the moment, so we need some somewhere
10199 // to put the updated value.
10200 ExprResult LocalRHS = CallerRHS;
10201 ExprResult &RHS = ConvertRHS ? CallerRHS : LocalRHS;
10202
10203 if (const auto *LHSPtrType = LHSType->getAs<PointerType>()) {
10204 if (const auto *RHSPtrType = RHS.get()->getType()->getAs<PointerType>()) {
10205 if (RHSPtrType->getPointeeType()->hasAttr(attr::NoDeref) &&
10206 !LHSPtrType->getPointeeType()->hasAttr(attr::NoDeref)) {
10207 Diag(RHS.get()->getExprLoc(),
10208 diag::warn_noderef_to_dereferenceable_pointer)
10209 << RHS.get()->getSourceRange();
10210 }
10211 }
10212 }
10213
10214 if (getLangOpts().CPlusPlus) {
10215 if (!LHSType->isRecordType() && !LHSType->isAtomicType()) {
10216 // C++ 5.17p3: If the left operand is not of class type, the
10217 // expression is implicitly converted (C++ 4) to the
10218 // cv-unqualified type of the left operand.
10219 QualType RHSType = RHS.get()->getType();
10220 if (Diagnose) {
10221 RHS = PerformImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(),
10222 AA_Assigning);
10223 } else {
10224 ImplicitConversionSequence ICS =
10225 TryImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(),
10226 /*SuppressUserConversions=*/false,
10227 AllowedExplicit::None,
10228 /*InOverloadResolution=*/false,
10229 /*CStyle=*/false,
10230 /*AllowObjCWritebackConversion=*/false);
10231 if (ICS.isFailure())
10232 return Incompatible;
10233 RHS = PerformImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(),
10234 ICS, AA_Assigning);
10235 }
10236 if (RHS.isInvalid())
10237 return Incompatible;
10238 Sema::AssignConvertType result = Compatible;
10239 if (getLangOpts().allowsNonTrivialObjCLifetimeQualifiers() &&
10240 !CheckObjCARCUnavailableWeakConversion(LHSType, RHSType))
10241 result = IncompatibleObjCWeakRef;
10242 return result;
10243 }
10244
10245 // FIXME: Currently, we fall through and treat C++ classes like C
10246 // structures.
10247 // FIXME: We also fall through for atomics; not sure what should
10248 // happen there, though.
10249 } else if (RHS.get()->getType() == Context.OverloadTy) {
10250 // As a set of extensions to C, we support overloading on functions. These
10251 // functions need to be resolved here.
10252 DeclAccessPair DAP;
10253 if (FunctionDecl *FD = ResolveAddressOfOverloadedFunction(
10254 RHS.get(), LHSType, /*Complain=*/false, DAP))
10255 RHS = FixOverloadedFunctionReference(RHS.get(), DAP, FD);
10256 else
10257 return Incompatible;
10258 }
10259
10260 // This check seems unnatural, however it is necessary to ensure the proper
10261 // conversion of functions/arrays. If the conversion were done for all
10262 // DeclExpr's (created by ActOnIdExpression), it would mess up the unary
10263 // expressions that suppress this implicit conversion (&, sizeof). This needs
10264 // to happen before we check for null pointer conversions because C does not
10265 // undergo the same implicit conversions as C++ does above (by the calls to
10266 // TryImplicitConversion() and PerformImplicitConversion()) which insert the
10267 // lvalue to rvalue cast before checking for null pointer constraints. This
10268 // addresses code like: nullptr_t val; int *ptr; ptr = val;
10269 //
10270 // Suppress this for references: C++ 8.5.3p5.
10271 if (!LHSType->isReferenceType()) {
10272 // FIXME: We potentially allocate here even if ConvertRHS is false.
10273 RHS = DefaultFunctionArrayLvalueConversion(RHS.get(), Diagnose);
10274 if (RHS.isInvalid())
10275 return Incompatible;
10276 }
10277
10278 // C99 6.5.16.1p1: the left operand is a pointer and the right is
10279 // a null pointer constant.
10280 if ((LHSType->isPointerType() || LHSType->isObjCObjectPointerType() ||
10281 LHSType->isBlockPointerType()) &&
10282 RHS.get()->isNullPointerConstant(Context,
10283 Expr::NPC_ValueDependentIsNull)) {
10284 if (Diagnose || ConvertRHS) {
10285 CastKind Kind;
10286 CXXCastPath Path;
10287 CheckPointerConversion(RHS.get(), LHSType, Kind, Path,
10288 /*IgnoreBaseAccess=*/false, Diagnose);
10289 if (ConvertRHS)
10290 RHS = ImpCastExprToType(RHS.get(), LHSType, Kind, VK_PRValue, &Path);
10291 }
10292 return Compatible;
10293 }
10294
10295 // OpenCL queue_t type assignment.
10296 if (LHSType->isQueueT() && RHS.get()->isNullPointerConstant(
10297 Context, Expr::NPC_ValueDependentIsNull)) {
10298 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer);
10299 return Compatible;
10300 }
10301
10302 CastKind Kind;
10303 Sema::AssignConvertType result =
10304 CheckAssignmentConstraints(LHSType, RHS, Kind, ConvertRHS);
10305
10306 // C99 6.5.16.1p2: The value of the right operand is converted to the
10307 // type of the assignment expression.
10308 // CheckAssignmentConstraints allows the left-hand side to be a reference,
10309 // so that we can use references in built-in functions even in C.
10310 // The getNonReferenceType() call makes sure that the resulting expression
10311 // does not have reference type.
10312 if (result != Incompatible && RHS.get()->getType() != LHSType) {
10313 QualType Ty = LHSType.getNonLValueExprType(Context);
10314 Expr *E = RHS.get();
10315
10316 // Check for various Objective-C errors. If we are not reporting
10317 // diagnostics and just checking for errors, e.g., during overload
10318 // resolution, return Incompatible to indicate the failure.
10319 if (getLangOpts().allowsNonTrivialObjCLifetimeQualifiers() &&
10320 CheckObjCConversion(SourceRange(), Ty, E, CCK_ImplicitConversion,
10321 Diagnose, DiagnoseCFAudited) != ACR_okay) {
10322 if (!Diagnose)
10323 return Incompatible;
10324 }
10325 if (getLangOpts().ObjC &&
10326 (CheckObjCBridgeRelatedConversions(E->getBeginLoc(), LHSType,
10327 E->getType(), E, Diagnose) ||
10328 CheckConversionToObjCLiteral(LHSType, E, Diagnose))) {
10329 if (!Diagnose)
10330 return Incompatible;
10331 // Replace the expression with a corrected version and continue so we
10332 // can find further errors.
10333 RHS = E;
10334 return Compatible;
10335 }
10336
10337 if (ConvertRHS)
10338 RHS = ImpCastExprToType(E, Ty, Kind);
10339 }
10340
10341 return result;
10342}
10343
10344namespace {
10345/// The original operand to an operator, prior to the application of the usual
10346/// arithmetic conversions and converting the arguments of a builtin operator
10347/// candidate.
10348struct OriginalOperand {
10349 explicit OriginalOperand(Expr *Op) : Orig(Op), Conversion(nullptr) {
10350 if (auto *MTE = dyn_cast<MaterializeTemporaryExpr>(Op))
10351 Op = MTE->getSubExpr();
10352 if (auto *BTE = dyn_cast<CXXBindTemporaryExpr>(Op))
10353 Op = BTE->getSubExpr();
10354 if (auto *ICE = dyn_cast<ImplicitCastExpr>(Op)) {
10355 Orig = ICE->getSubExprAsWritten();
10356 Conversion = ICE->getConversionFunction();
10357 }
10358 }
10359
10360 QualType getType() const { return Orig->getType(); }
10361
10362 Expr *Orig;
10363 NamedDecl *Conversion;
10364};
10365}
10366
10367QualType Sema::InvalidOperands(SourceLocation Loc, ExprResult &LHS,
10368 ExprResult &RHS) {
10369 OriginalOperand OrigLHS(LHS.get()), OrigRHS(RHS.get());
10370
10371 Diag(Loc, diag::err_typecheck_invalid_operands)
10372 << OrigLHS.getType() << OrigRHS.getType()
10373 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
10374
10375 // If a user-defined conversion was applied to either of the operands prior
10376 // to applying the built-in operator rules, tell the user about it.
10377 if (OrigLHS.Conversion) {
10378 Diag(OrigLHS.Conversion->getLocation(),
10379 diag::note_typecheck_invalid_operands_converted)
10380 << 0 << LHS.get()->getType();
10381 }
10382 if (OrigRHS.Conversion) {
10383 Diag(OrigRHS.Conversion->getLocation(),
10384 diag::note_typecheck_invalid_operands_converted)
10385 << 1 << RHS.get()->getType();
10386 }
10387
10388 return QualType();
10389}
10390
10391// Diagnose cases where a scalar was implicitly converted to a vector and
10392// diagnose the underlying types. Otherwise, diagnose the error
10393// as invalid vector logical operands for non-C++ cases.
10394QualType Sema::InvalidLogicalVectorOperands(SourceLocation Loc, ExprResult &LHS,
10395 ExprResult &RHS) {
10396 QualType LHSType = LHS.get()->IgnoreImpCasts()->getType();
10397 QualType RHSType = RHS.get()->IgnoreImpCasts()->getType();
10398
10399 bool LHSNatVec = LHSType->isVectorType();
10400 bool RHSNatVec = RHSType->isVectorType();
10401
10402 if (!(LHSNatVec && RHSNatVec)) {
10403 Expr *Vector = LHSNatVec ? LHS.get() : RHS.get();
10404 Expr *NonVector = !LHSNatVec ? LHS.get() : RHS.get();
10405 Diag(Loc, diag::err_typecheck_logical_vector_expr_gnu_cpp_restrict)
10406 << 0 << Vector->getType() << NonVector->IgnoreImpCasts()->getType()
10407 << Vector->getSourceRange();
10408 return QualType();
10409 }
10410
10411 Diag(Loc, diag::err_typecheck_logical_vector_expr_gnu_cpp_restrict)
10412 << 1 << LHSType << RHSType << LHS.get()->getSourceRange()
10413 << RHS.get()->getSourceRange();
10414
10415 return QualType();
10416}
10417
10418/// Try to convert a value of non-vector type to a vector type by converting
10419/// the type to the element type of the vector and then performing a splat.
10420/// If the language is OpenCL, we only use conversions that promote scalar
10421/// rank; for C, Obj-C, and C++ we allow any real scalar conversion except
10422/// for float->int.
10423///
10424/// OpenCL V2.0 6.2.6.p2:
10425/// An error shall occur if any scalar operand type has greater rank
10426/// than the type of the vector element.
10427///
10428/// \param scalar - if non-null, actually perform the conversions
10429/// \return true if the operation fails (but without diagnosing the failure)
10430static bool tryVectorConvertAndSplat(Sema &S, ExprResult *scalar,
10431 QualType scalarTy,
10432 QualType vectorEltTy,
10433 QualType vectorTy,
10434 unsigned &DiagID) {
10435 // The conversion to apply to the scalar before splatting it,
10436 // if necessary.
10437 CastKind scalarCast = CK_NoOp;
10438
10439 if (vectorEltTy->isIntegralType(S.Context)) {
10440 if (S.getLangOpts().OpenCL && (scalarTy->isRealFloatingType() ||
10441 (scalarTy->isIntegerType() &&
10442 S.Context.getIntegerTypeOrder(vectorEltTy, scalarTy) < 0))) {
10443 DiagID = diag::err_opencl_scalar_type_rank_greater_than_vector_type;
10444 return true;
10445 }
10446 if (!scalarTy->isIntegralType(S.Context))
10447 return true;
10448 scalarCast = CK_IntegralCast;
10449 } else if (vectorEltTy->isRealFloatingType()) {
10450 if (scalarTy->isRealFloatingType()) {
10451 if (S.getLangOpts().OpenCL &&
10452 S.Context.getFloatingTypeOrder(vectorEltTy, scalarTy) < 0) {
10453 DiagID = diag::err_opencl_scalar_type_rank_greater_than_vector_type;
10454 return true;
10455 }
10456 scalarCast = CK_FloatingCast;
10457 }
10458 else if (scalarTy->isIntegralType(S.Context))
10459 scalarCast = CK_IntegralToFloating;
10460 else
10461 return true;
10462 } else {
10463 return true;
10464 }
10465
10466 // Adjust scalar if desired.
10467 if (scalar) {
10468 if (scalarCast != CK_NoOp)
10469 *scalar = S.ImpCastExprToType(scalar->get(), vectorEltTy, scalarCast);
10470 *scalar = S.ImpCastExprToType(scalar->get(), vectorTy, CK_VectorSplat);
10471 }
10472 return false;
10473}
10474
10475/// Convert vector E to a vector with the same number of elements but different
10476/// element type.
10477static ExprResult convertVector(Expr *E, QualType ElementType, Sema &S) {
10478 const auto *VecTy = E->getType()->getAs<VectorType>();
10479 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", 10479, __extension__ __PRETTY_FUNCTION__
))
;
10480 QualType NewVecTy =
10481 VecTy->isExtVectorType()
10482 ? S.Context.getExtVectorType(ElementType, VecTy->getNumElements())
10483 : S.Context.getVectorType(ElementType, VecTy->getNumElements(),
10484 VecTy->getVectorKind());
10485
10486 // Look through the implicit cast. Return the subexpression if its type is
10487 // NewVecTy.
10488 if (auto *ICE = dyn_cast<ImplicitCastExpr>(E))
10489 if (ICE->getSubExpr()->getType() == NewVecTy)
10490 return ICE->getSubExpr();
10491
10492 auto Cast = ElementType->isIntegerType() ? CK_IntegralCast : CK_FloatingCast;
10493 return S.ImpCastExprToType(E, NewVecTy, Cast);
10494}
10495
10496/// Test if a (constant) integer Int can be casted to another integer type
10497/// IntTy without losing precision.
10498static bool canConvertIntToOtherIntTy(Sema &S, ExprResult *Int,
10499 QualType OtherIntTy) {
10500 QualType IntTy = Int->get()->getType().getUnqualifiedType();
10501
10502 // Reject cases where the value of the Int is unknown as that would
10503 // possibly cause truncation, but accept cases where the scalar can be
10504 // demoted without loss of precision.
10505 Expr::EvalResult EVResult;
10506 bool CstInt = Int->get()->EvaluateAsInt(EVResult, S.Context);
10507 int Order = S.Context.getIntegerTypeOrder(OtherIntTy, IntTy);
10508 bool IntSigned = IntTy->hasSignedIntegerRepresentation();
10509 bool OtherIntSigned = OtherIntTy->hasSignedIntegerRepresentation();
10510
10511 if (CstInt) {
10512 // If the scalar is constant and is of a higher order and has more active
10513 // bits that the vector element type, reject it.
10514 llvm::APSInt Result = EVResult.Val.getInt();
10515 unsigned NumBits = IntSigned
10516 ? (Result.isNegative() ? Result.getSignificantBits()
10517 : Result.getActiveBits())
10518 : Result.getActiveBits();
10519 if (Order < 0 && S.Context.getIntWidth(OtherIntTy) < NumBits)
10520 return true;
10521
10522 // If the signedness of the scalar type and the vector element type
10523 // differs and the number of bits is greater than that of the vector
10524 // element reject it.
10525 return (IntSigned != OtherIntSigned &&
10526 NumBits > S.Context.getIntWidth(OtherIntTy));
10527 }
10528
10529 // Reject cases where the value of the scalar is not constant and it's
10530 // order is greater than that of the vector element type.
10531 return (Order < 0);
10532}
10533
10534/// Test if a (constant) integer Int can be casted to floating point type
10535/// FloatTy without losing precision.
10536static bool canConvertIntTyToFloatTy(Sema &S, ExprResult *Int,
10537 QualType FloatTy) {
10538 QualType IntTy = Int->get()->getType().getUnqualifiedType();
10539
10540 // Determine if the integer constant can be expressed as a floating point
10541 // number of the appropriate type.
10542 Expr::EvalResult EVResult;
10543 bool CstInt = Int->get()->EvaluateAsInt(EVResult, S.Context);
10544
10545 uint64_t Bits = 0;
10546 if (CstInt) {
10547 // Reject constants that would be truncated if they were converted to
10548 // the floating point type. Test by simple to/from conversion.
10549 // FIXME: Ideally the conversion to an APFloat and from an APFloat
10550 // could be avoided if there was a convertFromAPInt method
10551 // which could signal back if implicit truncation occurred.
10552 llvm::APSInt Result = EVResult.Val.getInt();
10553 llvm::APFloat Float(S.Context.getFloatTypeSemantics(FloatTy));
10554 Float.convertFromAPInt(Result, IntTy->hasSignedIntegerRepresentation(),
10555 llvm::APFloat::rmTowardZero);
10556 llvm::APSInt ConvertBack(S.Context.getIntWidth(IntTy),
10557 !IntTy->hasSignedIntegerRepresentation());
10558 bool Ignored = false;
10559 Float.convertToInteger(ConvertBack, llvm::APFloat::rmNearestTiesToEven,
10560 &Ignored);
10561 if (Result != ConvertBack)
10562 return true;
10563 } else {
10564 // Reject types that cannot be fully encoded into the mantissa of
10565 // the float.
10566 Bits = S.Context.getTypeSize(IntTy);
10567 unsigned FloatPrec = llvm::APFloat::semanticsPrecision(
10568 S.Context.getFloatTypeSemantics(FloatTy));
10569 if (Bits > FloatPrec)
10570 return true;
10571 }
10572
10573 return false;
10574}
10575
10576/// Attempt to convert and splat Scalar into a vector whose types matches
10577/// Vector following GCC conversion rules. The rule is that implicit
10578/// conversion can occur when Scalar can be casted to match Vector's element
10579/// type without causing truncation of Scalar.
10580static bool tryGCCVectorConvertAndSplat(Sema &S, ExprResult *Scalar,
10581 ExprResult *Vector) {
10582 QualType ScalarTy = Scalar->get()->getType().getUnqualifiedType();
10583 QualType VectorTy = Vector->get()->getType().getUnqualifiedType();
10584 QualType VectorEltTy;
10585
10586 if (const auto *VT = VectorTy->getAs<VectorType>()) {
10587 assert(!isa<ExtVectorType>(VT) &&(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", 10588, __extension__ __PRETTY_FUNCTION__
))
10588 "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", 10588, __extension__ __PRETTY_FUNCTION__
))
;
10589 VectorEltTy = VT->getElementType();
10590 } else if (VectorTy->isVLSTBuiltinType()) {
10591 VectorEltTy =
10592 VectorTy->castAs<BuiltinType>()->getSveEltType(S.getASTContext());
10593 } else {
10594 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", 10594)
;
10595 }
10596
10597 // Reject cases where the vector element type or the scalar element type are
10598 // not integral or floating point types.
10599 if (!VectorEltTy->isArithmeticType() || !ScalarTy->isArithmeticType())
10600 return true;
10601
10602 // The conversion to apply to the scalar before splatting it,
10603 // if necessary.
10604 CastKind ScalarCast = CK_NoOp;
10605
10606 // Accept cases where the vector elements are integers and the scalar is
10607 // an integer.
10608 // FIXME: Notionally if the scalar was a floating point value with a precise
10609 // integral representation, we could cast it to an appropriate integer
10610 // type and then perform the rest of the checks here. GCC will perform
10611 // this conversion in some cases as determined by the input language.
10612 // We should accept it on a language independent basis.
10613 if (VectorEltTy->isIntegralType(S.Context) &&
10614 ScalarTy->isIntegralType(S.Context) &&
10615 S.Context.getIntegerTypeOrder(VectorEltTy, ScalarTy)) {
10616
10617 if (canConvertIntToOtherIntTy(S, Scalar, VectorEltTy))
10618 return true;
10619
10620 ScalarCast = CK_IntegralCast;
10621 } else if (VectorEltTy->isIntegralType(S.Context) &&
10622 ScalarTy->isRealFloatingType()) {
10623 if (S.Context.getTypeSize(VectorEltTy) == S.Context.getTypeSize(ScalarTy))
10624 ScalarCast = CK_FloatingToIntegral;
10625 else
10626 return true;
10627 } else if (VectorEltTy->isRealFloatingType()) {
10628 if (ScalarTy->isRealFloatingType()) {
10629
10630 // Reject cases where the scalar type is not a constant and has a higher
10631 // Order than the vector element type.
10632 llvm::APFloat Result(0.0);
10633
10634 // Determine whether this is a constant scalar. In the event that the
10635 // value is dependent (and thus cannot be evaluated by the constant
10636 // evaluator), skip the evaluation. This will then diagnose once the
10637 // expression is instantiated.
10638 bool CstScalar = Scalar->get()->isValueDependent() ||
10639 Scalar->get()->EvaluateAsFloat(Result, S.Context);
10640 int Order = S.Context.getFloatingTypeOrder(VectorEltTy, ScalarTy);
10641 if (!CstScalar && Order < 0)
10642 return true;
10643
10644 // If the scalar cannot be safely casted to the vector element type,
10645 // reject it.
10646 if (CstScalar) {
10647 bool Truncated = false;
10648 Result.convert(S.Context.getFloatTypeSemantics(VectorEltTy),
10649 llvm::APFloat::rmNearestTiesToEven, &Truncated);
10650 if (Truncated)
10651 return true;
10652 }
10653
10654 ScalarCast = CK_FloatingCast;
10655 } else if (ScalarTy->isIntegralType(S.Context)) {
10656 if (canConvertIntTyToFloatTy(S, Scalar, VectorEltTy))
10657 return true;
10658
10659 ScalarCast = CK_IntegralToFloating;
10660 } else
10661 return true;
10662 } else if (ScalarTy->isEnumeralType())
10663 return true;
10664
10665 // Adjust scalar if desired.
10666 if (Scalar) {
10667 if (ScalarCast != CK_NoOp)
10668 *Scalar = S.ImpCastExprToType(Scalar->get(), VectorEltTy, ScalarCast);
10669 *Scalar = S.ImpCastExprToType(Scalar->get(), VectorTy, CK_VectorSplat);
10670 }
10671 return false;
10672}
10673
10674QualType Sema::CheckVectorOperands(ExprResult &LHS, ExprResult &RHS,
10675 SourceLocation Loc, bool IsCompAssign,
10676 bool AllowBothBool,
10677 bool AllowBoolConversions,
10678 bool AllowBoolOperation,
10679 bool ReportInvalid) {
10680 if (!IsCompAssign) {
10681 LHS = DefaultFunctionArrayLvalueConversion(LHS.get());
10682 if (LHS.isInvalid())
10683 return QualType();
10684 }
10685 RHS = DefaultFunctionArrayLvalueConversion(RHS.get());
10686 if (RHS.isInvalid())
10687 return QualType();
10688
10689 // For conversion purposes, we ignore any qualifiers.
10690 // For example, "const float" and "float" are equivalent.
10691 QualType LHSType = LHS.get()->getType().getUnqualifiedType();
10692 QualType RHSType = RHS.get()->getType().getUnqualifiedType();
10693
10694 const VectorType *LHSVecType = LHSType->getAs<VectorType>();
10695 const VectorType *RHSVecType = RHSType->getAs<VectorType>();
10696 assert(LHSVecType || RHSVecType)(static_cast <bool> (LHSVecType || RHSVecType) ? void (
0) : __assert_fail ("LHSVecType || RHSVecType", "clang/lib/Sema/SemaExpr.cpp"
, 10696, __extension__ __PRETTY_FUNCTION__))
;
10697
10698 if ((LHSVecType && LHSVecType->getElementType()->isBFloat16Type()) ||
10699 (RHSVecType && RHSVecType->getElementType()->isBFloat16Type()))
10700 return ReportInvalid ? InvalidOperands(Loc, LHS, RHS) : QualType();
10701
10702 // AltiVec-style "vector bool op vector bool" combinations are allowed
10703 // for some operators but not others.
10704 if (!AllowBothBool &&
10705 LHSVecType && LHSVecType->getVectorKind() == VectorType::AltiVecBool &&
10706 RHSVecType && RHSVecType->getVectorKind() == VectorType::AltiVecBool)
10707 return ReportInvalid ? InvalidOperands(Loc, LHS, RHS) : QualType();
10708
10709 // This operation may not be performed on boolean vectors.
10710 if (!AllowBoolOperation &&
10711 (LHSType->isExtVectorBoolType() || RHSType->isExtVectorBoolType()))
10712 return ReportInvalid ? InvalidOperands(Loc, LHS, RHS) : QualType();
10713
10714 // If the vector types are identical, return.
10715 if (Context.hasSameType(LHSType, RHSType))
10716 return Context.getCommonSugaredType(LHSType, RHSType);
10717
10718 // If we have compatible AltiVec and GCC vector types, use the AltiVec type.
10719 if (LHSVecType && RHSVecType &&
10720 Context.areCompatibleVectorTypes(LHSType, RHSType)) {
10721 if (isa<ExtVectorType>(LHSVecType)) {
10722 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast);
10723 return LHSType;
10724 }
10725
10726 if (!IsCompAssign)
10727 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_BitCast);
10728 return RHSType;
10729 }
10730
10731 // AllowBoolConversions says that bool and non-bool AltiVec vectors
10732 // can be mixed, with the result being the non-bool type. The non-bool
10733 // operand must have integer element type.
10734 if (AllowBoolConversions && LHSVecType && RHSVecType &&
10735 LHSVecType->getNumElements() == RHSVecType->getNumElements() &&
10736 (Context.getTypeSize(LHSVecType->getElementType()) ==
10737 Context.getTypeSize(RHSVecType->getElementType()))) {
10738 if (LHSVecType->getVectorKind() == VectorType::AltiVecVector &&
10739 LHSVecType->getElementType()->isIntegerType() &&
10740 RHSVecType->getVectorKind() == VectorType::AltiVecBool) {
10741 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast);
10742 return LHSType;
10743 }
10744 if (!IsCompAssign &&
10745 LHSVecType->getVectorKind() == VectorType::AltiVecBool &&
10746 RHSVecType->getVectorKind() == VectorType::AltiVecVector &&
10747 RHSVecType->getElementType()->isIntegerType()) {
10748 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_BitCast);
10749 return RHSType;
10750 }
10751 }
10752
10753 // Expressions containing fixed-length and sizeless SVE vectors are invalid
10754 // since the ambiguity can affect the ABI.
10755 auto IsSveConversion = [](QualType FirstType, QualType SecondType) {
10756 const VectorType *VecType = SecondType->getAs<VectorType>();
10757 return FirstType->isSizelessBuiltinType() && VecType &&
10758 (VecType->getVectorKind() == VectorType::SveFixedLengthDataVector ||
10759 VecType->getVectorKind() ==
10760 VectorType::SveFixedLengthPredicateVector);
10761 };
10762
10763 if (IsSveConversion(LHSType, RHSType) || IsSveConversion(RHSType, LHSType)) {
10764 Diag(Loc, diag::err_typecheck_sve_ambiguous) << LHSType << RHSType;
10765 return QualType();
10766 }
10767
10768 // Expressions containing GNU and SVE or RVV (fixed or sizeless) vectors are
10769 // invalid since the ambiguity can affect the ABI.
10770 auto IsSveRVVGnuConversion = [](QualType FirstType, QualType SecondType,
10771 unsigned &SVEorRVV) {
10772 const VectorType *FirstVecType = FirstType->getAs<VectorType>();
10773 const VectorType *SecondVecType = SecondType->getAs<VectorType>();
10774
10775 SVEorRVV = 0;
10776 if (FirstVecType && SecondVecType)
10777 return FirstVecType->getVectorKind() == VectorType::GenericVector &&
10778 (SecondVecType->getVectorKind() ==
10779 VectorType::SveFixedLengthDataVector ||
10780 SecondVecType->getVectorKind() ==
10781 VectorType::SveFixedLengthPredicateVector);
10782
10783 if (SecondVecType &&
10784 SecondVecType->getVectorKind() == VectorType::GenericVector) {
10785 if (FirstType->isSVESizelessBuiltinType())
10786 return true;
10787 if (FirstType->isRVVSizelessBuiltinType()) {
10788 SVEorRVV = 1;
10789 return true;
10790 }
10791 }
10792
10793 return false;
10794 };
10795
10796 unsigned SVEorRVV;
10797 if (IsSveRVVGnuConversion(LHSType, RHSType, SVEorRVV) ||
10798 IsSveRVVGnuConversion(RHSType, LHSType, SVEorRVV)) {
10799 Diag(Loc, diag::err_typecheck_sve_rvv_gnu_ambiguous)
10800 << SVEorRVV << LHSType << RHSType;
10801 return QualType();
10802 }
10803
10804 // If there's a vector type and a scalar, try to convert the scalar to
10805 // the vector element type and splat.
10806 unsigned DiagID = diag::err_typecheck_vector_not_convertable;
10807 if (!RHSVecType) {
10808 if (isa<ExtVectorType>(LHSVecType)) {
10809 if (!tryVectorConvertAndSplat(*this, &RHS, RHSType,
10810 LHSVecType->getElementType(), LHSType,
10811 DiagID))
10812 return LHSType;
10813 } else {
10814 if (!tryGCCVectorConvertAndSplat(*this, &RHS, &LHS))
10815 return LHSType;
10816 }
10817 }
10818 if (!LHSVecType) {
10819 if (isa<ExtVectorType>(RHSVecType)) {
10820 if (!tryVectorConvertAndSplat(*this, (IsCompAssign ? nullptr : &LHS),
10821 LHSType, RHSVecType->getElementType(),
10822 RHSType, DiagID))
10823 return RHSType;
10824 } else {
10825 if (LHS.get()->isLValue() ||
10826 !tryGCCVectorConvertAndSplat(*this, &LHS, &RHS))
10827 return RHSType;
10828 }
10829 }
10830
10831 // FIXME: The code below also handles conversion between vectors and
10832 // non-scalars, we should break this down into fine grained specific checks
10833 // and emit proper diagnostics.
10834 QualType VecType = LHSVecType ? LHSType : RHSType;
10835 const VectorType *VT = LHSVecType ? LHSVecType : RHSVecType;
10836 QualType OtherType = LHSVecType ? RHSType : LHSType;
10837 ExprResult *OtherExpr = LHSVecType ? &RHS : &LHS;
10838 if (isLaxVectorConversion(OtherType, VecType)) {
10839 if (anyAltivecTypes(RHSType, LHSType) &&
10840 !Context.areCompatibleVectorTypes(RHSType, LHSType))
10841 Diag(Loc, diag::warn_deprecated_lax_vec_conv_all) << RHSType << LHSType;
10842 // If we're allowing lax vector conversions, only the total (data) size
10843 // needs to be the same. For non compound assignment, if one of the types is
10844 // scalar, the result is always the vector type.
10845 if (!IsCompAssign) {
10846 *OtherExpr = ImpCastExprToType(OtherExpr->get(), VecType, CK_BitCast);
10847 return VecType;
10848 // In a compound assignment, lhs += rhs, 'lhs' is a lvalue src, forbidding
10849 // any implicit cast. Here, the 'rhs' should be implicit casted to 'lhs'
10850 // type. Note that this is already done by non-compound assignments in
10851 // CheckAssignmentConstraints. If it's a scalar type, only bitcast for
10852 // <1 x T> -> T. The result is also a vector type.
10853 } else if (OtherType->isExtVectorType() || OtherType->isVectorType() ||
10854 (OtherType->isScalarType() && VT->getNumElements() == 1)) {
10855 ExprResult *RHSExpr = &RHS;
10856 *RHSExpr = ImpCastExprToType(RHSExpr->get(), LHSType, CK_BitCast);
10857 return VecType;
10858 }
10859 }
10860
10861 // Okay, the expression is invalid.
10862
10863 // If there's a non-vector, non-real operand, diagnose that.
10864 if ((!RHSVecType && !RHSType->isRealType()) ||
10865 (!LHSVecType && !LHSType->isRealType())) {
10866 Diag(Loc, diag::err_typecheck_vector_not_convertable_non_scalar)
10867 << LHSType << RHSType
10868 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
10869 return QualType();
10870 }
10871
10872 // OpenCL V1.1 6.2.6.p1:
10873 // If the operands are of more than one vector type, then an error shall
10874 // occur. Implicit conversions between vector types are not permitted, per
10875 // section 6.2.1.
10876 if (getLangOpts().OpenCL &&
10877 RHSVecType && isa<ExtVectorType>(RHSVecType) &&
10878 LHSVecType && isa<ExtVectorType>(LHSVecType)) {
10879 Diag(Loc, diag::err_opencl_implicit_vector_conversion) << LHSType
10880 << RHSType;
10881 return QualType();
10882 }
10883
10884
10885 // If there is a vector type that is not a ExtVector and a scalar, we reach
10886 // this point if scalar could not be converted to the vector's element type
10887 // without truncation.
10888 if ((RHSVecType && !isa<ExtVectorType>(RHSVecType)) ||
10889 (LHSVecType && !isa<ExtVectorType>(LHSVecType))) {
10890 QualType Scalar = LHSVecType ? RHSType : LHSType;
10891 QualType Vector = LHSVecType ? LHSType : RHSType;
10892 unsigned ScalarOrVector = LHSVecType && RHSVecType ? 1 : 0;
10893 Diag(Loc,
10894 diag::err_typecheck_vector_not_convertable_implict_truncation)
10895 << ScalarOrVector << Scalar << Vector;
10896
10897 return QualType();
10898 }
10899
10900 // Otherwise, use the generic diagnostic.
10901 Diag(Loc, DiagID)
10902 << LHSType << RHSType
10903 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
10904 return QualType();
10905}
10906
10907QualType Sema::CheckSizelessVectorOperands(ExprResult &LHS, ExprResult &RHS,
10908 SourceLocation Loc,
10909 bool IsCompAssign,
10910 ArithConvKind OperationKind) {
10911 if (!IsCompAssign) {
10912 LHS = DefaultFunctionArrayLvalueConversion(LHS.get());
10913 if (LHS.isInvalid())
10914 return QualType();
10915 }
10916 RHS = DefaultFunctionArrayLvalueConversion(RHS.get());
10917 if (RHS.isInvalid())
10918 return QualType();
10919
10920 QualType LHSType = LHS.get()->getType().getUnqualifiedType();
10921 QualType RHSType = RHS.get()->getType().getUnqualifiedType();
10922
10923 const BuiltinType *LHSBuiltinTy = LHSType->getAs<BuiltinType>();
10924 const BuiltinType *RHSBuiltinTy = RHSType->getAs<BuiltinType>();
10925
10926 unsigned DiagID = diag::err_typecheck_invalid_operands;
10927 if ((OperationKind == ACK_Arithmetic) &&
10928 ((LHSBuiltinTy && LHSBuiltinTy->isSVEBool()) ||
10929 (RHSBuiltinTy && RHSBuiltinTy->isSVEBool()))) {
10930 Diag(Loc, DiagID) << LHSType << RHSType << LHS.get()->getSourceRange()
10931 << RHS.get()->getSourceRange();
10932 return QualType();
10933 }
10934
10935 if (Context.hasSameType(LHSType, RHSType))
10936 return LHSType;
10937
10938 if (LHSType->isVLSTBuiltinType() && !RHSType->isVLSTBuiltinType()) {
10939 if (!tryGCCVectorConvertAndSplat(*this, &RHS, &LHS))
10940 return LHSType;
10941 }
10942 if (RHSType->isVLSTBuiltinType() && !LHSType->isVLSTBuiltinType()) {
10943 if (LHS.get()->isLValue() ||
10944 !tryGCCVectorConvertAndSplat(*this, &LHS, &RHS))
10945 return RHSType;
10946 }
10947
10948 if ((!LHSType->isVLSTBuiltinType() && !LHSType->isRealType()) ||
10949 (!RHSType->isVLSTBuiltinType() && !RHSType->isRealType())) {
10950 Diag(Loc, diag::err_typecheck_vector_not_convertable_non_scalar)
10951 << LHSType << RHSType << LHS.get()->getSourceRange()
10952 << RHS.get()->getSourceRange();
10953 return QualType();
10954 }
10955
10956 if (LHSType->isVLSTBuiltinType() && RHSType->isVLSTBuiltinType() &&
10957 Context.getBuiltinVectorTypeInfo(LHSBuiltinTy).EC !=
10958 Context.getBuiltinVectorTypeInfo(RHSBuiltinTy).EC) {
10959 Diag(Loc, diag::err_typecheck_vector_lengths_not_equal)
10960 << LHSType << RHSType << LHS.get()->getSourceRange()
10961 << RHS.get()->getSourceRange();
10962 return QualType();
10963 }
10964
10965 if (LHSType->isVLSTBuiltinType() || RHSType->isVLSTBuiltinType()) {
10966 QualType Scalar = LHSType->isVLSTBuiltinType() ? RHSType : LHSType;
10967 QualType Vector = LHSType->isVLSTBuiltinType() ? LHSType : RHSType;
10968 bool ScalarOrVector =
10969 LHSType->isVLSTBuiltinType() && RHSType->isVLSTBuiltinType();
10970
10971 Diag(Loc, diag::err_typecheck_vector_not_convertable_implict_truncation)
10972 << ScalarOrVector << Scalar << Vector;
10973
10974 return QualType();
10975 }
10976
10977 Diag(Loc, DiagID) << LHSType << RHSType << LHS.get()->getSourceRange()
10978 << RHS.get()->getSourceRange();
10979 return QualType();
10980}
10981
10982// checkArithmeticNull - Detect when a NULL constant is used improperly in an
10983// expression. These are mainly cases where the null pointer is used as an
10984// integer instead of a pointer.
10985static void checkArithmeticNull(Sema &S, ExprResult &LHS, ExprResult &RHS,
10986 SourceLocation Loc, bool IsCompare) {
10987 // The canonical way to check for a GNU null is with isNullPointerConstant,
10988 // but we use a bit of a hack here for speed; this is a relatively
10989 // hot path, and isNullPointerConstant is slow.
10990 bool LHSNull = isa<GNUNullExpr>(LHS.get()->IgnoreParenImpCasts());
10991 bool RHSNull = isa<GNUNullExpr>(RHS.get()->IgnoreParenImpCasts());
10992
10993 QualType NonNullType = LHSNull ? RHS.get()->getType() : LHS.get()->getType();
10994
10995 // Avoid analyzing cases where the result will either be invalid (and
10996 // diagnosed as such) or entirely valid and not something to warn about.
10997 if ((!LHSNull && !RHSNull) || NonNullType->isBlockPointerType() ||
10998 NonNullType->isMemberPointerType() || NonNullType->isFunctionType())
10999 return;
11000
11001 // Comparison operations would not make sense with a null pointer no matter
11002 // what the other expression is.
11003 if (!IsCompare) {
11004 S.Diag(Loc, diag::warn_null_in_arithmetic_operation)
11005 << (LHSNull ? LHS.get()->getSourceRange() : SourceRange())
11006 << (RHSNull ? RHS.get()->getSourceRange() : SourceRange());
11007 return;
11008 }
11009
11010 // The rest of the operations only make sense with a null pointer
11011 // if the other expression is a pointer.
11012 if (LHSNull == RHSNull || NonNullType->isAnyPointerType() ||
11013 NonNullType->canDecayToPointerType())
11014 return;
11015
11016 S.Diag(Loc, diag::warn_null_in_comparison_operation)
11017 << LHSNull /* LHS is NULL */ << NonNullType
11018 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
11019}
11020
11021static void DiagnoseDivisionSizeofPointerOrArray(Sema &S, Expr *LHS, Expr *RHS,
11022 SourceLocation Loc) {
11023 const auto *LUE = dyn_cast<UnaryExprOrTypeTraitExpr>(LHS);
11024 const auto *RUE = dyn_cast<UnaryExprOrTypeTraitExpr>(RHS);
11025 if (!LUE || !RUE)
11026 return;
11027 if (LUE->getKind() != UETT_SizeOf || LUE->isArgumentType() ||
11028 RUE->getKind() != UETT_SizeOf)
11029 return;
11030
11031 const Expr *LHSArg = LUE->getArgumentExpr()->IgnoreParens();
11032 QualType LHSTy = LHSArg->getType();
11033 QualType RHSTy;
11034
11035 if (RUE->isArgumentType())
11036 RHSTy = RUE->getArgumentType().getNonReferenceType();
11037 else
11038 RHSTy = RUE->getArgumentExpr()->IgnoreParens()->getType();
11039
11040 if (LHSTy->isPointerType() && !RHSTy->isPointerType()) {
11041 if (!S.Context.hasSameUnqualifiedType(LHSTy->getPointeeType(), RHSTy))
11042 return;
11043
11044 S.Diag(Loc, diag::warn_division_sizeof_ptr) << LHS << LHS->getSourceRange();
11045 if (const auto *DRE = dyn_cast<DeclRefExpr>(LHSArg)) {
11046 if (const ValueDecl *LHSArgDecl = DRE->getDecl())
11047 S.Diag(LHSArgDecl->getLocation(), diag::note_pointer_declared_here)
11048 << LHSArgDecl;
11049 }
11050 } else if (const auto *ArrayTy = S.Context.getAsArrayType(LHSTy)) {
11051 QualType ArrayElemTy = ArrayTy->getElementType();
11052 if (ArrayElemTy != S.Context.getBaseElementType(ArrayTy) ||
11053 ArrayElemTy->isDependentType() || RHSTy->isDependentType() ||
11054 RHSTy->isReferenceType() || ArrayElemTy->isCharType() ||
11055 S.Context.getTypeSize(ArrayElemTy) == S.Context.getTypeSize(RHSTy))
11056 return;
11057 S.Diag(Loc, diag::warn_division_sizeof_array)
11058 << LHSArg->getSourceRange() << ArrayElemTy << RHSTy;
11059 if (const auto *DRE = dyn_cast<DeclRefExpr>(LHSArg)) {
11060 if (const ValueDecl *LHSArgDecl = DRE->getDecl())
11061 S.Diag(LHSArgDecl->getLocation(), diag::note_array_declared_here)
11062 << LHSArgDecl;
11063 }
11064
11065 S.Diag(Loc, diag::note_precedence_silence) << RHS;
11066 }
11067}
11068
11069static void DiagnoseBadDivideOrRemainderValues(Sema& S, ExprResult &LHS,
11070 ExprResult &RHS,
11071 SourceLocation Loc, bool IsDiv) {
11072 // Check for division/remainder by zero.
11073 Expr::EvalResult RHSValue;
11074 if (!RHS.get()->isValueDependent() &&
11075 RHS.get()->EvaluateAsInt(RHSValue, S.Context) &&
11076 RHSValue.Val.getInt() == 0)
11077 S.DiagRuntimeBehavior(Loc, RHS.get(),
11078 S.PDiag(diag::warn_remainder_division_by_zero)
11079 << IsDiv << RHS.get()->getSourceRange());
11080}
11081
11082QualType Sema::CheckMultiplyDivideOperands(ExprResult &LHS, ExprResult &RHS,
11083 SourceLocation Loc,
11084 bool IsCompAssign, bool IsDiv) {
11085 checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/false);
11086
11087 QualType LHSTy = LHS.get()->getType();
11088 QualType RHSTy = RHS.get()->getType();
11089 if (LHSTy->isVectorType() || RHSTy->isVectorType())
11090 return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign,
11091 /*AllowBothBool*/ getLangOpts().AltiVec,
11092 /*AllowBoolConversions*/ false,
11093 /*AllowBooleanOperation*/ false,
11094 /*ReportInvalid*/ true);
11095 if (LHSTy->isVLSTBuiltinType() || RHSTy->isVLSTBuiltinType())
11096 return CheckSizelessVectorOperands(LHS, RHS, Loc, IsCompAssign,
11097 ACK_Arithmetic);
11098 if (!IsDiv &&
11099 (LHSTy->isConstantMatrixType() || RHSTy->isConstantMatrixType()))
11100 return CheckMatrixMultiplyOperands(LHS, RHS, Loc, IsCompAssign);
11101 // For division, only matrix-by-scalar is supported. Other combinations with
11102 // matrix types are invalid.
11103 if (IsDiv && LHSTy->isConstantMatrixType() && RHSTy->isArithmeticType())
11104 return CheckMatrixElementwiseOperands(LHS, RHS, Loc, IsCompAssign);
11105
11106 QualType compType = UsualArithmeticConversions(
11107 LHS, RHS, Loc, IsCompAssign ? ACK_CompAssign : ACK_Arithmetic);
11108 if (LHS.isInvalid() || RHS.isInvalid())
11109 return QualType();
11110
11111
11112 if (compType.isNull() || !compType->isArithmeticType())
11113 return InvalidOperands(Loc, LHS, RHS);
11114 if (IsDiv) {
11115 DiagnoseBadDivideOrRemainderValues(*this, LHS, RHS, Loc, IsDiv);
11116 DiagnoseDivisionSizeofPointerOrArray(*this, LHS.get(), RHS.get(), Loc);
11117 }
11118 return compType;
11119}
11120
11121QualType Sema::CheckRemainderOperands(
11122 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, bool IsCompAssign) {
11123 checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/false);
11124
11125 if (LHS.get()->getType()->isVectorType() ||
11126 RHS.get()->getType()->isVectorType()) {
11127 if (LHS.get()->getType()->hasIntegerRepresentation() &&
11128 RHS.get()->getType()->hasIntegerRepresentation())
11129 return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign,
11130 /*AllowBothBool*/ getLangOpts().AltiVec,
11131 /*AllowBoolConversions*/ false,
11132 /*AllowBooleanOperation*/ false,
11133 /*ReportInvalid*/ true);
11134 return InvalidOperands(Loc, LHS, RHS);
11135 }
11136
11137 if (LHS.get()->getType()->isVLSTBuiltinType() ||
11138 RHS.get()->getType()->isVLSTBuiltinType()) {
11139 if (LHS.get()->getType()->hasIntegerRepresentation() &&
11140 RHS.get()->getType()->hasIntegerRepresentation())
11141 return CheckSizelessVectorOperands(LHS, RHS, Loc, IsCompAssign,
11142 ACK_Arithmetic);
11143
11144 return InvalidOperands(Loc, LHS, RHS);
11145 }
11146
11147 QualType compType = UsualArithmeticConversions(
11148 LHS, RHS, Loc, IsCompAssign ? ACK_CompAssign : ACK_Arithmetic);
11149 if (LHS.isInvalid() || RHS.isInvalid())
11150 return QualType();
11151
11152 if (compType.isNull() || !compType->isIntegerType())
11153 return InvalidOperands(Loc, LHS, RHS);
11154 DiagnoseBadDivideOrRemainderValues(*this, LHS, RHS, Loc, false /* IsDiv */);
11155 return compType;
11156}
11157
11158/// Diagnose invalid arithmetic on two void pointers.
11159static void diagnoseArithmeticOnTwoVoidPointers(Sema &S, SourceLocation Loc,
11160 Expr *LHSExpr, Expr *RHSExpr) {
11161 S.Diag(Loc, S.getLangOpts().CPlusPlus
11162 ? diag::err_typecheck_pointer_arith_void_type
11163 : diag::ext_gnu_void_ptr)
11164 << 1 /* two pointers */ << LHSExpr->getSourceRange()
11165 << RHSExpr->getSourceRange();
11166}
11167
11168/// Diagnose invalid arithmetic on a void pointer.
11169static void diagnoseArithmeticOnVoidPointer(Sema &S, SourceLocation Loc,
11170 Expr *Pointer) {
11171 S.Diag(Loc, S.getLangOpts().CPlusPlus
11172 ? diag::err_typecheck_pointer_arith_void_type
11173 : diag::ext_gnu_void_ptr)
11174 << 0 /* one pointer */ << Pointer->getSourceRange();
11175}
11176
11177/// Diagnose invalid arithmetic on a null pointer.
11178///
11179/// If \p IsGNUIdiom is true, the operation is using the 'p = (i8*)nullptr + n'
11180/// idiom, which we recognize as a GNU extension.
11181///
11182static void diagnoseArithmeticOnNullPointer(Sema &S, SourceLocation Loc,
11183 Expr *Pointer, bool IsGNUIdiom) {
11184 if (IsGNUIdiom)
11185 S.Diag(Loc, diag::warn_gnu_null_ptr_arith)
11186 << Pointer->getSourceRange();
11187 else
11188 S.Diag(Loc, diag::warn_pointer_arith_null_ptr)
11189 << S.getLangOpts().CPlusPlus << Pointer->getSourceRange();
11190}
11191
11192/// Diagnose invalid subraction on a null pointer.
11193///
11194static void diagnoseSubtractionOnNullPointer(Sema &S, SourceLocation Loc,
11195 Expr *Pointer, bool BothNull) {
11196 // Null - null is valid in C++ [expr.add]p7
11197 if (BothNull && S.getLangOpts().CPlusPlus)
11198 return;
11199
11200 // Is this s a macro from a system header?
11201 if (S.Diags.getSuppressSystemWarnings() && S.SourceMgr.isInSystemMacro(Loc))
11202 return;
11203
11204 S.DiagRuntimeBehavior(Loc, Pointer,
11205 S.PDiag(diag::warn_pointer_sub_null_ptr)
11206 << S.getLangOpts().CPlusPlus
11207 << Pointer->getSourceRange());
11208}
11209
11210/// Diagnose invalid arithmetic on two function pointers.
11211static void diagnoseArithmeticOnTwoFunctionPointers(Sema &S, SourceLocation Loc,
11212 Expr *LHS, Expr *RHS) {
11213 assert(LHS->getType()->isAnyPointerType())(static_cast <bool> (LHS->getType()->isAnyPointerType
()) ? void (0) : __assert_fail ("LHS->getType()->isAnyPointerType()"
, "clang/lib/Sema/SemaExpr.cpp", 11213, __extension__ __PRETTY_FUNCTION__
))
;
11214 assert(RHS->getType()->isAnyPointerType())(static_cast <bool> (RHS->getType()->isAnyPointerType
()) ? void (0) : __assert_fail ("RHS->getType()->isAnyPointerType()"
, "clang/lib/Sema/SemaExpr.cpp", 11214, __extension__ __PRETTY_FUNCTION__
))
;
11215 S.Diag(Loc, S.getLangOpts().CPlusPlus
11216 ? diag::err_typecheck_pointer_arith_function_type
11217 : diag::ext_gnu_ptr_func_arith)
11218 << 1 /* two pointers */ << LHS->getType()->getPointeeType()
11219 // We only show the second type if it differs from the first.
11220 << (unsigned)!S.Context.hasSameUnqualifiedType(LHS->getType(),
11221 RHS->getType())
11222 << RHS->getType()->getPointeeType()
11223 << LHS->getSourceRange() << RHS->getSourceRange();
11224}
11225
11226/// Diagnose invalid arithmetic on a function pointer.
11227static void diagnoseArithmeticOnFunctionPointer(Sema &S, SourceLocation Loc,
11228 Expr *Pointer) {
11229 assert(Pointer->getType()->isAnyPointerType())(static_cast <bool> (Pointer->getType()->isAnyPointerType
()) ? void (0) : __assert_fail ("Pointer->getType()->isAnyPointerType()"
, "clang/lib/Sema/SemaExpr.cpp", 11229, __extension__ __PRETTY_FUNCTION__
))
;
11230 S.Diag(Loc, S.getLangOpts().CPlusPlus
11231 ? diag::err_typecheck_pointer_arith_function_type
11232 : diag::ext_gnu_ptr_func_arith)
11233 << 0 /* one pointer */ << Pointer->getType()->getPointeeType()
11234 << 0 /* one pointer, so only one type */
11235 << Pointer->getSourceRange();
11236}
11237
11238/// Emit error if Operand is incomplete pointer type
11239///
11240/// \returns True if pointer has incomplete type
11241static bool checkArithmeticIncompletePointerType(Sema &S, SourceLocation Loc,
11242 Expr *Operand) {
11243 QualType ResType = Operand->getType();
11244 if (const AtomicType *ResAtomicType = ResType->getAs<AtomicType>())
11245 ResType = ResAtomicType->getValueType();
11246
11247 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", 11247, __extension__ __PRETTY_FUNCTION__
))
;
11248 QualType PointeeTy = ResType->getPointeeType();
11249 return S.RequireCompleteSizedType(
11250 Loc, PointeeTy,
11251 diag::err_typecheck_arithmetic_incomplete_or_sizeless_type,
11252 Operand->getSourceRange());
11253}
11254
11255/// Check the validity of an arithmetic pointer operand.
11256///
11257/// If the operand has pointer type, this code will check for pointer types
11258/// which are invalid in arithmetic operations. These will be diagnosed
11259/// appropriately, including whether or not the use is supported as an
11260/// extension.
11261///
11262/// \returns True when the operand is valid to use (even if as an extension).
11263static bool checkArithmeticOpPointerOperand(Sema &S, SourceLocation Loc,
11264 Expr *Operand) {
11265 QualType ResType = Operand->getType();
11266 if (const AtomicType *ResAtomicType = ResType->getAs<AtomicType>())
11267 ResType = ResAtomicType->getValueType();
11268
11269 if (!ResType->isAnyPointerType()) return true;
11270
11271 QualType PointeeTy = ResType->getPointeeType();
11272 if (PointeeTy->isVoidType()) {
11273 diagnoseArithmeticOnVoidPointer(S, Loc, Operand);
11274 return !S.getLangOpts().CPlusPlus;
11275 }
11276 if (PointeeTy->isFunctionType()) {
11277 diagnoseArithmeticOnFunctionPointer(S, Loc, Operand);
11278 return !S.getLangOpts().CPlusPlus;
11279 }
11280
11281 if (checkArithmeticIncompletePointerType(S, Loc, Operand)) return false;
11282
11283 return true;
11284}
11285
11286/// Check the validity of a binary arithmetic operation w.r.t. pointer
11287/// operands.
11288///
11289/// This routine will diagnose any invalid arithmetic on pointer operands much
11290/// like \see checkArithmeticOpPointerOperand. However, it has special logic
11291/// for emitting a single diagnostic even for operations where both LHS and RHS
11292/// are (potentially problematic) pointers.
11293///
11294/// \returns True when the operand is valid to use (even if as an extension).
11295static bool checkArithmeticBinOpPointerOperands(Sema &S, SourceLocation Loc,
11296 Expr *LHSExpr, Expr *RHSExpr) {
11297 bool isLHSPointer = LHSExpr->getType()->isAnyPointerType();
11298 bool isRHSPointer = RHSExpr->getType()->isAnyPointerType();
11299 if (!isLHSPointer && !isRHSPointer) return true;
11300
11301 QualType LHSPointeeTy, RHSPointeeTy;
11302 if (isLHSPointer) LHSPointeeTy = LHSExpr->getType()->getPointeeType();
11303 if (isRHSPointer) RHSPointeeTy = RHSExpr->getType()->getPointeeType();
11304
11305 // if both are pointers check if operation is valid wrt address spaces
11306 if (isLHSPointer && isRHSPointer) {
11307 if (!LHSPointeeTy.isAddressSpaceOverlapping(RHSPointeeTy)) {
11308 S.Diag(Loc,
11309 diag::err_typecheck_op_on_nonoverlapping_address_space_pointers)
11310 << LHSExpr->getType() << RHSExpr->getType() << 1 /*arithmetic op*/
11311 << LHSExpr->getSourceRange() << RHSExpr->getSourceRange();
11312 return false;
11313 }
11314 }
11315
11316 // Check for arithmetic on pointers to incomplete types.
11317 bool isLHSVoidPtr = isLHSPointer && LHSPointeeTy->isVoidType();
11318 bool isRHSVoidPtr = isRHSPointer && RHSPointeeTy->isVoidType();
11319 if (isLHSVoidPtr || isRHSVoidPtr) {
11320 if (!isRHSVoidPtr) diagnoseArithmeticOnVoidPointer(S, Loc, LHSExpr);
11321 else if (!isLHSVoidPtr) diagnoseArithmeticOnVoidPointer(S, Loc, RHSExpr);
11322 else diagnoseArithmeticOnTwoVoidPointers(S, Loc, LHSExpr, RHSExpr);
11323
11324 return !S.getLangOpts().CPlusPlus;
11325 }
11326
11327 bool isLHSFuncPtr = isLHSPointer && LHSPointeeTy->isFunctionType();
11328 bool isRHSFuncPtr = isRHSPointer && RHSPointeeTy->isFunctionType();
11329 if (isLHSFuncPtr || isRHSFuncPtr) {
11330 if (!isRHSFuncPtr) diagnoseArithmeticOnFunctionPointer(S, Loc, LHSExpr);
11331 else if (!isLHSFuncPtr) diagnoseArithmeticOnFunctionPointer(S, Loc,
11332 RHSExpr);
11333 else diagnoseArithmeticOnTwoFunctionPointers(S, Loc, LHSExpr, RHSExpr);
11334
11335 return !S.getLangOpts().CPlusPlus;
11336 }
11337
11338 if (isLHSPointer && checkArithmeticIncompletePointerType(S, Loc, LHSExpr))
11339 return false;
11340 if (isRHSPointer && checkArithmeticIncompletePointerType(S, Loc, RHSExpr))
11341 return false;
11342
11343 return true;
11344}
11345
11346/// diagnoseStringPlusInt - Emit a warning when adding an integer to a string
11347/// literal.
11348static void diagnoseStringPlusInt(Sema &Self, SourceLocation OpLoc,
11349 Expr *LHSExpr, Expr *RHSExpr) {
11350 StringLiteral* StrExpr = dyn_cast<StringLiteral>(LHSExpr->IgnoreImpCasts());
11351 Expr* IndexExpr = RHSExpr;
11352 if (!StrExpr) {
11353 StrExpr = dyn_cast<StringLiteral>(RHSExpr->IgnoreImpCasts());
11354 IndexExpr = LHSExpr;
11355 }
11356
11357 bool IsStringPlusInt = StrExpr &&
11358 IndexExpr->getType()->isIntegralOrUnscopedEnumerationType();
11359 if (!IsStringPlusInt || IndexExpr->isValueDependent())
11360 return;
11361
11362 SourceRange DiagRange(LHSExpr->getBeginLoc(), RHSExpr->getEndLoc());
11363 Self.Diag(OpLoc, diag::warn_string_plus_int)
11364 << DiagRange << IndexExpr->IgnoreImpCasts()->getType();
11365
11366 // Only print a fixit for "str" + int, not for int + "str".
11367 if (IndexExpr == RHSExpr) {
11368 SourceLocation EndLoc = Self.getLocForEndOfToken(RHSExpr->getEndLoc());
11369 Self.Diag(OpLoc, diag::note_string_plus_scalar_silence)
11370 << FixItHint::CreateInsertion(LHSExpr->getBeginLoc(), "&")
11371 << FixItHint::CreateReplacement(SourceRange(OpLoc), "[")
11372 << FixItHint::CreateInsertion(EndLoc, "]");
11373 } else
11374 Self.Diag(OpLoc, diag::note_string_plus_scalar_silence);
11375}
11376
11377/// Emit a warning when adding a char literal to a string.
11378static void diagnoseStringPlusChar(Sema &Self, SourceLocation OpLoc,
11379 Expr *LHSExpr, Expr *RHSExpr) {
11380 const Expr *StringRefExpr = LHSExpr;
11381 const CharacterLiteral *CharExpr =
11382 dyn_cast<CharacterLiteral>(RHSExpr->IgnoreImpCasts());
11383
11384 if (!CharExpr) {
11385 CharExpr = dyn_cast<CharacterLiteral>(LHSExpr->IgnoreImpCasts());
11386 StringRefExpr = RHSExpr;
11387 }
11388
11389 if (!CharExpr || !StringRefExpr)
11390 return;
11391
11392 const QualType StringType = StringRefExpr->getType();
11393
11394 // Return if not a PointerType.
11395 if (!StringType->isAnyPointerType())
11396 return;
11397
11398 // Return if not a CharacterType.
11399 if (!StringType->getPointeeType()->isAnyCharacterType())
11400 return;
11401
11402 ASTContext &Ctx = Self.getASTContext();
11403 SourceRange DiagRange(LHSExpr->getBeginLoc(), RHSExpr->getEndLoc());
11404
11405 const QualType CharType = CharExpr->getType();
11406 if (!CharType->isAnyCharacterType() &&
11407 CharType->isIntegerType() &&
11408 llvm::isUIntN(Ctx.getCharWidth(), CharExpr->getValue())) {
11409 Self.Diag(OpLoc, diag::warn_string_plus_char)
11410 << DiagRange << Ctx.CharTy;
11411 } else {
11412 Self.Diag(OpLoc, diag::warn_string_plus_char)
11413 << DiagRange << CharExpr->getType();
11414 }
11415
11416 // Only print a fixit for str + char, not for char + str.
11417 if (isa<CharacterLiteral>(RHSExpr->IgnoreImpCasts())) {
11418 SourceLocation EndLoc = Self.getLocForEndOfToken(RHSExpr->getEndLoc());
11419 Self.Diag(OpLoc, diag::note_string_plus_scalar_silence)
11420 << FixItHint::CreateInsertion(LHSExpr->getBeginLoc(), "&")
11421 << FixItHint::CreateReplacement(SourceRange(OpLoc), "[")
11422 << FixItHint::CreateInsertion(EndLoc, "]");
11423 } else {
11424 Self.Diag(OpLoc, diag::note_string_plus_scalar_silence);
11425 }
11426}
11427
11428/// Emit error when two pointers are incompatible.
11429static void diagnosePointerIncompatibility(Sema &S, SourceLocation Loc,
11430 Expr *LHSExpr, Expr *RHSExpr) {
11431 assert(LHSExpr->getType()->isAnyPointerType())(static_cast <bool> (LHSExpr->getType()->isAnyPointerType
()) ? void (0) : __assert_fail ("LHSExpr->getType()->isAnyPointerType()"
, "clang/lib/Sema/SemaExpr.cpp", 11431, __extension__ __PRETTY_FUNCTION__
))
;
11432 assert(RHSExpr->getType()->isAnyPointerType())(static_cast <bool> (RHSExpr->getType()->isAnyPointerType
()) ? void (0) : __assert_fail ("RHSExpr->getType()->isAnyPointerType()"
, "clang/lib/Sema/SemaExpr.cpp", 11432, __extension__ __PRETTY_FUNCTION__
))
;
11433 S.Diag(Loc, diag::err_typecheck_sub_ptr_compatible)
11434 << LHSExpr->getType() << RHSExpr->getType() << LHSExpr->getSourceRange()
11435 << RHSExpr->getSourceRange();
11436}
11437
11438// C99 6.5.6
11439QualType Sema::CheckAdditionOperands(ExprResult &LHS, ExprResult &RHS,
11440 SourceLocation Loc, BinaryOperatorKind Opc,
11441 QualType* CompLHSTy) {
11442 checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/false);
11443
11444 if (LHS.get()->getType()->isVectorType() ||
11445 RHS.get()->getType()->isVectorType()) {
11446 QualType compType =
11447 CheckVectorOperands(LHS, RHS, Loc, CompLHSTy,
11448 /*AllowBothBool*/ getLangOpts().AltiVec,
11449 /*AllowBoolConversions*/ getLangOpts().ZVector,
11450 /*AllowBooleanOperation*/ false,
11451 /*ReportInvalid*/ true);
11452 if (CompLHSTy) *CompLHSTy = compType;
11453 return compType;
11454 }
11455
11456 if (LHS.get()->getType()->isVLSTBuiltinType() ||
11457 RHS.get()->getType()->isVLSTBuiltinType()) {
11458 QualType compType =
11459 CheckSizelessVectorOperands(LHS, RHS, Loc, CompLHSTy, ACK_Arithmetic);
11460 if (CompLHSTy)
11461 *CompLHSTy = compType;
11462 return compType;
11463 }
11464
11465 if (LHS.get()->getType()->isConstantMatrixType() ||
11466 RHS.get()->getType()->isConstantMatrixType()) {
11467 QualType compType =
11468 CheckMatrixElementwiseOperands(LHS, RHS, Loc, CompLHSTy);
11469 if (CompLHSTy)
11470 *CompLHSTy = compType;
11471 return compType;
11472 }
11473
11474 QualType compType = UsualArithmeticConversions(
11475 LHS, RHS, Loc, CompLHSTy ? ACK_CompAssign : ACK_Arithmetic);
11476 if (LHS.isInvalid() || RHS.isInvalid())
11477 return QualType();
11478
11479 // Diagnose "string literal" '+' int and string '+' "char literal".
11480 if (Opc == BO_Add) {
11481 diagnoseStringPlusInt(*this, Loc, LHS.get(), RHS.get());
11482 diagnoseStringPlusChar(*this, Loc, LHS.get(), RHS.get());
11483 }
11484
11485 // handle the common case first (both operands are arithmetic).
11486 if (!compType.isNull() && compType->isArithmeticType()) {
11487 if (CompLHSTy) *CompLHSTy = compType;
11488 return compType;
11489 }
11490
11491 // Type-checking. Ultimately the pointer's going to be in PExp;
11492 // note that we bias towards the LHS being the pointer.
11493 Expr *PExp = LHS.get(), *IExp = RHS.get();
11494
11495 bool isObjCPointer;
11496 if (PExp->getType()->isPointerType()) {
11497 isObjCPointer = false;
11498 } else if (PExp->getType()->isObjCObjectPointerType()) {
11499 isObjCPointer = true;
11500 } else {
11501 std::swap(PExp, IExp);
11502 if (PExp->getType()->isPointerType()) {
11503 isObjCPointer = false;
11504 } else if (PExp->getType()->isObjCObjectPointerType()) {
11505 isObjCPointer = true;
11506 } else {
11507 return InvalidOperands(Loc, LHS, RHS);
11508 }
11509 }
11510 assert(PExp->getType()->isAnyPointerType())(static_cast <bool> (PExp->getType()->isAnyPointerType
()) ? void (0) : __assert_fail ("PExp->getType()->isAnyPointerType()"
, "clang/lib/Sema/SemaExpr.cpp", 11510, __extension__ __PRETTY_FUNCTION__
))
;
11511
11512 if (!IExp->getType()->isIntegerType())
11513 return InvalidOperands(Loc, LHS, RHS);
11514
11515 // Adding to a null pointer results in undefined behavior.
11516 if (PExp->IgnoreParenCasts()->isNullPointerConstant(
11517 Context, Expr::NPC_ValueDependentIsNotNull)) {
11518 // In C++ adding zero to a null pointer is defined.
11519 Expr::EvalResult KnownVal;
11520 if (!getLangOpts().CPlusPlus ||
11521 (!IExp->isValueDependent() &&
11522 (!IExp->EvaluateAsInt(KnownVal, Context) ||
11523 KnownVal.Val.getInt() != 0))) {
11524 // Check the conditions to see if this is the 'p = nullptr + n' idiom.
11525 bool IsGNUIdiom = BinaryOperator::isNullPointerArithmeticExtension(
11526 Context, BO_Add, PExp, IExp);
11527 diagnoseArithmeticOnNullPointer(*this, Loc, PExp, IsGNUIdiom);
11528 }
11529 }
11530
11531 if (!checkArithmeticOpPointerOperand(*this, Loc, PExp))
11532 return QualType();
11533
11534 if (isObjCPointer && checkArithmeticOnObjCPointer(*this, Loc, PExp))
11535 return QualType();
11536
11537 // Check array bounds for pointer arithemtic
11538 CheckArrayAccess(PExp, IExp);
11539
11540 if (CompLHSTy) {
11541 QualType LHSTy = Context.isPromotableBitField(LHS.get());
11542 if (LHSTy.isNull()) {
11543 LHSTy = LHS.get()->getType();
11544 if (Context.isPromotableIntegerType(LHSTy))
11545 LHSTy = Context.getPromotedIntegerType(LHSTy);
11546 }
11547 *CompLHSTy = LHSTy;
11548 }
11549
11550 return PExp->getType();
11551}
11552
11553// C99 6.5.6
11554QualType Sema::CheckSubtractionOperands(ExprResult &LHS, ExprResult &RHS,
11555 SourceLocation Loc,
11556 QualType* CompLHSTy) {
11557 checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/false);
11558
11559 if (LHS.get()->getType()->isVectorType() ||
11560 RHS.get()->getType()->isVectorType()) {
11561 QualType compType =
11562 CheckVectorOperands(LHS, RHS, Loc, CompLHSTy,
11563 /*AllowBothBool*/ getLangOpts().AltiVec,
11564 /*AllowBoolConversions*/ getLangOpts().ZVector,
11565 /*AllowBooleanOperation*/ false,
11566 /*ReportInvalid*/ true);
11567 if (CompLHSTy) *CompLHSTy = compType;
11568 return compType;
11569 }
11570
11571 if (LHS.get()->getType()->isVLSTBuiltinType() ||
11572 RHS.get()->getType()->isVLSTBuiltinType()) {
11573 QualType compType =
11574 CheckSizelessVectorOperands(LHS, RHS, Loc, CompLHSTy, ACK_Arithmetic);
11575 if (CompLHSTy)
11576 *CompLHSTy = compType;
11577 return compType;
11578 }
11579
11580 if (LHS.get()->getType()->isConstantMatrixType() ||
11581 RHS.get()->getType()->isConstantMatrixType()) {
11582 QualType compType =
11583 CheckMatrixElementwiseOperands(LHS, RHS, Loc, CompLHSTy);
11584 if (CompLHSTy)
11585 *CompLHSTy = compType;
11586 return compType;
11587 }
11588
11589 QualType compType = UsualArithmeticConversions(
11590 LHS, RHS, Loc, CompLHSTy ? ACK_CompAssign : ACK_Arithmetic);
11591 if (LHS.isInvalid() || RHS.isInvalid())
11592 return QualType();
11593
11594 // Enforce type constraints: C99 6.5.6p3.
11595
11596 // Handle the common case first (both operands are arithmetic).
11597 if (!compType.isNull() && compType->isArithmeticType()) {
11598 if (CompLHSTy) *CompLHSTy = compType;
11599 return compType;
11600 }
11601
11602 // Either ptr - int or ptr - ptr.
11603 if (LHS.get()->getType()->isAnyPointerType()) {
11604 QualType lpointee = LHS.get()->getType()->getPointeeType();
11605
11606 // Diagnose bad cases where we step over interface counts.
11607 if (LHS.get()->getType()->isObjCObjectPointerType() &&
11608 checkArithmeticOnObjCPointer(*this, Loc, LHS.get()))
11609 return QualType();
11610
11611 // The result type of a pointer-int computation is the pointer type.
11612 if (RHS.get()->getType()->isIntegerType()) {
11613 // Subtracting from a null pointer should produce a warning.
11614 // The last argument to the diagnose call says this doesn't match the
11615 // GNU int-to-pointer idiom.
11616 if (LHS.get()->IgnoreParenCasts()->isNullPointerConstant(Context,
11617 Expr::NPC_ValueDependentIsNotNull)) {
11618 // In C++ adding zero to a null pointer is defined.
11619 Expr::EvalResult KnownVal;
11620 if (!getLangOpts().CPlusPlus ||
11621 (!RHS.get()->isValueDependent() &&
11622 (!RHS.get()->EvaluateAsInt(KnownVal, Context) ||
11623 KnownVal.Val.getInt() != 0))) {
11624 diagnoseArithmeticOnNullPointer(*this, Loc, LHS.get(), false);
11625 }
11626 }
11627
11628 if (!checkArithmeticOpPointerOperand(*this, Loc, LHS.get()))
11629 return QualType();
11630
11631 // Check array bounds for pointer arithemtic
11632 CheckArrayAccess(LHS.get(), RHS.get(), /*ArraySubscriptExpr*/nullptr,
11633 /*AllowOnePastEnd*/true, /*IndexNegated*/true);
11634
11635 if (CompLHSTy) *CompLHSTy = LHS.get()->getType();
11636 return LHS.get()->getType();
11637 }
11638
11639 // Handle pointer-pointer subtractions.
11640 if (const PointerType *RHSPTy
11641 = RHS.get()->getType()->getAs<PointerType>()) {
11642 QualType rpointee = RHSPTy->getPointeeType();
11643
11644 if (getLangOpts().CPlusPlus) {
11645 // Pointee types must be the same: C++ [expr.add]
11646 if (!Context.hasSameUnqualifiedType(lpointee, rpointee)) {
11647 diagnosePointerIncompatibility(*this, Loc, LHS.get(), RHS.get());
11648 }
11649 } else {
11650 // Pointee types must be compatible C99 6.5.6p3
11651 if (!Context.typesAreCompatible(
11652 Context.getCanonicalType(lpointee).getUnqualifiedType(),
11653 Context.getCanonicalType(rpointee).getUnqualifiedType())) {
11654 diagnosePointerIncompatibility(*this, Loc, LHS.get(), RHS.get());
11655 return QualType();
11656 }
11657 }
11658
11659 if (!checkArithmeticBinOpPointerOperands(*this, Loc,
11660 LHS.get(), RHS.get()))
11661 return QualType();
11662
11663 bool LHSIsNullPtr = LHS.get()->IgnoreParenCasts()->isNullPointerConstant(
11664 Context, Expr::NPC_ValueDependentIsNotNull);
11665 bool RHSIsNullPtr = RHS.get()->IgnoreParenCasts()->isNullPointerConstant(
11666 Context, Expr::NPC_ValueDependentIsNotNull);
11667
11668 // Subtracting nullptr or from nullptr is suspect
11669 if (LHSIsNullPtr)
11670 diagnoseSubtractionOnNullPointer(*this, Loc, LHS.get(), RHSIsNullPtr);
11671 if (RHSIsNullPtr)
11672 diagnoseSubtractionOnNullPointer(*this, Loc, RHS.get(), LHSIsNullPtr);
11673
11674 // The pointee type may have zero size. As an extension, a structure or
11675 // union may have zero size or an array may have zero length. In this
11676 // case subtraction does not make sense.
11677 if (!rpointee->isVoidType() && !rpointee->isFunctionType()) {
11678 CharUnits ElementSize = Context.getTypeSizeInChars(rpointee);
11679 if (ElementSize.isZero()) {
11680 Diag(Loc,diag::warn_sub_ptr_zero_size_types)
11681 << rpointee.getUnqualifiedType()
11682 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
11683 }
11684 }
11685
11686 if (CompLHSTy) *CompLHSTy = LHS.get()->getType();
11687 return Context.getPointerDiffType();
11688 }
11689 }
11690
11691 return InvalidOperands(Loc, LHS, RHS);
11692}
11693
11694static bool isScopedEnumerationType(QualType T) {
11695 if (const EnumType *ET = T->getAs<EnumType>())
11696 return ET->getDecl()->isScoped();
11697 return false;
11698}
11699
11700static void DiagnoseBadShiftValues(Sema& S, ExprResult &LHS, ExprResult &RHS,
11701 SourceLocation Loc, BinaryOperatorKind Opc,
11702 QualType LHSType) {
11703 // OpenCL 6.3j: shift values are effectively % word size of LHS (more defined),
11704 // so skip remaining warnings as we don't want to modify values within Sema.
11705 if (S.getLangOpts().OpenCL)
11706 return;
11707
11708 // Check right/shifter operand
11709 Expr::EvalResult RHSResult;
11710 if (RHS.get()->isValueDependent() ||
11711 !RHS.get()->EvaluateAsInt(RHSResult, S.Context))
11712 return;
11713 llvm::APSInt Right = RHSResult.Val.getInt();
11714
11715 if (Right.isNegative()) {
11716 S.DiagRuntimeBehavior(Loc, RHS.get(),
11717 S.PDiag(diag::warn_shift_negative)
11718 << RHS.get()->getSourceRange());
11719 return;
11720 }
11721
11722 QualType LHSExprType = LHS.get()->getType();
11723 uint64_t LeftSize = S.Context.getTypeSize(LHSExprType);
11724 if (LHSExprType->isBitIntType())
11725 LeftSize = S.Context.getIntWidth(LHSExprType);
11726 else if (LHSExprType->isFixedPointType()) {
11727 auto FXSema = S.Context.getFixedPointSemantics(LHSExprType);
11728 LeftSize = FXSema.getWidth() - (unsigned)FXSema.hasUnsignedPadding();
11729 }
11730 llvm::APInt LeftBits(Right.getBitWidth(), LeftSize);
11731 if (Right.uge(LeftBits)) {
11732 S.DiagRuntimeBehavior(Loc, RHS.get(),
11733 S.PDiag(diag::warn_shift_gt_typewidth)
11734 << RHS.get()->getSourceRange());
11735 return;
11736 }
11737
11738 // FIXME: We probably need to handle fixed point types specially here.
11739 if (Opc != BO_Shl || LHSExprType->isFixedPointType())
11740 return;
11741
11742 // When left shifting an ICE which is signed, we can check for overflow which
11743 // according to C++ standards prior to C++2a has undefined behavior
11744 // ([expr.shift] 5.8/2). Unsigned integers have defined behavior modulo one
11745 // more than the maximum value representable in the result type, so never
11746 // warn for those. (FIXME: Unsigned left-shift overflow in a constant
11747 // expression is still probably a bug.)
11748 Expr::EvalResult LHSResult;
11749 if (LHS.get()->isValueDependent() ||
11750 LHSType->hasUnsignedIntegerRepresentation() ||
11751 !LHS.get()->EvaluateAsInt(LHSResult, S.Context))
11752 return;
11753 llvm::APSInt Left = LHSResult.Val.getInt();
11754
11755 // Don't warn if signed overflow is defined, then all the rest of the
11756 // diagnostics will not be triggered because the behavior is defined.
11757 // Also don't warn in C++20 mode (and newer), as signed left shifts
11758 // always wrap and never overflow.
11759 if (S.getLangOpts().isSignedOverflowDefined() || S.getLangOpts().CPlusPlus20)
11760 return;
11761
11762 // If LHS does not have a non-negative value then, the
11763 // behavior is undefined before C++2a. Warn about it.
11764 if (Left.isNegative()) {
11765 S.DiagRuntimeBehavior(Loc, LHS.get(),
11766 S.PDiag(diag::warn_shift_lhs_negative)
11767 << LHS.get()->getSourceRange());
11768 return;
11769 }
11770
11771 llvm::APInt ResultBits =
11772 static_cast<llvm::APInt &>(Right) + Left.getSignificantBits();
11773 if (LeftBits.uge(ResultBits))
11774 return;
11775 llvm::APSInt Result = Left.extend(ResultBits.getLimitedValue());
11776 Result = Result.shl(Right);
11777
11778 // Print the bit representation of the signed integer as an unsigned
11779 // hexadecimal number.
11780 SmallString<40> HexResult;
11781 Result.toString(HexResult, 16, /*Signed =*/false, /*Literal =*/true);
11782
11783 // If we are only missing a sign bit, this is less likely to result in actual
11784 // bugs -- if the result is cast back to an unsigned type, it will have the
11785 // expected value. Thus we place this behind a different warning that can be
11786 // turned off separately if needed.
11787 if (LeftBits == ResultBits - 1) {
11788 S.Diag(Loc, diag::warn_shift_result_sets_sign_bit)
11789 << HexResult << LHSType
11790 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
11791 return;
11792 }
11793
11794 S.Diag(Loc, diag::warn_shift_result_gt_typewidth)
11795 << HexResult.str() << Result.getSignificantBits() << LHSType
11796 << Left.getBitWidth() << LHS.get()->getSourceRange()
11797 << RHS.get()->getSourceRange();
11798}
11799
11800/// Return the resulting type when a vector is shifted
11801/// by a scalar or vector shift amount.
11802static QualType checkVectorShift(Sema &S, ExprResult &LHS, ExprResult &RHS,
11803 SourceLocation Loc, bool IsCompAssign) {
11804 // OpenCL v1.1 s6.3.j says RHS can be a vector only if LHS is a vector.
11805 if ((S.LangOpts.OpenCL || S.LangOpts.ZVector) &&
11806 !LHS.get()->getType()->isVectorType()) {
11807 S.Diag(Loc, diag::err_shift_rhs_only_vector)
11808 << RHS.get()->getType() << LHS.get()->getType()
11809 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
11810 return QualType();
11811 }
11812
11813 if (!IsCompAssign) {
11814 LHS = S.UsualUnaryConversions(LHS.get());
11815 if (LHS.isInvalid()) return QualType();
11816 }
11817
11818 RHS = S.UsualUnaryConversions(RHS.get());
11819 if (RHS.isInvalid()) return QualType();
11820
11821 QualType LHSType = LHS.get()->getType();
11822 // Note that LHS might be a scalar because the routine calls not only in
11823 // OpenCL case.
11824 const VectorType *LHSVecTy = LHSType->getAs<VectorType>();
11825 QualType LHSEleType = LHSVecTy ? LHSVecTy->getElementType() : LHSType;
11826
11827 // Note that RHS might not be a vector.
11828 QualType RHSType = RHS.get()->getType();
11829 const VectorType *RHSVecTy = RHSType->getAs<VectorType>();
11830 QualType RHSEleType = RHSVecTy ? RHSVecTy->getElementType() : RHSType;
11831
11832 // Do not allow shifts for boolean vectors.
11833 if ((LHSVecTy && LHSVecTy->isExtVectorBoolType()) ||
11834 (RHSVecTy && RHSVecTy->isExtVectorBoolType())) {
11835 S.Diag(Loc, diag::err_typecheck_invalid_operands)
11836 << LHS.get()->getType() << RHS.get()->getType()
11837 << LHS.get()->getSourceRange();
11838 return QualType();
11839 }
11840
11841 // The operands need to be integers.
11842 if (!LHSEleType->isIntegerType()) {
11843 S.Diag(Loc, diag::err_typecheck_expect_int)
11844 << LHS.get()->getType() << LHS.get()->getSourceRange();
11845 return QualType();
11846 }
11847
11848 if (!RHSEleType->isIntegerType()) {
11849 S.Diag(Loc, diag::err_typecheck_expect_int)
11850 << RHS.get()->getType() << RHS.get()->getSourceRange();
11851 return QualType();
11852 }
11853
11854 if (!LHSVecTy) {
11855 assert(RHSVecTy)(static_cast <bool> (RHSVecTy) ? void (0) : __assert_fail
("RHSVecTy", "clang/lib/Sema/SemaExpr.cpp", 11855, __extension__
__PRETTY_FUNCTION__))
;
11856 if (IsCompAssign)
11857 return RHSType;
11858 if (LHSEleType != RHSEleType) {
11859 LHS = S.ImpCastExprToType(LHS.get(),RHSEleType, CK_IntegralCast);
11860 LHSEleType = RHSEleType;
11861 }
11862 QualType VecTy =
11863 S.Context.getExtVectorType(LHSEleType, RHSVecTy->getNumElements());
11864 LHS = S.ImpCastExprToType(LHS.get(), VecTy, CK_VectorSplat);
11865 LHSType = VecTy;
11866 } else if (RHSVecTy) {
11867 // OpenCL v1.1 s6.3.j says that for vector types, the operators
11868 // are applied component-wise. So if RHS is a vector, then ensure
11869 // that the number of elements is the same as LHS...
11870 if (RHSVecTy->getNumElements() != LHSVecTy->getNumElements()) {
11871 S.Diag(Loc, diag::err_typecheck_vector_lengths_not_equal)
11872 << LHS.get()->getType() << RHS.get()->getType()
11873 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
11874 return QualType();
11875 }
11876 if (!S.LangOpts.OpenCL && !S.LangOpts.ZVector) {
11877 const BuiltinType *LHSBT = LHSEleType->getAs<clang::BuiltinType>();
11878 const BuiltinType *RHSBT = RHSEleType->getAs<clang::BuiltinType>();
11879 if (LHSBT != RHSBT &&
11880 S.Context.getTypeSize(LHSBT) != S.Context.getTypeSize(RHSBT)) {
11881 S.Diag(Loc, diag::warn_typecheck_vector_element_sizes_not_equal)
11882 << LHS.get()->getType() << RHS.get()->getType()
11883 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
11884 }
11885 }
11886 } else {
11887 // ...else expand RHS to match the number of elements in LHS.
11888 QualType VecTy =
11889 S.Context.getExtVectorType(RHSEleType, LHSVecTy->getNumElements());
11890 RHS = S.ImpCastExprToType(RHS.get(), VecTy, CK_VectorSplat);
11891 }
11892
11893 return LHSType;
11894}
11895
11896static QualType checkSizelessVectorShift(Sema &S, ExprResult &LHS,
11897 ExprResult &RHS, SourceLocation Loc,
11898 bool IsCompAssign) {
11899 if (!IsCompAssign) {
11900 LHS = S.UsualUnaryConversions(LHS.get());
11901 if (LHS.isInvalid())
11902 return QualType();
11903 }
11904
11905 RHS = S.UsualUnaryConversions(RHS.get());
11906 if (RHS.isInvalid())
11907 return QualType();
11908
11909 QualType LHSType = LHS.get()->getType();
11910 const BuiltinType *LHSBuiltinTy = LHSType->getAs<BuiltinType>();
11911 QualType LHSEleType = LHSType->isVLSTBuiltinType()
11912 ? LHSBuiltinTy->getSveEltType(S.getASTContext())
11913 : LHSType;
11914
11915 // Note that RHS might not be a vector
11916 QualType RHSType = RHS.get()->getType();
11917 const BuiltinType *RHSBuiltinTy = RHSType->getAs<BuiltinType>();
11918 QualType RHSEleType = RHSType->isVLSTBuiltinType()
11919 ? RHSBuiltinTy->getSveEltType(S.getASTContext())
11920 : RHSType;
11921
11922 if ((LHSBuiltinTy && LHSBuiltinTy->isSVEBool()) ||
11923 (RHSBuiltinTy && RHSBuiltinTy->isSVEBool())) {
11924 S.Diag(Loc, diag::err_typecheck_invalid_operands)
11925 << LHSType << RHSType << LHS.get()->getSourceRange();
11926 return QualType();
11927 }
11928
11929 if (!LHSEleType->isIntegerType()) {
11930 S.Diag(Loc, diag::err_typecheck_expect_int)
11931 << LHS.get()->getType() << LHS.get()->getSourceRange();
11932 return QualType();
11933 }
11934
11935 if (!RHSEleType->isIntegerType()) {
11936 S.Diag(Loc, diag::err_typecheck_expect_int)
11937 << RHS.get()->getType() << RHS.get()->getSourceRange();
11938 return QualType();
11939 }
11940
11941 if (LHSType->isVLSTBuiltinType() && RHSType->isVLSTBuiltinType() &&
11942 (S.Context.getBuiltinVectorTypeInfo(LHSBuiltinTy).EC !=
11943 S.Context.getBuiltinVectorTypeInfo(RHSBuiltinTy).EC)) {
11944 S.Diag(Loc, diag::err_typecheck_invalid_operands)
11945 << LHSType << RHSType << LHS.get()->getSourceRange()
11946 << RHS.get()->getSourceRange();
11947 return QualType();
11948 }
11949
11950 if (!LHSType->isVLSTBuiltinType()) {
11951 assert(RHSType->isVLSTBuiltinType())(static_cast <bool> (RHSType->isVLSTBuiltinType()) ?
void (0) : __assert_fail ("RHSType->isVLSTBuiltinType()",
"clang/lib/Sema/SemaExpr.cpp", 11951, __extension__ __PRETTY_FUNCTION__
))
;
11952 if (IsCompAssign)
11953 return RHSType;
11954 if (LHSEleType != RHSEleType) {
11955 LHS = S.ImpCastExprToType(LHS.get(), RHSEleType, clang::CK_IntegralCast);
11956 LHSEleType = RHSEleType;
11957 }
11958 const llvm::ElementCount VecSize =
11959 S.Context.getBuiltinVectorTypeInfo(RHSBuiltinTy).EC;
11960 QualType VecTy =
11961 S.Context.getScalableVectorType(LHSEleType, VecSize.getKnownMinValue());
11962 LHS = S.ImpCastExprToType(LHS.get(), VecTy, clang::CK_VectorSplat);
11963 LHSType = VecTy;
11964 } else if (RHSBuiltinTy && RHSBuiltinTy->isVLSTBuiltinType()) {
11965 if (S.Context.getTypeSize(RHSBuiltinTy) !=
11966 S.Context.getTypeSize(LHSBuiltinTy)) {
11967 S.Diag(Loc, diag::err_typecheck_vector_lengths_not_equal)
11968 << LHSType << RHSType << LHS.get()->getSourceRange()
11969 << RHS.get()->getSourceRange();
11970 return QualType();
11971 }
11972 } else {
11973 const llvm::ElementCount VecSize =
11974 S.Context.getBuiltinVectorTypeInfo(LHSBuiltinTy).EC;
11975 if (LHSEleType != RHSEleType) {
11976 RHS = S.ImpCastExprToType(RHS.get(), LHSEleType, clang::CK_IntegralCast);
11977 RHSEleType = LHSEleType;
11978 }
11979 QualType VecTy =
11980 S.Context.getScalableVectorType(RHSEleType, VecSize.getKnownMinValue());
11981 RHS = S.ImpCastExprToType(RHS.get(), VecTy, CK_VectorSplat);
11982 }
11983
11984 return LHSType;
11985}
11986
11987// C99 6.5.7
11988QualType Sema::CheckShiftOperands(ExprResult &LHS, ExprResult &RHS,
11989 SourceLocation Loc, BinaryOperatorKind Opc,
11990 bool IsCompAssign) {
11991 checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/false);
11992
11993 // Vector shifts promote their scalar inputs to vector type.
11994 if (LHS.get()->getType()->isVectorType() ||
11995 RHS.get()->getType()->isVectorType()) {
11996 if (LangOpts.ZVector) {
11997 // The shift operators for the z vector extensions work basically
11998 // like general shifts, except that neither the LHS nor the RHS is
11999 // allowed to be a "vector bool".
12000 if (auto LHSVecType = LHS.get()->getType()->getAs<VectorType>())
12001 if (LHSVecType->getVectorKind() == VectorType::AltiVecBool)
12002 return InvalidOperands(Loc, LHS, RHS);
12003 if (auto RHSVecType = RHS.get()->getType()->getAs<VectorType>())
12004 if (RHSVecType->getVectorKind() == VectorType::AltiVecBool)
12005 return InvalidOperands(Loc, LHS, RHS);
12006 }
12007 return checkVectorShift(*this, LHS, RHS, Loc, IsCompAssign);
12008 }
12009
12010 if (LHS.get()->getType()->isVLSTBuiltinType() ||
12011 RHS.get()->getType()->isVLSTBuiltinType())
12012 return checkSizelessVectorShift(*this, LHS, RHS, Loc, IsCompAssign);
12013
12014 // Shifts don't perform usual arithmetic conversions, they just do integer
12015 // promotions on each operand. C99 6.5.7p3
12016
12017 // For the LHS, do usual unary conversions, but then reset them away
12018 // if this is a compound assignment.
12019 ExprResult OldLHS = LHS;
12020 LHS = UsualUnaryConversions(LHS.get());
12021 if (LHS.isInvalid())
12022 return QualType();
12023 QualType LHSType = LHS.get()->getType();
12024 if (IsCompAssign) LHS = OldLHS;
12025
12026 // The RHS is simpler.
12027 RHS = UsualUnaryConversions(RHS.get());
12028 if (RHS.isInvalid())
12029 return QualType();
12030 QualType RHSType = RHS.get()->getType();
12031
12032 // C99 6.5.7p2: Each of the operands shall have integer type.
12033 // Embedded-C 4.1.6.2.2: The LHS may also be fixed-point.
12034 if ((!LHSType->isFixedPointOrIntegerType() &&
12035 !LHSType->hasIntegerRepresentation()) ||
12036 !RHSType->hasIntegerRepresentation())
12037 return InvalidOperands(Loc, LHS, RHS);
12038
12039 // C++0x: Don't allow scoped enums. FIXME: Use something better than
12040 // hasIntegerRepresentation() above instead of this.
12041 if (isScopedEnumerationType(LHSType) ||
12042 isScopedEnumerationType(RHSType)) {
12043 return InvalidOperands(Loc, LHS, RHS);
12044 }
12045 DiagnoseBadShiftValues(*this, LHS, RHS, Loc, Opc, LHSType);
12046
12047 // "The type of the result is that of the promoted left operand."
12048 return LHSType;
12049}
12050
12051/// Diagnose bad pointer comparisons.
12052static void diagnoseDistinctPointerComparison(Sema &S, SourceLocation Loc,
12053 ExprResult &LHS, ExprResult &RHS,
12054 bool IsError) {
12055 S.Diag(Loc, IsError ? diag::err_typecheck_comparison_of_distinct_pointers
12056 : diag::ext_typecheck_comparison_of_distinct_pointers)
12057 << LHS.get()->getType() << RHS.get()->getType()
12058 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
12059}
12060
12061/// Returns false if the pointers are converted to a composite type,
12062/// true otherwise.
12063static bool convertPointersToCompositeType(Sema &S, SourceLocation Loc,
12064 ExprResult &LHS, ExprResult &RHS) {
12065 // C++ [expr.rel]p2:
12066 // [...] Pointer conversions (4.10) and qualification
12067 // conversions (4.4) are performed on pointer operands (or on
12068 // a pointer operand and a null pointer constant) to bring
12069 // them to their composite pointer type. [...]
12070 //
12071 // C++ [expr.eq]p1 uses the same notion for (in)equality
12072 // comparisons of pointers.
12073
12074 QualType LHSType = LHS.get()->getType();
12075 QualType RHSType = RHS.get()->getType();
12076 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", 12077, __extension__ __PRETTY_FUNCTION__
))
12077 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", 12077, __extension__ __PRETTY_FUNCTION__
))
;
12078
12079 QualType T = S.FindCompositePointerType(Loc, LHS, RHS);
12080 if (T.isNull()) {
12081 if ((LHSType->isAnyPointerType() || LHSType->isMemberPointerType()) &&
12082 (RHSType->isAnyPointerType() || RHSType->isMemberPointerType()))
12083 diagnoseDistinctPointerComparison(S, Loc, LHS, RHS, /*isError*/true);
12084 else
12085 S.InvalidOperands(Loc, LHS, RHS);
12086 return true;
12087 }
12088
12089 return false;
12090}
12091
12092static void diagnoseFunctionPointerToVoidComparison(Sema &S, SourceLocation Loc,
12093 ExprResult &LHS,
12094 ExprResult &RHS,
12095 bool IsError) {
12096 S.Diag(Loc, IsError ? diag::err_typecheck_comparison_of_fptr_to_void
12097 : diag::ext_typecheck_comparison_of_fptr_to_void)
12098 << LHS.get()->getType() << RHS.get()->getType()
12099 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
12100}
12101
12102static bool isObjCObjectLiteral(ExprResult &E) {
12103 switch (E.get()->IgnoreParenImpCasts()->getStmtClass()) {
12104 case Stmt::ObjCArrayLiteralClass:
12105 case Stmt::ObjCDictionaryLiteralClass:
12106 case Stmt::ObjCStringLiteralClass:
12107 case Stmt::ObjCBoxedExprClass:
12108 return true;
12109 default:
12110 // Note that ObjCBoolLiteral is NOT an object literal!
12111 return false;
12112 }
12113}
12114
12115static bool hasIsEqualMethod(Sema &S, const Expr *LHS, const Expr *RHS) {
12116 const ObjCObjectPointerType *Type =
12117 LHS->getType()->getAs<ObjCObjectPointerType>();
12118
12119 // If this is not actually an Objective-C object, bail out.
12120 if (!Type)
12121 return false;
12122
12123 // Get the LHS object's interface type.
12124 QualType InterfaceType = Type->getPointeeType();
12125
12126 // If the RHS isn't an Objective-C object, bail out.
12127 if (!RHS->getType()->isObjCObjectPointerType())
12128 return false;
12129
12130 // Try to find the -isEqual: method.
12131 Selector IsEqualSel = S.NSAPIObj->getIsEqualSelector();
12132 ObjCMethodDecl *Method = S.LookupMethodInObjectType(IsEqualSel,
12133 InterfaceType,
12134 /*IsInstance=*/true);
12135 if (!Method) {
12136 if (Type->isObjCIdType()) {
12137 // For 'id', just check the global pool.
12138 Method = S.LookupInstanceMethodInGlobalPool(IsEqualSel, SourceRange(),
12139 /*receiverId=*/true);
12140 } else {
12141 // Check protocols.
12142 Method = S.LookupMethodInQualifiedType(IsEqualSel, Type,
12143 /*IsInstance=*/true);
12144 }
12145 }
12146
12147 if (!Method)
12148 return false;
12149
12150 QualType T = Method->parameters()[0]->getType();
12151 if (!T->isObjCObjectPointerType())
12152 return false;
12153
12154 QualType R = Method->getReturnType();
12155 if (!R->isScalarType())
12156 return false;
12157
12158 return true;
12159}
12160
12161Sema::ObjCLiteralKind Sema::CheckLiteralKind(Expr *FromE) {
12162 FromE = FromE->IgnoreParenImpCasts();
12163 switch (FromE->getStmtClass()) {
12164 default:
12165 break;
12166 case Stmt::ObjCStringLiteralClass:
12167 // "string literal"
12168 return LK_String;
12169 case Stmt::ObjCArrayLiteralClass:
12170 // "array literal"
12171 return LK_Array;
12172 case Stmt::ObjCDictionaryLiteralClass:
12173 // "dictionary literal"
12174 return LK_Dictionary;
12175 case Stmt::BlockExprClass:
12176 return LK_Block;
12177 case Stmt::ObjCBoxedExprClass: {
12178 Expr *Inner = cast<ObjCBoxedExpr>(FromE)->getSubExpr()->IgnoreParens();
12179 switch (Inner->getStmtClass()) {
12180 case Stmt::IntegerLiteralClass:
12181 case Stmt::FloatingLiteralClass:
12182 case Stmt::CharacterLiteralClass:
12183 case Stmt::ObjCBoolLiteralExprClass:
12184 case Stmt::CXXBoolLiteralExprClass:
12185 // "numeric literal"
12186 return LK_Numeric;
12187 case Stmt::ImplicitCastExprClass: {
12188 CastKind CK = cast<CastExpr>(Inner)->getCastKind();
12189 // Boolean literals can be represented by implicit casts.
12190 if (CK == CK_IntegralToBoolean || CK == CK_IntegralCast)
12191 return LK_Numeric;
12192 break;
12193 }
12194 default:
12195 break;
12196 }
12197 return LK_Boxed;
12198 }
12199 }
12200 return LK_None;
12201}
12202
12203static void diagnoseObjCLiteralComparison(Sema &S, SourceLocation Loc,
12204 ExprResult &LHS, ExprResult &RHS,
12205 BinaryOperator::Opcode Opc){
12206 Expr *Literal;
12207 Expr *Other;
12208 if (isObjCObjectLiteral(LHS)) {
12209 Literal = LHS.get();
12210 Other = RHS.get();
12211 } else {
12212 Literal = RHS.get();
12213 Other = LHS.get();
12214 }
12215
12216 // Don't warn on comparisons against nil.
12217 Other = Other->IgnoreParenCasts();
12218 if (Other->isNullPointerConstant(S.getASTContext(),
12219 Expr::NPC_ValueDependentIsNotNull))
12220 return;
12221
12222 // This should be kept in sync with warn_objc_literal_comparison.
12223 // LK_String should always be after the other literals, since it has its own
12224 // warning flag.
12225 Sema::ObjCLiteralKind LiteralKind = S.CheckLiteralKind(Literal);
12226 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"
, 12226, __extension__ __PRETTY_FUNCTION__))
;
12227 if (LiteralKind == Sema::LK_None) {
12228 llvm_unreachable("Unknown Objective-C object literal kind")::llvm::llvm_unreachable_internal("Unknown Objective-C object literal kind"
, "clang/lib/Sema/SemaExpr.cpp", 12228)
;
12229 }
12230
12231 if (LiteralKind == Sema::LK_String)
12232 S.Diag(Loc, diag::warn_objc_string_literal_comparison)
12233 << Literal->getSourceRange();
12234 else
12235 S.Diag(Loc, diag::warn_objc_literal_comparison)
12236 << LiteralKind << Literal->getSourceRange();
12237
12238 if (BinaryOperator::isEqualityOp(Opc) &&
12239 hasIsEqualMethod(S, LHS.get(), RHS.get())) {
12240 SourceLocation Start = LHS.get()->getBeginLoc();
12241 SourceLocation End = S.getLocForEndOfToken(RHS.get()->getEndLoc());
12242 CharSourceRange OpRange =
12243 CharSourceRange::getCharRange(Loc, S.getLocForEndOfToken(Loc));
12244
12245 S.Diag(Loc, diag::note_objc_literal_comparison_isequal)
12246 << FixItHint::CreateInsertion(Start, Opc == BO_EQ ? "[" : "![")
12247 << FixItHint::CreateReplacement(OpRange, " isEqual:")
12248 << FixItHint::CreateInsertion(End, "]");
12249 }
12250}
12251
12252/// Warns on !x < y, !x & y where !(x < y), !(x & y) was probably intended.
12253static void diagnoseLogicalNotOnLHSofCheck(Sema &S, ExprResult &LHS,
12254 ExprResult &RHS, SourceLocation Loc,
12255 BinaryOperatorKind Opc) {
12256 // Check that left hand side is !something.
12257 UnaryOperator *UO = dyn_cast<UnaryOperator>(LHS.get()->IgnoreImpCasts());
12258 if (!UO || UO->getOpcode() != UO_LNot) return;
12259
12260 // Only check if the right hand side is non-bool arithmetic type.
12261 if (RHS.get()->isKnownToHaveBooleanValue()) return;
12262
12263 // Make sure that the something in !something is not bool.
12264 Expr *SubExpr = UO->getSubExpr()->IgnoreImpCasts();
12265 if (SubExpr->isKnownToHaveBooleanValue()) return;
12266
12267 // Emit warning.
12268 bool IsBitwiseOp = Opc == BO_And || Opc == BO_Or || Opc == BO_Xor;
12269 S.Diag(UO->getOperatorLoc(), diag::warn_logical_not_on_lhs_of_check)
12270 << Loc << IsBitwiseOp;
12271
12272 // First note suggest !(x < y)
12273 SourceLocation FirstOpen = SubExpr->getBeginLoc();
12274 SourceLocation FirstClose = RHS.get()->getEndLoc();
12275 FirstClose = S.getLocForEndOfToken(FirstClose);
12276 if (FirstClose.isInvalid())
12277 FirstOpen = SourceLocation();
12278 S.Diag(UO->getOperatorLoc(), diag::note_logical_not_fix)
12279 << IsBitwiseOp
12280 << FixItHint::CreateInsertion(FirstOpen, "(")
12281 << FixItHint::CreateInsertion(FirstClose, ")");
12282
12283 // Second note suggests (!x) < y
12284 SourceLocation SecondOpen = LHS.get()->getBeginLoc();
12285 SourceLocation SecondClose = LHS.get()->getEndLoc();
12286 SecondClose = S.getLocForEndOfToken(SecondClose);
12287 if (SecondClose.isInvalid())
12288 SecondOpen = SourceLocation();
12289 S.Diag(UO->getOperatorLoc(), diag::note_logical_not_silence_with_parens)
12290 << FixItHint::CreateInsertion(SecondOpen, "(")
12291 << FixItHint::CreateInsertion(SecondClose, ")");
12292}
12293
12294// Returns true if E refers to a non-weak array.
12295static bool checkForArray(const Expr *E) {
12296 const ValueDecl *D = nullptr;
12297 if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(E)) {
12298 D = DR->getDecl();
12299 } else if (const MemberExpr *Mem = dyn_cast<MemberExpr>(E)) {
12300 if (Mem->isImplicitAccess())
12301 D = Mem->getMemberDecl();
12302 }
12303 if (!D)
12304 return false;
12305 return D->getType()->isArrayType() && !D->isWeak();
12306}
12307
12308/// Diagnose some forms of syntactically-obvious tautological comparison.
12309static void diagnoseTautologicalComparison(Sema &S, SourceLocation Loc,
12310 Expr *LHS, Expr *RHS,
12311 BinaryOperatorKind Opc) {
12312 Expr *LHSStripped = LHS->IgnoreParenImpCasts();
12313 Expr *RHSStripped = RHS->IgnoreParenImpCasts();
12314
12315 QualType LHSType = LHS->getType();
12316 QualType RHSType = RHS->getType();
12317 if (LHSType->hasFloatingRepresentation() ||
12318 (LHSType->isBlockPointerType() && !BinaryOperator::isEqualityOp(Opc)) ||
12319 S.inTemplateInstantiation())
12320 return;
12321
12322 // Comparisons between two array types are ill-formed for operator<=>, so
12323 // we shouldn't emit any additional warnings about it.
12324 if (Opc == BO_Cmp && LHSType->isArrayType() && RHSType->isArrayType())
12325 return;
12326
12327 // For non-floating point types, check for self-comparisons of the form
12328 // x == x, x != x, x < x, etc. These always evaluate to a constant, and
12329 // often indicate logic errors in the program.
12330 //
12331 // NOTE: Don't warn about comparison expressions resulting from macro
12332 // expansion. Also don't warn about comparisons which are only self
12333 // comparisons within a template instantiation. The warnings should catch
12334 // obvious cases in the definition of the template anyways. The idea is to
12335 // warn when the typed comparison operator will always evaluate to the same
12336 // result.
12337
12338 // Used for indexing into %select in warn_comparison_always
12339 enum {
12340 AlwaysConstant,
12341 AlwaysTrue,
12342 AlwaysFalse,
12343 AlwaysEqual, // std::strong_ordering::equal from operator<=>
12344 };
12345
12346 // C++2a [depr.array.comp]:
12347 // Equality and relational comparisons ([expr.eq], [expr.rel]) between two
12348 // operands of array type are deprecated.
12349 if (S.getLangOpts().CPlusPlus20 && LHSStripped->getType()->isArrayType() &&
12350 RHSStripped->getType()->isArrayType()) {
12351 S.Diag(Loc, diag::warn_depr_array_comparison)
12352 << LHS->getSourceRange() << RHS->getSourceRange()
12353 << LHSStripped->getType() << RHSStripped->getType();
12354 // Carry on to produce the tautological comparison warning, if this
12355 // expression is potentially-evaluated, we can resolve the array to a
12356 // non-weak declaration, and so on.
12357 }
12358
12359 if (!LHS->getBeginLoc().isMacroID() && !RHS->getBeginLoc().isMacroID()) {
12360 if (Expr::isSameComparisonOperand(LHS, RHS)) {
12361 unsigned Result;
12362 switch (Opc) {
12363 case BO_EQ:
12364 case BO_LE:
12365 case BO_GE:
12366 Result = AlwaysTrue;
12367 break;
12368 case BO_NE:
12369 case BO_LT:
12370 case BO_GT:
12371 Result = AlwaysFalse;
12372 break;
12373 case BO_Cmp:
12374 Result = AlwaysEqual;
12375 break;
12376 default:
12377 Result = AlwaysConstant;
12378 break;
12379 }
12380 S.DiagRuntimeBehavior(Loc, nullptr,
12381 S.PDiag(diag::warn_comparison_always)
12382 << 0 /*self-comparison*/
12383 << Result);
12384 } else if (checkForArray(LHSStripped) && checkForArray(RHSStripped)) {
12385 // What is it always going to evaluate to?
12386 unsigned Result;
12387 switch (Opc) {
12388 case BO_EQ: // e.g. array1 == array2
12389 Result = AlwaysFalse;
12390 break;
12391 case BO_NE: // e.g. array1 != array2
12392 Result = AlwaysTrue;
12393 break;
12394 default: // e.g. array1 <= array2
12395 // The best we can say is 'a constant'
12396 Result = AlwaysConstant;
12397 break;
12398 }
12399 S.DiagRuntimeBehavior(Loc, nullptr,
12400 S.PDiag(diag::warn_comparison_always)
12401 << 1 /*array comparison*/
12402 << Result);
12403 }
12404 }
12405
12406 if (isa<CastExpr>(LHSStripped))
12407 LHSStripped = LHSStripped->IgnoreParenCasts();
12408 if (isa<CastExpr>(RHSStripped))
12409 RHSStripped = RHSStripped->IgnoreParenCasts();
12410
12411 // Warn about comparisons against a string constant (unless the other
12412 // operand is null); the user probably wants string comparison function.
12413 Expr *LiteralString = nullptr;
12414 Expr *LiteralStringStripped = nullptr;
12415 if ((isa<StringLiteral>(LHSStripped) || isa<ObjCEncodeExpr>(LHSStripped)) &&
12416 !RHSStripped->isNullPointerConstant(S.Context,
12417 Expr::NPC_ValueDependentIsNull)) {
12418 LiteralString = LHS;
12419 LiteralStringStripped = LHSStripped;
12420 } else if ((isa<StringLiteral>(RHSStripped) ||
12421 isa<ObjCEncodeExpr>(RHSStripped)) &&
12422 !LHSStripped->isNullPointerConstant(S.Context,
12423 Expr::NPC_ValueDependentIsNull)) {
12424 LiteralString = RHS;
12425 LiteralStringStripped = RHSStripped;
12426 }
12427
12428 if (LiteralString) {
12429 S.DiagRuntimeBehavior(Loc, nullptr,
12430 S.PDiag(diag::warn_stringcompare)
12431 << isa<ObjCEncodeExpr>(LiteralStringStripped)
12432 << LiteralString->getSourceRange());
12433 }
12434}
12435
12436static ImplicitConversionKind castKindToImplicitConversionKind(CastKind CK) {
12437 switch (CK) {
12438 default: {
12439#ifndef NDEBUG
12440 llvm::errs() << "unhandled cast kind: " << CastExpr::getCastKindName(CK)
12441 << "\n";
12442#endif
12443 llvm_unreachable("unhandled cast kind")::llvm::llvm_unreachable_internal("unhandled cast kind", "clang/lib/Sema/SemaExpr.cpp"
, 12443)
;
12444 }
12445 case CK_UserDefinedConversion:
12446 return ICK_Identity;
12447 case CK_LValueToRValue:
12448 return ICK_Lvalue_To_Rvalue;
12449 case CK_ArrayToPointerDecay:
12450 return ICK_Array_To_Pointer;
12451 case CK_FunctionToPointerDecay:
12452 return ICK_Function_To_Pointer;
12453 case CK_IntegralCast:
12454 return ICK_Integral_Conversion;
12455 case CK_FloatingCast:
12456 return ICK_Floating_Conversion;
12457 case CK_IntegralToFloating:
12458 case CK_FloatingToIntegral:
12459 return ICK_Floating_Integral;
12460 case CK_IntegralComplexCast:
12461 case CK_FloatingComplexCast:
12462 case CK_FloatingComplexToIntegralComplex:
12463 case CK_IntegralComplexToFloatingComplex:
12464 return ICK_Complex_Conversion;
12465 case CK_FloatingComplexToReal:
12466 case CK_FloatingRealToComplex:
12467 case CK_IntegralComplexToReal:
12468 case CK_IntegralRealToComplex:
12469 return ICK_Complex_Real;
12470 }
12471}
12472
12473static bool checkThreeWayNarrowingConversion(Sema &S, QualType ToType, Expr *E,
12474 QualType FromType,
12475 SourceLocation Loc) {
12476 // Check for a narrowing implicit conversion.
12477 StandardConversionSequence SCS;
12478 SCS.setAsIdentityConversion();
12479 SCS.setToType(0, FromType);
12480 SCS.setToType(1, ToType);
12481 if (const auto *ICE = dyn_cast<ImplicitCastExpr>(E))
12482 SCS.Second = castKindToImplicitConversionKind(ICE->getCastKind());
12483
12484 APValue PreNarrowingValue;
12485 QualType PreNarrowingType;
12486 switch (SCS.getNarrowingKind(S.Context, E, PreNarrowingValue,
12487 PreNarrowingType,
12488 /*IgnoreFloatToIntegralConversion*/ true)) {
12489 case NK_Dependent_Narrowing:
12490 // Implicit conversion to a narrower type, but the expression is
12491 // value-dependent so we can't tell whether it's actually narrowing.
12492 case NK_Not_Narrowing:
12493 return false;
12494
12495 case NK_Constant_Narrowing:
12496 // Implicit conversion to a narrower type, and the value is not a constant
12497 // expression.
12498 S.Diag(E->getBeginLoc(), diag::err_spaceship_argument_narrowing)
12499 << /*Constant*/ 1
12500 << PreNarrowingValue.getAsString(S.Context, PreNarrowingType) << ToType;
12501 return true;
12502
12503 case NK_Variable_Narrowing:
12504 // Implicit conversion to a narrower type, and the value is not a constant
12505 // expression.
12506 case NK_Type_Narrowing:
12507 S.Diag(E->getBeginLoc(), diag::err_spaceship_argument_narrowing)
12508 << /*Constant*/ 0 << FromType << ToType;
12509 // TODO: It's not a constant expression, but what if the user intended it
12510 // to be? Can we produce notes to help them figure out why it isn't?
12511 return true;
12512 }
12513 llvm_unreachable("unhandled case in switch")::llvm::llvm_unreachable_internal("unhandled case in switch",
"clang/lib/Sema/SemaExpr.cpp", 12513)
;
12514}
12515
12516static QualType checkArithmeticOrEnumeralThreeWayCompare(Sema &S,
12517 ExprResult &LHS,
12518 ExprResult &RHS,
12519 SourceLocation Loc) {
12520 QualType LHSType = LHS.get()->getType();
12521 QualType RHSType = RHS.get()->getType();
12522 // Dig out the original argument type and expression before implicit casts
12523 // were applied. These are the types/expressions we need to check the
12524 // [expr.spaceship] requirements against.
12525 ExprResult LHSStripped = LHS.get()->IgnoreParenImpCasts();
12526 ExprResult RHSStripped = RHS.get()->IgnoreParenImpCasts();
12527 QualType LHSStrippedType = LHSStripped.get()->getType();
12528 QualType RHSStrippedType = RHSStripped.get()->getType();
12529
12530 // C++2a [expr.spaceship]p3: If one of the operands is of type bool and the
12531 // other is not, the program is ill-formed.
12532 if (LHSStrippedType->isBooleanType() != RHSStrippedType->isBooleanType()) {
12533 S.InvalidOperands(Loc, LHSStripped, RHSStripped);
12534 return QualType();
12535 }
12536
12537 // FIXME: Consider combining this with checkEnumArithmeticConversions.
12538 int NumEnumArgs = (int)LHSStrippedType->isEnumeralType() +
12539 RHSStrippedType->isEnumeralType();
12540 if (NumEnumArgs == 1) {
12541 bool LHSIsEnum = LHSStrippedType->isEnumeralType();
12542 QualType OtherTy = LHSIsEnum ? RHSStrippedType : LHSStrippedType;
12543 if (OtherTy->hasFloatingRepresentation()) {
12544 S.InvalidOperands(Loc, LHSStripped, RHSStripped);
12545 return QualType();
12546 }
12547 }
12548 if (NumEnumArgs == 2) {
12549 // C++2a [expr.spaceship]p5: If both operands have the same enumeration
12550 // type E, the operator yields the result of converting the operands
12551 // to the underlying type of E and applying <=> to the converted operands.
12552 if (!S.Context.hasSameUnqualifiedType(LHSStrippedType, RHSStrippedType)) {
12553 S.InvalidOperands(Loc, LHS, RHS);
12554 return QualType();
12555 }
12556 QualType IntType =
12557 LHSStrippedType->castAs<EnumType>()->getDecl()->getIntegerType();
12558 assert(IntType->isArithmeticType())(static_cast <bool> (IntType->isArithmeticType()) ? void
(0) : __assert_fail ("IntType->isArithmeticType()", "clang/lib/Sema/SemaExpr.cpp"
, 12558, __extension__ __PRETTY_FUNCTION__))
;
12559
12560 // We can't use `CK_IntegralCast` when the underlying type is 'bool', so we
12561 // promote the boolean type, and all other promotable integer types, to
12562 // avoid this.
12563 if (S.Context.isPromotableIntegerType(IntType))
12564 IntType = S.Context.getPromotedIntegerType(IntType);
12565
12566 LHS = S.ImpCastExprToType(LHS.get(), IntType, CK_IntegralCast);
12567 RHS = S.ImpCastExprToType(RHS.get(), IntType, CK_IntegralCast);
12568 LHSType = RHSType = IntType;
12569 }
12570
12571 // C++2a [expr.spaceship]p4: If both operands have arithmetic types, the
12572 // usual arithmetic conversions are applied to the operands.
12573 QualType Type =
12574 S.UsualArithmeticConversions(LHS, RHS, Loc, Sema::ACK_Comparison);
12575 if (LHS.isInvalid() || RHS.isInvalid())
12576 return QualType();
12577 if (Type.isNull())
12578 return S.InvalidOperands(Loc, LHS, RHS);
12579
12580 std::optional<ComparisonCategoryType> CCT =
12581 getComparisonCategoryForBuiltinCmp(Type);
12582 if (!CCT)
12583 return S.InvalidOperands(Loc, LHS, RHS);
12584
12585 bool HasNarrowing = checkThreeWayNarrowingConversion(
12586 S, Type, LHS.get(), LHSType, LHS.get()->getBeginLoc());
12587 HasNarrowing |= checkThreeWayNarrowingConversion(S, Type, RHS.get(), RHSType,
12588 RHS.get()->getBeginLoc());
12589 if (HasNarrowing)
12590 return QualType();
12591
12592 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", 12592, __extension__ __PRETTY_FUNCTION__
))
;
12593
12594 return S.CheckComparisonCategoryType(
12595 *CCT, Loc, Sema::ComparisonCategoryUsage::OperatorInExpression);
12596}
12597
12598static QualType checkArithmeticOrEnumeralCompare(Sema &S, ExprResult &LHS,
12599 ExprResult &RHS,
12600 SourceLocation Loc,
12601 BinaryOperatorKind Opc) {
12602 if (Opc == BO_Cmp)
12603 return checkArithmeticOrEnumeralThreeWayCompare(S, LHS, RHS, Loc);
12604
12605 // C99 6.5.8p3 / C99 6.5.9p4
12606 QualType Type =
12607 S.UsualArithmeticConversions(LHS, RHS, Loc, Sema::ACK_Comparison);
12608 if (LHS.isInvalid() || RHS.isInvalid())
12609 return QualType();
12610 if (Type.isNull())
12611 return S.InvalidOperands(Loc, LHS, RHS);
12612 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", 12612, __extension__ __PRETTY_FUNCTION__
))
;
12613
12614 if (Type->isAnyComplexType() && BinaryOperator::isRelationalOp(Opc))
12615 return S.InvalidOperands(Loc, LHS, RHS);
12616
12617 // Check for comparisons of floating point operands using != and ==.
12618 if (Type->hasFloatingRepresentation())
12619 S.CheckFloatComparison(Loc, LHS.get(), RHS.get(), Opc);
12620
12621 // The result of comparisons is 'bool' in C++, 'int' in C.
12622 return S.Context.getLogicalOperationType();
12623}
12624
12625void Sema::CheckPtrComparisonWithNullChar(ExprResult &E, ExprResult &NullE) {
12626 if (!NullE.get()->getType()->isAnyPointerType())
12627 return;
12628 int NullValue = PP.isMacroDefined("NULL") ? 0 : 1;
12629 if (!E.get()->getType()->isAnyPointerType() &&
12630 E.get()->isNullPointerConstant(Context,
12631 Expr::NPC_ValueDependentIsNotNull) ==
12632 Expr::NPCK_ZeroExpression) {
12633 if (const auto *CL = dyn_cast<CharacterLiteral>(E.get())) {
12634 if (CL->getValue() == 0)
12635 Diag(E.get()->getExprLoc(), diag::warn_pointer_compare)
12636 << NullValue
12637 << FixItHint::CreateReplacement(E.get()->getExprLoc(),
12638 NullValue ? "NULL" : "(void *)0");
12639 } else if (const auto *CE = dyn_cast<CStyleCastExpr>(E.get())) {
12640 TypeSourceInfo *TI = CE->getTypeInfoAsWritten();
12641 QualType T = Context.getCanonicalType(TI->getType()).getUnqualifiedType();
12642 if (T == Context.CharTy)
12643 Diag(E.get()->getExprLoc(), diag::warn_pointer_compare)
12644 << NullValue
12645 << FixItHint::CreateReplacement(E.get()->getExprLoc(),
12646 NullValue ? "NULL" : "(void *)0");
12647 }
12648 }
12649}
12650
12651// C99 6.5.8, C++ [expr.rel]
12652QualType Sema::CheckCompareOperands(ExprResult &LHS, ExprResult &RHS,
12653 SourceLocation Loc,
12654 BinaryOperatorKind Opc) {
12655 bool IsRelational = BinaryOperator::isRelationalOp(Opc);
12656 bool IsThreeWay = Opc == BO_Cmp;
12657 bool IsOrdered = IsRelational || IsThreeWay;
12658 auto IsAnyPointerType = [](ExprResult E) {
12659 QualType Ty = E.get()->getType();
12660 return Ty->isPointerType() || Ty->isMemberPointerType();
12661 };
12662
12663 // C++2a [expr.spaceship]p6: If at least one of the operands is of pointer
12664 // type, array-to-pointer, ..., conversions are performed on both operands to
12665 // bring them to their composite type.
12666 // Otherwise, all comparisons expect an rvalue, so convert to rvalue before
12667 // any type-related checks.
12668 if (!IsThreeWay || IsAnyPointerType(LHS) || IsAnyPointerType(RHS)) {
12669 LHS = DefaultFunctionArrayLvalueConversion(LHS.get());
12670 if (LHS.isInvalid())
12671 return QualType();
12672 RHS = DefaultFunctionArrayLvalueConversion(RHS.get());
12673 if (RHS.isInvalid())
12674 return QualType();
12675 } else {
12676 LHS = DefaultLvalueConversion(LHS.get());
12677 if (LHS.isInvalid())
12678 return QualType();
12679 RHS = DefaultLvalueConversion(RHS.get());
12680 if (RHS.isInvalid())
12681 return QualType();
12682 }
12683
12684 checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/true);
12685 if (!getLangOpts().CPlusPlus && BinaryOperator::isEqualityOp(Opc)) {
12686 CheckPtrComparisonWithNullChar(LHS, RHS);
12687 CheckPtrComparisonWithNullChar(RHS, LHS);
12688 }
12689
12690 // Handle vector comparisons separately.
12691 if (LHS.get()->getType()->isVectorType() ||
12692 RHS.get()->getType()->isVectorType())
12693 return CheckVectorCompareOperands(LHS, RHS, Loc, Opc);
12694
12695 if (LHS.get()->getType()->isVLSTBuiltinType() ||
12696 RHS.get()->getType()->isVLSTBuiltinType())
12697 return CheckSizelessVectorCompareOperands(LHS, RHS, Loc, Opc);
12698
12699 diagnoseLogicalNotOnLHSofCheck(*this, LHS, RHS, Loc, Opc);
12700 diagnoseTautologicalComparison(*this, Loc, LHS.get(), RHS.get(), Opc);
12701
12702 QualType LHSType = LHS.get()->getType();
12703 QualType RHSType = RHS.get()->getType();
12704 if ((LHSType->isArithmeticType() || LHSType->isEnumeralType()) &&
12705 (RHSType->isArithmeticType() || RHSType->isEnumeralType()))
12706 return checkArithmeticOrEnumeralCompare(*this, LHS, RHS, Loc, Opc);
12707
12708 const Expr::NullPointerConstantKind LHSNullKind =
12709 LHS.get()->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull);
12710 const Expr::NullPointerConstantKind RHSNullKind =
12711 RHS.get()->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull);
12712 bool LHSIsNull = LHSNullKind != Expr::NPCK_NotNull;
12713 bool RHSIsNull = RHSNullKind != Expr::NPCK_NotNull;
12714
12715 auto computeResultTy = [&]() {
12716 if (Opc != BO_Cmp)
12717 return Context.getLogicalOperationType();
12718 assert(getLangOpts().CPlusPlus)(static_cast <bool> (getLangOpts().CPlusPlus) ? void (0
) : __assert_fail ("getLangOpts().CPlusPlus", "clang/lib/Sema/SemaExpr.cpp"
, 12718, __extension__ __PRETTY_FUNCTION__))
;
12719 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", 12719, __extension__ __PRETTY_FUNCTION__
))
;
12720
12721 QualType CompositeTy = LHS.get()->getType();
12722 assert(!CompositeTy->isReferenceType())(static_cast <bool> (!CompositeTy->isReferenceType()
) ? void (0) : __assert_fail ("!CompositeTy->isReferenceType()"
, "clang/lib/Sema/SemaExpr.cpp", 12722, __extension__ __PRETTY_FUNCTION__
))
;
12723
12724 std::optional<ComparisonCategoryType> CCT =
12725 getComparisonCategoryForBuiltinCmp(CompositeTy);
12726 if (!CCT)
12727 return InvalidOperands(Loc, LHS, RHS);
12728
12729 if (CompositeTy->isPointerType() && LHSIsNull != RHSIsNull) {
12730 // P0946R0: Comparisons between a null pointer constant and an object
12731 // pointer result in std::strong_equality, which is ill-formed under
12732 // P1959R0.
12733 Diag(Loc, diag::err_typecheck_three_way_comparison_of_pointer_and_zero)
12734 << (LHSIsNull ? LHS.get()->getSourceRange()
12735 : RHS.get()->getSourceRange());
12736 return QualType();
12737 }
12738
12739 return CheckComparisonCategoryType(
12740 *CCT, Loc, ComparisonCategoryUsage::OperatorInExpression);
12741 };
12742
12743 if (!IsOrdered && LHSIsNull != RHSIsNull) {
12744 bool IsEquality = Opc == BO_EQ;
12745 if (RHSIsNull)
12746 DiagnoseAlwaysNonNullPointer(LHS.get(), RHSNullKind, IsEquality,
12747 RHS.get()->getSourceRange());
12748 else
12749 DiagnoseAlwaysNonNullPointer(RHS.get(), LHSNullKind, IsEquality,
12750 LHS.get()->getSourceRange());
12751 }
12752
12753 if (IsOrdered && LHSType->isFunctionPointerType() &&
12754 RHSType->isFunctionPointerType()) {
12755 // Valid unless a relational comparison of function pointers
12756 bool IsError = Opc == BO_Cmp;
12757 auto DiagID =
12758 IsError ? diag::err_typecheck_ordered_comparison_of_function_pointers
12759 : getLangOpts().CPlusPlus
12760 ? diag::warn_typecheck_ordered_comparison_of_function_pointers
12761 : diag::ext_typecheck_ordered_comparison_of_function_pointers;
12762 Diag(Loc, DiagID) << LHSType << RHSType << LHS.get()->getSourceRange()
12763 << RHS.get()->getSourceRange();
12764 if (IsError)
12765 return QualType();
12766 }
12767
12768 if ((LHSType->isIntegerType() && !LHSIsNull) ||
12769 (RHSType->isIntegerType() && !RHSIsNull)) {
12770 // Skip normal pointer conversion checks in this case; we have better
12771 // diagnostics for this below.
12772 } else if (getLangOpts().CPlusPlus) {
12773 // Equality comparison of a function pointer to a void pointer is invalid,
12774 // but we allow it as an extension.
12775 // FIXME: If we really want to allow this, should it be part of composite
12776 // pointer type computation so it works in conditionals too?
12777 if (!IsOrdered &&
12778 ((LHSType->isFunctionPointerType() && RHSType->isVoidPointerType()) ||
12779 (RHSType->isFunctionPointerType() && LHSType->isVoidPointerType()))) {
12780 // This is a gcc extension compatibility comparison.
12781 // In a SFINAE context, we treat this as a hard error to maintain
12782 // conformance with the C++ standard.
12783 diagnoseFunctionPointerToVoidComparison(
12784 *this, Loc, LHS, RHS, /*isError*/ (bool)isSFINAEContext());
12785
12786 if (isSFINAEContext())
12787 return QualType();
12788
12789 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast);
12790 return computeResultTy();
12791 }
12792
12793 // C++ [expr.eq]p2:
12794 // If at least one operand is a pointer [...] bring them to their
12795 // composite pointer type.
12796 // C++ [expr.spaceship]p6
12797 // If at least one of the operands is of pointer type, [...] bring them
12798 // to their composite pointer type.
12799 // C++ [expr.rel]p2:
12800 // If both operands are pointers, [...] bring them to their composite
12801 // pointer type.
12802 // For <=>, the only valid non-pointer types are arrays and functions, and
12803 // we already decayed those, so this is really the same as the relational
12804 // comparison rule.
12805 if ((int)LHSType->isPointerType() + (int)RHSType->isPointerType() >=
12806 (IsOrdered ? 2 : 1) &&
12807 (!LangOpts.ObjCAutoRefCount || !(LHSType->isObjCObjectPointerType() ||
12808 RHSType->isObjCObjectPointerType()))) {
12809 if (convertPointersToCompositeType(*this, Loc, LHS, RHS))
12810 return QualType();
12811 return computeResultTy();
12812 }
12813 } else if (LHSType->isPointerType() &&
12814 RHSType->isPointerType()) { // C99 6.5.8p2
12815 // All of the following pointer-related warnings are GCC extensions, except
12816 // when handling null pointer constants.
12817 QualType LCanPointeeTy =
12818 LHSType->castAs<PointerType>()->getPointeeType().getCanonicalType();
12819 QualType RCanPointeeTy =
12820 RHSType->castAs<PointerType>()->getPointeeType().getCanonicalType();
12821
12822 // C99 6.5.9p2 and C99 6.5.8p2
12823 if (Context.typesAreCompatible(LCanPointeeTy.getUnqualifiedType(),
12824 RCanPointeeTy.getUnqualifiedType())) {
12825 if (IsRelational) {
12826 // Pointers both need to point to complete or incomplete types
12827 if ((LCanPointeeTy->isIncompleteType() !=
12828 RCanPointeeTy->isIncompleteType()) &&
12829 !getLangOpts().C11) {
12830 Diag(Loc, diag::ext_typecheck_compare_complete_incomplete_pointers)
12831 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange()
12832 << LHSType << RHSType << LCanPointeeTy->isIncompleteType()
12833 << RCanPointeeTy->isIncompleteType();
12834 }
12835 }
12836 } else if (!IsRelational &&
12837 (LCanPointeeTy->isVoidType() || RCanPointeeTy->isVoidType())) {
12838 // Valid unless comparison between non-null pointer and function pointer
12839 if ((LCanPointeeTy->isFunctionType() || RCanPointeeTy->isFunctionType())
12840 && !LHSIsNull && !RHSIsNull)
12841 diagnoseFunctionPointerToVoidComparison(*this, Loc, LHS, RHS,
12842 /*isError*/false);
12843 } else {
12844 // Invalid
12845 diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS, /*isError*/false);
12846 }
12847 if (LCanPointeeTy != RCanPointeeTy) {
12848 // Treat NULL constant as a special case in OpenCL.
12849 if (getLangOpts().OpenCL && !LHSIsNull && !RHSIsNull) {
12850 if (!LCanPointeeTy.isAddressSpaceOverlapping(RCanPointeeTy)) {
12851 Diag(Loc,
12852 diag::err_typecheck_op_on_nonoverlapping_address_space_pointers)
12853 << LHSType << RHSType << 0 /* comparison */
12854 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
12855 }
12856 }
12857 LangAS AddrSpaceL = LCanPointeeTy.getAddressSpace();
12858 LangAS AddrSpaceR = RCanPointeeTy.getAddressSpace();
12859 CastKind Kind = AddrSpaceL != AddrSpaceR ? CK_AddressSpaceConversion
12860 : CK_BitCast;
12861 if (LHSIsNull && !RHSIsNull)
12862 LHS = ImpCastExprToType(LHS.get(), RHSType, Kind);
12863 else
12864 RHS = ImpCastExprToType(RHS.get(), LHSType, Kind);
12865 }
12866 return computeResultTy();
12867 }
12868
12869
12870 // C++ [expr.eq]p4:
12871 // Two operands of type std::nullptr_t or one operand of type
12872 // std::nullptr_t and the other a null pointer constant compare
12873 // equal.
12874 // C2x 6.5.9p5:
12875 // If both operands have type nullptr_t or one operand has type nullptr_t
12876 // and the other is a null pointer constant, they compare equal.
12877 if (!IsOrdered && LHSIsNull && RHSIsNull) {
12878 if (LHSType->isNullPtrType()) {
12879 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer);
12880 return computeResultTy();
12881 }
12882 if (RHSType->isNullPtrType()) {
12883 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer);
12884 return computeResultTy();
12885 }
12886 }
12887
12888 if (!getLangOpts().CPlusPlus && !IsOrdered && (LHSIsNull || RHSIsNull)) {
12889 // C2x 6.5.9p6:
12890 // Otherwise, at least one operand is a pointer. If one is a pointer and
12891 // the other is a null pointer constant, the null pointer constant is
12892 // converted to the type of the pointer.
12893 if (LHSIsNull && RHSType->isPointerType()) {
12894 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer);
12895 return computeResultTy();
12896 }
12897 if (RHSIsNull && LHSType->isPointerType()) {
12898 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer);
12899 return computeResultTy();
12900 }
12901 }
12902
12903 // Comparison of Objective-C pointers and block pointers against nullptr_t.
12904 // These aren't covered by the composite pointer type rules.
12905 if (!IsOrdered && RHSType->isNullPtrType() &&
12906 (LHSType->isObjCObjectPointerType() || LHSType->isBlockPointerType())) {
12907 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer);
12908 return computeResultTy();
12909 }
12910 if (!IsOrdered && LHSType->isNullPtrType() &&
12911 (RHSType->isObjCObjectPointerType() || RHSType->isBlockPointerType())) {
12912 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer);
12913 return computeResultTy();
12914 }
12915
12916 if (getLangOpts().CPlusPlus) {
12917 if (IsRelational &&
12918 ((LHSType->isNullPtrType() && RHSType->isPointerType()) ||
12919 (RHSType->isNullPtrType() && LHSType->isPointerType()))) {
12920 // HACK: Relational comparison of nullptr_t against a pointer type is
12921 // invalid per DR583, but we allow it within std::less<> and friends,
12922 // since otherwise common uses of it break.
12923 // FIXME: Consider removing this hack once LWG fixes std::less<> and
12924 // friends to have std::nullptr_t overload candidates.
12925 DeclContext *DC = CurContext;
12926 if (isa<FunctionDecl>(DC))
12927 DC = DC->getParent();
12928 if (auto *CTSD = dyn_cast<ClassTemplateSpecializationDecl>(DC)) {
12929 if (CTSD->isInStdNamespace() &&
12930 llvm::StringSwitch<bool>(CTSD->getName())
12931 .Cases("less", "less_equal", "greater", "greater_equal", true)
12932 .Default(false)) {
12933 if (RHSType->isNullPtrType())
12934 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer);
12935 else
12936 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer);
12937 return computeResultTy();
12938 }
12939 }
12940 }
12941
12942 // C++ [expr.eq]p2:
12943 // If at least one operand is a pointer to member, [...] bring them to
12944 // their composite pointer type.
12945 if (!IsOrdered &&
12946 (LHSType->isMemberPointerType() || RHSType->isMemberPointerType())) {
12947 if (convertPointersToCompositeType(*this, Loc, LHS, RHS))
12948 return QualType();
12949 else
12950 return computeResultTy();
12951 }
12952 }
12953
12954 // Handle block pointer types.
12955 if (!IsOrdered && LHSType->isBlockPointerType() &&
12956 RHSType->isBlockPointerType()) {
12957 QualType lpointee = LHSType->castAs<BlockPointerType>()->getPointeeType();
12958 QualType rpointee = RHSType->castAs<BlockPointerType>()->getPointeeType();
12959
12960 if (!LHSIsNull && !RHSIsNull &&
12961 !Context.typesAreCompatible(lpointee, rpointee)) {
12962 Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks)
12963 << LHSType << RHSType << LHS.get()->getSourceRange()
12964 << RHS.get()->getSourceRange();
12965 }
12966 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast);
12967 return computeResultTy();
12968 }
12969
12970 // Allow block pointers to be compared with null pointer constants.
12971 if (!IsOrdered
12972 && ((LHSType->isBlockPointerType() && RHSType->isPointerType())
12973 || (LHSType->isPointerType() && RHSType->isBlockPointerType()))) {
12974 if (!LHSIsNull && !RHSIsNull) {
12975 if (!((RHSType->isPointerType() && RHSType->castAs<PointerType>()
12976 ->getPointeeType()->isVoidType())
12977 || (LHSType->isPointerType() && LHSType->castAs<PointerType>()
12978 ->getPointeeType()->isVoidType())))
12979 Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks)
12980 << LHSType << RHSType << LHS.get()->getSourceRange()
12981 << RHS.get()->getSourceRange();
12982 }
12983 if (LHSIsNull && !RHSIsNull)
12984 LHS = ImpCastExprToType(LHS.get(), RHSType,
12985 RHSType->isPointerType() ? CK_BitCast
12986 : CK_AnyPointerToBlockPointerCast);
12987 else
12988 RHS = ImpCastExprToType(RHS.get(), LHSType,
12989 LHSType->isPointerType() ? CK_BitCast
12990 : CK_AnyPointerToBlockPointerCast);
12991 return computeResultTy();
12992 }
12993
12994 if (LHSType->isObjCObjectPointerType() ||
12995 RHSType->isObjCObjectPointerType()) {
12996 const PointerType *LPT = LHSType->getAs<PointerType>();
12997 const PointerType *RPT = RHSType->getAs<PointerType>();
12998 if (LPT || RPT) {
12999 bool LPtrToVoid = LPT ? LPT->getPointeeType()->isVoidType() : false;
13000 bool RPtrToVoid = RPT ? RPT->getPointeeType()->isVoidType() : false;
13001
13002 if (!LPtrToVoid && !RPtrToVoid &&
13003 !Context.typesAreCompatible(LHSType, RHSType)) {
13004 diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS,
13005 /*isError*/false);
13006 }
13007 // FIXME: If LPtrToVoid, we should presumably convert the LHS rather than
13008 // the RHS, but we have test coverage for this behavior.
13009 // FIXME: Consider using convertPointersToCompositeType in C++.
13010 if (LHSIsNull && !RHSIsNull) {
13011 Expr *E = LHS.get();
13012 if (getLangOpts().ObjCAutoRefCount)
13013 CheckObjCConversion(SourceRange(), RHSType, E,
13014 CCK_ImplicitConversion);
13015 LHS = ImpCastExprToType(E, RHSType,
13016 RPT ? CK_BitCast :CK_CPointerToObjCPointerCast);
13017 }
13018 else {
13019 Expr *E = RHS.get();
13020 if (getLangOpts().ObjCAutoRefCount)
13021 CheckObjCConversion(SourceRange(), LHSType, E, CCK_ImplicitConversion,
13022 /*Diagnose=*/true,
13023 /*DiagnoseCFAudited=*/false, Opc);
13024 RHS = ImpCastExprToType(E, LHSType,
13025 LPT ? CK_BitCast :CK_CPointerToObjCPointerCast);
13026 }
13027 return computeResultTy();
13028 }
13029 if (LHSType->isObjCObjectPointerType() &&
13030 RHSType->isObjCObjectPointerType()) {
13031 if (!Context.areComparableObjCPointerTypes(LHSType, RHSType))
13032 diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS,
13033 /*isError*/false);
13034 if (isObjCObjectLiteral(LHS) || isObjCObjectLiteral(RHS))
13035 diagnoseObjCLiteralComparison(*this, Loc, LHS, RHS, Opc);
13036
13037 if (LHSIsNull && !RHSIsNull)
13038 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_BitCast);
13039 else
13040 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast);
13041 return computeResultTy();
13042 }
13043
13044 if (!IsOrdered && LHSType->isBlockPointerType() &&
13045 RHSType->isBlockCompatibleObjCPointerType(Context)) {
13046 LHS = ImpCastExprToType(LHS.get(), RHSType,
13047 CK_BlockPointerToObjCPointerCast);
13048 return computeResultTy();
13049 } else if (!IsOrdered &&
13050 LHSType->isBlockCompatibleObjCPointerType(Context) &&
13051 RHSType->isBlockPointerType()) {
13052 RHS = ImpCastExprToType(RHS.get(), LHSType,
13053 CK_BlockPointerToObjCPointerCast);
13054 return computeResultTy();
13055 }
13056 }
13057 if ((LHSType->isAnyPointerType() && RHSType->isIntegerType()) ||
13058 (LHSType->isIntegerType() && RHSType->isAnyPointerType())) {
13059 unsigned DiagID = 0;
13060 bool isError = false;
13061 if (LangOpts.DebuggerSupport) {
13062 // Under a debugger, allow the comparison of pointers to integers,
13063 // since users tend to want to compare addresses.
13064 } else if ((LHSIsNull && LHSType->isIntegerType()) ||
13065 (RHSIsNull && RHSType->isIntegerType())) {
13066 if (IsOrdered) {
13067 isError = getLangOpts().CPlusPlus;
13068 DiagID =
13069 isError ? diag::err_typecheck_ordered_comparison_of_pointer_and_zero
13070 : diag::ext_typecheck_ordered_comparison_of_pointer_and_zero;
13071 }
13072 } else if (getLangOpts().CPlusPlus) {
13073 DiagID = diag::err_typecheck_comparison_of_pointer_integer;
13074 isError = true;
13075 } else if (IsOrdered)
13076 DiagID = diag::ext_typecheck_ordered_comparison_of_pointer_integer;
13077 else
13078 DiagID = diag::ext_typecheck_comparison_of_pointer_integer;
13079
13080 if (DiagID) {
13081 Diag(Loc, DiagID)
13082 << LHSType << RHSType << LHS.get()->getSourceRange()
13083 << RHS.get()->getSourceRange();
13084 if (isError)
13085 return QualType();
13086 }
13087
13088 if (LHSType->isIntegerType())
13089 LHS = ImpCastExprToType(LHS.get(), RHSType,
13090 LHSIsNull ? CK_NullToPointer : CK_IntegralToPointer);
13091 else
13092 RHS = ImpCastExprToType(RHS.get(), LHSType,
13093 RHSIsNull ? CK_NullToPointer : CK_IntegralToPointer);
13094 return computeResultTy();
13095 }
13096
13097 // Handle block pointers.
13098 if (!IsOrdered && RHSIsNull
13099 && LHSType->isBlockPointerType() && RHSType->isIntegerType()) {
13100 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer);
13101 return computeResultTy();
13102 }
13103 if (!IsOrdered && LHSIsNull
13104 && LHSType->isIntegerType() && RHSType->isBlockPointerType()) {
13105 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer);
13106 return computeResultTy();
13107 }
13108
13109 if (getLangOpts().getOpenCLCompatibleVersion() >= 200) {
13110 if (LHSType->isClkEventT() && RHSType->isClkEventT()) {
13111 return computeResultTy();
13112 }
13113
13114 if (LHSType->isQueueT() && RHSType->isQueueT()) {
13115 return computeResultTy();
13116 }
13117
13118 if (LHSIsNull && RHSType->isQueueT()) {
13119 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer);
13120 return computeResultTy();
13121 }
13122
13123 if (LHSType->isQueueT() && RHSIsNull) {
13124 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer);
13125 return computeResultTy();
13126 }
13127 }
13128
13129 return InvalidOperands(Loc, LHS, RHS);
13130}
13131
13132// Return a signed ext_vector_type that is of identical size and number of
13133// elements. For floating point vectors, return an integer type of identical
13134// size and number of elements. In the non ext_vector_type case, search from
13135// the largest type to the smallest type to avoid cases where long long == long,
13136// where long gets picked over long long.
13137QualType Sema::GetSignedVectorType(QualType V) {
13138 const VectorType *VTy = V->castAs<VectorType>();
13139 unsigned TypeSize = Context.getTypeSize(VTy->getElementType());
13140
13141 if (isa<ExtVectorType>(VTy)) {
13142 if (VTy->isExtVectorBoolType())
13143 return Context.getExtVectorType(Context.BoolTy, VTy->getNumElements());
13144 if (TypeSize == Context.getTypeSize(Context.CharTy))
13145 return Context.getExtVectorType(Context.CharTy, VTy->getNumElements());
13146 if (TypeSize == Context.getTypeSize(Context.ShortTy))
13147 return Context.getExtVectorType(Context.ShortTy, VTy->getNumElements());
13148 if (TypeSize == Context.getTypeSize(Context.IntTy))
13149 return Context.getExtVectorType(Context.IntTy, VTy->getNumElements());
13150 if (TypeSize == Context.getTypeSize(Context.Int128Ty))
13151 return Context.getExtVectorType(Context.Int128Ty, VTy->getNumElements());
13152 if (TypeSize == Context.getTypeSize(Context.LongTy))
13153 return Context.getExtVectorType(Context.LongTy, VTy->getNumElements());
13154 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", 13155, __extension__ __PRETTY_FUNCTION__
))
13155 "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", 13155, __extension__ __PRETTY_FUNCTION__
))
;
13156 return Context.getExtVectorType(Context.LongLongTy, VTy->getNumElements());
13157 }
13158
13159 if (TypeSize == Context.getTypeSize(Context.Int128Ty))
13160 return Context.getVectorType(Context.Int128Ty, VTy->getNumElements(),
13161 VectorType::GenericVector);
13162 if (TypeSize == Context.getTypeSize(Context.LongLongTy))
13163 return Context.getVectorType(Context.LongLongTy, VTy->getNumElements(),
13164 VectorType::GenericVector);
13165 if (TypeSize == Context.getTypeSize(Context.LongTy))
13166 return Context.getVectorType(Context.LongTy, VTy->getNumElements(),
13167 VectorType::GenericVector);
13168 if (TypeSize == Context.getTypeSize(Context.IntTy))
13169 return Context.getVectorType(Context.IntTy, VTy->getNumElements(),
13170 VectorType::GenericVector);
13171 if (TypeSize == Context.getTypeSize(Context.ShortTy))
13172 return Context.getVectorType(Context.ShortTy, VTy->getNumElements(),
13173 VectorType::GenericVector);
13174 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", 13175, __extension__ __PRETTY_FUNCTION__
))
13175 "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", 13175, __extension__ __PRETTY_FUNCTION__
))
;
13176 return Context.getVectorType(Context.CharTy, VTy->getNumElements(),
13177 VectorType::GenericVector);
13178}
13179
13180QualType Sema::GetSignedSizelessVectorType(QualType V) {
13181 const BuiltinType *VTy = V->castAs<BuiltinType>();
13182 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", 13182, __extension__ __PRETTY_FUNCTION__
))
;
13183
13184 const QualType ETy = V->getSveEltType(Context);
13185 const auto TypeSize = Context.getTypeSize(ETy);
13186
13187 const QualType IntTy = Context.getIntTypeForBitwidth(TypeSize, true);
13188 const llvm::ElementCount VecSize = Context.getBuiltinVectorTypeInfo(VTy).EC;
13189 return Context.getScalableVectorType(IntTy, VecSize.getKnownMinValue());
13190}
13191
13192/// CheckVectorCompareOperands - vector comparisons are a clang extension that
13193/// operates on extended vector types. Instead of producing an IntTy result,
13194/// like a scalar comparison, a vector comparison produces a vector of integer
13195/// types.
13196QualType Sema::CheckVectorCompareOperands(ExprResult &LHS, ExprResult &RHS,
13197 SourceLocation Loc,
13198 BinaryOperatorKind Opc) {
13199 if (Opc == BO_Cmp) {
13200 Diag(Loc, diag::err_three_way_vector_comparison);
13201 return QualType();
13202 }
13203
13204 // Check to make sure we're operating on vectors of the same type and width,
13205 // Allowing one side to be a scalar of element type.
13206 QualType vType =
13207 CheckVectorOperands(LHS, RHS, Loc, /*isCompAssign*/ false,
13208 /*AllowBothBool*/ true,
13209 /*AllowBoolConversions*/ getLangOpts().ZVector,
13210 /*AllowBooleanOperation*/ true,
13211 /*ReportInvalid*/ true);
13212 if (vType.isNull())
13213 return vType;
13214
13215 QualType LHSType = LHS.get()->getType();
13216
13217 // Determine the return type of a vector compare. By default clang will return
13218 // a scalar for all vector compares except vector bool and vector pixel.
13219 // With the gcc compiler we will always return a vector type and with the xl
13220 // compiler we will always return a scalar type. This switch allows choosing
13221 // which behavior is prefered.
13222 if (getLangOpts().AltiVec) {
13223 switch (getLangOpts().getAltivecSrcCompat()) {
13224 case LangOptions::AltivecSrcCompatKind::Mixed:
13225 // If AltiVec, the comparison results in a numeric type, i.e.
13226 // bool for C++, int for C
13227 if (vType->castAs<VectorType>()->getVectorKind() ==
13228 VectorType::AltiVecVector)
13229 return Context.getLogicalOperationType();
13230 else
13231 Diag(Loc, diag::warn_deprecated_altivec_src_compat);
13232 break;
13233 case LangOptions::AltivecSrcCompatKind::GCC:
13234 // For GCC we always return the vector type.
13235 break;
13236 case LangOptions::AltivecSrcCompatKind::XL:
13237 return Context.getLogicalOperationType();
13238 break;
13239 }
13240 }
13241
13242 // For non-floating point types, check for self-comparisons of the form
13243 // x == x, x != x, x < x, etc. These always evaluate to a constant, and
13244 // often indicate logic errors in the program.
13245 diagnoseTautologicalComparison(*this, Loc, LHS.get(), RHS.get(), Opc);
13246
13247 // Check for comparisons of floating point operands using != and ==.
13248 if (LHSType->hasFloatingRepresentation()) {
13249 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", 13249, __extension__ __PRETTY_FUNCTION__
))
;
13250 CheckFloatComparison(Loc, LHS.get(), RHS.get(), Opc);
13251 }
13252
13253 // Return a signed type for the vector.
13254 return GetSignedVectorType(vType);
13255}
13256
13257QualType Sema::CheckSizelessVectorCompareOperands(ExprResult &LHS,
13258 ExprResult &RHS,
13259 SourceLocation Loc,
13260 BinaryOperatorKind Opc) {
13261 if (Opc == BO_Cmp) {
13262 Diag(Loc, diag::err_three_way_vector_comparison);
13263 return QualType();
13264 }
13265
13266 // Check to make sure we're operating on vectors of the same type and width,
13267 // Allowing one side to be a scalar of element type.
13268 QualType vType = CheckSizelessVectorOperands(
13269 LHS, RHS, Loc, /*isCompAssign*/ false, ACK_Comparison);
13270
13271 if (vType.isNull())
13272 return vType;
13273
13274 QualType LHSType = LHS.get()->getType();
13275
13276 // For non-floating point types, check for self-comparisons of the form
13277 // x == x, x != x, x < x, etc. These always evaluate to a constant, and
13278 // often indicate logic errors in the program.
13279 diagnoseTautologicalComparison(*this, Loc, LHS.get(), RHS.get(), Opc);
13280
13281 // Check for comparisons of floating point operands using != and ==.
13282 if (LHSType->hasFloatingRepresentation()) {
13283 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", 13283, __extension__ __PRETTY_FUNCTION__
))
;
13284 CheckFloatComparison(Loc, LHS.get(), RHS.get(), Opc);
13285 }
13286
13287 const BuiltinType *LHSBuiltinTy = LHSType->getAs<BuiltinType>();
13288 const BuiltinType *RHSBuiltinTy = RHS.get()->getType()->getAs<BuiltinType>();
13289
13290 if (LHSBuiltinTy && RHSBuiltinTy && LHSBuiltinTy->isSVEBool() &&
13291 RHSBuiltinTy->isSVEBool())
13292 return LHSType;
13293
13294 // Return a signed type for the vector.
13295 return GetSignedSizelessVectorType(vType);
13296}
13297
13298static void diagnoseXorMisusedAsPow(Sema &S, const ExprResult &XorLHS,
13299 const ExprResult &XorRHS,
13300 const SourceLocation Loc) {
13301 // Do not diagnose macros.
13302 if (Loc.isMacroID())
13303 return;
13304
13305 // Do not diagnose if both LHS and RHS are macros.
13306 if (XorLHS.get()->getExprLoc().isMacroID() &&
13307 XorRHS.get()->getExprLoc().isMacroID())
13308 return;
13309
13310 bool Negative = false;
13311 bool ExplicitPlus = false;
13312 const auto *LHSInt = dyn_cast<IntegerLiteral>(XorLHS.get());
13313 const auto *RHSInt = dyn_cast<IntegerLiteral>(XorRHS.get());
13314
13315 if (!LHSInt)
13316 return;
13317 if (!RHSInt) {
13318 // Check negative literals.
13319 if (const auto *UO = dyn_cast<UnaryOperator>(XorRHS.get())) {
13320 UnaryOperatorKind Opc = UO->getOpcode();
13321 if (Opc != UO_Minus && Opc != UO_Plus)
13322 return;
13323 RHSInt = dyn_cast<IntegerLiteral>(UO->getSubExpr());
13324 if (!RHSInt)
13325 return;
13326 Negative = (Opc == UO_Minus);
13327 ExplicitPlus = !Negative;
13328 } else {
13329 return;
13330 }
13331 }
13332
13333 const llvm::APInt &LeftSideValue = LHSInt->getValue();
13334 llvm::APInt RightSideValue = RHSInt->getValue();
13335 if (LeftSideValue != 2 && LeftSideValue != 10)
13336 return;
13337
13338 if (LeftSideValue.getBitWidth() != RightSideValue.getBitWidth())
13339 return;
13340
13341 CharSourceRange ExprRange = CharSourceRange::getCharRange(
13342 LHSInt->getBeginLoc(), S.getLocForEndOfToken(RHSInt->getLocation()));
13343 llvm::StringRef ExprStr =
13344 Lexer::getSourceText(ExprRange, S.getSourceManager(), S.getLangOpts());
13345
13346 CharSourceRange XorRange =
13347 CharSourceRange::getCharRange(Loc, S.getLocForEndOfToken(Loc));
13348 llvm::StringRef XorStr =
13349 Lexer::getSourceText(XorRange, S.getSourceManager(), S.getLangOpts());
13350 // Do not diagnose if xor keyword/macro is used.
13351 if (XorStr == "xor")
13352 return;
13353
13354 std::string LHSStr = std::string(Lexer::getSourceText(
13355 CharSourceRange::getTokenRange(LHSInt->getSourceRange()),
13356 S.getSourceManager(), S.getLangOpts()));
13357 std::string RHSStr = std::string(Lexer::getSourceText(
13358 CharSourceRange::getTokenRange(RHSInt->getSourceRange()),
13359 S.getSourceManager(), S.getLangOpts()));
13360
13361 if (Negative) {
13362 RightSideValue = -RightSideValue;
13363 RHSStr = "-" + RHSStr;
13364 } else if (ExplicitPlus) {
13365 RHSStr = "+" + RHSStr;
13366 }
13367
13368 StringRef LHSStrRef = LHSStr;
13369 StringRef RHSStrRef = RHSStr;
13370 // Do not diagnose literals with digit separators, binary, hexadecimal, octal
13371 // literals.
13372 if (LHSStrRef.startswith("0b") || LHSStrRef.startswith("0B") ||
13373 RHSStrRef.startswith("0b") || RHSStrRef.startswith("0B") ||
13374 LHSStrRef.startswith("0x") || LHSStrRef.startswith("0X") ||
13375 RHSStrRef.startswith("0x") || RHSStrRef.startswith("0X") ||
13376 (LHSStrRef.size() > 1 && LHSStrRef.startswith("0")) ||
13377 (RHSStrRef.size() > 1 && RHSStrRef.startswith("0")) ||
13378 LHSStrRef.contains('\'') || RHSStrRef.contains('\''))
13379 return;
13380
13381 bool SuggestXor =
13382 S.getLangOpts().CPlusPlus || S.getPreprocessor().isMacroDefined("xor");
13383 const llvm::APInt XorValue = LeftSideValue ^ RightSideValue;
13384 int64_t RightSideIntValue = RightSideValue.getSExtValue();
13385 if (LeftSideValue == 2 && RightSideIntValue >= 0) {
13386 std::string SuggestedExpr = "1 << " + RHSStr;
13387 bool Overflow = false;
13388 llvm::APInt One = (LeftSideValue - 1);
13389 llvm::APInt PowValue = One.sshl_ov(RightSideValue, Overflow);
13390 if (Overflow) {
13391 if (RightSideIntValue < 64)
13392 S.Diag(Loc, diag::warn_xor_used_as_pow_base)
13393 << ExprStr << toString(XorValue, 10, true) << ("1LL << " + RHSStr)
13394 << FixItHint::CreateReplacement(ExprRange, "1LL << " + RHSStr);
13395 else if (RightSideIntValue == 64)
13396 S.Diag(Loc, diag::warn_xor_used_as_pow)
13397 << ExprStr << toString(XorValue, 10, true);
13398 else
13399 return;
13400 } else {
13401 S.Diag(Loc, diag::warn_xor_used_as_pow_base_extra)
13402 << ExprStr << toString(XorValue, 10, true) << SuggestedExpr
13403 << toString(PowValue, 10, true)
13404 << FixItHint::CreateReplacement(
13405 ExprRange, (RightSideIntValue == 0) ? "1" : SuggestedExpr);
13406 }
13407
13408 S.Diag(Loc, diag::note_xor_used_as_pow_silence)
13409 << ("0x2 ^ " + RHSStr) << SuggestXor;
13410 } else if (LeftSideValue == 10) {
13411 std::string SuggestedValue = "1e" + std::to_string(RightSideIntValue);
13412 S.Diag(Loc, diag::warn_xor_used_as_pow_base)
13413 << ExprStr << toString(XorValue, 10, true) << SuggestedValue
13414 << FixItHint::CreateReplacement(ExprRange, SuggestedValue);
13415 S.Diag(Loc, diag::note_xor_used_as_pow_silence)
13416 << ("0xA ^ " + RHSStr) << SuggestXor;
13417 }
13418}
13419
13420QualType Sema::CheckVectorLogicalOperands(ExprResult &LHS, ExprResult &RHS,
13421 SourceLocation Loc) {
13422 // Ensure that either both operands are of the same vector type, or
13423 // one operand is of a vector type and the other is of its element type.
13424 QualType vType = CheckVectorOperands(LHS, RHS, Loc, false,
13425 /*AllowBothBool*/ true,
13426 /*AllowBoolConversions*/ false,
13427 /*AllowBooleanOperation*/ false,
13428 /*ReportInvalid*/ false);
13429 if (vType.isNull())
13430 return InvalidOperands(Loc, LHS, RHS);
13431 if (getLangOpts().OpenCL &&
13432 getLangOpts().getOpenCLCompatibleVersion() < 120 &&
13433 vType->hasFloatingRepresentation())
13434 return InvalidOperands(Loc, LHS, RHS);
13435 // FIXME: The check for C++ here is for GCC compatibility. GCC rejects the
13436 // usage of the logical operators && and || with vectors in C. This
13437 // check could be notionally dropped.
13438 if (!getLangOpts().CPlusPlus &&
13439 !(isa<ExtVectorType>(vType->getAs<VectorType>())))
13440 return InvalidLogicalVectorOperands(Loc, LHS, RHS);
13441
13442 return GetSignedVectorType(LHS.get()->getType());
13443}
13444
13445QualType Sema::CheckMatrixElementwiseOperands(ExprResult &LHS, ExprResult &RHS,
13446 SourceLocation Loc,
13447 bool IsCompAssign) {
13448 if (!IsCompAssign) {
13449 LHS = DefaultFunctionArrayLvalueConversion(LHS.get());
13450 if (LHS.isInvalid())
13451 return QualType();
13452 }
13453 RHS = DefaultFunctionArrayLvalueConversion(RHS.get());
13454 if (RHS.isInvalid())
13455 return QualType();
13456
13457 // For conversion purposes, we ignore any qualifiers.
13458 // For example, "const float" and "float" are equivalent.
13459 QualType LHSType = LHS.get()->getType().getUnqualifiedType();
13460 QualType RHSType = RHS.get()->getType().getUnqualifiedType();
13461
13462 const MatrixType *LHSMatType = LHSType->getAs<MatrixType>();
13463 const MatrixType *RHSMatType = RHSType->getAs<MatrixType>();
13464 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", 13464, __extension__ __PRETTY_FUNCTION__
))
;
13465
13466 if (Context.hasSameType(LHSType, RHSType))
13467 return Context.getCommonSugaredType(LHSType, RHSType);
13468
13469 // Type conversion may change LHS/RHS. Keep copies to the original results, in
13470 // case we have to return InvalidOperands.
13471 ExprResult OriginalLHS = LHS;
13472 ExprResult OriginalRHS = RHS;
13473 if (LHSMatType && !RHSMatType) {
13474 RHS = tryConvertExprToType(RHS.get(), LHSMatType->getElementType());
13475 if (!RHS.isInvalid())
13476 return LHSType;
13477
13478 return InvalidOperands(Loc, OriginalLHS, OriginalRHS);
13479 }
13480
13481 if (!LHSMatType && RHSMatType) {
13482 LHS = tryConvertExprToType(LHS.get(), RHSMatType->getElementType());
13483 if (!LHS.isInvalid())
13484 return RHSType;
13485 return InvalidOperands(Loc, OriginalLHS, OriginalRHS);
13486 }
13487
13488 return InvalidOperands(Loc, LHS, RHS);
13489}
13490
13491QualType Sema::CheckMatrixMultiplyOperands(ExprResult &LHS, ExprResult &RHS,
13492 SourceLocation Loc,
13493 bool IsCompAssign) {
13494 if (!IsCompAssign) {
13495 LHS = DefaultFunctionArrayLvalueConversion(LHS.get());
13496 if (LHS.isInvalid())
13497 return QualType();
13498 }
13499 RHS = DefaultFunctionArrayLvalueConversion(RHS.get());
13500 if (RHS.isInvalid())
13501 return QualType();
13502
13503 auto *LHSMatType = LHS.get()->getType()->getAs<ConstantMatrixType>();
13504 auto *RHSMatType = RHS.get()->getType()->getAs<ConstantMatrixType>();
13505 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", 13505, __extension__ __PRETTY_FUNCTION__
))
;
13506
13507 if (LHSMatType && RHSMatType) {
13508 if (LHSMatType->getNumColumns() != RHSMatType->getNumRows())
13509 return InvalidOperands(Loc, LHS, RHS);
13510
13511 if (Context.hasSameType(LHSMatType, RHSMatType))
13512 return Context.getCommonSugaredType(
13513 LHS.get()->getType().getUnqualifiedType(),
13514 RHS.get()->getType().getUnqualifiedType());
13515
13516 QualType LHSELTy = LHSMatType->getElementType(),
13517 RHSELTy = RHSMatType->getElementType();
13518 if (!Context.hasSameType(LHSELTy, RHSELTy))
13519 return InvalidOperands(Loc, LHS, RHS);
13520
13521 return Context.getConstantMatrixType(
13522 Context.getCommonSugaredType(LHSELTy, RHSELTy),
13523 LHSMatType->getNumRows(), RHSMatType->getNumColumns());
13524 }
13525 return CheckMatrixElementwiseOperands(LHS, RHS, Loc, IsCompAssign);
13526}
13527
13528static bool isLegalBoolVectorBinaryOp(BinaryOperatorKind Opc) {
13529 switch (Opc) {
13530 default:
13531 return false;
13532 case BO_And:
13533 case BO_AndAssign:
13534 case BO_Or:
13535 case BO_OrAssign:
13536 case BO_Xor:
13537 case BO_XorAssign:
13538 return true;
13539 }
13540}
13541
13542inline QualType Sema::CheckBitwiseOperands(ExprResult &LHS, ExprResult &RHS,
13543 SourceLocation Loc,
13544 BinaryOperatorKind Opc) {
13545 checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/false);
13546
13547 bool IsCompAssign =
13548 Opc == BO_AndAssign || Opc == BO_OrAssign || Opc == BO_XorAssign;
13549
13550 bool LegalBoolVecOperator = isLegalBoolVectorBinaryOp(Opc);
13551
13552 if (LHS.get()->getType()->isVectorType() ||
13553 RHS.get()->getType()->isVectorType()) {
13554 if (LHS.get()->getType()->hasIntegerRepresentation() &&
13555 RHS.get()->getType()->hasIntegerRepresentation())
13556 return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign,
13557 /*AllowBothBool*/ true,
13558 /*AllowBoolConversions*/ getLangOpts().ZVector,
13559 /*AllowBooleanOperation*/ LegalBoolVecOperator,
13560 /*ReportInvalid*/ true);
13561 return InvalidOperands(Loc, LHS, RHS);
13562 }
13563
13564 if (LHS.get()->getType()->isVLSTBuiltinType() ||
13565 RHS.get()->getType()->isVLSTBuiltinType()) {
13566 if (LHS.get()->getType()->hasIntegerRepresentation() &&
13567 RHS.get()->getType()->hasIntegerRepresentation())
13568 return CheckSizelessVectorOperands(LHS, RHS, Loc, IsCompAssign,
13569 ACK_BitwiseOp);
13570 return InvalidOperands(Loc, LHS, RHS);
13571 }
13572
13573 if (LHS.get()->getType()->isVLSTBuiltinType() ||
13574 RHS.get()->getType()->isVLSTBuiltinType()) {
13575 if (LHS.get()->getType()->hasIntegerRepresentation() &&
13576 RHS.get()->getType()->hasIntegerRepresentation())
13577 return CheckSizelessVectorOperands(LHS, RHS, Loc, IsCompAssign,
13578 ACK_BitwiseOp);
13579 return InvalidOperands(Loc, LHS, RHS);
13580 }
13581
13582 if (Opc == BO_And)
13583 diagnoseLogicalNotOnLHSofCheck(*this, LHS, RHS, Loc, Opc);
13584
13585 if (LHS.get()->getType()->hasFloatingRepresentation() ||
13586 RHS.get()->getType()->hasFloatingRepresentation())
13587 return InvalidOperands(Loc, LHS, RHS);
13588
13589 ExprResult LHSResult = LHS, RHSResult = RHS;
13590 QualType compType = UsualArithmeticConversions(
13591 LHSResult, RHSResult, Loc, IsCompAssign ? ACK_CompAssign : ACK_BitwiseOp);
13592 if (LHSResult.isInvalid() || RHSResult.isInvalid())
13593 return QualType();
13594 LHS = LHSResult.get();
13595 RHS = RHSResult.get();
13596
13597 if (Opc == BO_Xor)
13598 diagnoseXorMisusedAsPow(*this, LHS, RHS, Loc);
13599
13600 if (!compType.isNull() && compType->isIntegralOrUnscopedEnumerationType())
13601 return compType;
13602 return InvalidOperands(Loc, LHS, RHS);
13603}
13604
13605// C99 6.5.[13,14]
13606inline QualType Sema::CheckLogicalOperands(ExprResult &LHS, ExprResult &RHS,
13607 SourceLocation Loc,
13608 BinaryOperatorKind Opc) {
13609 // Check vector operands differently.
13610 if (LHS.get()->getType()->isVectorType() ||
13611 RHS.get()->getType()->isVectorType())
13612 return CheckVectorLogicalOperands(LHS, RHS, Loc);
13613
13614 bool EnumConstantInBoolContext = false;
13615 for (const ExprResult &HS : {LHS, RHS}) {
13616 if (const auto *DREHS = dyn_cast<DeclRefExpr>(HS.get())) {
13617 const auto *ECDHS = dyn_cast<EnumConstantDecl>(DREHS->getDecl());
13618 if (ECDHS && ECDHS->getInitVal() != 0 && ECDHS->getInitVal() != 1)
13619 EnumConstantInBoolContext = true;
13620 }
13621 }
13622
13623 if (EnumConstantInBoolContext)
13624 Diag(Loc, diag::warn_enum_constant_in_bool_context);
13625
13626 // Diagnose cases where the user write a logical and/or but probably meant a
13627 // bitwise one. We do this when the LHS is a non-bool integer and the RHS
13628 // is a constant.
13629 if (!EnumConstantInBoolContext && LHS.get()->getType()->isIntegerType() &&
13630 !LHS.get()->getType()->isBooleanType() &&
13631 RHS.get()->getType()->isIntegerType() && !RHS.get()->isValueDependent() &&
13632 // Don't warn in macros or template instantiations.
13633 !Loc.isMacroID() && !inTemplateInstantiation()) {
13634 // If the RHS can be constant folded, and if it constant folds to something
13635 // that isn't 0 or 1 (which indicate a potential logical operation that
13636 // happened to fold to true/false) then warn.
13637 // Parens on the RHS are ignored.
13638 Expr::EvalResult EVResult;
13639 if (RHS.get()->EvaluateAsInt(EVResult, Context)) {
13640 llvm::APSInt Result = EVResult.Val.getInt();
13641 if ((getLangOpts().Bool && !RHS.get()->getType()->isBooleanType() &&
13642 !RHS.get()->getExprLoc().isMacroID()) ||
13643 (Result != 0 && Result != 1)) {
13644 Diag(Loc, diag::warn_logical_instead_of_bitwise)
13645 << RHS.get()->getSourceRange() << (Opc == BO_LAnd ? "&&" : "||");
13646 // Suggest replacing the logical operator with the bitwise version
13647 Diag(Loc, diag::note_logical_instead_of_bitwise_change_operator)
13648 << (Opc == BO_LAnd ? "&" : "|")
13649 << FixItHint::CreateReplacement(
13650 SourceRange(Loc, getLocForEndOfToken(Loc)),
13651 Opc == BO_LAnd ? "&" : "|");
13652 if (Opc == BO_LAnd)
13653 // Suggest replacing "Foo() && kNonZero" with "Foo()"
13654 Diag(Loc, diag::note_logical_instead_of_bitwise_remove_constant)
13655 << FixItHint::CreateRemoval(
13656 SourceRange(getLocForEndOfToken(LHS.get()->getEndLoc()),
13657 RHS.get()->getEndLoc()));
13658 }
13659 }
13660 }
13661
13662 if (!Context.getLangOpts().CPlusPlus) {
13663 // OpenCL v1.1 s6.3.g: The logical operators and (&&), or (||) do
13664 // not operate on the built-in scalar and vector float types.
13665 if (Context.getLangOpts().OpenCL &&
13666 Context.getLangOpts().OpenCLVersion < 120) {
13667 if (LHS.get()->getType()->isFloatingType() ||
13668 RHS.get()->getType()->isFloatingType())
13669 return InvalidOperands(Loc, LHS, RHS);
13670 }
13671
13672 LHS = UsualUnaryConversions(LHS.get());
13673 if (LHS.isInvalid())
13674 return QualType();
13675
13676 RHS = UsualUnaryConversions(RHS.get());
13677 if (RHS.isInvalid())
13678 return QualType();
13679
13680 if (!LHS.get()->getType()->isScalarType() ||
13681 !RHS.get()->getType()->isScalarType())
13682 return InvalidOperands(Loc, LHS, RHS);
13683
13684 return Context.IntTy;
13685 }
13686
13687 // The following is safe because we only use this method for
13688 // non-overloadable operands.
13689
13690 // C++ [expr.log.and]p1
13691 // C++ [expr.log.or]p1
13692 // The operands are both contextually converted to type bool.
13693 ExprResult LHSRes = PerformContextuallyConvertToBool(LHS.get());
13694 if (LHSRes.isInvalid())
13695 return InvalidOperands(Loc, LHS, RHS);
13696 LHS = LHSRes;
13697
13698 ExprResult RHSRes = PerformContextuallyConvertToBool(RHS.get());
13699 if (RHSRes.isInvalid())
13700 return InvalidOperands(Loc, LHS, RHS);
13701 RHS = RHSRes;
13702
13703 // C++ [expr.log.and]p2
13704 // C++ [expr.log.or]p2
13705 // The result is a bool.
13706 return Context.BoolTy;
13707}
13708
13709static bool IsReadonlyMessage(Expr *E, Sema &S) {
13710 const MemberExpr *ME = dyn_cast<MemberExpr>(E);
13711 if (!ME) return false;
13712 if (!isa<FieldDecl>(ME->getMemberDecl())) return false;
13713 ObjCMessageExpr *Base = dyn_cast<ObjCMessageExpr>(
13714 ME->getBase()->IgnoreImplicit()->IgnoreParenImpCasts());
13715 if (!Base) return false;
13716 return Base->getMethodDecl() != nullptr;
13717}
13718
13719/// Is the given expression (which must be 'const') a reference to a
13720/// variable which was originally non-const, but which has become
13721/// 'const' due to being captured within a block?
13722enum NonConstCaptureKind { NCCK_None, NCCK_Block, NCCK_Lambda };
13723static NonConstCaptureKind isReferenceToNonConstCapture(Sema &S, Expr *E) {
13724 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", 13724, __extension__ __PRETTY_FUNCTION__
))
;
13725 E = E->IgnoreParens();
13726
13727 // Must be a reference to a declaration from an enclosing scope.
13728 DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E);
13729 if (!DRE) return NCCK_None;
13730 if (!DRE->refersToEnclosingVariableOrCapture()) return NCCK_None;
13731
13732 // The declaration must be a variable which is not declared 'const'.
13733 VarDecl *var = dyn_cast<VarDecl>(DRE->getDecl());
13734 if (!var) return NCCK_None;
13735 if (var->getType().isConstQualified()) return NCCK_None;
13736 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", 13736, __extension__ __PRETTY_FUNCTION__
))
;
13737
13738 // Decide whether the first capture was for a block or a lambda.
13739 DeclContext *DC = S.CurContext, *Prev = nullptr;
13740 // Decide whether the first capture was for a block or a lambda.
13741 while (DC) {
13742 // For init-capture, it is possible that the variable belongs to the
13743 // template pattern of the current context.
13744 if (auto *FD = dyn_cast<FunctionDecl>(DC))
13745 if (var->isInitCapture() &&
13746 FD->getTemplateInstantiationPattern() == var->getDeclContext())
13747 break;
13748 if (DC == var->getDeclContext())
13749 break;
13750 Prev = DC;
13751 DC = DC->getParent();
13752 }
13753 // Unless we have an init-capture, we've gone one step too far.
13754 if (!var->isInitCapture())
13755 DC = Prev;
13756 return (isa<BlockDecl>(DC) ? NCCK_Block : NCCK_Lambda);
13757}
13758
13759static bool IsTypeModifiable(QualType Ty, bool IsDereference) {
13760 Ty = Ty.getNonReferenceType();
13761 if (IsDereference && Ty->isPointerType())
13762 Ty = Ty->getPointeeType();
13763 return !Ty.isConstQualified();
13764}
13765
13766// Update err_typecheck_assign_const and note_typecheck_assign_const
13767// when this enum is changed.
13768enum {
13769 ConstFunction,
13770 ConstVariable,
13771 ConstMember,
13772 ConstMethod,
13773 NestedConstMember,
13774 ConstUnknown, // Keep as last element
13775};
13776
13777/// Emit the "read-only variable not assignable" error and print notes to give
13778/// more information about why the variable is not assignable, such as pointing
13779/// to the declaration of a const variable, showing that a method is const, or
13780/// that the function is returning a const reference.
13781static void DiagnoseConstAssignment(Sema &S, const Expr *E,
13782 SourceLocation Loc) {
13783 SourceRange ExprRange = E->getSourceRange();
13784
13785 // Only emit one error on the first const found. All other consts will emit
13786 // a note to the error.
13787 bool DiagnosticEmitted = false;
13788
13789 // Track if the current expression is the result of a dereference, and if the
13790 // next checked expression is the result of a dereference.
13791 bool IsDereference = false;
13792 bool NextIsDereference = false;
13793
13794 // Loop to process MemberExpr chains.
13795 while (true) {
13796 IsDereference = NextIsDereference;
13797
13798 E = E->IgnoreImplicit()->IgnoreParenImpCasts();
13799 if (const MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
13800 NextIsDereference = ME->isArrow();
13801 const ValueDecl *VD = ME->getMemberDecl();
13802 if (const FieldDecl *Field = dyn_cast<FieldDecl>(VD)) {
13803 // Mutable fields can be modified even if the class is const.
13804 if (Field->isMutable()) {
13805 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", 13805, __extension__ __PRETTY_FUNCTION__
))
;
13806 break;
13807 }
13808
13809 if (!IsTypeModifiable(Field->getType(), IsDereference)) {
13810 if (!DiagnosticEmitted) {
13811 S.Diag(Loc, diag::err_typecheck_assign_const)
13812 << ExprRange << ConstMember << false /*static*/ << Field
13813 << Field->getType();
13814 DiagnosticEmitted = true;
13815 }
13816 S.Diag(VD->getLocation(), diag::note_typecheck_assign_const)
13817 << ConstMember << false /*static*/ << Field << Field->getType()
13818 << Field->getSourceRange();
13819 }
13820 E = ME->getBase();
13821 continue;
13822 } else if (const VarDecl *VDecl = dyn_cast<VarDecl>(VD)) {
13823 if (VDecl->getType().isConstQualified()) {
13824 if (!DiagnosticEmitted) {
13825 S.Diag(Loc, diag::err_typecheck_assign_const)
13826 << ExprRange << ConstMember << true /*static*/ << VDecl
13827 << VDecl->getType();
13828 DiagnosticEmitted = true;
13829 }
13830 S.Diag(VD->getLocation(), diag::note_typecheck_assign_const)
13831 << ConstMember << true /*static*/ << VDecl << VDecl->getType()
13832 << VDecl->getSourceRange();
13833 }
13834 // Static fields do not inherit constness from parents.
13835 break;
13836 }
13837 break; // End MemberExpr
13838 } else if (const ArraySubscriptExpr *ASE =
13839 dyn_cast<ArraySubscriptExpr>(E)) {
13840 E = ASE->getBase()->IgnoreParenImpCasts();
13841 continue;
13842 } else if (const ExtVectorElementExpr *EVE =
13843 dyn_cast<ExtVectorElementExpr>(E)) {
13844 E = EVE->getBase()->IgnoreParenImpCasts();
13845 continue;
13846 }
13847 break;
13848 }
13849
13850 if (const CallExpr *CE = dyn_cast<CallExpr>(E)) {
13851 // Function calls
13852 const FunctionDecl *FD = CE->getDirectCallee();
13853 if (FD && !IsTypeModifiable(FD->getReturnType(), IsDereference)) {
13854 if (!DiagnosticEmitted) {
13855 S.Diag(Loc, diag::err_typecheck_assign_const) << ExprRange
13856 << ConstFunction << FD;
13857 DiagnosticEmitted = true;
13858 }
13859 S.Diag(FD->getReturnTypeSourceRange().getBegin(),
13860 diag::note_typecheck_assign_const)
13861 << ConstFunction << FD << FD->getReturnType()
13862 << FD->getReturnTypeSourceRange();
13863 }
13864 } else if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
13865 // Point to variable declaration.
13866 if (const ValueDecl *VD = DRE->getDecl()) {
13867 if (!IsTypeModifiable(VD->getType(), IsDereference)) {
13868 if (!DiagnosticEmitted) {
13869 S.Diag(Loc, diag::err_typecheck_assign_const)
13870 << ExprRange << ConstVariable << VD << VD->getType();
13871 DiagnosticEmitted = true;
13872 }
13873 S.Diag(VD->getLocation(), diag::note_typecheck_assign_const)
13874 << ConstVariable << VD << VD->getType() << VD->getSourceRange();
13875 }
13876 }
13877 } else if (isa<CXXThisExpr>(E)) {
13878 if (const DeclContext *DC = S.getFunctionLevelDeclContext()) {
13879 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(DC)) {
13880 if (MD->isConst()) {
13881 if (!DiagnosticEmitted) {
13882 S.Diag(Loc, diag::err_typecheck_assign_const) << ExprRange
13883 << ConstMethod << MD;
13884 DiagnosticEmitted = true;
13885 }
13886 S.Diag(MD->getLocation(), diag::note_typecheck_assign_const)
13887 << ConstMethod << MD << MD->getSourceRange();
13888 }
13889 }
13890 }
13891 }
13892
13893 if (DiagnosticEmitted)
13894 return;
13895
13896 // Can't determine a more specific message, so display the generic error.
13897 S.Diag(Loc, diag::err_typecheck_assign_const) << ExprRange << ConstUnknown;
13898}
13899
13900enum OriginalExprKind {
13901 OEK_Variable,
13902 OEK_Member,
13903 OEK_LValue
13904};
13905
13906static void DiagnoseRecursiveConstFields(Sema &S, const ValueDecl *VD,
13907 const RecordType *Ty,
13908 SourceLocation Loc, SourceRange Range,
13909 OriginalExprKind OEK,
13910 bool &DiagnosticEmitted) {
13911 std::vector<const RecordType *> RecordTypeList;
13912 RecordTypeList.push_back(Ty);
13913 unsigned NextToCheckIndex = 0;
13914 // We walk the record hierarchy breadth-first to ensure that we print
13915 // diagnostics in field nesting order.
13916 while (RecordTypeList.size() > NextToCheckIndex) {
13917 bool IsNested = NextToCheckIndex > 0;
13918 for (const FieldDecl *Field :
13919 RecordTypeList[NextToCheckIndex]->getDecl()->fields()) {
13920 // First, check every field for constness.
13921 QualType FieldTy = Field->getType();
13922 if (FieldTy.isConstQualified()) {
13923 if (!DiagnosticEmitted) {
13924 S.Diag(Loc, diag::err_typecheck_assign_const)
13925 << Range << NestedConstMember << OEK << VD
13926 << IsNested << Field;
13927 DiagnosticEmitted = true;
13928 }
13929 S.Diag(Field->getLocation(), diag::note_typecheck_assign_const)
13930 << NestedConstMember << IsNested << Field
13931 << FieldTy << Field->getSourceRange();
13932 }
13933
13934 // Then we append it to the list to check next in order.
13935 FieldTy = FieldTy.getCanonicalType();
13936 if (const auto *FieldRecTy = FieldTy->getAs<RecordType>()) {
13937 if (!llvm::is_contained(RecordTypeList, FieldRecTy))
13938 RecordTypeList.push_back(FieldRecTy);
13939 }
13940 }
13941 ++NextToCheckIndex;
13942 }
13943}
13944
13945/// Emit an error for the case where a record we are trying to assign to has a
13946/// const-qualified field somewhere in its hierarchy.
13947static void DiagnoseRecursiveConstFields(Sema &S, const Expr *E,
13948 SourceLocation Loc) {
13949 QualType Ty = E->getType();
13950 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", 13950, __extension__ __PRETTY_FUNCTION__
))
;
13951 SourceRange Range = E->getSourceRange();
13952 const RecordType *RTy = Ty.getCanonicalType()->getAs<RecordType>();
13953 bool DiagEmitted = false;
13954
13955 if (const MemberExpr *ME = dyn_cast<MemberExpr>(E))
13956 DiagnoseRecursiveConstFields(S, ME->getMemberDecl(), RTy, Loc,
13957 Range, OEK_Member, DiagEmitted);
13958 else if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
13959 DiagnoseRecursiveConstFields(S, DRE->getDecl(), RTy, Loc,
13960 Range, OEK_Variable, DiagEmitted);
13961 else
13962 DiagnoseRecursiveConstFields(S, nullptr, RTy, Loc,
13963 Range, OEK_LValue, DiagEmitted);
13964 if (!DiagEmitted)
13965 DiagnoseConstAssignment(S, E, Loc);
13966}
13967
13968/// CheckForModifiableLvalue - Verify that E is a modifiable lvalue. If not,
13969/// emit an error and return true. If so, return false.
13970static bool CheckForModifiableLvalue(Expr *E, SourceLocation Loc, Sema &S) {
13971 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", 13971, __extension__ __PRETTY_FUNCTION__
))
;
13972
13973 S.CheckShadowingDeclModification(E, Loc);
13974
13975 SourceLocation OrigLoc = Loc;
13976 Expr::isModifiableLvalueResult IsLV = E->isModifiableLvalue(S.Context,
13977 &Loc);
13978 if (IsLV == Expr::MLV_ClassTemporary && IsReadonlyMessage(E, S))
13979 IsLV = Expr::MLV_InvalidMessageExpression;
13980 if (IsLV == Expr::MLV_Valid)
13981 return false;
13982
13983 unsigned DiagID = 0;
13984 bool NeedType = false;
13985 switch (IsLV) { // C99 6.5.16p2
13986 case Expr::MLV_ConstQualified:
13987 // Use a specialized diagnostic when we're assigning to an object
13988 // from an enclosing function or block.
13989 if (NonConstCaptureKind NCCK = isReferenceToNonConstCapture(S, E)) {
13990 if (NCCK == NCCK_Block)
13991 DiagID = diag::err_block_decl_ref_not_modifiable_lvalue;
13992 else
13993 DiagID = diag::err_lambda_decl_ref_not_modifiable_lvalue;
13994 break;
13995 }
13996
13997 // In ARC, use some specialized diagnostics for occasions where we
13998 // infer 'const'. These are always pseudo-strong variables.
13999 if (S.getLangOpts().ObjCAutoRefCount) {
14000 DeclRefExpr *declRef = dyn_cast<DeclRefExpr>(E->IgnoreParenCasts());
14001 if (declRef && isa<VarDecl>(declRef->getDecl())) {
14002 VarDecl *var = cast<VarDecl>(declRef->getDecl());
14003
14004 // Use the normal diagnostic if it's pseudo-__strong but the
14005 // user actually wrote 'const'.
14006 if (var->isARCPseudoStrong() &&
14007 (!var->getTypeSourceInfo() ||
14008 !var->getTypeSourceInfo()->getType().isConstQualified())) {
14009 // There are three pseudo-strong cases:
14010 // - self
14011 ObjCMethodDecl *method = S.getCurMethodDecl();
14012 if (method && var == method->getSelfDecl()) {
14013 DiagID = method->isClassMethod()
14014 ? diag::err_typecheck_arc_assign_self_class_method
14015 : diag::err_typecheck_arc_assign_self;
14016
14017 // - Objective-C externally_retained attribute.
14018 } else if (var->hasAttr<ObjCExternallyRetainedAttr>() ||
14019 isa<ParmVarDecl>(var)) {
14020 DiagID = diag::err_typecheck_arc_assign_externally_retained;
14021
14022 // - fast enumeration variables
14023 } else {
14024 DiagID = diag::err_typecheck_arr_assign_enumeration;
14025 }
14026
14027 SourceRange Assign;
14028 if (Loc != OrigLoc)
14029 Assign = SourceRange(OrigLoc, OrigLoc);
14030 S.Diag(Loc, DiagID) << E->getSourceRange() << Assign;
14031 // We need to preserve the AST regardless, so migration tool
14032 // can do its job.
14033 return false;
14034 }
14035 }
14036 }
14037
14038 // If none of the special cases above are triggered, then this is a
14039 // simple const assignment.
14040 if (DiagID == 0) {
14041 DiagnoseConstAssignment(S, E, Loc);
14042 return true;
14043 }
14044
14045 break;
14046 case Expr::MLV_ConstAddrSpace:
14047 DiagnoseConstAssignment(S, E, Loc);
14048 return true;
14049 case Expr::MLV_ConstQualifiedField:
14050 DiagnoseRecursiveConstFields(S, E, Loc);
14051 return true;
14052 case Expr::MLV_ArrayType:
14053 case Expr::MLV_ArrayTemporary:
14054 DiagID = diag::err_typecheck_array_not_modifiable_lvalue;
14055 NeedType = true;
14056 break;
14057 case Expr::MLV_NotObjectType:
14058 DiagID = diag::err_typecheck_non_object_not_modifiable_lvalue;
14059 NeedType = true;
14060 break;
14061 case Expr::MLV_LValueCast:
14062 DiagID = diag::err_typecheck_lvalue_casts_not_supported;
14063 break;
14064 case Expr::MLV_Valid:
14065 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", 14065)
;
14066 case Expr::MLV_InvalidExpression:
14067 case Expr::MLV_MemberFunction:
14068 case Expr::MLV_ClassTemporary:
14069 DiagID = diag::err_typecheck_expression_not_modifiable_lvalue;
14070 break;
14071 case Expr::MLV_IncompleteType:
14072 case Expr::MLV_IncompleteVoidType:
14073 return S.RequireCompleteType(Loc, E->getType(),
14074 diag::err_typecheck_incomplete_type_not_modifiable_lvalue, E);
14075 case Expr::MLV_DuplicateVectorComponents:
14076 DiagID = diag::err_typecheck_duplicate_vector_components_not_mlvalue;
14077 break;
14078 case Expr::MLV_NoSetterProperty:
14079 llvm_unreachable("readonly properties should be processed differently")::llvm::llvm_unreachable_internal("readonly properties should be processed differently"
, "clang/lib/Sema/SemaExpr.cpp", 14079)
;
14080 case Expr::MLV_InvalidMessageExpression:
14081 DiagID = diag::err_readonly_message_assignment;
14082 break;
14083 case Expr::MLV_SubObjCPropertySetting:
14084 DiagID = diag::err_no_subobject_property_setting;
14085 break;
14086 }
14087
14088 SourceRange Assign;
14089 if (Loc != OrigLoc)
14090 Assign = SourceRange(OrigLoc, OrigLoc);
14091 if (NeedType)
14092 S.Diag(Loc, DiagID) << E->getType() << E->getSourceRange() << Assign;
14093 else
14094 S.Diag(Loc, DiagID) << E->getSourceRange() << Assign;
14095 return true;
14096}
14097
14098static void CheckIdentityFieldAssignment(Expr *LHSExpr, Expr *RHSExpr,
14099 SourceLocation Loc,
14100 Sema &Sema) {
14101 if (Sema.inTemplateInstantiation())
14102 return;
14103 if (Sema.isUnevaluatedContext())
14104 return;
14105 if (Loc.isInvalid() || Loc.isMacroID())
14106 return;
14107 if (LHSExpr->getExprLoc().isMacroID() || RHSExpr->getExprLoc().isMacroID())
14108 return;
14109
14110 // C / C++ fields
14111 MemberExpr *ML = dyn_cast<MemberExpr>(LHSExpr);
14112 MemberExpr *MR = dyn_cast<MemberExpr>(RHSExpr);
14113 if (ML && MR) {
14114 if (!(isa<CXXThisExpr>(ML->getBase()) && isa<CXXThisExpr>(MR->getBase())))
14115 return;
14116 const ValueDecl *LHSDecl =
14117 cast<ValueDecl>(ML->getMemberDecl()->getCanonicalDecl());
14118 const ValueDecl *RHSDecl =
14119 cast<ValueDecl>(MR->getMemberDecl()->getCanonicalDecl());
14120 if (LHSDecl != RHSDecl)
14121 return;
14122 if (LHSDecl->getType().isVolatileQualified())
14123 return;
14124 if (const ReferenceType *RefTy = LHSDecl->getType()->getAs<ReferenceType>())
14125 if (RefTy->getPointeeType().isVolatileQualified())
14126 return;
14127
14128 Sema.Diag(Loc, diag::warn_identity_field_assign) << 0;
14129 }
14130
14131 // Objective-C instance variables
14132 ObjCIvarRefExpr *OL = dyn_cast<ObjCIvarRefExpr>(LHSExpr);
14133 ObjCIvarRefExpr *OR = dyn_cast<ObjCIvarRefExpr>(RHSExpr);
14134 if (OL && OR && OL->getDecl() == OR->getDecl()) {
14135 DeclRefExpr *RL = dyn_cast<DeclRefExpr>(OL->getBase()->IgnoreImpCasts());
14136 DeclRefExpr *RR = dyn_cast<DeclRefExpr>(OR->getBase()->IgnoreImpCasts());
14137 if (RL && RR && RL->getDecl() == RR->getDecl())
14138 Sema.Diag(Loc, diag::warn_identity_field_assign) << 1;
14139 }
14140}
14141
14142// C99 6.5.16.1
14143QualType Sema::CheckAssignmentOperands(Expr *LHSExpr, ExprResult &RHS,
14144 SourceLocation Loc,
14145 QualType CompoundType,
14146 BinaryOperatorKind Opc) {
14147 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", 14147, __extension__ __PRETTY_FUNCTION__
))
;
14148
14149 // Verify that LHS is a modifiable lvalue, and emit error if not.
14150 if (CheckForModifiableLvalue(LHSExpr, Loc, *this))
14151 return QualType();
14152
14153 QualType LHSType = LHSExpr->getType();
14154 QualType RHSType = CompoundType.isNull() ? RHS.get()->getType() :
14155 CompoundType;
14156 // OpenCL v1.2 s6.1.1.1 p2:
14157 // The half data type can only be used to declare a pointer to a buffer that
14158 // contains half values
14159 if (getLangOpts().OpenCL &&
14160 !getOpenCLOptions().isAvailableOption("cl_khr_fp16", getLangOpts()) &&
14161 LHSType->isHalfType()) {
14162 Diag(Loc, diag::err_opencl_half_load_store) << 1
14163 << LHSType.getUnqualifiedType();
14164 return QualType();
14165 }
14166
14167 AssignConvertType ConvTy;
14168 if (CompoundType.isNull()) {
14169 Expr *RHSCheck = RHS.get();
14170
14171 CheckIdentityFieldAssignment(LHSExpr, RHSCheck, Loc, *this);
14172
14173 QualType LHSTy(LHSType);
14174 ConvTy = CheckSingleAssignmentConstraints(LHSTy, RHS);
14175 if (RHS.isInvalid())
14176 return QualType();
14177 // Special case of NSObject attributes on c-style pointer types.
14178 if (ConvTy == IncompatiblePointer &&
14179 ((Context.isObjCNSObjectType(LHSType) &&
14180 RHSType->isObjCObjectPointerType()) ||
14181 (Context.isObjCNSObjectType(RHSType) &&
14182 LHSType->isObjCObjectPointerType())))
14183 ConvTy = Compatible;
14184
14185 if (ConvTy == Compatible &&
14186 LHSType->isObjCObjectType())
14187 Diag(Loc, diag::err_objc_object_assignment)
14188 << LHSType;
14189
14190 // If the RHS is a unary plus or minus, check to see if they = and + are
14191 // right next to each other. If so, the user may have typo'd "x =+ 4"
14192 // instead of "x += 4".
14193 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(RHSCheck))
14194 RHSCheck = ICE->getSubExpr();
14195 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(RHSCheck)) {
14196 if ((UO->getOpcode() == UO_Plus || UO->getOpcode() == UO_Minus) &&
14197 Loc.isFileID() && UO->getOperatorLoc().isFileID() &&
14198 // Only if the two operators are exactly adjacent.
14199 Loc.getLocWithOffset(1) == UO->getOperatorLoc() &&
14200 // And there is a space or other character before the subexpr of the
14201 // unary +/-. We don't want to warn on "x=-1".
14202 Loc.getLocWithOffset(2) != UO->getSubExpr()->getBeginLoc() &&
14203 UO->getSubExpr()->getBeginLoc().isFileID()) {
14204 Diag(Loc, diag::warn_not_compound_assign)
14205 << (UO->getOpcode() == UO_Plus ? "+" : "-")
14206 << SourceRange(UO->getOperatorLoc(), UO->getOperatorLoc());
14207 }
14208 }
14209
14210 if (ConvTy == Compatible) {
14211 if (LHSType.getObjCLifetime() == Qualifiers::OCL_Strong) {
14212 // Warn about retain cycles where a block captures the LHS, but
14213 // not if the LHS is a simple variable into which the block is
14214 // being stored...unless that variable can be captured by reference!
14215 const Expr *InnerLHS = LHSExpr->IgnoreParenCasts();
14216 const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(InnerLHS);
14217 if (!DRE || DRE->getDecl()->hasAttr<BlocksAttr>())
14218 checkRetainCycles(LHSExpr, RHS.get());
14219 }
14220
14221 if (LHSType.getObjCLifetime() == Qualifiers::OCL_Strong ||
14222 LHSType.isNonWeakInMRRWithObjCWeak(Context)) {
14223 // It is safe to assign a weak reference into a strong variable.
14224 // Although this code can still have problems:
14225 // id x = self.weakProp;
14226 // id y = self.weakProp;
14227 // we do not warn to warn spuriously when 'x' and 'y' are on separate
14228 // paths through the function. This should be revisited if
14229 // -Wrepeated-use-of-weak is made flow-sensitive.
14230 // For ObjCWeak only, we do not warn if the assign is to a non-weak
14231 // variable, which will be valid for the current autorelease scope.
14232 if (!Diags.isIgnored(diag::warn_arc_repeated_use_of_weak,
14233 RHS.get()->getBeginLoc()))
14234 getCurFunction()->markSafeWeakUse(RHS.get());
14235
14236 } else if (getLangOpts().ObjCAutoRefCount || getLangOpts().ObjCWeak) {
14237 checkUnsafeExprAssigns(Loc, LHSExpr, RHS.get());
14238 }
14239 }
14240 } else {
14241 // Compound assignment "x += y"
14242 ConvTy = CheckAssignmentConstraints(Loc, LHSType, RHSType);
14243 }
14244
14245 if (DiagnoseAssignmentResult(ConvTy, Loc, LHSType, RHSType,
14246 RHS.get(), AA_Assigning))
14247 return QualType();
14248
14249 CheckForNullPointerDereference(*this, LHSExpr);
14250
14251 if (getLangOpts().CPlusPlus20 && LHSType.isVolatileQualified()) {
14252 if (CompoundType.isNull()) {
14253 // C++2a [expr.ass]p5:
14254 // A simple-assignment whose left operand is of a volatile-qualified
14255 // type is deprecated unless the assignment is either a discarded-value
14256 // expression or an unevaluated operand
14257 ExprEvalContexts.back().VolatileAssignmentLHSs.push_back(LHSExpr);
14258 }
14259 }
14260
14261 // C11 6.5.16p3: The type of an assignment expression is the type of the
14262 // left operand would have after lvalue conversion.
14263 // C11 6.3.2.1p2: ...this is called lvalue conversion. If the lvalue has
14264 // qualified type, the value has the unqualified version of the type of the
14265 // lvalue; additionally, if the lvalue has atomic type, the value has the
14266 // non-atomic version of the type of the lvalue.
14267 // C++ 5.17p1: the type of the assignment expression is that of its left
14268 // operand.
14269 return getLangOpts().CPlusPlus ? LHSType : LHSType.getAtomicUnqualifiedType();
14270}
14271
14272// Scenarios to ignore if expression E is:
14273// 1. an explicit cast expression into void
14274// 2. a function call expression that returns void
14275static bool IgnoreCommaOperand(const Expr *E, const ASTContext &Context) {
14276 E = E->IgnoreParens();
14277
14278 if (const CastExpr *CE = dyn_cast<CastExpr>(E)) {
14279 if (CE->getCastKind() == CK_ToVoid) {
14280 return true;
14281 }
14282
14283 // static_cast<void> on a dependent type will not show up as CK_ToVoid.
14284 if (CE->getCastKind() == CK_Dependent && E->getType()->isVoidType() &&
14285 CE->getSubExpr()->getType()->isDependentType()) {
14286 return true;
14287 }
14288 }
14289
14290 if (const auto *CE = dyn_cast<CallExpr>(E))
14291 return CE->getCallReturnType(Context)->isVoidType();
14292 return false;
14293}
14294
14295// Look for instances where it is likely the comma operator is confused with
14296// another operator. There is an explicit list of acceptable expressions for
14297// the left hand side of the comma operator, otherwise emit a warning.
14298void Sema::DiagnoseCommaOperator(const Expr *LHS, SourceLocation Loc) {
14299 // No warnings in macros
14300 if (Loc.isMacroID())
14301 return;
14302
14303 // Don't warn in template instantiations.
14304 if (inTemplateInstantiation())
14305 return;
14306
14307 // Scope isn't fine-grained enough to explicitly list the specific cases, so
14308 // instead, skip more than needed, then call back into here with the
14309 // CommaVisitor in SemaStmt.cpp.
14310 // The listed locations are the initialization and increment portions
14311 // of a for loop. The additional checks are on the condition of
14312 // if statements, do/while loops, and for loops.
14313 // Differences in scope flags for C89 mode requires the extra logic.
14314 const unsigned ForIncrementFlags =
14315 getLangOpts().C99 || getLangOpts().CPlusPlus
14316 ? Scope::ControlScope | Scope::ContinueScope | Scope::BreakScope
14317 : Scope::ContinueScope | Scope::BreakScope;
14318 const unsigned ForInitFlags = Scope::ControlScope | Scope::DeclScope;
14319 const unsigned ScopeFlags = getCurScope()->getFlags();
14320 if ((ScopeFlags & ForIncrementFlags) == ForIncrementFlags ||
14321 (ScopeFlags & ForInitFlags) == ForInitFlags)
14322 return;
14323
14324 // If there are multiple comma operators used together, get the RHS of the
14325 // of the comma operator as the LHS.
14326 while (const BinaryOperator *BO = dyn_cast<BinaryOperator>(LHS)) {
14327 if (BO->getOpcode() != BO_Comma)
14328 break;
14329 LHS = BO->getRHS();
14330 }
14331
14332 // Only allow some expressions on LHS to not warn.
14333 if (IgnoreCommaOperand(LHS, Context))
14334 return;
14335
14336 Diag(Loc, diag::warn_comma_operator);
14337 Diag(LHS->getBeginLoc(), diag::note_cast_to_void)
14338 << LHS->getSourceRange()
14339 << FixItHint::CreateInsertion(LHS->getBeginLoc(),
14340 LangOpts.CPlusPlus ? "static_cast<void>("
14341 : "(void)(")
14342 << FixItHint::CreateInsertion(PP.getLocForEndOfToken(LHS->getEndLoc()),
14343 ")");
14344}
14345
14346// C99 6.5.17
14347static QualType CheckCommaOperands(Sema &S, ExprResult &LHS, ExprResult &RHS,
14348 SourceLocation Loc) {
14349 LHS = S.CheckPlaceholderExpr(LHS.get());
14350 RHS = S.CheckPlaceholderExpr(RHS.get());
14351 if (LHS.isInvalid() || RHS.isInvalid())
14352 return QualType();
14353
14354 // C's comma performs lvalue conversion (C99 6.3.2.1) on both its
14355 // operands, but not unary promotions.
14356 // C++'s comma does not do any conversions at all (C++ [expr.comma]p1).
14357
14358 // So we treat the LHS as a ignored value, and in C++ we allow the
14359 // containing site to determine what should be done with the RHS.
14360 LHS = S.IgnoredValueConversions(LHS.get());
14361 if (LHS.isInvalid())
14362 return QualType();
14363
14364 S.DiagnoseUnusedExprResult(LHS.get(), diag::warn_unused_comma_left_operand);
14365
14366 if (!S.getLangOpts().CPlusPlus) {
14367 RHS = S.DefaultFunctionArrayLvalueConversion(RHS.get());
14368 if (RHS.isInvalid())
14369 return QualType();
14370 if (!RHS.get()->getType()->isVoidType())
14371 S.RequireCompleteType(Loc, RHS.get()->getType(),
14372 diag::err_incomplete_type);
14373 }
14374
14375 if (!S.getDiagnostics().isIgnored(diag::warn_comma_operator, Loc))
14376 S.DiagnoseCommaOperator(LHS.get(), Loc);
14377
14378 return RHS.get()->getType();
14379}
14380
14381/// CheckIncrementDecrementOperand - unlike most "Check" methods, this routine
14382/// doesn't need to call UsualUnaryConversions or UsualArithmeticConversions.
14383static QualType CheckIncrementDecrementOperand(Sema &S, Expr *Op,
14384 ExprValueKind &VK,
14385 ExprObjectKind &OK,
14386 SourceLocation OpLoc,
14387 bool IsInc, bool IsPrefix) {
14388 if (Op->isTypeDependent())
14389 return S.Context.DependentTy;
14390
14391 QualType ResType = Op->getType();
14392 // Atomic types can be used for increment / decrement where the non-atomic
14393 // versions can, so ignore the _Atomic() specifier for the purpose of
14394 // checking.
14395 if (const AtomicType *ResAtomicType = ResType->getAs<AtomicType>())
14396 ResType = ResAtomicType->getValueType();
14397
14398 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", 14398, __extension__ __PRETTY_FUNCTION__
))
;
14399
14400 if (S.getLangOpts().CPlusPlus && ResType->isBooleanType()) {
14401 // Decrement of bool is not allowed.
14402 if (!IsInc) {
14403 S.Diag(OpLoc, diag::err_decrement_bool) << Op->getSourceRange();
14404 return QualType();
14405 }
14406 // Increment of bool sets it to true, but is deprecated.
14407 S.Diag(OpLoc, S.getLangOpts().CPlusPlus17 ? diag::ext_increment_bool
14408 : diag::warn_increment_bool)
14409 << Op->getSourceRange();
14410 } else if (S.getLangOpts().CPlusPlus && ResType->isEnumeralType()) {
14411 // Error on enum increments and decrements in C++ mode
14412 S.Diag(OpLoc, diag::err_increment_decrement_enum) << IsInc << ResType;
14413 return QualType();
14414 } else if (ResType->isRealType()) {
14415 // OK!
14416 } else if (ResType->isPointerType()) {
14417 // C99 6.5.2.4p2, 6.5.6p2
14418 if (!checkArithmeticOpPointerOperand(S, OpLoc, Op))
14419 return QualType();
14420 } else if (ResType->isObjCObjectPointerType()) {
14421 // On modern runtimes, ObjC pointer arithmetic is forbidden.
14422 // Otherwise, we just need a complete type.
14423 if (checkArithmeticIncompletePointerType(S, OpLoc, Op) ||
14424 checkArithmeticOnObjCPointer(S, OpLoc, Op))
14425 return QualType();
14426 } else if (ResType->isAnyComplexType()) {
14427 // C99 does not support ++/-- on complex types, we allow as an extension.
14428 S.Diag(OpLoc, diag::ext_integer_increment_complex)
14429 << ResType << Op->getSourceRange();
14430 } else if (ResType->isPlaceholderType()) {
14431 ExprResult PR = S.CheckPlaceholderExpr(Op);
14432 if (PR.isInvalid()) return QualType();
14433 return CheckIncrementDecrementOperand(S, PR.get(), VK, OK, OpLoc,
14434 IsInc, IsPrefix);
14435 } else if (S.getLangOpts().AltiVec && ResType->isVectorType()) {
14436 // OK! ( C/C++ Language Extensions for CBEA(Version 2.6) 10.3 )
14437 } else if (S.getLangOpts().ZVector && ResType->isVectorType() &&
14438 (ResType->castAs<VectorType>()->getVectorKind() !=
14439 VectorType::AltiVecBool)) {
14440 // The z vector extensions allow ++ and -- for non-bool vectors.
14441 } else if(S.getLangOpts().OpenCL && ResType->isVectorType() &&
14442 ResType->castAs<VectorType>()->getElementType()->isIntegerType()) {
14443 // OpenCL V1.2 6.3 says dec/inc ops operate on integer vector types.
14444 } else {
14445 S.Diag(OpLoc, diag::err_typecheck_illegal_increment_decrement)
14446 << ResType << int(IsInc) << Op->getSourceRange();
14447 return QualType();
14448 }
14449 // At this point, we know we have a real, complex or pointer type.
14450 // Now make sure the operand is a modifiable lvalue.
14451 if (CheckForModifiableLvalue(Op, OpLoc, S))
14452 return QualType();
14453 if (S.getLangOpts().CPlusPlus20 && ResType.isVolatileQualified()) {
14454 // C++2a [expr.pre.inc]p1, [expr.post.inc]p1:
14455 // An operand with volatile-qualified type is deprecated
14456 S.Diag(OpLoc, diag::warn_deprecated_increment_decrement_volatile)
14457 << IsInc << ResType;
14458 }
14459 // In C++, a prefix increment is the same type as the operand. Otherwise
14460 // (in C or with postfix), the increment is the unqualified type of the
14461 // operand.
14462 if (IsPrefix && S.getLangOpts().CPlusPlus) {
14463 VK = VK_LValue;
14464 OK = Op->getObjectKind();
14465 return ResType;
14466 } else {
14467 VK = VK_PRValue;
14468 return ResType.getUnqualifiedType();
14469 }
14470}
14471
14472
14473/// getPrimaryDecl - Helper function for CheckAddressOfOperand().
14474/// This routine allows us to typecheck complex/recursive expressions
14475/// where the declaration is needed for type checking. We only need to
14476/// handle cases when the expression references a function designator
14477/// or is an lvalue. Here are some examples:
14478/// - &(x) => x
14479/// - &*****f => f for f a function designator.
14480/// - &s.xx => s
14481/// - &s.zz[1].yy -> s, if zz is an array
14482/// - *(x + 1) -> x, if x is an array
14483/// - &"123"[2] -> 0
14484/// - & __real__ x -> x
14485///
14486/// FIXME: We don't recurse to the RHS of a comma, nor handle pointers to
14487/// members.
14488static ValueDecl *getPrimaryDecl(Expr *E) {
14489 switch (E->getStmtClass()) {
14490 case Stmt::DeclRefExprClass:
14491 return cast<DeclRefExpr>(E)->getDecl();
14492 case Stmt::MemberExprClass:
14493 // If this is an arrow operator, the address is an offset from
14494 // the base's value, so the object the base refers to is
14495 // irrelevant.
14496 if (cast<MemberExpr>(E)->isArrow())
14497 return nullptr;
14498 // Otherwise, the expression refers to a part of the base
14499 return getPrimaryDecl(cast<MemberExpr>(E)->getBase());
14500 case Stmt::ArraySubscriptExprClass: {
14501 // FIXME: This code shouldn't be necessary! We should catch the implicit
14502 // promotion of register arrays earlier.
14503 Expr* Base = cast<ArraySubscriptExpr>(E)->getBase();
14504 if (ImplicitCastExpr* ICE = dyn_cast<ImplicitCastExpr>(Base)) {
14505 if (ICE->getSubExpr()->getType()->isArrayType())
14506 return getPrimaryDecl(ICE->getSubExpr());
14507 }
14508 return nullptr;
14509 }
14510 case Stmt::UnaryOperatorClass: {
14511 UnaryOperator *UO = cast<UnaryOperator>(E);
14512
14513 switch(UO->getOpcode()) {
14514 case UO_Real:
14515 case UO_Imag:
14516 case UO_Extension:
14517 return getPrimaryDecl(UO->getSubExpr());
14518 default:
14519 return nullptr;
14520 }
14521 }
14522 case Stmt::ParenExprClass:
14523 return getPrimaryDecl(cast<ParenExpr>(E)->getSubExpr());
14524 case Stmt::ImplicitCastExprClass:
14525 // If the result of an implicit cast is an l-value, we care about
14526 // the sub-expression; otherwise, the result here doesn't matter.
14527 return getPrimaryDecl(cast<ImplicitCastExpr>(E)->getSubExpr());
14528 case Stmt::CXXUuidofExprClass:
14529 return cast<CXXUuidofExpr>(E)->getGuidDecl();
14530 default:
14531 return nullptr;
14532 }
14533}
14534
14535namespace {
14536enum {
14537 AO_Bit_Field = 0,
14538 AO_Vector_Element = 1,
14539 AO_Property_Expansion = 2,
14540 AO_Register_Variable = 3,
14541 AO_Matrix_Element = 4,
14542 AO_No_Error = 5
14543};
14544}
14545/// Diagnose invalid operand for address of operations.
14546///
14547/// \param Type The type of operand which cannot have its address taken.
14548static void diagnoseAddressOfInvalidType(Sema &S, SourceLocation Loc,
14549 Expr *E, unsigned Type) {
14550 S.Diag(Loc, diag::err_typecheck_address_of) << Type << E->getSourceRange();
14551}
14552
14553/// CheckAddressOfOperand - The operand of & must be either a function
14554/// designator or an lvalue designating an object. If it is an lvalue, the
14555/// object cannot be declared with storage class register or be a bit field.
14556/// Note: The usual conversions are *not* applied to the operand of the &
14557/// operator (C99 6.3.2.1p[2-4]), and its result is never an lvalue.
14558/// In C++, the operand might be an overloaded function name, in which case
14559/// we allow the '&' but retain the overloaded-function type.
14560QualType Sema::CheckAddressOfOperand(ExprResult &OrigOp, SourceLocation OpLoc) {
14561 if (const BuiltinType *PTy = OrigOp.get()->getType()->getAsPlaceholderType()){
14562 if (PTy->getKind() == BuiltinType::Overload) {
14563 Expr *E = OrigOp.get()->IgnoreParens();
14564 if (!isa<OverloadExpr>(E)) {
14565 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", 14565, __extension__ __PRETTY_FUNCTION__
))
;
14566 Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof_addrof_function)
14567 << OrigOp.get()->getSourceRange();
14568 return QualType();
14569 }
14570
14571 OverloadExpr *Ovl = cast<OverloadExpr>(E);
14572 if (isa<UnresolvedMemberExpr>(Ovl))
14573 if (!ResolveSingleFunctionTemplateSpecialization(Ovl)) {
14574 Diag(OpLoc, diag::err_invalid_form_pointer_member_function)
14575 << OrigOp.get()->getSourceRange();
14576 return QualType();
14577 }
14578
14579 return Context.OverloadTy;
14580 }
14581
14582 if (PTy->getKind() == BuiltinType::UnknownAny)
14583 return Context.UnknownAnyTy;
14584
14585 if (PTy->getKind() == BuiltinType::BoundMember) {
14586 Diag(OpLoc, diag::err_invalid_form_pointer_member_function)
14587 << OrigOp.get()->getSourceRange();
14588 return QualType();
14589 }
14590
14591 OrigOp = CheckPlaceholderExpr(OrigOp.get());
14592 if (OrigOp.isInvalid()) return QualType();
14593 }
14594
14595 if (OrigOp.get()->isTypeDependent())
14596 return Context.DependentTy;
14597
14598 assert(!OrigOp.get()->hasPlaceholderType())(static_cast <bool> (!OrigOp.get()->hasPlaceholderType
()) ? void (0) : __assert_fail ("!OrigOp.get()->hasPlaceholderType()"
, "clang/lib/Sema/SemaExpr.cpp", 14598, __extension__ __PRETTY_FUNCTION__
))
;
14599
14600 // Make sure to ignore parentheses in subsequent checks
14601 Expr *op = OrigOp.get()->IgnoreParens();
14602
14603 // In OpenCL captures for blocks called as lambda functions
14604 // are located in the private address space. Blocks used in
14605 // enqueue_kernel can be located in a different address space
14606 // depending on a vendor implementation. Thus preventing
14607 // taking an address of the capture to avoid invalid AS casts.
14608 if (LangOpts.OpenCL) {
14609 auto* VarRef = dyn_cast<DeclRefExpr>(op);
14610 if (VarRef && VarRef->refersToEnclosingVariableOrCapture()) {
14611 Diag(op->getExprLoc(), diag::err_opencl_taking_address_capture);
14612 return QualType();
14613 }
14614 }
14615
14616 if (getLangOpts().C99) {
14617 // Implement C99-only parts of addressof rules.
14618 if (UnaryOperator* uOp = dyn_cast<UnaryOperator>(op)) {
14619 if (uOp->getOpcode() == UO_Deref)
14620 // Per C99 6.5.3.2, the address of a deref always returns a valid result
14621 // (assuming the deref expression is valid).
14622 return uOp->getSubExpr()->getType();
14623 }
14624 // Technically, there should be a check for array subscript
14625 // expressions here, but the result of one is always an lvalue anyway.
14626 }
14627 ValueDecl *dcl = getPrimaryDecl(op);
14628
14629 if (auto *FD = dyn_cast_or_null<FunctionDecl>(dcl))
14630 if (!checkAddressOfFunctionIsAvailable(FD, /*Complain=*/true,
14631 op->getBeginLoc()))
14632 return QualType();
14633
14634 Expr::LValueClassification lval = op->ClassifyLValue(Context);
14635 unsigned AddressOfError = AO_No_Error;
14636
14637 if (lval == Expr::LV_ClassTemporary || lval == Expr::LV_ArrayTemporary) {
14638 bool sfinae = (bool)isSFINAEContext();
14639 Diag(OpLoc, isSFINAEContext() ? diag::err_typecheck_addrof_temporary
14640 : diag::ext_typecheck_addrof_temporary)
14641 << op->getType() << op->getSourceRange();
14642 if (sfinae)
14643 return QualType();
14644 // Materialize the temporary as an lvalue so that we can take its address.
14645 OrigOp = op =
14646 CreateMaterializeTemporaryExpr(op->getType(), OrigOp.get(), true);
14647 } else if (isa<ObjCSelectorExpr>(op)) {
14648 return Context.getPointerType(op->getType());
14649 } else if (lval == Expr::LV_MemberFunction) {
14650 // If it's an instance method, make a member pointer.
14651 // The expression must have exactly the form &A::foo.
14652
14653 // If the underlying expression isn't a decl ref, give up.
14654 if (!isa<DeclRefExpr>(op)) {
14655 Diag(OpLoc, diag::err_invalid_form_pointer_member_function)
14656 << OrigOp.get()->getSourceRange();
14657 return QualType();
14658 }
14659 DeclRefExpr *DRE = cast<DeclRefExpr>(op);
14660 CXXMethodDecl *MD = cast<CXXMethodDecl>(DRE->getDecl());
14661
14662 // The id-expression was parenthesized.
14663 if (OrigOp.get() != DRE) {
14664 Diag(OpLoc, diag::err_parens_pointer_member_function)
14665 << OrigOp.get()->getSourceRange();
14666
14667 // The method was named without a qualifier.
14668 } else if (!DRE->getQualifier()) {
14669 if (MD->getParent()->getName().empty())
14670 Diag(OpLoc, diag::err_unqualified_pointer_member_function)
14671 << op->getSourceRange();
14672 else {
14673 SmallString<32> Str;
14674 StringRef Qual = (MD->getParent()->getName() + "::").toStringRef(Str);
14675 Diag(OpLoc, diag::err_unqualified_pointer_member_function)
14676 << op->getSourceRange()
14677 << FixItHint::CreateInsertion(op->getSourceRange().getBegin(), Qual);
14678 }
14679 }
14680
14681 // Taking the address of a dtor is illegal per C++ [class.dtor]p2.
14682 if (isa<CXXDestructorDecl>(MD))
14683 Diag(OpLoc, diag::err_typecheck_addrof_dtor) << op->getSourceRange();
14684
14685 QualType MPTy = Context.getMemberPointerType(
14686 op->getType(), Context.getTypeDeclType(MD->getParent()).getTypePtr());
14687 // Under the MS ABI, lock down the inheritance model now.
14688 if (Context.getTargetInfo().getCXXABI().isMicrosoft())
14689 (void)isCompleteType(OpLoc, MPTy);
14690 return MPTy;
14691 } else if (lval != Expr::LV_Valid && lval != Expr::LV_IncompleteVoidType) {
14692 // C99 6.5.3.2p1
14693 // The operand must be either an l-value or a function designator
14694 if (!op->getType()->isFunctionType()) {
14695 // Use a special diagnostic for loads from property references.
14696 if (isa<PseudoObjectExpr>(op)) {
14697 AddressOfError = AO_Property_Expansion;
14698 } else {
14699 Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof)
14700 << op->getType() << op->getSourceRange();
14701 return QualType();
14702 }
14703 }
14704 } else if (op->getObjectKind() == OK_BitField) { // C99 6.5.3.2p1
14705 // The operand cannot be a bit-field
14706 AddressOfError = AO_Bit_Field;
14707 } else if (op->getObjectKind() == OK_VectorComponent) {
14708 // The operand cannot be an element of a vector
14709 AddressOfError = AO_Vector_Element;
14710 } else if (op->getObjectKind() == OK_MatrixComponent) {
14711 // The operand cannot be an element of a matrix.
14712 AddressOfError = AO_Matrix_Element;
14713 } else if (dcl) { // C99 6.5.3.2p1
14714 // We have an lvalue with a decl. Make sure the decl is not declared
14715 // with the register storage-class specifier.
14716 if (const VarDecl *vd = dyn_cast<VarDecl>(dcl)) {
14717 // in C++ it is not error to take address of a register
14718 // variable (c++03 7.1.1P3)
14719 if (vd->getStorageClass() == SC_Register &&
14720 !getLangOpts().CPlusPlus) {
14721 AddressOfError = AO_Register_Variable;
14722 }
14723 } else if (isa<MSPropertyDecl>(dcl)) {
14724 AddressOfError = AO_Property_Expansion;
14725 } else if (isa<FunctionTemplateDecl>(dcl)) {
14726 return Context.OverloadTy;
14727 } else if (isa<FieldDecl>(dcl) || isa<IndirectFieldDecl>(dcl)) {
14728 // Okay: we can take the address of a field.
14729 // Could be a pointer to member, though, if there is an explicit
14730 // scope qualifier for the class.
14731 if (isa<DeclRefExpr>(op) && cast<DeclRefExpr>(op)->getQualifier()) {
14732 DeclContext *Ctx = dcl->getDeclContext();
14733 if (Ctx && Ctx->isRecord()) {
14734 if (dcl->getType()->isReferenceType()) {
14735 Diag(OpLoc,
14736 diag::err_cannot_form_pointer_to_member_of_reference_type)
14737 << dcl->getDeclName() << dcl->getType();
14738 return QualType();
14739 }
14740
14741 while (cast<RecordDecl>(Ctx)->isAnonymousStructOrUnion())
14742 Ctx = Ctx->getParent();
14743
14744 QualType MPTy = Context.getMemberPointerType(
14745 op->getType(),
14746 Context.getTypeDeclType(cast<RecordDecl>(Ctx)).getTypePtr());
14747 // Under the MS ABI, lock down the inheritance model now.
14748 if (Context.getTargetInfo().getCXXABI().isMicrosoft())
14749 (void)isCompleteType(OpLoc, MPTy);
14750 return MPTy;
14751 }
14752 }
14753 } else if (!isa<FunctionDecl, NonTypeTemplateParmDecl, BindingDecl,
14754 MSGuidDecl, UnnamedGlobalConstantDecl>(dcl))
14755 llvm_unreachable("Unknown/unexpected decl type")::llvm::llvm_unreachable_internal("Unknown/unexpected decl type"
, "clang/lib/Sema/SemaExpr.cpp", 14755)
;
14756 }
14757
14758 if (AddressOfError != AO_No_Error) {
14759 diagnoseAddressOfInvalidType(*this, OpLoc, op, AddressOfError);
14760 return QualType();
14761 }
14762
14763 if (lval == Expr::LV_IncompleteVoidType) {
14764 // Taking the address of a void variable is technically illegal, but we
14765 // allow it in cases which are otherwise valid.
14766 // Example: "extern void x; void* y = &x;".
14767 Diag(OpLoc, diag::ext_typecheck_addrof_void) << op->getSourceRange();
14768 }
14769
14770 // If the operand has type "type", the result has type "pointer to type".
14771 if (op->getType()->isObjCObjectType())
14772 return Context.getObjCObjectPointerType(op->getType());
14773
14774 if (Context.getTargetInfo().getTriple().isWasm() &&
14775 op->getType()->isWebAssemblyReferenceType()) {
14776 Diag(OpLoc, diag::err_wasm_ca_reference)
14777 << 1 << OrigOp.get()->getSourceRange();
14778 return QualType();
14779 }
14780
14781 CheckAddressOfPackedMember(op);
14782
14783 return Context.getPointerType(op->getType());
14784}
14785
14786static void RecordModifiableNonNullParam(Sema &S, const Expr *Exp) {
14787 const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Exp);
14788 if (!DRE)
14789 return;
14790 const Decl *D = DRE->getDecl();
14791 if (!D)
14792 return;
14793 const ParmVarDecl *Param = dyn_cast<ParmVarDecl>(D);
14794 if (!Param)
14795 return;
14796 if (const FunctionDecl* FD = dyn_cast<FunctionDecl>(Param->getDeclContext()))
14797 if (!FD->hasAttr<NonNullAttr>() && !Param->hasAttr<NonNullAttr>())
14798 return;
14799 if (FunctionScopeInfo *FD = S.getCurFunction())
14800 FD->ModifiedNonNullParams.insert(Param);
14801}
14802
14803/// CheckIndirectionOperand - Type check unary indirection (prefix '*').
14804static QualType CheckIndirectionOperand(Sema &S, Expr *Op, ExprValueKind &VK,
14805 SourceLocation OpLoc,
14806 bool IsAfterAmp = false) {
14807 if (Op->isTypeDependent())
14808 return S.Context.DependentTy;
14809
14810 ExprResult ConvResult = S.UsualUnaryConversions(Op);
14811 if (ConvResult.isInvalid())
14812 return QualType();
14813 Op = ConvResult.get();
14814 QualType OpTy = Op->getType();
14815 QualType Result;
14816
14817 if (isa<CXXReinterpretCastExpr>(Op)) {
14818 QualType OpOrigType = Op->IgnoreParenCasts()->getType();
14819 S.CheckCompatibleReinterpretCast(OpOrigType, OpTy, /*IsDereference*/true,
14820 Op->getSourceRange());
14821 }
14822
14823 if (const PointerType *PT = OpTy->getAs<PointerType>())
14824 {
14825 Result = PT->getPointeeType();
14826 }
14827 else if (const ObjCObjectPointerType *OPT =
14828 OpTy->getAs<ObjCObjectPointerType>())
14829 Result = OPT->getPointeeType();
14830 else {
14831 ExprResult PR = S.CheckPlaceholderExpr(Op);
14832 if (PR.isInvalid()) return QualType();
14833 if (PR.get() != Op)
14834 return CheckIndirectionOperand(S, PR.get(), VK, OpLoc);
14835 }
14836
14837 if (Result.isNull()) {
14838 S.Diag(OpLoc, diag::err_typecheck_indirection_requires_pointer)
14839 << OpTy << Op->getSourceRange();
14840 return QualType();
14841 }
14842
14843 if (Result->isVoidType()) {
14844 // C++ [expr.unary.op]p1:
14845 // [...] the expression to which [the unary * operator] is applied shall
14846 // be a pointer to an object type, or a pointer to a function type
14847 LangOptions LO = S.getLangOpts();
14848 if (LO.CPlusPlus)
14849 S.Diag(OpLoc, diag::ext_typecheck_indirection_through_void_pointer_cpp)
14850 << OpTy << Op->getSourceRange();
14851 else if (!(LO.C99 && IsAfterAmp) && !S.isUnevaluatedContext())
14852 S.Diag(OpLoc, diag::ext_typecheck_indirection_through_void_pointer)
14853 << OpTy << Op->getSourceRange();
14854 }
14855
14856 // Dereferences are usually l-values...
14857 VK = VK_LValue;
14858
14859 // ...except that certain expressions are never l-values in C.
14860 if (!S.getLangOpts().CPlusPlus && Result.isCForbiddenLValueType())
14861 VK = VK_PRValue;
14862
14863 return Result;
14864}
14865
14866BinaryOperatorKind Sema::ConvertTokenKindToBinaryOpcode(tok::TokenKind Kind) {
14867 BinaryOperatorKind Opc;
14868 switch (Kind) {
14869 default: llvm_unreachable("Unknown binop!")::llvm::llvm_unreachable_internal("Unknown binop!", "clang/lib/Sema/SemaExpr.cpp"
, 14869)
;
14870 case tok::periodstar: Opc = BO_PtrMemD; break;
14871 case tok::arrowstar: Opc = BO_PtrMemI; break;
14872 case tok::star: Opc = BO_Mul; break;
14873 case tok::slash: Opc = BO_Div; break;
14874 case tok::percent: Opc = BO_Rem; break;
14875 case tok::plus: Opc = BO_Add; break;
14876 case tok::minus: Opc = BO_Sub; break;
14877 case tok::lessless: Opc = BO_Shl; break;
14878 case tok::greatergreater: Opc = BO_Shr; break;
14879 case tok::lessequal: Opc = BO_LE; break;
14880 case tok::less: Opc = BO_LT; break;
14881 case tok::greaterequal: Opc = BO_GE; break;
14882 case tok::greater: Opc = BO_GT; break;
14883 case tok::exclaimequal: Opc = BO_NE; break;
14884 case tok::equalequal: Opc = BO_EQ; break;
14885 case tok::spaceship: Opc = BO_Cmp; break;
14886 case tok::amp: Opc = BO_And; break;
14887 case tok::caret: Opc = BO_Xor; break;
14888 case tok::pipe: Opc = BO_Or; break;
14889 case tok::ampamp: Opc = BO_LAnd; break;
14890 case tok::pipepipe: Opc = BO_LOr; break;
14891 case tok::equal: Opc = BO_Assign; break;
14892 case tok::starequal: Opc = BO_MulAssign; break;
14893 case tok::slashequal: Opc = BO_DivAssign; break;
14894 case tok::percentequal: Opc = BO_RemAssign; break;
14895 case tok::plusequal: Opc = BO_AddAssign; break;
14896 case tok::minusequal: Opc = BO_SubAssign; break;
14897 case tok::lesslessequal: Opc = BO_ShlAssign; break;
14898 case tok::greatergreaterequal: Opc = BO_ShrAssign; break;
14899 case tok::ampequal: Opc = BO_AndAssign; break;
14900 case tok::caretequal: Opc = BO_XorAssign; break;
14901 case tok::pipeequal: Opc = BO_OrAssign; break;
14902 case tok::comma: Opc = BO_Comma; break;
14903 }
14904 return Opc;
14905}
14906
14907static inline UnaryOperatorKind ConvertTokenKindToUnaryOpcode(
14908 tok::TokenKind Kind) {
14909 UnaryOperatorKind Opc;
14910 switch (Kind) {
14911 default: llvm_unreachable("Unknown unary op!")::llvm::llvm_unreachable_internal("Unknown unary op!", "clang/lib/Sema/SemaExpr.cpp"
, 14911)
;
14912 case tok::plusplus: Opc = UO_PreInc; break;
14913 case tok::minusminus: Opc = UO_PreDec; break;
14914 case tok::amp: Opc = UO_AddrOf; break;
14915 case tok::star: Opc = UO_Deref; break;
14916 case tok::plus: Opc = UO_Plus; break;
14917 case tok::minus: Opc = UO_Minus; break;
14918 case tok::tilde: Opc = UO_Not; break;
14919 case tok::exclaim: Opc = UO_LNot; break;
14920 case tok::kw___real: Opc = UO_Real; break;
14921 case tok::kw___imag: Opc = UO_Imag; break;
14922 case tok::kw___extension__: Opc = UO_Extension; break;
14923 }
14924 return Opc;
14925}
14926
14927const FieldDecl *
14928Sema::getSelfAssignmentClassMemberCandidate(const ValueDecl *SelfAssigned) {
14929 // Explore the case for adding 'this->' to the LHS of a self assignment, very
14930 // common for setters.
14931 // struct A {
14932 // int X;
14933 // -void setX(int X) { X = X; }
14934 // +void setX(int X) { this->X = X; }
14935 // };
14936
14937 // Only consider parameters for self assignment fixes.
14938 if (!isa<ParmVarDecl>(SelfAssigned))
14939 return nullptr;
14940 const auto *Method =
14941 dyn_cast_or_null<CXXMethodDecl>(getCurFunctionDecl(true));
14942 if (!Method)
14943 return nullptr;
14944
14945 const CXXRecordDecl *Parent = Method->getParent();
14946 // In theory this is fixable if the lambda explicitly captures this, but
14947 // that's added complexity that's rarely going to be used.
14948 if (Parent->isLambda())
14949 return nullptr;
14950
14951 // FIXME: Use an actual Lookup operation instead of just traversing fields
14952 // in order to get base class fields.
14953 auto Field =
14954 llvm::find_if(Parent->fields(),
14955 [Name(SelfAssigned->getDeclName())](const FieldDecl *F) {
14956 return F->getDeclName() == Name;
14957 });
14958 return (Field != Parent->field_end()) ? *Field : nullptr;
14959}
14960
14961/// DiagnoseSelfAssignment - Emits a warning if a value is assigned to itself.
14962/// This warning suppressed in the event of macro expansions.
14963static void DiagnoseSelfAssignment(Sema &S, Expr *LHSExpr, Expr *RHSExpr,
14964 SourceLocation OpLoc, bool IsBuiltin) {
14965 if (S.inTemplateInstantiation())
14966 return;
14967 if (S.isUnevaluatedContext())
14968 return;
14969 if (OpLoc.isInvalid() || OpLoc.isMacroID())
14970 return;
14971 LHSExpr = LHSExpr->IgnoreParenImpCasts();
14972 RHSExpr = RHSExpr->IgnoreParenImpCasts();
14973 const DeclRefExpr *LHSDeclRef = dyn_cast<DeclRefExpr>(LHSExpr);
14974 const DeclRefExpr *RHSDeclRef = dyn_cast<DeclRefExpr>(RHSExpr);
14975 if (!LHSDeclRef || !RHSDeclRef ||
14976 LHSDeclRef->getLocation().isMacroID() ||
14977 RHSDeclRef->getLocation().isMacroID())
14978 return;
14979 const ValueDecl *LHSDecl =
14980 cast<ValueDecl>(LHSDeclRef->getDecl()->getCanonicalDecl());
14981 const ValueDecl *RHSDecl =
14982 cast<ValueDecl>(RHSDeclRef->getDecl()->getCanonicalDecl());
14983 if (LHSDecl != RHSDecl)
14984 return;
14985 if (LHSDecl->getType().isVolatileQualified())
14986 return;
14987 if (const ReferenceType *RefTy = LHSDecl->getType()->getAs<ReferenceType>())
14988 if (RefTy->getPointeeType().isVolatileQualified())
14989 return;
14990
14991 auto Diag = S.Diag(OpLoc, IsBuiltin ? diag::warn_self_assignment_builtin
14992 : diag::warn_self_assignment_overloaded)
14993 << LHSDeclRef->getType() << LHSExpr->getSourceRange()
14994 << RHSExpr->getSourceRange();
14995 if (const FieldDecl *SelfAssignField =
14996 S.getSelfAssignmentClassMemberCandidate(RHSDecl))
14997 Diag << 1 << SelfAssignField
14998 << FixItHint::CreateInsertion(LHSDeclRef->getBeginLoc(), "this->");
14999 else
15000 Diag << 0;
15001}
15002
15003/// Check if a bitwise-& is performed on an Objective-C pointer. This
15004/// is usually indicative of introspection within the Objective-C pointer.
15005static void checkObjCPointerIntrospection(Sema &S, ExprResult &L, ExprResult &R,
15006 SourceLocation OpLoc) {
15007 if (!S.getLangOpts().ObjC)
15008 return;
15009
15010 const Expr *ObjCPointerExpr = nullptr, *OtherExpr = nullptr;
15011 const Expr *LHS = L.get();
15012 const Expr *RHS = R.get();
15013
15014 if (LHS->IgnoreParenCasts()->getType()->isObjCObjectPointerType()) {
15015 ObjCPointerExpr = LHS;
15016 OtherExpr = RHS;
15017 }
15018 else if (RHS->IgnoreParenCasts()->getType()->isObjCObjectPointerType()) {
15019 ObjCPointerExpr = RHS;
15020 OtherExpr = LHS;
15021 }
15022
15023 // This warning is deliberately made very specific to reduce false
15024 // positives with logic that uses '&' for hashing. This logic mainly
15025 // looks for code trying to introspect into tagged pointers, which
15026 // code should generally never do.
15027 if (ObjCPointerExpr && isa<IntegerLiteral>(OtherExpr->IgnoreParenCasts())) {
15028 unsigned Diag = diag::warn_objc_pointer_masking;
15029 // Determine if we are introspecting the result of performSelectorXXX.
15030 const Expr *Ex = ObjCPointerExpr->IgnoreParenCasts();
15031 // Special case messages to -performSelector and friends, which
15032 // can return non-pointer values boxed in a pointer value.
15033 // Some clients may wish to silence warnings in this subcase.
15034 if (const ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(Ex)) {
15035 Selector S = ME->getSelector();
15036 StringRef SelArg0 = S.getNameForSlot(0);
15037 if (SelArg0.startswith("performSelector"))
15038 Diag = diag::warn_objc_pointer_masking_performSelector;
15039 }
15040
15041 S.Diag(OpLoc, Diag)
15042 << ObjCPointerExpr->getSourceRange();
15043 }
15044}
15045
15046static NamedDecl *getDeclFromExpr(Expr *E) {
15047 if (!E)
15048 return nullptr;
15049 if (auto *DRE = dyn_cast<DeclRefExpr>(E))
15050 return DRE->getDecl();
15051 if (auto *ME = dyn_cast<MemberExpr>(E))
15052 return ME->getMemberDecl();
15053 if (auto *IRE = dyn_cast<ObjCIvarRefExpr>(E))
15054 return IRE->getDecl();
15055 return nullptr;
15056}
15057
15058// This helper function promotes a binary operator's operands (which are of a
15059// half vector type) to a vector of floats and then truncates the result to
15060// a vector of either half or short.
15061static ExprResult convertHalfVecBinOp(Sema &S, ExprResult LHS, ExprResult RHS,
15062 BinaryOperatorKind Opc, QualType ResultTy,
15063 ExprValueKind VK, ExprObjectKind OK,
15064 bool IsCompAssign, SourceLocation OpLoc,
15065 FPOptionsOverride FPFeatures) {
15066 auto &Context = S.getASTContext();
15067 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", 15069, __extension__ __PRETTY_FUNCTION__
))
15068 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", 15069, __extension__ __PRETTY_FUNCTION__
))
15069 "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", 15069, __extension__ __PRETTY_FUNCTION__
))
;
15070 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", 15072, __extension__ __PRETTY_FUNCTION__
))
15071 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", 15072, __extension__ __PRETTY_FUNCTION__
))
15072 "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", 15072, __extension__ __PRETTY_FUNCTION__
))
;
15073
15074 RHS = convertVector(RHS.get(), Context.FloatTy, S);
15075 QualType BinOpResTy = RHS.get()->getType();
15076
15077 // If Opc is a comparison, ResultType is a vector of shorts. In that case,
15078 // change BinOpResTy to a vector of ints.
15079 if (isVector(ResultTy, Context.ShortTy))
15080 BinOpResTy = S.GetSignedVectorType(BinOpResTy);
15081
15082 if (IsCompAssign)
15083 return CompoundAssignOperator::Create(Context, LHS.get(), RHS.get(), Opc,
15084 ResultTy, VK, OK, OpLoc, FPFeatures,
15085 BinOpResTy, BinOpResTy);
15086
15087 LHS = convertVector(LHS.get(), Context.FloatTy, S);
15088 auto *BO = BinaryOperator::Create(Context, LHS.get(), RHS.get(), Opc,
15089 BinOpResTy, VK, OK, OpLoc, FPFeatures);
15090 return convertVector(BO, ResultTy->castAs<VectorType>()->getElementType(), S);
15091}
15092
15093static std::pair<ExprResult, ExprResult>
15094CorrectDelayedTyposInBinOp(Sema &S, BinaryOperatorKind Opc, Expr *LHSExpr,
15095 Expr *RHSExpr) {
15096 ExprResult LHS = LHSExpr, RHS = RHSExpr;
15097 if (!S.Context.isDependenceAllowed()) {
15098 // C cannot handle TypoExpr nodes on either side of a binop because it
15099 // doesn't handle dependent types properly, so make sure any TypoExprs have
15100 // been dealt with before checking the operands.
15101 LHS = S.CorrectDelayedTyposInExpr(LHS);
15102 RHS = S.CorrectDelayedTyposInExpr(
15103 RHS, /*InitDecl=*/nullptr, /*RecoverUncorrectedTypos=*/false,
15104 [Opc, LHS](Expr *E) {
15105 if (Opc != BO_Assign)
15106 return ExprResult(E);
15107 // Avoid correcting the RHS to the same Expr as the LHS.
15108 Decl *D = getDeclFromExpr(E);
15109 return (D && D == getDeclFromExpr(LHS.get())) ? ExprError() : E;
15110 });
15111 }
15112 return std::make_pair(LHS, RHS);
15113}
15114
15115/// Returns true if conversion between vectors of halfs and vectors of floats
15116/// is needed.
15117static bool needsConversionOfHalfVec(bool OpRequiresConversion, ASTContext &Ctx,
15118 Expr *E0, Expr *E1 = nullptr) {
15119 if (!OpRequiresConversion || Ctx.getLangOpts().NativeHalfType ||
15120 Ctx.getTargetInfo().useFP16ConversionIntrinsics())
15121 return false;
15122
15123 auto HasVectorOfHalfType = [&Ctx](Expr *E) {
15124 QualType Ty = E->IgnoreImplicit()->getType();
15125
15126 // Don't promote half precision neon vectors like float16x4_t in arm_neon.h
15127 // to vectors of floats. Although the element type of the vectors is __fp16,
15128 // the vectors shouldn't be treated as storage-only types. See the
15129 // discussion here: https://reviews.llvm.org/rG825235c140e7
15130 if (const VectorType *VT = Ty->getAs<VectorType>()) {
15131 if (VT->getVectorKind() == VectorType::NeonVector)
15132 return false;
15133 return VT->getElementType().getCanonicalType() == Ctx.HalfTy;
15134 }
15135 return false;
15136 };
15137
15138 return HasVectorOfHalfType(E0) && (!E1 || HasVectorOfHalfType(E1));
15139}
15140
15141/// CreateBuiltinBinOp - Creates a new built-in binary operation with
15142/// operator @p Opc at location @c TokLoc. This routine only supports
15143/// built-in operations; ActOnBinOp handles overloaded operators.
15144ExprResult Sema::CreateBuiltinBinOp(SourceLocation OpLoc,
15145 BinaryOperatorKind Opc,
15146 Expr *LHSExpr, Expr *RHSExpr) {
15147 if (getLangOpts().CPlusPlus11 && isa<InitListExpr>(RHSExpr)) {
15148 // The syntax only allows initializer lists on the RHS of assignment,
15149 // so we don't need to worry about accepting invalid code for
15150 // non-assignment operators.
15151 // C++11 5.17p9:
15152 // The meaning of x = {v} [...] is that of x = T(v) [...]. The meaning
15153 // of x = {} is x = T().
15154 InitializationKind Kind = InitializationKind::CreateDirectList(
15155 RHSExpr->getBeginLoc(), RHSExpr->getBeginLoc(), RHSExpr->getEndLoc());
15156 InitializedEntity Entity =
15157 InitializedEntity::InitializeTemporary(LHSExpr->getType());
15158 InitializationSequence InitSeq(*this, Entity, Kind, RHSExpr);
15159 ExprResult Init = InitSeq.Perform(*this, Entity, Kind, RHSExpr);
15160 if (Init.isInvalid())
15161 return Init;
15162 RHSExpr = Init.get();
15163 }
15164
15165 ExprResult LHS = LHSExpr, RHS = RHSExpr;
15166 QualType ResultTy; // Result type of the binary operator.
15167 // The following two variables are used for compound assignment operators
15168 QualType CompLHSTy; // Type of LHS after promotions for computation
15169 QualType CompResultTy; // Type of computation result
15170 ExprValueKind VK = VK_PRValue;
15171 ExprObjectKind OK = OK_Ordinary;
15172 bool ConvertHalfVec = false;
15173
15174 std::tie(LHS, RHS) = CorrectDelayedTyposInBinOp(*this, Opc, LHSExpr, RHSExpr);
15175 if (!LHS.isUsable() || !RHS.isUsable())
15176 return ExprError();
15177
15178 if (getLangOpts().OpenCL) {
15179 QualType LHSTy = LHSExpr->getType();
15180 QualType RHSTy = RHSExpr->getType();
15181 // OpenCLC v2.0 s6.13.11.1 allows atomic variables to be initialized by
15182 // the ATOMIC_VAR_INIT macro.
15183 if (LHSTy->isAtomicType() || RHSTy->isAtomicType()) {
15184 SourceRange SR(LHSExpr->getBeginLoc(), RHSExpr->getEndLoc());
15185 if (BO_Assign == Opc)
15186 Diag(OpLoc, diag::err_opencl_atomic_init) << 0 << SR;
15187 else
15188 ResultTy = InvalidOperands(OpLoc, LHS, RHS);
15189 return ExprError();
15190 }
15191
15192 // OpenCL special types - image, sampler, pipe, and blocks are to be used
15193 // only with a builtin functions and therefore should be disallowed here.
15194 if (LHSTy->isImageType() || RHSTy->isImageType() ||
15195 LHSTy->isSamplerT() || RHSTy->isSamplerT() ||
15196 LHSTy->isPipeType() || RHSTy->isPipeType() ||
15197 LHSTy->isBlockPointerType() || RHSTy->isBlockPointerType()) {
15198 ResultTy = InvalidOperands(OpLoc, LHS, RHS);
15199 return ExprError();
15200 }
15201 }
15202
15203 checkTypeSupport(LHSExpr->getType(), OpLoc, /*ValueDecl*/ nullptr);
15204 checkTypeSupport(RHSExpr->getType(), OpLoc, /*ValueDecl*/ nullptr);
15205
15206 switch (Opc) {
15207 case BO_Assign:
15208 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, QualType(), Opc);
15209 if (getLangOpts().CPlusPlus &&
15210 LHS.get()->getObjectKind() != OK_ObjCProperty) {
15211 VK = LHS.get()->getValueKind();
15212 OK = LHS.get()->getObjectKind();
15213 }
15214 if (!ResultTy.isNull()) {
15215 DiagnoseSelfAssignment(*this, LHS.get(), RHS.get(), OpLoc, true);
15216 DiagnoseSelfMove(LHS.get(), RHS.get(), OpLoc);
15217
15218 // Avoid copying a block to the heap if the block is assigned to a local
15219 // auto variable that is declared in the same scope as the block. This
15220 // optimization is unsafe if the local variable is declared in an outer
15221 // scope. For example:
15222 //
15223 // BlockTy b;
15224 // {
15225 // b = ^{...};
15226 // }
15227 // // It is unsafe to invoke the block here if it wasn't copied to the
15228 // // heap.
15229 // b();
15230
15231 if (auto *BE = dyn_cast<BlockExpr>(RHS.get()->IgnoreParens()))
15232 if (auto *DRE = dyn_cast<DeclRefExpr>(LHS.get()->IgnoreParens()))
15233 if (auto *VD = dyn_cast<VarDecl>(DRE->getDecl()))
15234 if (VD->hasLocalStorage() && getCurScope()->isDeclScope(VD))
15235 BE->getBlockDecl()->setCanAvoidCopyToHeap();
15236
15237 if (LHS.get()->getType().hasNonTrivialToPrimitiveCopyCUnion())
15238 checkNonTrivialCUnion(LHS.get()->getType(), LHS.get()->getExprLoc(),
15239 NTCUC_Assignment, NTCUK_Copy);
15240 }
15241 RecordModifiableNonNullParam(*this, LHS.get());
15242 break;
15243 case BO_PtrMemD:
15244 case BO_PtrMemI:
15245 ResultTy = CheckPointerToMemberOperands(LHS, RHS, VK, OpLoc,
15246 Opc == BO_PtrMemI);
15247 break;
15248 case BO_Mul:
15249 case BO_Div:
15250 ConvertHalfVec = true;
15251 ResultTy = CheckMultiplyDivideOperands(LHS, RHS, OpLoc, false,
15252 Opc == BO_Div);
15253 break;
15254 case BO_Rem:
15255 ResultTy = CheckRemainderOperands(LHS, RHS, OpLoc);
15256 break;
15257 case BO_Add:
15258 ConvertHalfVec = true;
15259 ResultTy = CheckAdditionOperands(LHS, RHS, OpLoc, Opc);
15260 break;
15261 case BO_Sub:
15262 ConvertHalfVec = true;
15263 ResultTy = CheckSubtractionOperands(LHS, RHS, OpLoc);
15264 break;
15265 case BO_Shl:
15266 case BO_Shr:
15267 ResultTy = CheckShiftOperands(LHS, RHS, OpLoc, Opc);
15268 break;
15269 case BO_LE:
15270 case BO_LT:
15271 case BO_GE:
15272 case BO_GT:
15273 ConvertHalfVec = true;
15274 ResultTy = CheckCompareOperands(LHS, RHS, OpLoc, Opc);
15275 break;
15276 case BO_EQ:
15277 case BO_NE:
15278 ConvertHalfVec = true;
15279 ResultTy = CheckCompareOperands(LHS, RHS, OpLoc, Opc);
15280 break;
15281 case BO_Cmp:
15282 ConvertHalfVec = true;
15283 ResultTy = CheckCompareOperands(LHS, RHS, OpLoc, Opc);
15284 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", 15284, __extension__ __PRETTY_FUNCTION__
))
;
15285 break;
15286 case BO_And:
15287 checkObjCPointerIntrospection(*this, LHS, RHS, OpLoc);
15288 [[fallthrough]];
15289 case BO_Xor:
15290 case BO_Or:
15291 ResultTy = CheckBitwiseOperands(LHS, RHS, OpLoc, Opc);
15292 break;
15293 case BO_LAnd:
15294 case BO_LOr:
15295 ConvertHalfVec = true;
15296 ResultTy = CheckLogicalOperands(LHS, RHS, OpLoc, Opc);
15297 break;
15298 case BO_MulAssign:
15299 case BO_DivAssign:
15300 ConvertHalfVec = true;
15301 CompResultTy = CheckMultiplyDivideOperands(LHS, RHS, OpLoc, true,
15302 Opc == BO_DivAssign);
15303 CompLHSTy = CompResultTy;
15304 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
15305 ResultTy =
15306 CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy, Opc);
15307 break;
15308 case BO_RemAssign:
15309 CompResultTy = CheckRemainderOperands(LHS, RHS, OpLoc, true);
15310 CompLHSTy = CompResultTy;
15311 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
15312 ResultTy =
15313 CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy, Opc);
15314 break;
15315 case BO_AddAssign:
15316 ConvertHalfVec = true;
15317 CompResultTy = CheckAdditionOperands(LHS, RHS, OpLoc, Opc, &CompLHSTy);
15318 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
15319 ResultTy =
15320 CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy, Opc);
15321 break;
15322 case BO_SubAssign:
15323 ConvertHalfVec = true;
15324 CompResultTy = CheckSubtractionOperands(LHS, RHS, OpLoc, &CompLHSTy);
15325 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
15326 ResultTy =
15327 CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy, Opc);
15328 break;
15329 case BO_ShlAssign:
15330 case BO_ShrAssign:
15331 CompResultTy = CheckShiftOperands(LHS, RHS, OpLoc, Opc, true);
15332 CompLHSTy = CompResultTy;
15333 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
15334 ResultTy =
15335 CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy, Opc);
15336 break;
15337 case BO_AndAssign:
15338 case BO_OrAssign: // fallthrough
15339 DiagnoseSelfAssignment(*this, LHS.get(), RHS.get(), OpLoc, true);
15340 [[fallthrough]];
15341 case BO_XorAssign:
15342 CompResultTy = CheckBitwiseOperands(LHS, RHS, OpLoc, Opc);
15343 CompLHSTy = CompResultTy;
15344 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
15345 ResultTy =
15346 CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy, Opc);
15347 break;
15348 case BO_Comma:
15349 ResultTy = CheckCommaOperands(*this, LHS, RHS, OpLoc);
15350 if (getLangOpts().CPlusPlus && !RHS.isInvalid()) {
15351 VK = RHS.get()->getValueKind();
15352 OK = RHS.get()->getObjectKind();
15353 }
15354 break;
15355 }
15356 if (ResultTy.isNull() || LHS.isInvalid() || RHS.isInvalid())
15357 return ExprError();
15358
15359 // Some of the binary operations require promoting operands of half vector to
15360 // float vectors and truncating the result back to half vector. For now, we do
15361 // this only when HalfArgsAndReturn is set (that is, when the target is arm or
15362 // arm64).
15363 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", 15366, __extension__ __PRETTY_FUNCTION__
))
15364 (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", 15366, __extension__ __PRETTY_FUNCTION__
))
15365 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", 15366, __extension__ __PRETTY_FUNCTION__
))
15366 "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", 15366, __extension__ __PRETTY_FUNCTION__
))
;
15367 ConvertHalfVec =
15368 needsConversionOfHalfVec(ConvertHalfVec, Context, LHS.get(), RHS.get());
15369
15370 // Check for array bounds violations for both sides of the BinaryOperator
15371 CheckArrayAccess(LHS.get());
15372 CheckArrayAccess(RHS.get());
15373
15374 if (const ObjCIsaExpr *OISA = dyn_cast<ObjCIsaExpr>(LHS.get()->IgnoreParenCasts())) {
15375 NamedDecl *ObjectSetClass = LookupSingleName(TUScope,
15376 &Context.Idents.get("object_setClass"),
15377 SourceLocation(), LookupOrdinaryName);
15378 if (ObjectSetClass && isa<ObjCIsaExpr>(LHS.get())) {
15379 SourceLocation RHSLocEnd = getLocForEndOfToken(RHS.get()->getEndLoc());
15380 Diag(LHS.get()->getExprLoc(), diag::warn_objc_isa_assign)
15381 << FixItHint::CreateInsertion(LHS.get()->getBeginLoc(),
15382 "object_setClass(")
15383 << FixItHint::CreateReplacement(SourceRange(OISA->getOpLoc(), OpLoc),
15384 ",")
15385 << FixItHint::CreateInsertion(RHSLocEnd, ")");
15386 }
15387 else
15388 Diag(LHS.get()->getExprLoc(), diag::warn_objc_isa_assign);
15389 }
15390 else if (const ObjCIvarRefExpr *OIRE =
15391 dyn_cast<ObjCIvarRefExpr>(LHS.get()->IgnoreParenCasts()))
15392 DiagnoseDirectIsaAccess(*this, OIRE, OpLoc, RHS.get());
15393
15394 // Opc is not a compound assignment if CompResultTy is null.
15395 if (CompResultTy.isNull()) {
15396 if (ConvertHalfVec)
15397 return convertHalfVecBinOp(*this, LHS, RHS, Opc, ResultTy, VK, OK, false,
15398 OpLoc, CurFPFeatureOverrides());
15399 return BinaryOperator::Create(Context, LHS.get(), RHS.get(), Opc, ResultTy,
15400 VK, OK, OpLoc, CurFPFeatureOverrides());
15401 }
15402
15403 // Handle compound assignments.
15404 if (getLangOpts().CPlusPlus && LHS.get()->getObjectKind() !=
15405 OK_ObjCProperty) {
15406 VK = VK_LValue;
15407 OK = LHS.get()->getObjectKind();
15408 }
15409
15410 // The LHS is not converted to the result type for fixed-point compound
15411 // assignment as the common type is computed on demand. Reset the CompLHSTy
15412 // to the LHS type we would have gotten after unary conversions.
15413 if (CompResultTy->isFixedPointType())
15414 CompLHSTy = UsualUnaryConversions(LHS.get()).get()->getType();
15415
15416 if (ConvertHalfVec)
15417 return convertHalfVecBinOp(*this, LHS, RHS, Opc, ResultTy, VK, OK, true,
15418 OpLoc, CurFPFeatureOverrides());
15419
15420 return CompoundAssignOperator::Create(
15421 Context, LHS.get(), RHS.get(), Opc, ResultTy, VK, OK, OpLoc,
15422 CurFPFeatureOverrides(), CompLHSTy, CompResultTy);
15423}
15424
15425/// DiagnoseBitwisePrecedence - Emit a warning when bitwise and comparison
15426/// operators are mixed in a way that suggests that the programmer forgot that
15427/// comparison operators have higher precedence. The most typical example of
15428/// such code is "flags & 0x0020 != 0", which is equivalent to "flags & 1".
15429static void DiagnoseBitwisePrecedence(Sema &Self, BinaryOperatorKind Opc,
15430 SourceLocation OpLoc, Expr *LHSExpr,
15431 Expr *RHSExpr) {
15432 BinaryOperator *LHSBO = dyn_cast<BinaryOperator>(LHSExpr);
15433 BinaryOperator *RHSBO = dyn_cast<BinaryOperator>(RHSExpr);
15434
15435 // Check that one of the sides is a comparison operator and the other isn't.
15436 bool isLeftComp = LHSBO && LHSBO->isComparisonOp();
15437 bool isRightComp = RHSBO && RHSBO->isComparisonOp();
15438 if (isLeftComp == isRightComp)
15439 return;
15440
15441 // Bitwise operations are sometimes used as eager logical ops.
15442 // Don't diagnose this.
15443 bool isLeftBitwise = LHSBO && LHSBO->isBitwiseOp();
15444 bool isRightBitwise = RHSBO && RHSBO->isBitwiseOp();
15445 if (isLeftBitwise || isRightBitwise)
15446 return;
15447
15448 SourceRange DiagRange = isLeftComp
15449 ? SourceRange(LHSExpr->getBeginLoc(), OpLoc)
15450 : SourceRange(OpLoc, RHSExpr->getEndLoc());
15451 StringRef OpStr = isLeftComp ? LHSBO->getOpcodeStr() : RHSBO->getOpcodeStr();
15452 SourceRange ParensRange =
15453 isLeftComp
15454 ? SourceRange(LHSBO->getRHS()->getBeginLoc(), RHSExpr->getEndLoc())
15455 : SourceRange(LHSExpr->getBeginLoc(), RHSBO->getLHS()->getEndLoc());
15456
15457 Self.Diag(OpLoc, diag::warn_precedence_bitwise_rel)
15458 << DiagRange << BinaryOperator::getOpcodeStr(Opc) << OpStr;
15459 SuggestParentheses(Self, OpLoc,
15460 Self.PDiag(diag::note_precedence_silence) << OpStr,
15461 (isLeftComp ? LHSExpr : RHSExpr)->getSourceRange());
15462 SuggestParentheses(Self, OpLoc,
15463 Self.PDiag(diag::note_precedence_bitwise_first)
15464 << BinaryOperator::getOpcodeStr(Opc),
15465 ParensRange);
15466}
15467
15468/// It accepts a '&&' expr that is inside a '||' one.
15469/// Emit a diagnostic together with a fixit hint that wraps the '&&' expression
15470/// in parentheses.
15471static void
15472EmitDiagnosticForLogicalAndInLogicalOr(Sema &Self, SourceLocation OpLoc,
15473 BinaryOperator *Bop) {
15474 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"
, 15474, __extension__ __PRETTY_FUNCTION__))
;
15475 Self.Diag(Bop->getOperatorLoc(), diag::warn_logical_and_in_logical_or)
15476 << Bop->getSourceRange() << OpLoc;
15477 SuggestParentheses(Self, Bop->getOperatorLoc(),
15478 Self.PDiag(diag::note_precedence_silence)
15479 << Bop->getOpcodeStr(),
15480 Bop->getSourceRange());
15481}
15482
15483/// Look for '&&' in the left hand of a '||' expr.
15484static void DiagnoseLogicalAndInLogicalOrLHS(Sema &S, SourceLocation OpLoc,
15485 Expr *LHSExpr, Expr *RHSExpr) {
15486 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(LHSExpr)) {
15487 if (Bop->getOpcode() == BO_LAnd) {
15488 // If it's "string_literal && a || b" don't warn since the precedence
15489 // doesn't matter.
15490 if (!isa<StringLiteral>(Bop->getLHS()->IgnoreParenImpCasts()))
15491 return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, Bop);
15492 } else if (Bop->getOpcode() == BO_LOr) {
15493 if (BinaryOperator *RBop = dyn_cast<BinaryOperator>(Bop->getRHS())) {
15494 // If it's "a || b && string_literal || c" we didn't warn earlier for
15495 // "a || b && string_literal", but warn now.
15496 if (RBop->getOpcode() == BO_LAnd &&
15497 isa<StringLiteral>(RBop->getRHS()->IgnoreParenImpCasts()))
15498 return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, RBop);
15499 }
15500 }
15501 }
15502}
15503
15504/// Look for '&&' in the right hand of a '||' expr.
15505static void DiagnoseLogicalAndInLogicalOrRHS(Sema &S, SourceLocation OpLoc,
15506 Expr *LHSExpr, Expr *RHSExpr) {
15507 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(RHSExpr)) {
15508 if (Bop->getOpcode() == BO_LAnd) {
15509 // If it's "a || b && string_literal" don't warn since the precedence
15510 // doesn't matter.
15511 if (!isa<StringLiteral>(Bop->getRHS()->IgnoreParenImpCasts()))
15512 return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, Bop);
15513 }
15514 }
15515}
15516
15517/// Look for bitwise op in the left or right hand of a bitwise op with
15518/// lower precedence and emit a diagnostic together with a fixit hint that wraps
15519/// the '&' expression in parentheses.
15520static void DiagnoseBitwiseOpInBitwiseOp(Sema &S, BinaryOperatorKind Opc,
15521 SourceLocation OpLoc, Expr *SubExpr) {
15522 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(SubExpr)) {
15523 if (Bop->isBitwiseOp() && Bop->getOpcode() < Opc) {
15524 S.Diag(Bop->getOperatorLoc(), diag::warn_bitwise_op_in_bitwise_op)
15525 << Bop->getOpcodeStr() << BinaryOperator::getOpcodeStr(Opc)
15526 << Bop->getSourceRange() << OpLoc;
15527 SuggestParentheses(S, Bop->getOperatorLoc(),
15528 S.PDiag(diag::note_precedence_silence)
15529 << Bop->getOpcodeStr(),
15530 Bop->getSourceRange());
15531 }
15532 }
15533}
15534
15535static void DiagnoseAdditionInShift(Sema &S, SourceLocation OpLoc,
15536 Expr *SubExpr, StringRef Shift) {
15537 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(SubExpr)) {
15538 if (Bop->getOpcode() == BO_Add || Bop->getOpcode() == BO_Sub) {
15539 StringRef Op = Bop->getOpcodeStr();
15540 S.Diag(Bop->getOperatorLoc(), diag::warn_addition_in_bitshift)
15541 << Bop->getSourceRange() << OpLoc << Shift << Op;
15542 SuggestParentheses(S, Bop->getOperatorLoc(),
15543 S.PDiag(diag::note_precedence_silence) << Op,
15544 Bop->getSourceRange());
15545 }
15546 }
15547}
15548
15549static void DiagnoseShiftCompare(Sema &S, SourceLocation OpLoc,
15550 Expr *LHSExpr, Expr *RHSExpr) {
15551 CXXOperatorCallExpr *OCE = dyn_cast<CXXOperatorCallExpr>(LHSExpr);
15552 if (!OCE)
15553 return;
15554
15555 FunctionDecl *FD = OCE->getDirectCallee();
15556 if (!FD || !FD->isOverloadedOperator())
15557 return;
15558
15559 OverloadedOperatorKind Kind = FD->getOverloadedOperator();
15560 if (Kind != OO_LessLess && Kind != OO_GreaterGreater)
15561 return;
15562
15563 S.Diag(OpLoc, diag::warn_overloaded_shift_in_comparison)
15564 << LHSExpr->getSourceRange() << RHSExpr->getSourceRange()
15565 << (Kind == OO_LessLess);
15566 SuggestParentheses(S, OCE->getOperatorLoc(),
15567 S.PDiag(diag::note_precedence_silence)
15568 << (Kind == OO_LessLess ? "<<" : ">>"),
15569 OCE->getSourceRange());
15570 SuggestParentheses(
15571 S, OpLoc, S.PDiag(diag::note_evaluate_comparison_first),
15572 SourceRange(OCE->getArg(1)->getBeginLoc(), RHSExpr->getEndLoc()));
15573}
15574
15575/// DiagnoseBinOpPrecedence - Emit warnings for expressions with tricky
15576/// precedence.
15577static void DiagnoseBinOpPrecedence(Sema &Self, BinaryOperatorKind Opc,
15578 SourceLocation OpLoc, Expr *LHSExpr,
15579 Expr *RHSExpr){
15580 // Diagnose "arg1 'bitwise' arg2 'eq' arg3".
15581 if (BinaryOperator::isBitwiseOp(Opc))
15582 DiagnoseBitwisePrecedence(Self, Opc, OpLoc, LHSExpr, RHSExpr);
15583
15584 // Diagnose "arg1 & arg2 | arg3"
15585 if ((Opc == BO_Or || Opc == BO_Xor) &&
15586 !OpLoc.isMacroID()/* Don't warn in macros. */) {
15587 DiagnoseBitwiseOpInBitwiseOp(Self, Opc, OpLoc, LHSExpr);
15588 DiagnoseBitwiseOpInBitwiseOp(Self, Opc, OpLoc, RHSExpr);
15589 }
15590
15591 // Warn about arg1 || arg2 && arg3, as GCC 4.3+ does.
15592 // We don't warn for 'assert(a || b && "bad")' since this is safe.
15593 if (Opc == BO_LOr && !OpLoc.isMacroID()/* Don't warn in macros. */) {
15594 DiagnoseLogicalAndInLogicalOrLHS(Self, OpLoc, LHSExpr, RHSExpr);
15595 DiagnoseLogicalAndInLogicalOrRHS(Self, OpLoc, LHSExpr, RHSExpr);
15596 }
15597
15598 if ((Opc == BO_Shl && LHSExpr->getType()->isIntegralType(Self.getASTContext()))
15599 || Opc == BO_Shr) {
15600 StringRef Shift = BinaryOperator::getOpcodeStr(Opc);
15601 DiagnoseAdditionInShift(Self, OpLoc, LHSExpr, Shift);
15602 DiagnoseAdditionInShift(Self, OpLoc, RHSExpr, Shift);
15603 }
15604
15605 // Warn on overloaded shift operators and comparisons, such as:
15606 // cout << 5 == 4;
15607 if (BinaryOperator::isComparisonOp(Opc))
15608 DiagnoseShiftCompare(Self, OpLoc, LHSExpr, RHSExpr);
15609}
15610
15611// Binary Operators. 'Tok' is the token for the operator.
15612ExprResult Sema::ActOnBinOp(Scope *S, SourceLocation TokLoc,
15613 tok::TokenKind Kind,
15614 Expr *LHSExpr, Expr *RHSExpr) {
15615 BinaryOperatorKind Opc = ConvertTokenKindToBinaryOpcode(Kind);
15616 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", 15616, __extension__ __PRETTY_FUNCTION__
))
;
15617 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", 15617, __extension__ __PRETTY_FUNCTION__
))
;
15618
15619 // Emit warnings for tricky precedence issues, e.g. "bitfield & 0x4 == 0"
15620 DiagnoseBinOpPrecedence(*this, Opc, TokLoc, LHSExpr, RHSExpr);
15621
15622 return BuildBinOp(S, TokLoc, Opc, LHSExpr, RHSExpr);
15623}
15624
15625void Sema::LookupBinOp(Scope *S, SourceLocation OpLoc, BinaryOperatorKind Opc,
15626 UnresolvedSetImpl &Functions) {
15627 OverloadedOperatorKind OverOp = BinaryOperator::getOverloadedOperator(Opc);
15628 if (OverOp != OO_None && OverOp != OO_Equal)
15629 LookupOverloadedOperatorName(OverOp, S, Functions);
15630
15631 // In C++20 onwards, we may have a second operator to look up.
15632 if (getLangOpts().CPlusPlus20) {
15633 if (OverloadedOperatorKind ExtraOp = getRewrittenOverloadedOperator(OverOp))
15634 LookupOverloadedOperatorName(ExtraOp, S, Functions);
15635 }
15636}
15637
15638/// Build an overloaded binary operator expression in the given scope.
15639static ExprResult BuildOverloadedBinOp(Sema &S, Scope *Sc, SourceLocation OpLoc,
15640 BinaryOperatorKind Opc,
15641 Expr *LHS, Expr *RHS) {
15642 switch (Opc) {
15643 case BO_Assign:
15644 case BO_DivAssign:
15645 case BO_RemAssign:
15646 case BO_SubAssign:
15647 case BO_AndAssign:
15648 case BO_OrAssign:
15649 case BO_XorAssign:
15650 DiagnoseSelfAssignment(S, LHS, RHS, OpLoc, false);
15651 CheckIdentityFieldAssignment(LHS, RHS, OpLoc, S);
15652 break;
15653 default:
15654 break;
15655 }
15656
15657 // Find all of the overloaded operators visible from this point.
15658 UnresolvedSet<16> Functions;
15659 S.LookupBinOp(Sc, OpLoc, Opc, Functions);
15660
15661 // Build the (potentially-overloaded, potentially-dependent)
15662 // binary operation.
15663 return S.CreateOverloadedBinOp(OpLoc, Opc, Functions, LHS, RHS);
15664}
15665
15666ExprResult Sema::BuildBinOp(Scope *S, SourceLocation OpLoc,
15667 BinaryOperatorKind Opc,
15668 Expr *LHSExpr, Expr *RHSExpr) {
15669 ExprResult LHS, RHS;
15670 std::tie(LHS, RHS) = CorrectDelayedTyposInBinOp(*this, Opc, LHSExpr, RHSExpr);
15671 if (!LHS.isUsable() || !RHS.isUsable())
15672 return ExprError();
15673 LHSExpr = LHS.get();
15674 RHSExpr = RHS.get();
15675
15676 // We want to end up calling one of checkPseudoObjectAssignment
15677 // (if the LHS is a pseudo-object), BuildOverloadedBinOp (if
15678 // both expressions are overloadable or either is type-dependent),
15679 // or CreateBuiltinBinOp (in any other case). We also want to get
15680 // any placeholder types out of the way.
15681
15682 // Handle pseudo-objects in the LHS.
15683 if (const BuiltinType *pty = LHSExpr->getType()->getAsPlaceholderType()) {
15684 // Assignments with a pseudo-object l-value need special analysis.
15685 if (pty->getKind() == BuiltinType::PseudoObject &&
15686 BinaryOperator::isAssignmentOp(Opc))
15687 return checkPseudoObjectAssignment(S, OpLoc, Opc, LHSExpr, RHSExpr);
15688
15689 // Don't resolve overloads if the other type is overloadable.
15690 if (getLangOpts().CPlusPlus && pty->getKind() == BuiltinType::Overload) {
15691 // We can't actually test that if we still have a placeholder,
15692 // though. Fortunately, none of the exceptions we see in that
15693 // code below are valid when the LHS is an overload set. Note
15694 // that an overload set can be dependently-typed, but it never
15695 // instantiates to having an overloadable type.
15696 ExprResult resolvedRHS = CheckPlaceholderExpr(RHSExpr);
15697 if (resolvedRHS.isInvalid()) return ExprError();
15698 RHSExpr = resolvedRHS.get();
15699
15700 if (RHSExpr->isTypeDependent() ||
15701 RHSExpr->getType()->isOverloadableType())
15702 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
15703 }
15704
15705 // If we're instantiating "a.x < b" or "A::x < b" and 'x' names a function
15706 // template, diagnose the missing 'template' keyword instead of diagnosing
15707 // an invalid use of a bound member function.
15708 //
15709 // Note that "A::x < b" might be valid if 'b' has an overloadable type due
15710 // to C++1z [over.over]/1.4, but we already checked for that case above.
15711 if (Opc == BO_LT && inTemplateInstantiation() &&
15712 (pty->getKind() == BuiltinType::BoundMember ||
15713 pty->getKind() == BuiltinType::Overload)) {
15714 auto *OE = dyn_cast<OverloadExpr>(LHSExpr);
15715 if (OE && !OE->hasTemplateKeyword() && !OE->hasExplicitTemplateArgs() &&
15716 llvm::any_of(OE->decls(), [](NamedDecl *ND) {
15717 return isa<FunctionTemplateDecl>(ND);
15718 })) {
15719 Diag(OE->getQualifier() ? OE->getQualifierLoc().getBeginLoc()
15720 : OE->getNameLoc(),
15721 diag::err_template_kw_missing)
15722 << OE->getName().getAsString() << "";
15723 return ExprError();
15724 }
15725 }
15726
15727 ExprResult LHS = CheckPlaceholderExpr(LHSExpr);
15728 if (LHS.isInvalid()) return ExprError();
15729 LHSExpr = LHS.get();
15730 }
15731
15732 // Handle pseudo-objects in the RHS.
15733 if (const BuiltinType *pty = RHSExpr->getType()->getAsPlaceholderType()) {
15734 // An overload in the RHS can potentially be resolved by the type
15735 // being assigned to.
15736 if (Opc == BO_Assign && pty->getKind() == BuiltinType::Overload) {
15737 if (getLangOpts().CPlusPlus &&
15738 (LHSExpr->isTypeDependent() || RHSExpr->isTypeDependent() ||
15739 LHSExpr->getType()->isOverloadableType()))
15740 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
15741
15742 return CreateBuiltinBinOp(OpLoc, Opc, LHSExpr, RHSExpr);
15743 }
15744
15745 // Don't resolve overloads if the other type is overloadable.
15746 if (getLangOpts().CPlusPlus && pty->getKind() == BuiltinType::Overload &&
15747 LHSExpr->getType()->isOverloadableType())
15748 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
15749
15750 ExprResult resolvedRHS = CheckPlaceholderExpr(RHSExpr);
15751 if (!resolvedRHS.isUsable()) return ExprError();
15752 RHSExpr = resolvedRHS.get();
15753 }
15754
15755 if (getLangOpts().CPlusPlus) {
15756 // If either expression is type-dependent, always build an
15757 // overloaded op.
15758 if (LHSExpr->isTypeDependent() || RHSExpr->isTypeDependent())
15759 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
15760
15761 // Otherwise, build an overloaded op if either expression has an
15762 // overloadable type.
15763 if (LHSExpr->getType()->isOverloadableType() ||
15764 RHSExpr->getType()->isOverloadableType())
15765 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
15766 }
15767
15768 if (getLangOpts().RecoveryAST &&
15769 (LHSExpr->isTypeDependent() || RHSExpr->isTypeDependent())) {
15770 assert(!getLangOpts().CPlusPlus)(static_cast <bool> (!getLangOpts().CPlusPlus) ? void (
0) : __assert_fail ("!getLangOpts().CPlusPlus", "clang/lib/Sema/SemaExpr.cpp"
, 15770, __extension__ __PRETTY_FUNCTION__))
;
15771 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", 15772, __extension__ __PRETTY_FUNCTION__
))
15772 "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", 15772, __extension__ __PRETTY_FUNCTION__
))
;
15773 if (BinaryOperator::isCompoundAssignmentOp(Opc))
15774 // C [6.15.16] p3:
15775 // An assignment expression has the value of the left operand after the
15776 // assignment, but is not an lvalue.
15777 return CompoundAssignOperator::Create(
15778 Context, LHSExpr, RHSExpr, Opc,
15779 LHSExpr->getType().getUnqualifiedType(), VK_PRValue, OK_Ordinary,
15780 OpLoc, CurFPFeatureOverrides());
15781 QualType ResultType;
15782 switch (Opc) {
15783 case BO_Assign:
15784 ResultType = LHSExpr->getType().getUnqualifiedType();
15785 break;
15786 case BO_LT:
15787 case BO_GT:
15788 case BO_LE:
15789 case BO_GE:
15790 case BO_EQ:
15791 case BO_NE:
15792 case BO_LAnd:
15793 case BO_LOr:
15794 // These operators have a fixed result type regardless of operands.
15795 ResultType = Context.IntTy;
15796 break;
15797 case BO_Comma:
15798 ResultType = RHSExpr->getType();
15799 break;
15800 default:
15801 ResultType = Context.DependentTy;
15802 break;
15803 }
15804 return BinaryOperator::Create(Context, LHSExpr, RHSExpr, Opc, ResultType,
15805 VK_PRValue, OK_Ordinary, OpLoc,
15806 CurFPFeatureOverrides());
15807 }
15808
15809 // Build a built-in binary operation.
15810 return CreateBuiltinBinOp(OpLoc, Opc, LHSExpr, RHSExpr);
15811}
15812
15813static bool isOverflowingIntegerType(ASTContext &Ctx, QualType T) {
15814 if (T.isNull() || T->isDependentType())
15815 return false;
15816
15817 if (!Ctx.isPromotableIntegerType(T))
15818 return true;
15819
15820 return Ctx.getIntWidth(T) >= Ctx.getIntWidth(Ctx.IntTy);
15821}
15822
15823ExprResult Sema::CreateBuiltinUnaryOp(SourceLocation OpLoc,
15824 UnaryOperatorKind Opc, Expr *InputExpr,
15825 bool IsAfterAmp) {
15826 ExprResult Input = InputExpr;
15827 ExprValueKind VK = VK_PRValue;
15828 ExprObjectKind OK = OK_Ordinary;
15829 QualType resultType;
15830 bool CanOverflow = false;
15831
15832 bool ConvertHalfVec = false;
15833 if (getLangOpts().OpenCL) {
15834 QualType Ty = InputExpr->getType();
15835 // The only legal unary operation for atomics is '&'.
15836 if ((Opc != UO_AddrOf && Ty->isAtomicType()) ||
15837 // OpenCL special types - image, sampler, pipe, and blocks are to be used
15838 // only with a builtin functions and therefore should be disallowed here.
15839 (Ty->isImageType() || Ty->isSamplerT() || Ty->isPipeType()
15840 || Ty->isBlockPointerType())) {
15841 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
15842 << InputExpr->getType()
15843 << Input.get()->getSourceRange());
15844 }
15845 }
15846
15847 if (getLangOpts().HLSL && OpLoc.isValid()) {
15848 if (Opc == UO_AddrOf)
15849 return ExprError(Diag(OpLoc, diag::err_hlsl_operator_unsupported) << 0);
15850 if (Opc == UO_Deref)
15851 return ExprError(Diag(OpLoc, diag::err_hlsl_operator_unsupported) << 1);
15852 }
15853
15854 switch (Opc) {
15855 case UO_PreInc:
15856 case UO_PreDec:
15857 case UO_PostInc:
15858 case UO_PostDec:
15859 resultType = CheckIncrementDecrementOperand(*this, Input.get(), VK, OK,
15860 OpLoc,
15861 Opc == UO_PreInc ||
15862 Opc == UO_PostInc,
15863 Opc == UO_PreInc ||
15864 Opc == UO_PreDec);
15865 CanOverflow = isOverflowingIntegerType(Context, resultType);
15866 break;
15867 case UO_AddrOf:
15868 resultType = CheckAddressOfOperand(Input, OpLoc);
15869 CheckAddressOfNoDeref(InputExpr);
15870 RecordModifiableNonNullParam(*this, InputExpr);
15871 break;
15872 case UO_Deref: {
15873 Input = DefaultFunctionArrayLvalueConversion(Input.get());
15874 if (Input.isInvalid()) return ExprError();
15875 resultType =
15876 CheckIndirectionOperand(*this, Input.get(), VK, OpLoc, IsAfterAmp);
15877 break;
15878 }
15879 case UO_Plus:
15880 case UO_Minus:
15881 CanOverflow = Opc == UO_Minus &&
15882 isOverflowingIntegerType(Context, Input.get()->getType());
15883 Input = UsualUnaryConversions(Input.get());
15884 if (Input.isInvalid()) return ExprError();
15885 // Unary plus and minus require promoting an operand of half vector to a
15886 // float vector and truncating the result back to a half vector. For now, we
15887 // do this only when HalfArgsAndReturns is set (that is, when the target is
15888 // arm or arm64).
15889 ConvertHalfVec = needsConversionOfHalfVec(true, Context, Input.get());
15890
15891 // If the operand is a half vector, promote it to a float vector.
15892 if (ConvertHalfVec)
15893 Input = convertVector(Input.get(), Context.FloatTy, *this);
15894 resultType = Input.get()->getType();
15895 if (resultType->isDependentType())
15896 break;
15897 if (resultType->isArithmeticType()) // C99 6.5.3.3p1
15898 break;
15899 else if (resultType->isVectorType() &&
15900 // The z vector extensions don't allow + or - with bool vectors.
15901 (!Context.getLangOpts().ZVector ||
15902 resultType->castAs<VectorType>()->getVectorKind() !=
15903 VectorType::AltiVecBool))
15904 break;
15905 else if (resultType->isVLSTBuiltinType()) // SVE vectors allow + and -
15906 break;
15907 else if (getLangOpts().CPlusPlus && // C++ [expr.unary.op]p6
15908 Opc == UO_Plus &&
15909 resultType->isPointerType())
15910 break;
15911
15912 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
15913 << resultType << Input.get()->getSourceRange());
15914
15915 case UO_Not: // bitwise complement
15916 Input = UsualUnaryConversions(Input.get());
15917 if (Input.isInvalid())
15918 return ExprError();
15919 resultType = Input.get()->getType();
15920 if (resultType->isDependentType())
15921 break;
15922 // C99 6.5.3.3p1. We allow complex int and float as a GCC extension.
15923 if (resultType->isComplexType() || resultType->isComplexIntegerType())
15924 // C99 does not support '~' for complex conjugation.
15925 Diag(OpLoc, diag::ext_integer_complement_complex)
15926 << resultType << Input.get()->getSourceRange();
15927 else if (resultType->hasIntegerRepresentation())
15928 break;
15929 else if (resultType->isExtVectorType() && Context.getLangOpts().OpenCL) {
15930 // OpenCL v1.1 s6.3.f: The bitwise operator not (~) does not operate
15931 // on vector float types.
15932 QualType T = resultType->castAs<ExtVectorType>()->getElementType();
15933 if (!T->isIntegerType())
15934 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
15935 << resultType << Input.get()->getSourceRange());
15936 } else {
15937 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
15938 << resultType << Input.get()->getSourceRange());
15939 }
15940 break;
15941
15942 case UO_LNot: // logical negation
15943 // Unlike +/-/~, integer promotions aren't done here (C99 6.5.3.3p5).
15944 Input = DefaultFunctionArrayLvalueConversion(Input.get());
15945 if (Input.isInvalid()) return ExprError();
15946 resultType = Input.get()->getType();
15947
15948 // Though we still have to promote half FP to float...
15949 if (resultType->isHalfType() && !Context.getLangOpts().NativeHalfType) {
15950 Input = ImpCastExprToType(Input.get(), Context.FloatTy, CK_FloatingCast).get();
15951 resultType = Context.FloatTy;
15952 }
15953
15954 if (resultType->isDependentType())
15955 break;
15956 if (resultType->isScalarType() && !isScopedEnumerationType(resultType)) {
15957 // C99 6.5.3.3p1: ok, fallthrough;
15958 if (Context.getLangOpts().CPlusPlus) {
15959 // C++03 [expr.unary.op]p8, C++0x [expr.unary.op]p9:
15960 // operand contextually converted to bool.
15961 Input = ImpCastExprToType(Input.get(), Context.BoolTy,
15962 ScalarTypeToBooleanCastKind(resultType));
15963 } else if (Context.getLangOpts().OpenCL &&
15964 Context.getLangOpts().OpenCLVersion < 120) {
15965 // OpenCL v1.1 6.3.h: The logical operator not (!) does not
15966 // operate on scalar float types.
15967 if (!resultType->isIntegerType() && !resultType->isPointerType())
15968 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
15969 << resultType << Input.get()->getSourceRange());
15970 }
15971 } else if (resultType->isExtVectorType()) {
15972 if (Context.getLangOpts().OpenCL &&
15973 Context.getLangOpts().getOpenCLCompatibleVersion() < 120) {
15974 // OpenCL v1.1 6.3.h: The logical operator not (!) does not
15975 // operate on vector float types.
15976 QualType T = resultType->castAs<ExtVectorType>()->getElementType();
15977 if (!T->isIntegerType())
15978 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
15979 << resultType << Input.get()->getSourceRange());
15980 }
15981 // Vector logical not returns the signed variant of the operand type.
15982 resultType = GetSignedVectorType(resultType);
15983 break;
15984 } else if (Context.getLangOpts().CPlusPlus && resultType->isVectorType()) {
15985 const VectorType *VTy = resultType->castAs<VectorType>();
15986 if (VTy->getVectorKind() != VectorType::GenericVector)
15987 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
15988 << resultType << Input.get()->getSourceRange());
15989
15990 // Vector logical not returns the signed variant of the operand type.
15991 resultType = GetSignedVectorType(resultType);
15992 break;
15993 } else {
15994 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
15995 << resultType << Input.get()->getSourceRange());
15996 }
15997
15998 // LNot always has type int. C99 6.5.3.3p5.
15999 // In C++, it's bool. C++ 5.3.1p8
16000 resultType = Context.getLogicalOperationType();
16001 break;
16002 case UO_Real:
16003 case UO_Imag:
16004 resultType = CheckRealImagOperand(*this, Input, OpLoc, Opc == UO_Real);
16005 // _Real maps ordinary l-values into ordinary l-values. _Imag maps ordinary
16006 // complex l-values to ordinary l-values and all other values to r-values.
16007 if (Input.isInvalid()) return ExprError();
16008 if (Opc == UO_Real || Input.get()->getType()->isAnyComplexType()) {
16009 if (Input.get()->isGLValue() &&
16010 Input.get()->getObjectKind() == OK_Ordinary)
16011 VK = Input.get()->getValueKind();
16012 } else if (!getLangOpts().CPlusPlus) {
16013 // In C, a volatile scalar is read by __imag. In C++, it is not.
16014 Input = DefaultLvalueConversion(Input.get());
16015 }
16016 break;
16017 case UO_Extension:
16018 resultType = Input.get()->getType();
16019 VK = Input.get()->getValueKind();
16020 OK = Input.get()->getObjectKind();
16021 break;
16022 case UO_Coawait:
16023 // It's unnecessary to represent the pass-through operator co_await in the
16024 // AST; just return the input expression instead.
16025 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", 16027, __extension__ __PRETTY_FUNCTION__
))
16026 "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", 16027, __extension__ __PRETTY_FUNCTION__
))
16027 "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", 16027, __extension__ __PRETTY_FUNCTION__
))
;
16028 return Input;
16029 }
16030 if (resultType.isNull() || Input.isInvalid())
16031 return ExprError();
16032
16033 // Check for array bounds violations in the operand of the UnaryOperator,
16034 // except for the '*' and '&' operators that have to be handled specially
16035 // by CheckArrayAccess (as there are special cases like &array[arraysize]
16036 // that are explicitly defined as valid by the standard).
16037 if (Opc != UO_AddrOf && Opc != UO_Deref)
16038 CheckArrayAccess(Input.get());
16039
16040 auto *UO =
16041 UnaryOperator::Create(Context, Input.get(), Opc, resultType, VK, OK,
16042 OpLoc, CanOverflow, CurFPFeatureOverrides());
16043
16044 if (Opc == UO_Deref && UO->getType()->hasAttr(attr::NoDeref) &&
16045 !isa<ArrayType>(UO->getType().getDesugaredType(Context)) &&
16046 !isUnevaluatedContext())
16047 ExprEvalContexts.back().PossibleDerefs.insert(UO);
16048
16049 // Convert the result back to a half vector.
16050 if (ConvertHalfVec)
16051 return convertVector(UO, Context.HalfTy, *this);
16052 return UO;
16053}
16054
16055/// Determine whether the given expression is a qualified member
16056/// access expression, of a form that could be turned into a pointer to member
16057/// with the address-of operator.
16058bool Sema::isQualifiedMemberAccess(Expr *E) {
16059 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
16060 if (!DRE->getQualifier())
16061 return false;
16062
16063 ValueDecl *VD = DRE->getDecl();
16064 if (!VD->isCXXClassMember())
16065 return false;
16066
16067 if (isa<FieldDecl>(VD) || isa<IndirectFieldDecl>(VD))
16068 return true;
16069 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(VD))
16070 return Method->isInstance();
16071
16072 return false;
16073 }
16074
16075 if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(E)) {
16076 if (!ULE->getQualifier())
16077 return false;
16078
16079 for (NamedDecl *D : ULE->decls()) {
16080 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) {
16081 if (Method->isInstance())
16082 return true;
16083 } else {
16084 // Overload set does not contain methods.
16085 break;
16086 }
16087 }
16088
16089 return false;
16090 }
16091
16092 return false;
16093}
16094
16095ExprResult Sema::BuildUnaryOp(Scope *S, SourceLocation OpLoc,
16096 UnaryOperatorKind Opc, Expr *Input,
16097 bool IsAfterAmp) {
16098 // First things first: handle placeholders so that the
16099 // overloaded-operator check considers the right type.
16100 if (const BuiltinType *pty = Input->getType()->getAsPlaceholderType()) {
16101 // Increment and decrement of pseudo-object references.
16102 if (pty->getKind() == BuiltinType::PseudoObject &&
16103 UnaryOperator::isIncrementDecrementOp(Opc))
16104 return checkPseudoObjectIncDec(S, OpLoc, Opc, Input);
16105
16106 // extension is always a builtin operator.
16107 if (Opc == UO_Extension)
16108 return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
16109
16110 // & gets special logic for several kinds of placeholder.
16111 // The builtin code knows what to do.
16112 if (Opc == UO_AddrOf &&
16113 (pty->getKind() == BuiltinType::Overload ||
16114 pty->getKind() == BuiltinType::UnknownAny ||
16115 pty->getKind() == BuiltinType::BoundMember))
16116 return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
16117
16118 // Anything else needs to be handled now.
16119 ExprResult Result = CheckPlaceholderExpr(Input);
16120 if (Result.isInvalid()) return ExprError();
16121 Input = Result.get();
16122 }
16123
16124 if (getLangOpts().CPlusPlus && Input->getType()->isOverloadableType() &&
16125 UnaryOperator::getOverloadedOperator(Opc) != OO_None &&
16126 !(Opc == UO_AddrOf && isQualifiedMemberAccess(Input))) {
16127 // Find all of the overloaded operators visible from this point.
16128 UnresolvedSet<16> Functions;
16129 OverloadedOperatorKind OverOp = UnaryOperator::getOverloadedOperator(Opc);
16130 if (S && OverOp != OO_None)
16131 LookupOverloadedOperatorName(OverOp, S, Functions);
16132
16133 return CreateOverloadedUnaryOp(OpLoc, Opc, Functions, Input);
16134 }
16135
16136 return CreateBuiltinUnaryOp(OpLoc, Opc, Input, IsAfterAmp);
16137}
16138
16139// Unary Operators. 'Tok' is the token for the operator.
16140ExprResult Sema::ActOnUnaryOp(Scope *S, SourceLocation OpLoc, tok::TokenKind Op,
16141 Expr *Input, bool IsAfterAmp) {
16142 return BuildUnaryOp(S, OpLoc, ConvertTokenKindToUnaryOpcode(Op), Input,
16143 IsAfterAmp);
16144}
16145
16146/// ActOnAddrLabel - Parse the GNU address of label extension: "&&foo".
16147ExprResult Sema::ActOnAddrLabel(SourceLocation OpLoc, SourceLocation LabLoc,
16148 LabelDecl *TheDecl) {
16149 TheDecl->markUsed(Context);
16150 // Create the AST node. The address of a label always has type 'void*'.
16151 auto *Res = new (Context) AddrLabelExpr(
16152 OpLoc, LabLoc, TheDecl, Context.getPointerType(Context.VoidTy));
16153
16154 if (getCurFunction())
16155 getCurFunction()->AddrLabels.push_back(Res);
16156
16157 return Res;
16158}
16159
16160void Sema::ActOnStartStmtExpr() {
16161 PushExpressionEvaluationContext(ExprEvalContexts.back().Context);
16162}
16163
16164void Sema::ActOnStmtExprError() {
16165 // Note that function is also called by TreeTransform when leaving a
16166 // StmtExpr scope without rebuilding anything.
16167
16168 DiscardCleanupsInEvaluationContext();
16169 PopExpressionEvaluationContext();
16170}
16171
16172ExprResult Sema::ActOnStmtExpr(Scope *S, SourceLocation LPLoc, Stmt *SubStmt,
16173 SourceLocation RPLoc) {
16174 return BuildStmtExpr(LPLoc, SubStmt, RPLoc, getTemplateDepth(S));
16175}
16176
16177ExprResult Sema::BuildStmtExpr(SourceLocation LPLoc, Stmt *SubStmt,
16178 SourceLocation RPLoc, unsigned TemplateDepth) {
16179 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", 16179, __extension__ __PRETTY_FUNCTION__
))
;
16180 CompoundStmt *Compound = cast<CompoundStmt>(SubStmt);
16181
16182 if (hasAnyUnrecoverableErrorsInThisFunction())
16183 DiscardCleanupsInEvaluationContext();
16184 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", 16185, __extension__ __PRETTY_FUNCTION__
))
16185 "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", 16185, __extension__ __PRETTY_FUNCTION__
))
;
16186 PopExpressionEvaluationContext();
16187
16188 // FIXME: there are a variety of strange constraints to enforce here, for
16189 // example, it is not possible to goto into a stmt expression apparently.
16190 // More semantic analysis is needed.
16191
16192 // If there are sub-stmts in the compound stmt, take the type of the last one
16193 // as the type of the stmtexpr.
16194 QualType Ty = Context.VoidTy;
16195 bool StmtExprMayBindToTemp = false;
16196 if (!Compound->body_empty()) {
16197 // For GCC compatibility we get the last Stmt excluding trailing NullStmts.
16198 if (const auto *LastStmt =
16199 dyn_cast<ValueStmt>(Compound->getStmtExprResult())) {
16200 if (const Expr *Value = LastStmt->getExprStmt()) {
16201 StmtExprMayBindToTemp = true;
16202 Ty = Value->getType();
16203 }
16204 }
16205 }
16206
16207 // FIXME: Check that expression type is complete/non-abstract; statement
16208 // expressions are not lvalues.
16209 Expr *ResStmtExpr =
16210 new (Context) StmtExpr(Compound, Ty, LPLoc, RPLoc, TemplateDepth);
16211 if (StmtExprMayBindToTemp)
16212 return MaybeBindToTemporary(ResStmtExpr);
16213 return ResStmtExpr;
16214}
16215
16216ExprResult Sema::ActOnStmtExprResult(ExprResult ER) {
16217 if (ER.isInvalid())
16218 return ExprError();
16219
16220 // Do function/array conversion on the last expression, but not
16221 // lvalue-to-rvalue. However, initialize an unqualified type.
16222 ER = DefaultFunctionArrayConversion(ER.get());
16223 if (ER.isInvalid())
16224 return ExprError();
16225 Expr *E = ER.get();
16226
16227 if (E->isTypeDependent())
16228 return E;
16229
16230 // In ARC, if the final expression ends in a consume, splice
16231 // the consume out and bind it later. In the alternate case
16232 // (when dealing with a retainable type), the result
16233 // initialization will create a produce. In both cases the
16234 // result will be +1, and we'll need to balance that out with
16235 // a bind.
16236 auto *Cast = dyn_cast<ImplicitCastExpr>(E);
16237 if (Cast && Cast->getCastKind() == CK_ARCConsumeObject)
16238 return Cast->getSubExpr();
16239
16240 // FIXME: Provide a better location for the initialization.
16241 return PerformCopyInitialization(
16242 InitializedEntity::InitializeStmtExprResult(
16243 E->getBeginLoc(), E->getType().getUnqualifiedType()),
16244 SourceLocation(), E);
16245}
16246
16247ExprResult Sema::BuildBuiltinOffsetOf(SourceLocation BuiltinLoc,
16248 TypeSourceInfo *TInfo,
16249 ArrayRef<OffsetOfComponent> Components,
16250 SourceLocation RParenLoc) {
16251 QualType ArgTy = TInfo->getType();
16252 bool Dependent = ArgTy->isDependentType();
16253 SourceRange TypeRange = TInfo->getTypeLoc().getLocalSourceRange();
16254
16255 // We must have at least one component that refers to the type, and the first
16256 // one is known to be a field designator. Verify that the ArgTy represents
16257 // a struct/union/class.
16258 if (!Dependent && !ArgTy->isRecordType())
16259 return ExprError(Diag(BuiltinLoc, diag::err_offsetof_record_type)
16260 << ArgTy << TypeRange);
16261
16262 // Type must be complete per C99 7.17p3 because a declaring a variable
16263 // with an incomplete type would be ill-formed.
16264 if (!Dependent
16265 && RequireCompleteType(BuiltinLoc, ArgTy,
16266 diag::err_offsetof_incomplete_type, TypeRange))
16267 return ExprError();
16268
16269 bool DidWarnAboutNonPOD = false;
16270 QualType CurrentType = ArgTy;
16271 SmallVector<OffsetOfNode, 4> Comps;
16272 SmallVector<Expr*, 4> Exprs;
16273 for (const OffsetOfComponent &OC : Components) {
16274 if (OC.isBrackets) {
16275 // Offset of an array sub-field. TODO: Should we allow vector elements?
16276 if (!CurrentType->isDependentType()) {
16277 const ArrayType *AT = Context.getAsArrayType(CurrentType);
16278 if(!AT)
16279 return ExprError(Diag(OC.LocEnd, diag::err_offsetof_array_type)
16280 << CurrentType);
16281 CurrentType = AT->getElementType();
16282 } else
16283 CurrentType = Context.DependentTy;
16284
16285 ExprResult IdxRval = DefaultLvalueConversion(static_cast<Expr*>(OC.U.E));
16286 if (IdxRval.isInvalid())
16287 return ExprError();
16288 Expr *Idx = IdxRval.get();
16289
16290 // The expression must be an integral expression.
16291 // FIXME: An integral constant expression?
16292 if (!Idx->isTypeDependent() && !Idx->isValueDependent() &&
16293 !Idx->getType()->isIntegerType())
16294 return ExprError(
16295 Diag(Idx->getBeginLoc(), diag::err_typecheck_subscript_not_integer)
16296 << Idx->getSourceRange());
16297
16298 // Record this array index.
16299 Comps.push_back(OffsetOfNode(OC.LocStart, Exprs.size(), OC.LocEnd));
16300 Exprs.push_back(Idx);
16301 continue;
16302 }
16303
16304 // Offset of a field.
16305 if (CurrentType->isDependentType()) {
16306 // We have the offset of a field, but we can't look into the dependent
16307 // type. Just record the identifier of the field.
16308 Comps.push_back(OffsetOfNode(OC.LocStart, OC.U.IdentInfo, OC.LocEnd));
16309 CurrentType = Context.DependentTy;
16310 continue;
16311 }
16312
16313 // We need to have a complete type to look into.
16314 if (RequireCompleteType(OC.LocStart, CurrentType,
16315 diag::err_offsetof_incomplete_type))
16316 return ExprError();
16317
16318 // Look for the designated field.
16319 const RecordType *RC = CurrentType->getAs<RecordType>();
16320 if (!RC)
16321 return ExprError(Diag(OC.LocEnd, diag::err_offsetof_record_type)
16322 << CurrentType);
16323 RecordDecl *RD = RC->getDecl();
16324
16325 // C++ [lib.support.types]p5:
16326 // The macro offsetof accepts a restricted set of type arguments in this
16327 // International Standard. type shall be a POD structure or a POD union
16328 // (clause 9).
16329 // C++11 [support.types]p4:
16330 // If type is not a standard-layout class (Clause 9), the results are
16331 // undefined.
16332 if (CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) {
16333 bool IsSafe = LangOpts.CPlusPlus11? CRD->isStandardLayout() : CRD->isPOD();
16334 unsigned DiagID =
16335 LangOpts.CPlusPlus11? diag::ext_offsetof_non_standardlayout_type
16336 : diag::ext_offsetof_non_pod_type;
16337
16338 if (!IsSafe && !DidWarnAboutNonPOD &&
16339 DiagRuntimeBehavior(BuiltinLoc, nullptr,
16340 PDiag(DiagID)
16341 << SourceRange(Components[0].LocStart, OC.LocEnd)
16342 << CurrentType))
16343 DidWarnAboutNonPOD = true;
16344 }
16345
16346 // Look for the field.
16347 LookupResult R(*this, OC.U.IdentInfo, OC.LocStart, LookupMemberName);
16348 LookupQualifiedName(R, RD);
16349 FieldDecl *MemberDecl = R.getAsSingle<FieldDecl>();
16350 IndirectFieldDecl *IndirectMemberDecl = nullptr;
16351 if (!MemberDecl) {
16352 if ((IndirectMemberDecl = R.getAsSingle<IndirectFieldDecl>()))
16353 MemberDecl = IndirectMemberDecl->getAnonField();
16354 }
16355
16356 if (!MemberDecl)
16357 return ExprError(Diag(BuiltinLoc, diag::err_no_member)
16358 << OC.U.IdentInfo << RD << SourceRange(OC.LocStart,
16359 OC.LocEnd));
16360
16361 // C99 7.17p3:
16362 // (If the specified member is a bit-field, the behavior is undefined.)
16363 //
16364 // We diagnose this as an error.
16365 if (MemberDecl->isBitField()) {
16366 Diag(OC.LocEnd, diag::err_offsetof_bitfield)
16367 << MemberDecl->getDeclName()
16368 << SourceRange(BuiltinLoc, RParenLoc);
16369 Diag(MemberDecl->getLocation(), diag::note_bitfield_decl);
16370 return ExprError();
16371 }
16372
16373 RecordDecl *Parent = MemberDecl->getParent();
16374 if (IndirectMemberDecl)
16375 Parent = cast<RecordDecl>(IndirectMemberDecl->getDeclContext());
16376
16377 // If the member was found in a base class, introduce OffsetOfNodes for
16378 // the base class indirections.
16379 CXXBasePaths Paths;
16380 if (IsDerivedFrom(OC.LocStart, CurrentType, Context.getTypeDeclType(Parent),
16381 Paths)) {
16382 if (Paths.getDetectedVirtual()) {
16383 Diag(OC.LocEnd, diag::err_offsetof_field_of_virtual_base)
16384 << MemberDecl->getDeclName()
16385 << SourceRange(BuiltinLoc, RParenLoc);
16386 return ExprError();
16387 }
16388
16389 CXXBasePath &Path = Paths.front();
16390 for (const CXXBasePathElement &B : Path)
16391 Comps.push_back(OffsetOfNode(B.Base));
16392 }
16393
16394 if (IndirectMemberDecl) {
16395 for (auto *FI : IndirectMemberDecl->chain()) {
16396 assert(isa<FieldDecl>(FI))(static_cast <bool> (isa<FieldDecl>(FI)) ? void (
0) : __assert_fail ("isa<FieldDecl>(FI)", "clang/lib/Sema/SemaExpr.cpp"
, 16396, __extension__ __PRETTY_FUNCTION__))
;
16397 Comps.push_back(OffsetOfNode(OC.LocStart,
16398 cast<FieldDecl>(FI), OC.LocEnd));
16399 }
16400 } else
16401 Comps.push_back(OffsetOfNode(OC.LocStart, MemberDecl, OC.LocEnd));
16402
16403 CurrentType = MemberDecl->getType().getNonReferenceType();
16404 }
16405
16406 return OffsetOfExpr::Create(Context, Context.getSizeType(), BuiltinLoc, TInfo,
16407 Comps, Exprs, RParenLoc);
16408}
16409
16410ExprResult Sema::ActOnBuiltinOffsetOf(Scope *S,
16411 SourceLocation BuiltinLoc,
16412 SourceLocation TypeLoc,
16413 ParsedType ParsedArgTy,
16414 ArrayRef<OffsetOfComponent> Components,
16415 SourceLocation RParenLoc) {
16416
16417 TypeSourceInfo *ArgTInfo;
16418 QualType ArgTy = GetTypeFromParser(ParsedArgTy, &ArgTInfo);
16419 if (ArgTy.isNull())
16420 return ExprError();
16421
16422 if (!ArgTInfo)
16423 ArgTInfo = Context.getTrivialTypeSourceInfo(ArgTy, TypeLoc);
16424
16425 return BuildBuiltinOffsetOf(BuiltinLoc, ArgTInfo, Components, RParenLoc);
16426}
16427
16428
16429ExprResult Sema::ActOnChooseExpr(SourceLocation BuiltinLoc,
16430 Expr *CondExpr,
16431 Expr *LHSExpr, Expr *RHSExpr,
16432 SourceLocation RPLoc) {
16433 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", 16433, __extension__ __PRETTY_FUNCTION__
))
;
16434
16435 ExprValueKind VK = VK_PRValue;
16436 ExprObjectKind OK = OK_Ordinary;
16437 QualType resType;
16438 bool CondIsTrue = false;
16439 if (CondExpr->isTypeDependent() || CondExpr->isValueDependent()) {
16440 resType = Context.DependentTy;
16441 } else {
16442 // The conditional expression is required to be a constant expression.
16443 llvm::APSInt condEval(32);
16444 ExprResult CondICE = VerifyIntegerConstantExpression(
16445 CondExpr, &condEval, diag::err_typecheck_choose_expr_requires_constant);
16446 if (CondICE.isInvalid())
16447 return ExprError();
16448 CondExpr = CondICE.get();
16449 CondIsTrue = condEval.getZExtValue();
16450
16451 // If the condition is > zero, then the AST type is the same as the LHSExpr.
16452 Expr *ActiveExpr = CondIsTrue ? LHSExpr : RHSExpr;
16453
16454 resType = ActiveExpr->getType();
16455 VK = ActiveExpr->getValueKind();
16456 OK = ActiveExpr->getObjectKind();
16457 }
16458
16459 return new (Context) ChooseExpr(BuiltinLoc, CondExpr, LHSExpr, RHSExpr,
16460 resType, VK, OK, RPLoc, CondIsTrue);
16461}
16462
16463//===----------------------------------------------------------------------===//
16464// Clang Extensions.
16465//===----------------------------------------------------------------------===//
16466
16467/// ActOnBlockStart - This callback is invoked when a block literal is started.
16468void Sema::ActOnBlockStart(SourceLocation CaretLoc, Scope *CurScope) {
16469 BlockDecl *Block = BlockDecl::Create(Context, CurContext, CaretLoc);
16470
16471 if (LangOpts.CPlusPlus) {
16472 MangleNumberingContext *MCtx;
16473 Decl *ManglingContextDecl;
16474 std::tie(MCtx, ManglingContextDecl) =
16475 getCurrentMangleNumberContext(Block->getDeclContext());
16476 if (MCtx) {
16477 unsigned ManglingNumber = MCtx->getManglingNumber(Block);
16478 Block->setBlockMangling(ManglingNumber, ManglingContextDecl);
16479 }
16480 }
16481
16482 PushBlockScope(CurScope, Block);
16483 CurContext->addDecl(Block);
16484 if (CurScope)
16485 PushDeclContext(CurScope, Block);
16486 else
16487 CurContext = Block;
16488
16489 getCurBlock()->HasImplicitReturnType = true;
16490
16491 // Enter a new evaluation context to insulate the block from any
16492 // cleanups from the enclosing full-expression.
16493 PushExpressionEvaluationContext(
16494 ExpressionEvaluationContext::PotentiallyEvaluated);
16495}
16496
16497void Sema::ActOnBlockArguments(SourceLocation CaretLoc, Declarator &ParamInfo,
16498 Scope *CurScope) {
16499 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", 16500, __extension__ __PRETTY_FUNCTION__
))
16500 "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", 16500, __extension__ __PRETTY_FUNCTION__
))
;
16501 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", 16501, __extension__ __PRETTY_FUNCTION__
))
;
16502 BlockScopeInfo *CurBlock = getCurBlock();
16503
16504 TypeSourceInfo *Sig = GetTypeForDeclarator(ParamInfo, CurScope);
16505 QualType T = Sig->getType();
16506
16507 // FIXME: We should allow unexpanded parameter packs here, but that would,
16508 // in turn, make the block expression contain unexpanded parameter packs.
16509 if (DiagnoseUnexpandedParameterPack(CaretLoc, Sig, UPPC_Block)) {
16510 // Drop the parameters.
16511 FunctionProtoType::ExtProtoInfo EPI;
16512 EPI.HasTrailingReturn = false;
16513 EPI.TypeQuals.addConst();
16514 T = Context.getFunctionType(Context.DependentTy, std::nullopt, EPI);
16515 Sig = Context.getTrivialTypeSourceInfo(T);
16516 }
16517
16518 // GetTypeForDeclarator always produces a function type for a block
16519 // literal signature. Furthermore, it is always a FunctionProtoType
16520 // unless the function was written with a typedef.
16521 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", 16522, __extension__ __PRETTY_FUNCTION__
))
16522 "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", 16522, __extension__ __PRETTY_FUNCTION__
))
;
16523
16524 // Look for an explicit signature in that function type.
16525 FunctionProtoTypeLoc ExplicitSignature;
16526
16527 if ((ExplicitSignature = Sig->getTypeLoc()
16528 .getAsAdjusted<FunctionProtoTypeLoc>())) {
16529
16530 // Check whether that explicit signature was synthesized by
16531 // GetTypeForDeclarator. If so, don't save that as part of the
16532 // written signature.
16533 if (ExplicitSignature.getLocalRangeBegin() ==
16534 ExplicitSignature.getLocalRangeEnd()) {
16535 // This would be much cheaper if we stored TypeLocs instead of
16536 // TypeSourceInfos.
16537 TypeLoc Result = ExplicitSignature.getReturnLoc();
16538 unsigned Size = Result.getFullDataSize();
16539 Sig = Context.CreateTypeSourceInfo(Result.getType(), Size);
16540 Sig->getTypeLoc().initializeFullCopy(Result, Size);
16541
16542 ExplicitSignature = FunctionProtoTypeLoc();
16543 }
16544 }
16545
16546 CurBlock->TheDecl->setSignatureAsWritten(Sig);
16547 CurBlock->FunctionType = T;
16548
16549 const auto *Fn = T->castAs<FunctionType>();
16550 QualType RetTy = Fn->getReturnType();
16551 bool isVariadic =
16552 (isa<FunctionProtoType>(Fn) && cast<FunctionProtoType>(Fn)->isVariadic());
16553
16554 CurBlock->TheDecl->setIsVariadic(isVariadic);
16555
16556 // Context.DependentTy is used as a placeholder for a missing block
16557 // return type. TODO: what should we do with declarators like:
16558 // ^ * { ... }
16559 // If the answer is "apply template argument deduction"....
16560 if (RetTy != Context.DependentTy) {
16561 CurBlock->ReturnType = RetTy;
16562 CurBlock->TheDecl->setBlockMissingReturnType(false);
16563 CurBlock->HasImplicitReturnType = false;
16564 }
16565
16566 // Push block parameters from the declarator if we had them.
16567 SmallVector<ParmVarDecl*, 8> Params;
16568 if (ExplicitSignature) {
16569 for (unsigned I = 0, E = ExplicitSignature.getNumParams(); I != E; ++I) {
16570 ParmVarDecl *Param = ExplicitSignature.getParam(I);
16571 if (Param->getIdentifier() == nullptr && !Param->isImplicit() &&
16572 !Param->isInvalidDecl() && !getLangOpts().CPlusPlus) {
16573 // Diagnose this as an extension in C17 and earlier.
16574 if (!getLangOpts().C2x)
16575 Diag(Param->getLocation(), diag::ext_parameter_name_omitted_c2x);
16576 }
16577 Params.push_back(Param);
16578 }
16579
16580 // Fake up parameter variables if we have a typedef, like
16581 // ^ fntype { ... }
16582 } else if (const FunctionProtoType *Fn = T->getAs<FunctionProtoType>()) {
16583 for (const auto &I : Fn->param_types()) {
16584 ParmVarDecl *Param = BuildParmVarDeclForTypedef(
16585 CurBlock->TheDecl, ParamInfo.getBeginLoc(), I);
16586 Params.push_back(Param);
16587 }
16588 }
16589
16590 // Set the parameters on the block decl.
16591 if (!Params.empty()) {
16592 CurBlock->TheDecl->setParams(Params);
16593 CheckParmsForFunctionDef(CurBlock->TheDecl->parameters(),
16594 /*CheckParameterNames=*/false);
16595 }
16596
16597 // Finally we can process decl attributes.
16598 ProcessDeclAttributes(CurScope, CurBlock->TheDecl, ParamInfo);
16599
16600 // Put the parameter variables in scope.
16601 for (auto *AI : CurBlock->TheDecl->parameters()) {
16602 AI->setOwningFunction(CurBlock->TheDecl);
16603
16604 // If this has an identifier, add it to the scope stack.
16605 if (AI->getIdentifier()) {
16606 CheckShadow(CurBlock->TheScope, AI);
16607
16608 PushOnScopeChains(AI, CurBlock->TheScope);
16609 }
16610 }
16611}
16612
16613/// ActOnBlockError - If there is an error parsing a block, this callback
16614/// is invoked to pop the information about the block from the action impl.
16615void Sema::ActOnBlockError(SourceLocation CaretLoc, Scope *CurScope) {
16616 // Leave the expression-evaluation context.
16617 DiscardCleanupsInEvaluationContext();
16618 PopExpressionEvaluationContext();
16619
16620 // Pop off CurBlock, handle nested blocks.
16621 PopDeclContext();
16622 PopFunctionScopeInfo();
16623}
16624
16625/// ActOnBlockStmtExpr - This is called when the body of a block statement
16626/// literal was successfully completed. ^(int x){...}
16627ExprResult Sema::ActOnBlockStmtExpr(SourceLocation CaretLoc,
16628 Stmt *Body, Scope *CurScope) {
16629 // If blocks are disabled, emit an error.
16630 if (!LangOpts.Blocks)
16631 Diag(CaretLoc, diag::err_blocks_disable) << LangOpts.OpenCL;
16632
16633 // Leave the expression-evaluation context.
16634 if (hasAnyUnrecoverableErrorsInThisFunction())
16635 DiscardCleanupsInEvaluationContext();
16636 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", 16637, __extension__ __PRETTY_FUNCTION__
))
16637 "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", 16637, __extension__ __PRETTY_FUNCTION__
))
;
16638 PopExpressionEvaluationContext();
16639
16640 BlockScopeInfo *BSI = cast<BlockScopeInfo>(FunctionScopes.back());
16641 BlockDecl *BD = BSI->TheDecl;
16642
16643 if (BSI->HasImplicitReturnType)
16644 deduceClosureReturnType(*BSI);
16645
16646 QualType RetTy = Context.VoidTy;
16647 if (!BSI->ReturnType.isNull())
16648 RetTy = BSI->ReturnType;
16649
16650 bool NoReturn = BD->hasAttr<NoReturnAttr>();
16651 QualType BlockTy;
16652
16653 // If the user wrote a function type in some form, try to use that.
16654 if (!BSI->FunctionType.isNull()) {
16655 const FunctionType *FTy = BSI->FunctionType->castAs<FunctionType>();
16656
16657 FunctionType::ExtInfo Ext = FTy->getExtInfo();
16658 if (NoReturn && !Ext.getNoReturn()) Ext = Ext.withNoReturn(true);
16659
16660 // Turn protoless block types into nullary block types.
16661 if (isa<FunctionNoProtoType>(FTy)) {
16662 FunctionProtoType::ExtProtoInfo EPI;
16663 EPI.ExtInfo = Ext;
16664 BlockTy = Context.getFunctionType(RetTy, std::nullopt, EPI);
16665
16666 // Otherwise, if we don't need to change anything about the function type,
16667 // preserve its sugar structure.
16668 } else if (FTy->getReturnType() == RetTy &&
16669 (!NoReturn || FTy->getNoReturnAttr())) {
16670 BlockTy = BSI->FunctionType;
16671
16672 // Otherwise, make the minimal modifications to the function type.
16673 } else {
16674 const FunctionProtoType *FPT = cast<FunctionProtoType>(FTy);
16675 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
16676 EPI.TypeQuals = Qualifiers();
16677 EPI.ExtInfo = Ext;
16678 BlockTy = Context.getFunctionType(RetTy, FPT->getParamTypes(), EPI);
16679 }
16680
16681 // If we don't have a function type, just build one from nothing.
16682 } else {
16683 FunctionProtoType::ExtProtoInfo EPI;
16684 EPI.ExtInfo = FunctionType::ExtInfo().withNoReturn(NoReturn);
16685 BlockTy = Context.getFunctionType(RetTy, std::nullopt, EPI);
16686 }
16687
16688 DiagnoseUnusedParameters(BD->parameters());
16689 BlockTy = Context.getBlockPointerType(BlockTy);
16690
16691 // If needed, diagnose invalid gotos and switches in the block.
16692 if (getCurFunction()->NeedsScopeChecking() &&
16693 !PP.isCodeCompletionEnabled())
16694 DiagnoseInvalidJumps(cast<CompoundStmt>(Body));
16695
16696 BD->setBody(cast<CompoundStmt>(Body));
16697
16698 if (Body && getCurFunction()->HasPotentialAvailabilityViolations)
16699 DiagnoseUnguardedAvailabilityViolations(BD);
16700
16701 // Try to apply the named return value optimization. We have to check again
16702 // if we can do this, though, because blocks keep return statements around
16703 // to deduce an implicit return type.
16704 if (getLangOpts().CPlusPlus && RetTy->isRecordType() &&
16705 !BD->isDependentContext())
16706 computeNRVO(Body, BSI);
16707
16708 if (RetTy.hasNonTrivialToPrimitiveDestructCUnion() ||
16709 RetTy.hasNonTrivialToPrimitiveCopyCUnion())
16710 checkNonTrivialCUnion(RetTy, BD->getCaretLocation(), NTCUC_FunctionReturn,
16711 NTCUK_Destruct|NTCUK_Copy);
16712
16713 PopDeclContext();
16714
16715 // Set the captured variables on the block.
16716 SmallVector<BlockDecl::Capture, 4> Captures;
16717 for (Capture &Cap : BSI->Captures) {
16718 if (Cap.isInvalid() || Cap.isThisCapture())
16719 continue;
16720 // Cap.getVariable() is always a VarDecl because
16721 // blocks cannot capture structured bindings or other ValueDecl kinds.
16722 auto *Var = cast<VarDecl>(Cap.getVariable());
16723 Expr *CopyExpr = nullptr;
16724 if (getLangOpts().CPlusPlus && Cap.isCopyCapture()) {
16725 if (const RecordType *Record =
16726 Cap.getCaptureType()->getAs<RecordType>()) {
16727 // The capture logic needs the destructor, so make sure we mark it.
16728 // Usually this is unnecessary because most local variables have
16729 // their destructors marked at declaration time, but parameters are
16730 // an exception because it's technically only the call site that
16731 // actually requires the destructor.
16732 if (isa<ParmVarDecl>(Var))
16733 FinalizeVarWithDestructor(Var, Record);
16734
16735 // Enter a separate potentially-evaluated context while building block
16736 // initializers to isolate their cleanups from those of the block
16737 // itself.
16738 // FIXME: Is this appropriate even when the block itself occurs in an
16739 // unevaluated operand?
16740 EnterExpressionEvaluationContext EvalContext(
16741 *this, ExpressionEvaluationContext::PotentiallyEvaluated);
16742
16743 SourceLocation Loc = Cap.getLocation();
16744
16745 ExprResult Result = BuildDeclarationNameExpr(
16746 CXXScopeSpec(), DeclarationNameInfo(Var->getDeclName(), Loc), Var);
16747
16748 // According to the blocks spec, the capture of a variable from
16749 // the stack requires a const copy constructor. This is not true
16750 // of the copy/move done to move a __block variable to the heap.
16751 if (!Result.isInvalid() &&
16752 !Result.get()->getType().isConstQualified()) {
16753 Result = ImpCastExprToType(Result.get(),
16754 Result.get()->getType().withConst(),
16755 CK_NoOp, VK_LValue);
16756 }
16757
16758 if (!Result.isInvalid()) {
16759 Result = PerformCopyInitialization(
16760 InitializedEntity::InitializeBlock(Var->getLocation(),
16761 Cap.getCaptureType()),
16762 Loc, Result.get());
16763 }
16764
16765 // Build a full-expression copy expression if initialization
16766 // succeeded and used a non-trivial constructor. Recover from
16767 // errors by pretending that the copy isn't necessary.
16768 if (!Result.isInvalid() &&
16769 !cast<CXXConstructExpr>(Result.get())->getConstructor()
16770 ->isTrivial()) {
16771 Result = MaybeCreateExprWithCleanups(Result);
16772 CopyExpr = Result.get();
16773 }
16774 }
16775 }
16776
16777 BlockDecl::Capture NewCap(Var, Cap.isBlockCapture(), Cap.isNested(),
16778 CopyExpr);
16779 Captures.push_back(NewCap);
16780 }
16781 BD->setCaptures(Context, Captures, BSI->CXXThisCaptureIndex != 0);
16782
16783 // Pop the block scope now but keep it alive to the end of this function.
16784 AnalysisBasedWarnings::Policy WP = AnalysisWarnings.getDefaultPolicy();
16785 PoppedFunctionScopePtr ScopeRAII = PopFunctionScopeInfo(&WP, BD, BlockTy);
16786
16787 BlockExpr *Result = new (Context) BlockExpr(BD, BlockTy);
16788
16789 // If the block isn't obviously global, i.e. it captures anything at
16790 // all, then we need to do a few things in the surrounding context:
16791 if (Result->getBlockDecl()->hasCaptures()) {
16792 // First, this expression has a new cleanup object.
16793 ExprCleanupObjects.push_back(Result->getBlockDecl());
16794 Cleanup.setExprNeedsCleanups(true);
16795
16796 // It also gets a branch-protected scope if any of the captured
16797 // variables needs destruction.
16798 for (const auto &CI : Result->getBlockDecl()->captures()) {
16799 const VarDecl *var = CI.getVariable();
16800 if (var->getType().isDestructedType() != QualType::DK_none) {
16801 setFunctionHasBranchProtectedScope();
16802 break;
16803 }
16804 }
16805 }
16806
16807 if (getCurFunction())
16808 getCurFunction()->addBlock(BD);
16809
16810 return Result;
16811}
16812
16813ExprResult Sema::ActOnVAArg(SourceLocation BuiltinLoc, Expr *E, ParsedType Ty,
16814 SourceLocation RPLoc) {
16815 TypeSourceInfo *TInfo;
16816 GetTypeFromParser(Ty, &TInfo);
16817 return BuildVAArgExpr(BuiltinLoc, E, TInfo, RPLoc);
16818}
16819
16820ExprResult Sema::BuildVAArgExpr(SourceLocation BuiltinLoc,
16821 Expr *E, TypeSourceInfo *TInfo,
16822 SourceLocation RPLoc) {
16823 Expr *OrigExpr = E;
16824 bool IsMS = false;
16825
16826 // CUDA device code does not support varargs.
16827 if (getLangOpts().CUDA && getLangOpts().CUDAIsDevice) {
16828 if (const FunctionDecl *F = dyn_cast<FunctionDecl>(CurContext)) {
16829 CUDAFunctionTarget T = IdentifyCUDATarget(F);
16830 if (T == CFT_Global || T == CFT_Device || T == CFT_HostDevice)
16831 return ExprError(Diag(E->getBeginLoc(), diag::err_va_arg_in_device));
16832 }
16833 }
16834
16835 // NVPTX does not support va_arg expression.
16836 if (getLangOpts().OpenMP && getLangOpts().OpenMPIsDevice &&
16837 Context.getTargetInfo().getTriple().isNVPTX())
16838 targetDiag(E->getBeginLoc(), diag::err_va_arg_in_device);
16839
16840 // It might be a __builtin_ms_va_list. (But don't ever mark a va_arg()
16841 // as Microsoft ABI on an actual Microsoft platform, where
16842 // __builtin_ms_va_list and __builtin_va_list are the same.)
16843 if (!E->isTypeDependent() && Context.getTargetInfo().hasBuiltinMSVaList() &&
16844 Context.getTargetInfo().getBuiltinVaListKind() != TargetInfo::CharPtrBuiltinVaList) {
16845 QualType MSVaListType = Context.getBuiltinMSVaListType();
16846 if (Context.hasSameType(MSVaListType, E->getType())) {
16847 if (CheckForModifiableLvalue(E, BuiltinLoc, *this))
16848 return ExprError();
16849 IsMS = true;
16850 }
16851 }
16852
16853 // Get the va_list type
16854 QualType VaListType = Context.getBuiltinVaListType();
16855 if (!IsMS) {
16856 if (VaListType->isArrayType()) {
16857 // Deal with implicit array decay; for example, on x86-64,
16858 // va_list is an array, but it's supposed to decay to
16859 // a pointer for va_arg.
16860 VaListType = Context.getArrayDecayedType(VaListType);
16861 // Make sure the input expression also decays appropriately.
16862 ExprResult Result = UsualUnaryConversions(E);
16863 if (Result.isInvalid())
16864 return ExprError();
16865 E = Result.get();
16866 } else if (VaListType->isRecordType() && getLangOpts().CPlusPlus) {
16867 // If va_list is a record type and we are compiling in C++ mode,
16868 // check the argument using reference binding.
16869 InitializedEntity Entity = InitializedEntity::InitializeParameter(
16870 Context, Context.getLValueReferenceType(VaListType), false);
16871 ExprResult Init = PerformCopyInitialization(Entity, SourceLocation(), E);
16872 if (Init.isInvalid())
16873 return ExprError();
16874 E = Init.getAs<Expr>();
16875 } else {
16876 // Otherwise, the va_list argument must be an l-value because
16877 // it is modified by va_arg.
16878 if (!E->isTypeDependent() &&
16879 CheckForModifiableLvalue(E, BuiltinLoc, *this))
16880 return ExprError();
16881 }
16882 }
16883
16884 if (!IsMS && !E->isTypeDependent() &&
16885 !Context.hasSameType(VaListType, E->getType()))
16886 return ExprError(
16887 Diag(E->getBeginLoc(),
16888 diag::err_first_argument_to_va_arg_not_of_type_va_list)
16889 << OrigExpr->getType() << E->getSourceRange());
16890
16891 if (!TInfo->getType()->isDependentType()) {
16892 if (RequireCompleteType(TInfo->getTypeLoc().getBeginLoc(), TInfo->getType(),
16893 diag::err_second_parameter_to_va_arg_incomplete,
16894 TInfo->getTypeLoc()))
16895 return ExprError();
16896
16897 if (RequireNonAbstractType(TInfo->getTypeLoc().getBeginLoc(),
16898 TInfo->getType(),
16899 diag::err_second_parameter_to_va_arg_abstract,
16900 TInfo->getTypeLoc()))
16901 return ExprError();
16902
16903 if (!TInfo->getType().isPODType(Context)) {
16904 Diag(TInfo->getTypeLoc().getBeginLoc(),
16905 TInfo->getType()->isObjCLifetimeType()
16906 ? diag::warn_second_parameter_to_va_arg_ownership_qualified
16907 : diag::warn_second_parameter_to_va_arg_not_pod)
16908 << TInfo->getType()
16909 << TInfo->getTypeLoc().getSourceRange();
16910 }
16911
16912 // Check for va_arg where arguments of the given type will be promoted
16913 // (i.e. this va_arg is guaranteed to have undefined behavior).
16914 QualType PromoteType;
16915 if (Context.isPromotableIntegerType(TInfo->getType())) {
16916 PromoteType = Context.getPromotedIntegerType(TInfo->getType());
16917 // [cstdarg.syn]p1 defers the C++ behavior to what the C standard says,
16918 // and C2x 7.16.1.1p2 says, in part:
16919 // If type is not compatible with the type of the actual next argument
16920 // (as promoted according to the default argument promotions), the
16921 // behavior is undefined, except for the following cases:
16922 // - both types are pointers to qualified or unqualified versions of
16923 // compatible types;
16924 // - one type is a signed integer type, the other type is the
16925 // corresponding unsigned integer type, and the value is
16926 // representable in both types;
16927 // - one type is pointer to qualified or unqualified void and the
16928 // other is a pointer to a qualified or unqualified character type.
16929 // Given that type compatibility is the primary requirement (ignoring
16930 // qualifications), you would think we could call typesAreCompatible()
16931 // directly to test this. However, in C++, that checks for *same type*,
16932 // which causes false positives when passing an enumeration type to
16933 // va_arg. Instead, get the underlying type of the enumeration and pass
16934 // that.
16935 QualType UnderlyingType = TInfo->getType();
16936 if (const auto *ET = UnderlyingType->getAs<EnumType>())
16937 UnderlyingType = ET->getDecl()->getIntegerType();
16938 if (Context.typesAreCompatible(PromoteType, UnderlyingType,
16939 /*CompareUnqualified*/ true))
16940 PromoteType = QualType();
16941
16942 // If the types are still not compatible, we need to test whether the
16943 // promoted type and the underlying type are the same except for
16944 // signedness. Ask the AST for the correctly corresponding type and see
16945 // if that's compatible.
16946 if (!PromoteType.isNull() && !UnderlyingType->isBooleanType() &&
16947 PromoteType->isUnsignedIntegerType() !=
16948 UnderlyingType->isUnsignedIntegerType()) {
16949 UnderlyingType =
16950 UnderlyingType->isUnsignedIntegerType()
16951 ? Context.getCorrespondingSignedType(UnderlyingType)
16952 : Context.getCorrespondingUnsignedType(UnderlyingType);
16953 if (Context.typesAreCompatible(PromoteType, UnderlyingType,
16954 /*CompareUnqualified*/ true))
16955 PromoteType = QualType();
16956 }
16957 }
16958 if (TInfo->getType()->isSpecificBuiltinType(BuiltinType::Float))
16959 PromoteType = Context.DoubleTy;
16960 if (!PromoteType.isNull())
16961 DiagRuntimeBehavior(TInfo->getTypeLoc().getBeginLoc(), E,
16962 PDiag(diag::warn_second_parameter_to_va_arg_never_compatible)
16963 << TInfo->getType()
16964 << PromoteType
16965 << TInfo->getTypeLoc().getSourceRange());
16966 }
16967
16968 QualType T = TInfo->getType().getNonLValueExprType(Context);
16969 return new (Context) VAArgExpr(BuiltinLoc, E, TInfo, RPLoc, T, IsMS);
16970}
16971
16972ExprResult Sema::ActOnGNUNullExpr(SourceLocation TokenLoc) {
16973 // The type of __null will be int or long, depending on the size of
16974 // pointers on the target.
16975 QualType Ty;
16976 unsigned pw = Context.getTargetInfo().getPointerWidth(LangAS::Default);
16977 if (pw == Context.getTargetInfo().getIntWidth())
16978 Ty = Context.IntTy;
16979 else if (pw == Context.getTargetInfo().getLongWidth())
16980 Ty = Context.LongTy;
16981 else if (pw == Context.getTargetInfo().getLongLongWidth())
16982 Ty = Context.LongLongTy;
16983 else {
16984 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", 16984)
;
16985 }
16986
16987 return new (Context) GNUNullExpr(Ty, TokenLoc);
16988}
16989
16990static CXXRecordDecl *LookupStdSourceLocationImpl(Sema &S, SourceLocation Loc) {
16991 CXXRecordDecl *ImplDecl = nullptr;
16992
16993 // Fetch the std::source_location::__impl decl.
16994 if (NamespaceDecl *Std = S.getStdNamespace()) {
16995 LookupResult ResultSL(S, &S.PP.getIdentifierTable().get("source_location"),
16996 Loc, Sema::LookupOrdinaryName);
16997 if (S.LookupQualifiedName(ResultSL, Std)) {
16998 if (auto *SLDecl = ResultSL.getAsSingle<RecordDecl>()) {
16999 LookupResult ResultImpl(S, &S.PP.getIdentifierTable().get("__impl"),
17000 Loc, Sema::LookupOrdinaryName);
17001 if ((SLDecl->isCompleteDefinition() || SLDecl->isBeingDefined()) &&
17002 S.LookupQualifiedName(ResultImpl, SLDecl)) {
17003 ImplDecl = ResultImpl.getAsSingle<CXXRecordDecl>();
17004 }
17005 }
17006 }
17007 }
17008
17009 if (!ImplDecl || !ImplDecl->isCompleteDefinition()) {
17010 S.Diag(Loc, diag::err_std_source_location_impl_not_found);
17011 return nullptr;
17012 }
17013
17014 // Verify that __impl is a trivial struct type, with no base classes, and with
17015 // only the four expected fields.
17016 if (ImplDecl->isUnion() || !ImplDecl->isStandardLayout() ||
17017 ImplDecl->getNumBases() != 0) {
17018 S.Diag(Loc, diag::err_std_source_location_impl_malformed);
17019 return nullptr;
17020 }
17021
17022 unsigned Count = 0;
17023 for (FieldDecl *F : ImplDecl->fields()) {
17024 StringRef Name = F->getName();
17025
17026 if (Name == "_M_file_name") {
17027 if (F->getType() !=
17028 S.Context.getPointerType(S.Context.CharTy.withConst()))
17029 break;
17030 Count++;
17031 } else if (Name == "_M_function_name") {
17032 if (F->getType() !=
17033 S.Context.getPointerType(S.Context.CharTy.withConst()))
17034 break;
17035 Count++;
17036 } else if (Name == "_M_line") {
17037 if (!F->getType()->isIntegerType())
17038 break;
17039 Count++;
17040 } else if (Name == "_M_column") {
17041 if (!F->getType()->isIntegerType())
17042 break;
17043 Count++;
17044 } else {
17045 Count = 100; // invalid
17046 break;
17047 }
17048 }
17049 if (Count != 4) {
17050 S.Diag(Loc, diag::err_std_source_location_impl_malformed);
17051 return nullptr;
17052 }
17053
17054 return ImplDecl;
17055}
17056
17057ExprResult Sema::ActOnSourceLocExpr(SourceLocExpr::IdentKind Kind,
17058 SourceLocation BuiltinLoc,
17059 SourceLocation RPLoc) {
17060 QualType ResultTy;
17061 switch (Kind) {
17062 case SourceLocExpr::File:
17063 case SourceLocExpr::FileName:
17064 case SourceLocExpr::Function: {
17065 QualType ArrTy = Context.getStringLiteralArrayType(Context.CharTy, 0);
17066 ResultTy =
17067 Context.getPointerType(ArrTy->getAsArrayTypeUnsafe()->getElementType());
17068 break;
17069 }
17070 case SourceLocExpr::Line:
17071 case SourceLocExpr::Column:
17072 ResultTy = Context.UnsignedIntTy;
17073 break;
17074 case SourceLocExpr::SourceLocStruct:
17075 if (!StdSourceLocationImplDecl) {
17076 StdSourceLocationImplDecl =
17077 LookupStdSourceLocationImpl(*this, BuiltinLoc);
17078 if (!StdSourceLocationImplDecl)
17079 return ExprError();
17080 }
17081 ResultTy = Context.getPointerType(
17082 Context.getRecordType(StdSourceLocationImplDecl).withConst());
17083 break;
17084 }
17085
17086 return BuildSourceLocExpr(Kind, ResultTy, BuiltinLoc, RPLoc, CurContext);
17087}
17088
17089ExprResult Sema::BuildSourceLocExpr(SourceLocExpr::IdentKind Kind,
17090 QualType ResultTy,
17091 SourceLocation BuiltinLoc,
17092 SourceLocation RPLoc,
17093 DeclContext *ParentContext) {
17094 return new (Context)
17095 SourceLocExpr(Context, Kind, ResultTy, BuiltinLoc, RPLoc, ParentContext);
17096}
17097
17098bool Sema::CheckConversionToObjCLiteral(QualType DstType, Expr *&Exp,
17099 bool Diagnose) {
17100 if (!getLangOpts().ObjC)
17101 return false;
17102
17103 const ObjCObjectPointerType *PT = DstType->getAs<ObjCObjectPointerType>();
17104 if (!PT)
17105 return false;
17106 const ObjCInterfaceDecl *ID = PT->getInterfaceDecl();
17107
17108 // Ignore any parens, implicit casts (should only be
17109 // array-to-pointer decays), and not-so-opaque values. The last is
17110 // important for making this trigger for property assignments.
17111 Expr *SrcExpr = Exp->IgnoreParenImpCasts();
17112 if (OpaqueValueExpr *OV = dyn_cast<OpaqueValueExpr>(SrcExpr))
17113 if (OV->getSourceExpr())
17114 SrcExpr = OV->getSourceExpr()->IgnoreParenImpCasts();
17115
17116 if (auto *SL = dyn_cast<StringLiteral>(SrcExpr)) {
17117 if (!PT->isObjCIdType() &&
17118 !(ID && ID->getIdentifier()->isStr("NSString")))
17119 return false;
17120 if (!SL->isOrdinary())
17121 return false;
17122
17123 if (Diagnose) {
17124 Diag(SL->getBeginLoc(), diag::err_missing_atsign_prefix)
17125 << /*string*/0 << FixItHint::CreateInsertion(SL->getBeginLoc(), "@");
17126 Exp = BuildObjCStringLiteral(SL->getBeginLoc(), SL).get();
17127 }
17128 return true;
17129 }
17130
17131 if ((isa<IntegerLiteral>(SrcExpr) || isa<CharacterLiteral>(SrcExpr) ||
17132 isa<FloatingLiteral>(SrcExpr) || isa<ObjCBoolLiteralExpr>(SrcExpr) ||
17133 isa<CXXBoolLiteralExpr>(SrcExpr)) &&
17134 !SrcExpr->isNullPointerConstant(
17135 getASTContext(), Expr::NPC_NeverValueDependent)) {
17136 if (!ID || !ID->getIdentifier()->isStr("NSNumber"))
17137 return false;
17138 if (Diagnose) {
17139 Diag(SrcExpr->getBeginLoc(), diag::err_missing_atsign_prefix)
17140 << /*number*/1
17141 << FixItHint::CreateInsertion(SrcExpr->getBeginLoc(), "@");
17142 Expr *NumLit =
17143 BuildObjCNumericLiteral(SrcExpr->getBeginLoc(), SrcExpr).get();
17144 if (NumLit)
17145 Exp = NumLit;
17146 }
17147 return true;
17148 }
17149
17150 return false;
17151}
17152
17153static bool maybeDiagnoseAssignmentToFunction(Sema &S, QualType DstType,
17154 const Expr *SrcExpr) {
17155 if (!DstType->isFunctionPointerType() ||
17156 !SrcExpr->getType()->isFunctionType())
17157 return false;
17158
17159 auto *DRE = dyn_cast<DeclRefExpr>(SrcExpr->IgnoreParenImpCasts());
17160 if (!DRE)
17161 return false;
17162
17163 auto *FD = dyn_cast<FunctionDecl>(DRE->getDecl());
17164 if (!FD)
17165 return false;
17166
17167 return !S.checkAddressOfFunctionIsAvailable(FD,
17168 /*Complain=*/true,
17169 SrcExpr->getBeginLoc());
17170}
17171
17172bool Sema::DiagnoseAssignmentResult(AssignConvertType ConvTy,
17173 SourceLocation Loc,
17174 QualType DstType, QualType SrcType,
17175 Expr *SrcExpr, AssignmentAction Action,
17176 bool *Complained) {
17177 if (Complained)
17178 *Complained = false;
17179
17180 // Decode the result (notice that AST's are still created for extensions).
17181 bool CheckInferredResultType = false;
17182 bool isInvalid = false;
17183 unsigned DiagKind = 0;
17184 ConversionFixItGenerator ConvHints;
17185 bool MayHaveConvFixit = false;
17186 bool MayHaveFunctionDiff = false;
17187 const ObjCInterfaceDecl *IFace = nullptr;
17188 const ObjCProtocolDecl *PDecl = nullptr;
17189
17190 switch (ConvTy) {
17191 case Compatible:
17192 DiagnoseAssignmentEnum(DstType, SrcType, SrcExpr);
17193 return false;
17194
17195 case PointerToInt:
17196 if (getLangOpts().CPlusPlus) {
17197 DiagKind = diag::err_typecheck_convert_pointer_int;
17198 isInvalid = true;
17199 } else {
17200 DiagKind = diag::ext_typecheck_convert_pointer_int;
17201 }
17202 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
17203 MayHaveConvFixit = true;
17204 break;
17205 case IntToPointer:
17206 if (getLangOpts().CPlusPlus) {
17207 DiagKind = diag::err_typecheck_convert_int_pointer;
17208 isInvalid = true;
17209 } else {
17210 DiagKind = diag::ext_typecheck_convert_int_pointer;
17211 }
17212 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
17213 MayHaveConvFixit = true;
17214 break;
17215 case IncompatibleFunctionPointerStrict:
17216 DiagKind =
17217 diag::warn_typecheck_convert_incompatible_function_pointer_strict;
17218 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
17219 MayHaveConvFixit = true;
17220 break;
17221 case IncompatibleFunctionPointer:
17222 if (getLangOpts().CPlusPlus) {
17223 DiagKind = diag::err_typecheck_convert_incompatible_function_pointer;
17224 isInvalid = true;
17225 } else {
17226 DiagKind = diag::ext_typecheck_convert_incompatible_function_pointer;
17227 }
17228 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
17229 MayHaveConvFixit = true;
17230 break;
17231 case IncompatiblePointer:
17232 if (Action == AA_Passing_CFAudited) {
17233 DiagKind = diag::err_arc_typecheck_convert_incompatible_pointer;
17234 } else if (getLangOpts().CPlusPlus) {
17235 DiagKind = diag::err_typecheck_convert_incompatible_pointer;
17236 isInvalid = true;
17237 } else {
17238 DiagKind = diag::ext_typecheck_convert_incompatible_pointer;
17239 }
17240 CheckInferredResultType = DstType->isObjCObjectPointerType() &&
17241 SrcType->isObjCObjectPointerType();
17242 if (!CheckInferredResultType) {
17243 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
17244 } else if (CheckInferredResultType) {
17245 SrcType = SrcType.getUnqualifiedType();
17246 DstType = DstType.getUnqualifiedType();
17247 }
17248 MayHaveConvFixit = true;
17249 break;
17250 case IncompatiblePointerSign:
17251 if (getLangOpts().CPlusPlus) {
17252 DiagKind = diag::err_typecheck_convert_incompatible_pointer_sign;
17253 isInvalid = true;
17254 } else {
17255 DiagKind = diag::ext_typecheck_convert_incompatible_pointer_sign;
17256 }
17257 break;
17258 case FunctionVoidPointer:
17259 if (getLangOpts().CPlusPlus) {
17260 DiagKind = diag::err_typecheck_convert_pointer_void_func;
17261 isInvalid = true;
17262 } else {
17263 DiagKind = diag::ext_typecheck_convert_pointer_void_func;
17264 }
17265 break;
17266 case IncompatiblePointerDiscardsQualifiers: {
17267 // Perform array-to-pointer decay if necessary.
17268 if (SrcType->isArrayType()) SrcType = Context.getArrayDecayedType(SrcType);
17269
17270 isInvalid = true;
17271
17272 Qualifiers lhq = SrcType->getPointeeType().getQualifiers();
17273 Qualifiers rhq = DstType->getPointeeType().getQualifiers();
17274 if (lhq.getAddressSpace() != rhq.getAddressSpace()) {
17275 DiagKind = diag::err_typecheck_incompatible_address_space;
17276 break;
17277
17278 } else if (lhq.getObjCLifetime() != rhq.getObjCLifetime()) {
17279 DiagKind = diag::err_typecheck_incompatible_ownership;
17280 break;
17281 }
17282
17283 llvm_unreachable("unknown error case for discarding qualifiers!")::llvm::llvm_unreachable_internal("unknown error case for discarding qualifiers!"
, "clang/lib/Sema/SemaExpr.cpp", 17283)
;
17284 // fallthrough
17285 }
17286 case CompatiblePointerDiscardsQualifiers:
17287 // If the qualifiers lost were because we were applying the
17288 // (deprecated) C++ conversion from a string literal to a char*
17289 // (or wchar_t*), then there was no error (C++ 4.2p2). FIXME:
17290 // Ideally, this check would be performed in
17291 // checkPointerTypesForAssignment. However, that would require a
17292 // bit of refactoring (so that the second argument is an
17293 // expression, rather than a type), which should be done as part
17294 // of a larger effort to fix checkPointerTypesForAssignment for
17295 // C++ semantics.
17296 if (getLangOpts().CPlusPlus &&
17297 IsStringLiteralToNonConstPointerConversion(SrcExpr, DstType))
17298 return false;
17299 if (getLangOpts().CPlusPlus) {
17300 DiagKind = diag::err_typecheck_convert_discards_qualifiers;
17301 isInvalid = true;
17302 } else {
17303 DiagKind = diag::ext_typecheck_convert_discards_qualifiers;
17304 }
17305
17306 break;
17307 case IncompatibleNestedPointerQualifiers:
17308 if (getLangOpts().CPlusPlus) {
17309 isInvalid = true;
17310 DiagKind = diag::err_nested_pointer_qualifier_mismatch;
17311 } else {
17312 DiagKind = diag::ext_nested_pointer_qualifier_mismatch;
17313 }
17314 break;
17315 case IncompatibleNestedPointerAddressSpaceMismatch:
17316 DiagKind = diag::err_typecheck_incompatible_nested_address_space;
17317 isInvalid = true;
17318 break;
17319 case IntToBlockPointer:
17320 DiagKind = diag::err_int_to_block_pointer;
17321 isInvalid = true;
17322 break;
17323 case IncompatibleBlockPointer:
17324 DiagKind = diag::err_typecheck_convert_incompatible_block_pointer;
17325 isInvalid = true;
17326 break;
17327 case IncompatibleObjCQualifiedId: {
17328 if (SrcType->isObjCQualifiedIdType()) {
17329 const ObjCObjectPointerType *srcOPT =
17330 SrcType->castAs<ObjCObjectPointerType>();
17331 for (auto *srcProto : srcOPT->quals()) {
17332 PDecl = srcProto;
17333 break;
17334 }
17335 if (const ObjCInterfaceType *IFaceT =
17336 DstType->castAs<ObjCObjectPointerType>()->getInterfaceType())
17337 IFace = IFaceT->getDecl();
17338 }
17339 else if (DstType->isObjCQualifiedIdType()) {
17340 const ObjCObjectPointerType *dstOPT =
17341 DstType->castAs<ObjCObjectPointerType>();
17342 for (auto *dstProto : dstOPT->quals()) {
17343 PDecl = dstProto;
17344 break;
17345 }
17346 if (const ObjCInterfaceType *IFaceT =
17347 SrcType->castAs<ObjCObjectPointerType>()->getInterfaceType())
17348 IFace = IFaceT->getDecl();
17349 }
17350 if (getLangOpts().CPlusPlus) {
17351 DiagKind = diag::err_incompatible_qualified_id;
17352 isInvalid = true;
17353 } else {
17354 DiagKind = diag::warn_incompatible_qualified_id;
17355 }
17356 break;
17357 }
17358 case IncompatibleVectors:
17359 if (getLangOpts().CPlusPlus) {
17360 DiagKind = diag::err_incompatible_vectors;
17361 isInvalid = true;
17362 } else {
17363 DiagKind = diag::warn_incompatible_vectors;
17364 }
17365 break;
17366 case IncompatibleObjCWeakRef:
17367 DiagKind = diag::err_arc_weak_unavailable_assign;
17368 isInvalid = true;
17369 break;
17370 case Incompatible:
17371 if (maybeDiagnoseAssignmentToFunction(*this, DstType, SrcExpr)) {
17372 if (Complained)
17373 *Complained = true;
17374 return true;
17375 }
17376
17377 DiagKind = diag::err_typecheck_convert_incompatible;
17378 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
17379 MayHaveConvFixit = true;
17380 isInvalid = true;
17381 MayHaveFunctionDiff = true;
17382 break;
17383 }
17384
17385 QualType FirstType, SecondType;
17386 switch (Action) {
17387 case AA_Assigning:
17388 case AA_Initializing:
17389 // The destination type comes first.
17390 FirstType = DstType;
17391 SecondType = SrcType;
17392 break;
17393
17394 case AA_Returning:
17395 case AA_Passing:
17396 case AA_Passing_CFAudited:
17397 case AA_Converting:
17398 case AA_Sending:
17399 case AA_Casting:
17400 // The source type comes first.
17401 FirstType = SrcType;
17402 SecondType = DstType;
17403 break;
17404 }
17405
17406 PartialDiagnostic FDiag = PDiag(DiagKind);
17407 AssignmentAction ActionForDiag = Action;
17408 if (Action == AA_Passing_CFAudited)
17409 ActionForDiag = AA_Passing;
17410
17411 FDiag << FirstType << SecondType << ActionForDiag
17412 << SrcExpr->getSourceRange();
17413
17414 if (DiagKind == diag::ext_typecheck_convert_incompatible_pointer_sign ||
17415 DiagKind == diag::err_typecheck_convert_incompatible_pointer_sign) {
17416 auto isPlainChar = [](const clang::Type *Type) {
17417 return Type->isSpecificBuiltinType(BuiltinType::Char_S) ||
17418 Type->isSpecificBuiltinType(BuiltinType::Char_U);
17419 };
17420 FDiag << (isPlainChar(FirstType->getPointeeOrArrayElementType()) ||
17421 isPlainChar(SecondType->getPointeeOrArrayElementType()));
17422 }
17423
17424 // If we can fix the conversion, suggest the FixIts.
17425 if (!ConvHints.isNull()) {
17426 for (FixItHint &H : ConvHints.Hints)
17427 FDiag << H;
17428 }
17429
17430 if (MayHaveConvFixit) { FDiag << (unsigned) (ConvHints.Kind); }
17431
17432 if (MayHaveFunctionDiff)
17433 HandleFunctionTypeMismatch(FDiag, SecondType, FirstType);
17434
17435 Diag(Loc, FDiag);
17436 if ((DiagKind == diag::warn_incompatible_qualified_id ||
17437 DiagKind == diag::err_incompatible_qualified_id) &&
17438 PDecl && IFace && !IFace->hasDefinition())
17439 Diag(IFace->getLocation(), diag::note_incomplete_class_and_qualified_id)
17440 << IFace << PDecl;
17441
17442 if (SecondType == Context.OverloadTy)
17443 NoteAllOverloadCandidates(OverloadExpr::find(SrcExpr).Expression,
17444 FirstType, /*TakingAddress=*/true);
17445
17446 if (CheckInferredResultType)
17447 EmitRelatedResultTypeNote(SrcExpr);
17448
17449 if (Action == AA_Returning && ConvTy == IncompatiblePointer)
17450 EmitRelatedResultTypeNoteForReturn(DstType);
17451
17452 if (Complained)
17453 *Complained = true;
17454 return isInvalid;
17455}
17456
17457ExprResult Sema::VerifyIntegerConstantExpression(Expr *E,
17458 llvm::APSInt *Result,
17459 AllowFoldKind CanFold) {
17460 class SimpleICEDiagnoser : public VerifyICEDiagnoser {
17461 public:
17462 SemaDiagnosticBuilder diagnoseNotICEType(Sema &S, SourceLocation Loc,
17463 QualType T) override {
17464 return S.Diag(Loc, diag::err_ice_not_integral)
17465 << T << S.LangOpts.CPlusPlus;
17466 }
17467 SemaDiagnosticBuilder diagnoseNotICE(Sema &S, SourceLocation Loc) override {
17468 return S.Diag(Loc, diag::err_expr_not_ice) << S.LangOpts.CPlusPlus;
17469 }
17470 } Diagnoser;
17471
17472 return VerifyIntegerConstantExpression(E, Result, Diagnoser, CanFold);
17473}
17474
17475ExprResult Sema::VerifyIntegerConstantExpression(Expr *E,
17476 llvm::APSInt *Result,
17477 unsigned DiagID,
17478 AllowFoldKind CanFold) {
17479 class IDDiagnoser : public VerifyICEDiagnoser {
17480 unsigned DiagID;
17481
17482 public:
17483 IDDiagnoser(unsigned DiagID)
17484 : VerifyICEDiagnoser(DiagID == 0), DiagID(DiagID) { }
17485
17486 SemaDiagnosticBuilder diagnoseNotICE(Sema &S, SourceLocation Loc) override {
17487 return S.Diag(Loc, DiagID);
17488 }
17489 } Diagnoser(DiagID);
17490
17491 return VerifyIntegerConstantExpression(E, Result, Diagnoser, CanFold);
17492}
17493
17494Sema::SemaDiagnosticBuilder
17495Sema::VerifyICEDiagnoser::diagnoseNotICEType(Sema &S, SourceLocation Loc,
17496 QualType T) {
17497 return diagnoseNotICE(S, Loc);
17498}
17499
17500Sema::SemaDiagnosticBuilder
17501Sema::VerifyICEDiagnoser::diagnoseFold(Sema &S, SourceLocation Loc) {
17502 return S.Diag(Loc, diag::ext_expr_not_ice) << S.LangOpts.CPlusPlus;
17503}
17504
17505ExprResult
17506Sema::VerifyIntegerConstantExpression(Expr *E, llvm::APSInt *Result,
17507 VerifyICEDiagnoser &Diagnoser,
17508 AllowFoldKind CanFold) {
17509 SourceLocation DiagLoc = E->getBeginLoc();
17510
17511 if (getLangOpts().CPlusPlus11) {
17512 // C++11 [expr.const]p5:
17513 // If an expression of literal class type is used in a context where an
17514 // integral constant expression is required, then that class type shall
17515 // have a single non-explicit conversion function to an integral or
17516 // unscoped enumeration type
17517 ExprResult Converted;
17518 class CXX11ConvertDiagnoser : public ICEConvertDiagnoser {
17519 VerifyICEDiagnoser &BaseDiagnoser;
17520 public:
17521 CXX11ConvertDiagnoser(VerifyICEDiagnoser &BaseDiagnoser)
17522 : ICEConvertDiagnoser(/*AllowScopedEnumerations*/ false,
17523 BaseDiagnoser.Suppress, true),
17524 BaseDiagnoser(BaseDiagnoser) {}
17525
17526 SemaDiagnosticBuilder diagnoseNotInt(Sema &S, SourceLocation Loc,
17527 QualType T) override {
17528 return BaseDiagnoser.diagnoseNotICEType(S, Loc, T);
17529 }
17530
17531 SemaDiagnosticBuilder diagnoseIncomplete(
17532 Sema &S, SourceLocation Loc, QualType T) override {
17533 return S.Diag(Loc, diag::err_ice_incomplete_type) << T;
17534 }
17535
17536 SemaDiagnosticBuilder diagnoseExplicitConv(
17537 Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) override {
17538 return S.Diag(Loc, diag::err_ice_explicit_conversion) << T << ConvTy;
17539 }
17540
17541 SemaDiagnosticBuilder noteExplicitConv(
17542 Sema &S, CXXConversionDecl *Conv, QualType ConvTy) override {
17543 return S.Diag(Conv->getLocation(), diag::note_ice_conversion_here)
17544 << ConvTy->isEnumeralType() << ConvTy;
17545 }
17546
17547 SemaDiagnosticBuilder diagnoseAmbiguous(
17548 Sema &S, SourceLocation Loc, QualType T) override {
17549 return S.Diag(Loc, diag::err_ice_ambiguous_conversion) << T;
17550 }
17551
17552 SemaDiagnosticBuilder noteAmbiguous(
17553 Sema &S, CXXConversionDecl *Conv, QualType ConvTy) override {
17554 return S.Diag(Conv->getLocation(), diag::note_ice_conversion_here)
17555 << ConvTy->isEnumeralType() << ConvTy;
17556 }
17557
17558 SemaDiagnosticBuilder diagnoseConversion(
17559 Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) override {
17560 llvm_unreachable("conversion functions are permitted")::llvm::llvm_unreachable_internal("conversion functions are permitted"
, "clang/lib/Sema/SemaExpr.cpp", 17560)
;
17561 }
17562 } ConvertDiagnoser(Diagnoser);
17563
17564 Converted = PerformContextualImplicitConversion(DiagLoc, E,
17565 ConvertDiagnoser);
17566 if (Converted.isInvalid())
17567 return Converted;
17568 E = Converted.get();
17569 if (!E->getType()->isIntegralOrUnscopedEnumerationType())
17570 return ExprError();
17571 } else if (!E->getType()->isIntegralOrUnscopedEnumerationType()) {
17572 // An ICE must be of integral or unscoped enumeration type.
17573 if (!Diagnoser.Suppress)
17574 Diagnoser.diagnoseNotICEType(*this, DiagLoc, E->getType())
17575 << E->getSourceRange();
17576 return ExprError();
17577 }
17578
17579 ExprResult RValueExpr = DefaultLvalueConversion(E);
17580 if (RValueExpr.isInvalid())
17581 return ExprError();
17582
17583 E = RValueExpr.get();
17584
17585 // Circumvent ICE checking in C++11 to avoid evaluating the expression twice
17586 // in the non-ICE case.
17587 if (!getLangOpts().CPlusPlus11 && E->isIntegerConstantExpr(Context)) {
17588 if (Result)
17589 *Result = E->EvaluateKnownConstIntCheckOverflow(Context);
17590 if (!isa<ConstantExpr>(E))
17591 E = Result ? ConstantExpr::Create(Context, E, APValue(*Result))
17592 : ConstantExpr::Create(Context, E);
17593 return E;
17594 }
17595
17596 Expr::EvalResult EvalResult;
17597 SmallVector<PartialDiagnosticAt, 8> Notes;
17598 EvalResult.Diag = &Notes;
17599
17600 // Try to evaluate the expression, and produce diagnostics explaining why it's
17601 // not a constant expression as a side-effect.
17602 bool Folded =
17603 E->EvaluateAsRValue(EvalResult, Context, /*isConstantContext*/ true) &&
17604 EvalResult.Val.isInt() && !EvalResult.HasSideEffects;
17605
17606 if (!isa<ConstantExpr>(E))
17607 E = ConstantExpr::Create(Context, E, EvalResult.Val);
17608
17609 // In C++11, we can rely on diagnostics being produced for any expression
17610 // which is not a constant expression. If no diagnostics were produced, then
17611 // this is a constant expression.
17612 if (Folded && getLangOpts().CPlusPlus11 && Notes.empty()) {
17613 if (Result)
17614 *Result = EvalResult.Val.getInt();
17615 return E;
17616 }
17617
17618 // If our only note is the usual "invalid subexpression" note, just point
17619 // the caret at its location rather than producing an essentially
17620 // redundant note.
17621 if (Notes.size() == 1 && Notes[0].second.getDiagID() ==
17622 diag::note_invalid_subexpr_in_const_expr) {
17623 DiagLoc = Notes[0].first;
17624 Notes.clear();
17625 }
17626
17627 if (!Folded || !CanFold) {
17628 if (!Diagnoser.Suppress) {
17629 Diagnoser.diagnoseNotICE(*this, DiagLoc) << E->getSourceRange();
17630 for (const PartialDiagnosticAt &Note : Notes)
17631 Diag(Note.first, Note.second);
17632 }
17633
17634 return ExprError();
17635 }
17636
17637 Diagnoser.diagnoseFold(*this, DiagLoc) << E->getSourceRange();
17638 for (const PartialDiagnosticAt &Note : Notes)
17639 Diag(Note.first, Note.second);
17640
17641 if (Result)
17642 *Result = EvalResult.Val.getInt();
17643 return E;
17644}
17645
17646namespace {
17647 // Handle the case where we conclude a expression which we speculatively
17648 // considered to be unevaluated is actually evaluated.
17649 class TransformToPE : public TreeTransform<TransformToPE> {
17650 typedef TreeTransform<TransformToPE> BaseTransform;
17651
17652 public:
17653 TransformToPE(Sema &SemaRef) : BaseTransform(SemaRef) { }
17654
17655 // Make sure we redo semantic analysis
17656 bool AlwaysRebuild() { return true; }
17657 bool ReplacingOriginal() { return true; }
17658
17659 // We need to special-case DeclRefExprs referring to FieldDecls which
17660 // are not part of a member pointer formation; normal TreeTransforming
17661 // doesn't catch this case because of the way we represent them in the AST.
17662 // FIXME: This is a bit ugly; is it really the best way to handle this
17663 // case?
17664 //
17665 // Error on DeclRefExprs referring to FieldDecls.
17666 ExprResult TransformDeclRefExpr(DeclRefExpr *E) {
17667 if (isa<FieldDecl>(E->getDecl()) &&
17668 !SemaRef.isUnevaluatedContext())
17669 return SemaRef.Diag(E->getLocation(),
17670 diag::err_invalid_non_static_member_use)
17671 << E->getDecl() << E->getSourceRange();
17672
17673 return BaseTransform::TransformDeclRefExpr(E);
17674 }
17675
17676 // Exception: filter out member pointer formation
17677 ExprResult TransformUnaryOperator(UnaryOperator *E) {
17678 if (E->getOpcode() == UO_AddrOf && E->getType()->isMemberPointerType())
17679 return E;
17680
17681 return BaseTransform::TransformUnaryOperator(E);
17682 }
17683
17684 // The body of a lambda-expression is in a separate expression evaluation
17685 // context so never needs to be transformed.
17686 // FIXME: Ideally we wouldn't transform the closure type either, and would
17687 // just recreate the capture expressions and lambda expression.
17688 StmtResult TransformLambdaBody(LambdaExpr *E, Stmt *Body) {
17689 return SkipLambdaBody(E, Body);
17690 }
17691 };
17692}
17693
17694ExprResult Sema::TransformToPotentiallyEvaluated(Expr *E) {
17695 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", 17696, __extension__ __PRETTY_FUNCTION__
))
17696 "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", 17696, __extension__ __PRETTY_FUNCTION__
))
;
17697 ExprEvalContexts.back().Context =
17698 ExprEvalContexts[ExprEvalContexts.size()-2].Context;
17699 if (isUnevaluatedContext())
17700 return E;
17701 return TransformToPE(*this).TransformExpr(E);
17702}
17703
17704TypeSourceInfo *Sema::TransformToPotentiallyEvaluated(TypeSourceInfo *TInfo) {
17705 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", 17706, __extension__ __PRETTY_FUNCTION__
))
17706 "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", 17706, __extension__ __PRETTY_FUNCTION__
))
;
17707 ExprEvalContexts.back().Context =
17708 ExprEvalContexts[ExprEvalContexts.size() - 2].Context;
17709 if (isUnevaluatedContext())
17710 return TInfo;
17711 return TransformToPE(*this).TransformType(TInfo);
17712}
17713
17714void
17715Sema::PushExpressionEvaluationContext(
17716 ExpressionEvaluationContext NewContext, Decl *LambdaContextDecl,
17717 ExpressionEvaluationContextRecord::ExpressionKind ExprContext) {
17718 ExprEvalContexts.emplace_back(NewContext, ExprCleanupObjects.size(), Cleanup,
17719 LambdaContextDecl, ExprContext);
17720
17721 // Discarded statements and immediate contexts nested in other
17722 // discarded statements or immediate context are themselves
17723 // a discarded statement or an immediate context, respectively.
17724 ExprEvalContexts.back().InDiscardedStatement =
17725 ExprEvalContexts[ExprEvalContexts.size() - 2]
17726 .isDiscardedStatementContext();
17727 ExprEvalContexts.back().InImmediateFunctionContext =
17728 ExprEvalContexts[ExprEvalContexts.size() - 2]
17729 .isImmediateFunctionContext();
17730
17731 Cleanup.reset();
17732 if (!MaybeODRUseExprs.empty())
17733 std::swap(MaybeODRUseExprs, ExprEvalContexts.back().SavedMaybeODRUseExprs);
17734}
17735
17736void
17737Sema::PushExpressionEvaluationContext(
17738 ExpressionEvaluationContext NewContext, ReuseLambdaContextDecl_t,
17739 ExpressionEvaluationContextRecord::ExpressionKind ExprContext) {
17740 Decl *ClosureContextDecl = ExprEvalContexts.back().ManglingContextDecl;
17741 PushExpressionEvaluationContext(NewContext, ClosureContextDecl, ExprContext);
17742}
17743
17744namespace {
17745
17746const DeclRefExpr *CheckPossibleDeref(Sema &S, const Expr *PossibleDeref) {
17747 PossibleDeref = PossibleDeref->IgnoreParenImpCasts();
17748 if (const auto *E = dyn_cast<UnaryOperator>(PossibleDeref)) {
17749 if (E->getOpcode() == UO_Deref)
17750 return CheckPossibleDeref(S, E->getSubExpr());
17751 } else if (const auto *E = dyn_cast<ArraySubscriptExpr>(PossibleDeref)) {
17752 return CheckPossibleDeref(S, E->getBase());
17753 } else if (const auto *E = dyn_cast<MemberExpr>(PossibleDeref)) {
17754 return CheckPossibleDeref(S, E->getBase());
17755 } else if (const auto E = dyn_cast<DeclRefExpr>(PossibleDeref)) {
17756 QualType Inner;
17757 QualType Ty = E->getType();
17758 if (const auto *Ptr = Ty->getAs<PointerType>())
17759 Inner = Ptr->getPointeeType();
17760 else if (const auto *Arr = S.Context.getAsArrayType(Ty))
17761 Inner = Arr->getElementType();
17762 else
17763 return nullptr;
17764
17765 if (Inner->hasAttr(attr::NoDeref))
17766 return E;
17767 }
17768 return nullptr;
17769}
17770
17771} // namespace
17772
17773void Sema::WarnOnPendingNoDerefs(ExpressionEvaluationContextRecord &Rec) {
17774 for (const Expr *E : Rec.PossibleDerefs) {
17775 const DeclRefExpr *DeclRef = CheckPossibleDeref(*this, E);
17776 if (DeclRef) {
17777 const ValueDecl *Decl = DeclRef->getDecl();
17778 Diag(E->getExprLoc(), diag::warn_dereference_of_noderef_type)
17779 << Decl->getName() << E->getSourceRange();
17780 Diag(Decl->getLocation(), diag::note_previous_decl) << Decl->getName();
17781 } else {
17782 Diag(E->getExprLoc(), diag::warn_dereference_of_noderef_type_no_decl)
17783 << E->getSourceRange();
17784 }
17785 }
17786 Rec.PossibleDerefs.clear();
17787}
17788
17789/// Check whether E, which is either a discarded-value expression or an
17790/// unevaluated operand, is a simple-assignment to a volatlie-qualified lvalue,
17791/// and if so, remove it from the list of volatile-qualified assignments that
17792/// we are going to warn are deprecated.
17793void Sema::CheckUnusedVolatileAssignment(Expr *E) {
17794 if (!E->getType().isVolatileQualified() || !getLangOpts().CPlusPlus20)
17795 return;
17796
17797 // Note: ignoring parens here is not justified by the standard rules, but
17798 // ignoring parentheses seems like a more reasonable approach, and this only
17799 // drives a deprecation warning so doesn't affect conformance.
17800 if (auto *BO = dyn_cast<BinaryOperator>(E->IgnoreParenImpCasts())) {
17801 if (BO->getOpcode() == BO_Assign) {
17802 auto &LHSs = ExprEvalContexts.back().VolatileAssignmentLHSs;
17803 llvm::erase_value(LHSs, BO->getLHS());
17804 }
17805 }
17806}
17807
17808ExprResult Sema::CheckForImmediateInvocation(ExprResult E, FunctionDecl *Decl) {
17809 if (isUnevaluatedContext() || !E.isUsable() || !Decl ||
17810 !Decl->isConsteval() || isConstantEvaluated() ||
17811 isCheckingDefaultArgumentOrInitializer() ||
17812 RebuildingImmediateInvocation || isImmediateFunctionContext())
17813 return E;
17814
17815 /// Opportunistically remove the callee from ReferencesToConsteval if we can.
17816 /// It's OK if this fails; we'll also remove this in
17817 /// HandleImmediateInvocations, but catching it here allows us to avoid
17818 /// walking the AST looking for it in simple cases.
17819 if (auto *Call = dyn_cast<CallExpr>(E.get()->IgnoreImplicit()))
17820 if (auto *DeclRef =
17821 dyn_cast<DeclRefExpr>(Call->getCallee()->IgnoreImplicit()))
17822 ExprEvalContexts.back().ReferenceToConsteval.erase(DeclRef);
17823
17824 E = MaybeCreateExprWithCleanups(E);
17825
17826 ConstantExpr *Res = ConstantExpr::Create(
17827 getASTContext(), E.get(),
17828 ConstantExpr::getStorageKind(Decl->getReturnType().getTypePtr(),
17829 getASTContext()),
17830 /*IsImmediateInvocation*/ true);
17831 /// Value-dependent constant expressions should not be immediately
17832 /// evaluated until they are instantiated.
17833 if (!Res->isValueDependent())
17834 ExprEvalContexts.back().ImmediateInvocationCandidates.emplace_back(Res, 0);
17835 return Res;
17836}
17837
17838static void EvaluateAndDiagnoseImmediateInvocation(
17839 Sema &SemaRef, Sema::ImmediateInvocationCandidate Candidate) {
17840 llvm::SmallVector<PartialDiagnosticAt, 8> Notes;
17841 Expr::EvalResult Eval;
17842 Eval.Diag = &Notes;
17843 ConstantExpr *CE = Candidate.getPointer();
17844 bool Result = CE->EvaluateAsConstantExpr(
17845 Eval, SemaRef.getASTContext(), ConstantExprKind::ImmediateInvocation);
17846 if (!Result || !Notes.empty()) {
17847 Expr *InnerExpr = CE->getSubExpr()->IgnoreImplicit();
17848 if (auto *FunctionalCast = dyn_cast<CXXFunctionalCastExpr>(InnerExpr))
17849 InnerExpr = FunctionalCast->getSubExpr();
17850 FunctionDecl *FD = nullptr;
17851 if (auto *Call = dyn_cast<CallExpr>(InnerExpr))
17852 FD = cast<FunctionDecl>(Call->getCalleeDecl());
17853 else if (auto *Call = dyn_cast<CXXConstructExpr>(InnerExpr))
17854 FD = Call->getConstructor();
17855 else
17856 llvm_unreachable("unhandled decl kind")::llvm::llvm_unreachable_internal("unhandled decl kind", "clang/lib/Sema/SemaExpr.cpp"
, 17856)
;
17857 assert(FD && FD->isConsteval())(static_cast <bool> (FD && FD->isConsteval()
) ? void (0) : __assert_fail ("FD && FD->isConsteval()"
, "clang/lib/Sema/SemaExpr.cpp", 17857, __extension__ __PRETTY_FUNCTION__
))
;
17858 SemaRef.Diag(CE->getBeginLoc(), diag::err_invalid_consteval_call) << FD;
17859 if (auto Context =
17860 SemaRef.InnermostDeclarationWithDelayedImmediateInvocations()) {
17861 SemaRef.Diag(Context->Loc, diag::note_invalid_consteval_initializer)
17862 << Context->Decl;
17863 SemaRef.Diag(Context->Decl->getBeginLoc(), diag::note_declared_at);
17864 }
17865 for (auto &Note : Notes)
17866 SemaRef.Diag(Note.first, Note.second);
17867 return;
17868 }
17869 CE->MoveIntoResult(Eval.Val, SemaRef.getASTContext());
17870}
17871
17872static void RemoveNestedImmediateInvocation(
17873 Sema &SemaRef, Sema::ExpressionEvaluationContextRecord &Rec,
17874 SmallVector<Sema::ImmediateInvocationCandidate, 4>::reverse_iterator It) {
17875 struct ComplexRemove : TreeTransform<ComplexRemove> {
17876 using Base = TreeTransform<ComplexRemove>;
17877 llvm::SmallPtrSetImpl<DeclRefExpr *> &DRSet;
17878 SmallVector<Sema::ImmediateInvocationCandidate, 4> &IISet;
17879 SmallVector<Sema::ImmediateInvocationCandidate, 4>::reverse_iterator
17880 CurrentII;
17881 ComplexRemove(Sema &SemaRef, llvm::SmallPtrSetImpl<DeclRefExpr *> &DR,
17882 SmallVector<Sema::ImmediateInvocationCandidate, 4> &II,
17883 SmallVector<Sema::ImmediateInvocationCandidate,
17884 4>::reverse_iterator Current)
17885 : Base(SemaRef), DRSet(DR), IISet(II), CurrentII(Current) {}
17886 void RemoveImmediateInvocation(ConstantExpr* E) {
17887 auto It = std::find_if(CurrentII, IISet.rend(),
17888 [E](Sema::ImmediateInvocationCandidate Elem) {
17889 return Elem.getPointer() == E;
17890 });
17891 assert(It != IISet.rend() &&(static_cast <bool> (It != IISet.rend() && "ConstantExpr marked IsImmediateInvocation should "
"be present") ? void (0) : __assert_fail ("It != IISet.rend() && \"ConstantExpr marked IsImmediateInvocation should \" \"be present\""
, "clang/lib/Sema/SemaExpr.cpp", 17893, __extension__ __PRETTY_FUNCTION__
))
17892 "ConstantExpr marked IsImmediateInvocation should "(static_cast <bool> (It != IISet.rend() && "ConstantExpr marked IsImmediateInvocation should "
"be present") ? void (0) : __assert_fail ("It != IISet.rend() && \"ConstantExpr marked IsImmediateInvocation should \" \"be present\""
, "clang/lib/Sema/SemaExpr.cpp", 17893, __extension__ __PRETTY_FUNCTION__
))
17893 "be present")(static_cast <bool> (It != IISet.rend() && "ConstantExpr marked IsImmediateInvocation should "
"be present") ? void (0) : __assert_fail ("It != IISet.rend() && \"ConstantExpr marked IsImmediateInvocation should \" \"be present\""
, "clang/lib/Sema/SemaExpr.cpp", 17893, __extension__ __PRETTY_FUNCTION__
))
;
17894 It->setInt(1); // Mark as deleted
17895 }
17896 ExprResult TransformConstantExpr(ConstantExpr *E) {
17897 if (!E->isImmediateInvocation())
17898 return Base::TransformConstantExpr(E);
17899 RemoveImmediateInvocation(E);
17900 return Base::TransformExpr(E->getSubExpr());
17901 }
17902 /// Base::TransfromCXXOperatorCallExpr doesn't traverse the callee so
17903 /// we need to remove its DeclRefExpr from the DRSet.
17904 ExprResult TransformCXXOperatorCallExpr(CXXOperatorCallExpr *E) {
17905 DRSet.erase(cast<DeclRefExpr>(E->getCallee()->IgnoreImplicit()));
17906 return Base::TransformCXXOperatorCallExpr(E);
17907 }
17908 /// Base::TransformInitializer skip ConstantExpr so we need to visit them
17909 /// here.
17910 ExprResult TransformInitializer(Expr *Init, bool NotCopyInit) {
17911 if (!Init)
17912 return Init;
17913 /// ConstantExpr are the first layer of implicit node to be removed so if
17914 /// Init isn't a ConstantExpr, no ConstantExpr will be skipped.
17915 if (auto *CE = dyn_cast<ConstantExpr>(Init))
17916 if (CE->isImmediateInvocation())
17917 RemoveImmediateInvocation(CE);
17918 return Base::TransformInitializer(Init, NotCopyInit);
17919 }
17920 ExprResult TransformDeclRefExpr(DeclRefExpr *E) {
17921 DRSet.erase(E);
17922 return E;
17923 }
17924 ExprResult TransformLambdaExpr(LambdaExpr *E) {
17925 // Do not rebuild lambdas to avoid creating a new type.
17926 // Lambdas have already been processed inside their eval context.
17927 return E;
17928 }
17929 bool AlwaysRebuild() { return false; }
17930 bool ReplacingOriginal() { return true; }
17931 bool AllowSkippingCXXConstructExpr() {
17932 bool Res = AllowSkippingFirstCXXConstructExpr;
17933 AllowSkippingFirstCXXConstructExpr = true;
17934 return Res;
17935 }
17936 bool AllowSkippingFirstCXXConstructExpr = true;
17937 } Transformer(SemaRef, Rec.ReferenceToConsteval,
17938 Rec.ImmediateInvocationCandidates, It);
17939
17940 /// CXXConstructExpr with a single argument are getting skipped by
17941 /// TreeTransform in some situtation because they could be implicit. This
17942 /// can only occur for the top-level CXXConstructExpr because it is used
17943 /// nowhere in the expression being transformed therefore will not be rebuilt.
17944 /// Setting AllowSkippingFirstCXXConstructExpr to false will prevent from
17945 /// skipping the first CXXConstructExpr.
17946 if (isa<CXXConstructExpr>(It->getPointer()->IgnoreImplicit()))
17947 Transformer.AllowSkippingFirstCXXConstructExpr = false;
17948
17949 ExprResult Res = Transformer.TransformExpr(It->getPointer()->getSubExpr());
17950 // The result may not be usable in case of previous compilation errors.
17951 // In this case evaluation of the expression may result in crash so just
17952 // don't do anything further with the result.
17953 if (Res.isUsable()) {
17954 Res = SemaRef.MaybeCreateExprWithCleanups(Res);
17955 It->getPointer()->setSubExpr(Res.get());
17956 }
17957}
17958
17959static void
17960HandleImmediateInvocations(Sema &SemaRef,
17961 Sema::ExpressionEvaluationContextRecord &Rec) {
17962 if ((Rec.ImmediateInvocationCandidates.size() == 0 &&
17963 Rec.ReferenceToConsteval.size() == 0) ||
17964 SemaRef.RebuildingImmediateInvocation)
17965 return;
17966
17967 /// When we have more then 1 ImmediateInvocationCandidates we need to check
17968 /// for nested ImmediateInvocationCandidates. when we have only 1 we only
17969 /// need to remove ReferenceToConsteval in the immediate invocation.
17970 if (Rec.ImmediateInvocationCandidates.size() > 1) {
17971
17972 /// Prevent sema calls during the tree transform from adding pointers that
17973 /// are already in the sets.
17974 llvm::SaveAndRestore DisableIITracking(
17975 SemaRef.RebuildingImmediateInvocation, true);
17976
17977 /// Prevent diagnostic during tree transfrom as they are duplicates
17978 Sema::TentativeAnalysisScope DisableDiag(SemaRef);
17979
17980 for (auto It = Rec.ImmediateInvocationCandidates.rbegin();
17981 It != Rec.ImmediateInvocationCandidates.rend(); It++)
17982 if (!It->getInt())
17983 RemoveNestedImmediateInvocation(SemaRef, Rec, It);
17984 } else if (Rec.ImmediateInvocationCandidates.size() == 1 &&
17985 Rec.ReferenceToConsteval.size()) {
17986 struct SimpleRemove : RecursiveASTVisitor<SimpleRemove> {
17987 llvm::SmallPtrSetImpl<DeclRefExpr *> &DRSet;
17988 SimpleRemove(llvm::SmallPtrSetImpl<DeclRefExpr *> &S) : DRSet(S) {}
17989 bool VisitDeclRefExpr(DeclRefExpr *E) {
17990 DRSet.erase(E);
17991 return DRSet.size();
17992 }
17993 } Visitor(Rec.ReferenceToConsteval);
17994 Visitor.TraverseStmt(
17995 Rec.ImmediateInvocationCandidates.front().getPointer()->getSubExpr());
17996 }
17997 for (auto CE : Rec.ImmediateInvocationCandidates)
17998 if (!CE.getInt())
17999 EvaluateAndDiagnoseImmediateInvocation(SemaRef, CE);
18000 for (auto *DR : Rec.ReferenceToConsteval) {
18001 NamedDecl *ND = cast<FunctionDecl>(DR->getDecl());
18002 if (auto *MD = llvm::dyn_cast<CXXMethodDecl>(ND);
18003 MD && (MD->isLambdaStaticInvoker() || isLambdaCallOperator(MD)))
18004 ND = MD->getParent();
18005 SemaRef.Diag(DR->getBeginLoc(), diag::err_invalid_consteval_take_address)
18006 << ND << isa<CXXRecordDecl>(ND);
18007 SemaRef.Diag(ND->getLocation(), diag::note_declared_at);
18008 }
18009}
18010
18011void Sema::PopExpressionEvaluationContext() {
18012 ExpressionEvaluationContextRecord& Rec = ExprEvalContexts.back();
18013 unsigned NumTypos = Rec.NumTypos;
18014
18015 if (!Rec.Lambdas.empty()) {
18016 using ExpressionKind = ExpressionEvaluationContextRecord::ExpressionKind;
18017 if (!getLangOpts().CPlusPlus20 &&
18018 (Rec.ExprContext == ExpressionKind::EK_TemplateArgument ||
18019 Rec.isUnevaluated() ||
18020 (Rec.isConstantEvaluated() && !getLangOpts().CPlusPlus17))) {
18021 unsigned D;
18022 if (Rec.isUnevaluated()) {
18023 // C++11 [expr.prim.lambda]p2:
18024 // A lambda-expression shall not appear in an unevaluated operand
18025 // (Clause 5).
18026 D = diag::err_lambda_unevaluated_operand;
18027 } else if (Rec.isConstantEvaluated() && !getLangOpts().CPlusPlus17) {
18028 // C++1y [expr.const]p2:
18029 // A conditional-expression e is a core constant expression unless the
18030 // evaluation of e, following the rules of the abstract machine, would
18031 // evaluate [...] a lambda-expression.
18032 D = diag::err_lambda_in_constant_expression;
18033 } else if (Rec.ExprContext == ExpressionKind::EK_TemplateArgument) {
18034 // C++17 [expr.prim.lamda]p2:
18035 // A lambda-expression shall not appear [...] in a template-argument.
18036 D = diag::err_lambda_in_invalid_context;
18037 } else
18038 llvm_unreachable("Couldn't infer lambda error message.")::llvm::llvm_unreachable_internal("Couldn't infer lambda error message."
, "clang/lib/Sema/SemaExpr.cpp", 18038)
;
18039
18040 for (const auto *L : Rec.Lambdas)
18041 Diag(L->getBeginLoc(), D);
18042 }
18043 }
18044
18045 WarnOnPendingNoDerefs(Rec);
18046 HandleImmediateInvocations(*this, Rec);
18047
18048 // Warn on any volatile-qualified simple-assignments that are not discarded-
18049 // value expressions nor unevaluated operands (those cases get removed from
18050 // this list by CheckUnusedVolatileAssignment).
18051 for (auto *BO : Rec.VolatileAssignmentLHSs)
18052 Diag(BO->getBeginLoc(), diag::warn_deprecated_simple_assign_volatile)
18053 << BO->getType();
18054
18055 // When are coming out of an unevaluated context, clear out any
18056 // temporaries that we may have created as part of the evaluation of
18057 // the expression in that context: they aren't relevant because they
18058 // will never be constructed.
18059 if (Rec.isUnevaluated() || Rec.isConstantEvaluated()) {
18060 ExprCleanupObjects.erase(ExprCleanupObjects.begin() + Rec.NumCleanupObjects,
18061 ExprCleanupObjects.end());
18062 Cleanup = Rec.ParentCleanup;
18063 CleanupVarDeclMarking();
18064 std::swap(MaybeODRUseExprs, Rec.SavedMaybeODRUseExprs);
18065 // Otherwise, merge the contexts together.
18066 } else {
18067 Cleanup.mergeFrom(Rec.ParentCleanup);
18068 MaybeODRUseExprs.insert(Rec.SavedMaybeODRUseExprs.begin(),
18069 Rec.SavedMaybeODRUseExprs.end());
18070 }
18071
18072 // Pop the current expression evaluation context off the stack.
18073 ExprEvalContexts.pop_back();
18074
18075 // The global expression evaluation context record is never popped.
18076 ExprEvalContexts.back().NumTypos += NumTypos;
18077}
18078
18079void Sema::DiscardCleanupsInEvaluationContext() {
18080 ExprCleanupObjects.erase(
18081 ExprCleanupObjects.begin() + ExprEvalContexts.back().NumCleanupObjects,
18082 ExprCleanupObjects.end());
18083 Cleanup.reset();
18084 MaybeODRUseExprs.clear();
18085}
18086
18087ExprResult Sema::HandleExprEvaluationContextForTypeof(Expr *E) {
18088 ExprResult Result = CheckPlaceholderExpr(E);
18089 if (Result.isInvalid())
18090 return ExprError();
18091 E = Result.get();
18092 if (!E->getType()->isVariablyModifiedType())
18093 return E;
18094 return TransformToPotentiallyEvaluated(E);
18095}
18096
18097/// Are we in a context that is potentially constant evaluated per C++20
18098/// [expr.const]p12?
18099static bool isPotentiallyConstantEvaluatedContext(Sema &SemaRef) {
18100 /// C++2a [expr.const]p12:
18101 // An expression or conversion is potentially constant evaluated if it is
18102 switch (SemaRef.ExprEvalContexts.back().Context) {
18103 case Sema::ExpressionEvaluationContext::ConstantEvaluated:
18104 case Sema::ExpressionEvaluationContext::ImmediateFunctionContext:
18105
18106 // -- a manifestly constant-evaluated expression,
18107 case Sema::ExpressionEvaluationContext::PotentiallyEvaluated:
18108 case Sema::ExpressionEvaluationContext::PotentiallyEvaluatedIfUsed:
18109 case Sema::ExpressionEvaluationContext::DiscardedStatement:
18110 // -- a potentially-evaluated expression,
18111 case Sema::ExpressionEvaluationContext::UnevaluatedList:
18112 // -- an immediate subexpression of a braced-init-list,
18113
18114 // -- [FIXME] an expression of the form & cast-expression that occurs
18115 // within a templated entity
18116 // -- a subexpression of one of the above that is not a subexpression of
18117 // a nested unevaluated operand.
18118 return true;
18119
18120 case Sema::ExpressionEvaluationContext::Unevaluated:
18121 case Sema::ExpressionEvaluationContext::UnevaluatedAbstract:
18122 // Expressions in this context are never evaluated.
18123 return false;
18124 }
18125 llvm_unreachable("Invalid context")::llvm::llvm_unreachable_internal("Invalid context", "clang/lib/Sema/SemaExpr.cpp"
, 18125)
;
18126}
18127
18128/// Return true if this function has a calling convention that requires mangling
18129/// in the size of the parameter pack.
18130static bool funcHasParameterSizeMangling(Sema &S, FunctionDecl *FD) {
18131 // These manglings don't do anything on non-Windows or non-x86 platforms, so
18132 // we don't need parameter type sizes.
18133 const llvm::Triple &TT = S.Context.getTargetInfo().getTriple();
18134 if (!TT.isOSWindows() || !TT.isX86())
18135 return false;
18136
18137 // If this is C++ and this isn't an extern "C" function, parameters do not
18138 // need to be complete. In this case, C++ mangling will apply, which doesn't
18139 // use the size of the parameters.
18140 if (S.getLangOpts().CPlusPlus && !FD->isExternC())
18141 return false;
18142
18143 // Stdcall, fastcall, and vectorcall need this special treatment.
18144 CallingConv CC = FD->getType()->castAs<FunctionType>()->getCallConv();
18145 switch (CC) {
18146 case CC_X86StdCall:
18147 case CC_X86FastCall:
18148 case CC_X86VectorCall:
18149 return true;
18150 default:
18151 break;
18152 }
18153 return false;
18154}
18155
18156/// Require that all of the parameter types of function be complete. Normally,
18157/// parameter types are only required to be complete when a function is called
18158/// or defined, but to mangle functions with certain calling conventions, the
18159/// mangler needs to know the size of the parameter list. In this situation,
18160/// MSVC doesn't emit an error or instantiate templates. Instead, MSVC mangles
18161/// the function as _foo@0, i.e. zero bytes of parameters, which will usually
18162/// result in a linker error. Clang doesn't implement this behavior, and instead
18163/// attempts to error at compile time.
18164static void CheckCompleteParameterTypesForMangler(Sema &S, FunctionDecl *FD,
18165 SourceLocation Loc) {
18166 class ParamIncompleteTypeDiagnoser : public Sema::TypeDiagnoser {
18167 FunctionDecl *FD;
18168 ParmVarDecl *Param;
18169
18170 public:
18171 ParamIncompleteTypeDiagnoser(FunctionDecl *FD, ParmVarDecl *Param)
18172 : FD(FD), Param(Param) {}
18173
18174 void diagnose(Sema &S, SourceLocation Loc, QualType T) override {
18175 CallingConv CC = FD->getType()->castAs<FunctionType>()->getCallConv();
18176 StringRef CCName;
18177 switch (CC) {
18178 case CC_X86StdCall:
18179 CCName = "stdcall";
18180 break;
18181 case CC_X86FastCall:
18182 CCName = "fastcall";
18183 break;
18184 case CC_X86VectorCall:
18185 CCName = "vectorcall";
18186 break;
18187 default:
18188 llvm_unreachable("CC does not need mangling")::llvm::llvm_unreachable_internal("CC does not need mangling"
, "clang/lib/Sema/SemaExpr.cpp", 18188)
;
18189 }
18190
18191 S.Diag(Loc, diag::err_cconv_incomplete_param_type)
18192 << Param->getDeclName() << FD->getDeclName() << CCName;
18193 }
18194 };
18195
18196 for (ParmVarDecl *Param : FD->parameters()) {
18197 ParamIncompleteTypeDiagnoser Diagnoser(FD, Param);
18198 S.RequireCompleteType(Loc, Param->getType(), Diagnoser);
18199 }
18200}
18201
18202namespace {
18203enum class OdrUseContext {
18204 /// Declarations in this context are not odr-used.
18205 None,
18206 /// Declarations in this context are formally odr-used, but this is a
18207 /// dependent context.
18208 Dependent,
18209 /// Declarations in this context are odr-used but not actually used (yet).
18210 FormallyOdrUsed,
18211 /// Declarations in this context are used.
18212 Used
18213};
18214}
18215
18216/// Are we within a context in which references to resolved functions or to
18217/// variables result in odr-use?
18218static OdrUseContext isOdrUseContext(Sema &SemaRef) {
18219 OdrUseContext Result;
18220
18221 switch (SemaRef.ExprEvalContexts.back().Context) {
18222 case Sema::ExpressionEvaluationContext::Unevaluated:
18223 case Sema::ExpressionEvaluationContext::UnevaluatedList:
18224 case Sema::ExpressionEvaluationContext::UnevaluatedAbstract:
18225 return OdrUseContext::None;
18226
18227 case Sema::ExpressionEvaluationContext::ConstantEvaluated:
18228 case Sema::ExpressionEvaluationContext::ImmediateFunctionContext:
18229 case Sema::ExpressionEvaluationContext::PotentiallyEvaluated:
18230 Result = OdrUseContext::Used;
18231 break;
18232
18233 case Sema::ExpressionEvaluationContext::DiscardedStatement:
18234 Result = OdrUseContext::FormallyOdrUsed;
18235 break;
18236
18237 case Sema::ExpressionEvaluationContext::PotentiallyEvaluatedIfUsed:
18238 // A default argument formally results in odr-use, but doesn't actually
18239 // result in a use in any real sense until it itself is used.
18240 Result = OdrUseContext::FormallyOdrUsed;
18241 break;
18242 }
18243
18244 if (SemaRef.CurContext->isDependentContext())
18245 return OdrUseContext::Dependent;
18246
18247 return Result;
18248}
18249
18250static bool isImplicitlyDefinableConstexprFunction(FunctionDecl *Func) {
18251 if (!Func->isConstexpr())
18252 return false;
18253
18254 if (Func->isImplicitlyInstantiable() || !Func->isUserProvided())
18255 return true;
18256 auto *CCD = dyn_cast<CXXConstructorDecl>(Func);
18257 return CCD && CCD->getInheritedConstructor();
18258}
18259
18260/// Mark a function referenced, and check whether it is odr-used
18261/// (C++ [basic.def.odr]p2, C99 6.9p3)
18262void Sema::MarkFunctionReferenced(SourceLocation Loc, FunctionDecl *Func,
18263 bool MightBeOdrUse) {
18264 assert(Func && "No function?")(static_cast <bool> (Func && "No function?") ? void
(0) : __assert_fail ("Func && \"No function?\"", "clang/lib/Sema/SemaExpr.cpp"
, 18264, __extension__ __PRETTY_FUNCTION__))
;
18265
18266 Func->setReferenced();
18267
18268 // Recursive functions aren't really used until they're used from some other
18269 // context.
18270 bool IsRecursiveCall = CurContext == Func;
18271
18272 // C++11 [basic.def.odr]p3:
18273 // A function whose name appears as a potentially-evaluated expression is
18274 // odr-used if it is the unique lookup result or the selected member of a
18275 // set of overloaded functions [...].
18276 //
18277 // We (incorrectly) mark overload resolution as an unevaluated context, so we
18278 // can just check that here.
18279 OdrUseContext OdrUse =
18280 MightBeOdrUse ? isOdrUseContext(*this) : OdrUseContext::None;
18281 if (IsRecursiveCall && OdrUse == OdrUseContext::Used)
18282 OdrUse = OdrUseContext::FormallyOdrUsed;
18283
18284 // Trivial default constructors and destructors are never actually used.
18285 // FIXME: What about other special members?
18286 if (Func->isTrivial() && !Func->hasAttr<DLLExportAttr>() &&
18287 OdrUse == OdrUseContext::Used) {
18288 if (auto *Constructor = dyn_cast<CXXConstructorDecl>(Func))
18289 if (Constructor->isDefaultConstructor())
18290 OdrUse = OdrUseContext::FormallyOdrUsed;
18291 if (isa<CXXDestructorDecl>(Func))
18292 OdrUse = OdrUseContext::FormallyOdrUsed;
18293 }
18294
18295 // C++20 [expr.const]p12:
18296 // A function [...] is needed for constant evaluation if it is [...] a
18297 // constexpr function that is named by an expression that is potentially
18298 // constant evaluated
18299 bool NeededForConstantEvaluation =
18300 isPotentiallyConstantEvaluatedContext(*this) &&
18301 isImplicitlyDefinableConstexprFunction(Func);
18302
18303 // Determine whether we require a function definition to exist, per
18304 // C++11 [temp.inst]p3:
18305 // Unless a function template specialization has been explicitly
18306 // instantiated or explicitly specialized, the function template
18307 // specialization is implicitly instantiated when the specialization is
18308 // referenced in a context that requires a function definition to exist.
18309 // C++20 [temp.inst]p7:
18310 // The existence of a definition of a [...] function is considered to
18311 // affect the semantics of the program if the [...] function is needed for
18312 // constant evaluation by an expression
18313 // C++20 [basic.def.odr]p10:
18314 // Every program shall contain exactly one definition of every non-inline
18315 // function or variable that is odr-used in that program outside of a
18316 // discarded statement
18317 // C++20 [special]p1:
18318 // The implementation will implicitly define [defaulted special members]
18319 // if they are odr-used or needed for constant evaluation.
18320 //
18321 // Note that we skip the implicit instantiation of templates that are only
18322 // used in unused default arguments or by recursive calls to themselves.
18323 // This is formally non-conforming, but seems reasonable in practice.
18324 bool NeedDefinition = !IsRecursiveCall && (OdrUse == OdrUseContext::Used ||
18325 NeededForConstantEvaluation);
18326
18327 // C++14 [temp.expl.spec]p6:
18328 // If a template [...] is explicitly specialized then that specialization
18329 // shall be declared before the first use of that specialization that would
18330 // cause an implicit instantiation to take place, in every translation unit
18331 // in which such a use occurs
18332 if (NeedDefinition &&
18333 (Func->getTemplateSpecializationKind() != TSK_Undeclared ||
18334 Func->getMemberSpecializationInfo()))
18335 checkSpecializationReachability(Loc, Func);
18336
18337 if (getLangOpts().CUDA)
18338 CheckCUDACall(Loc, Func);
18339
18340 if (getLangOpts().SYCLIsDevice)
18341 checkSYCLDeviceFunction(Loc, Func);
18342
18343 // If we need a definition, try to create one.
18344 if (NeedDefinition && !Func->getBody()) {
18345 runWithSufficientStackSpace(Loc, [&] {
18346 if (CXXConstructorDecl *Constructor =
18347 dyn_cast<CXXConstructorDecl>(Func)) {
18348 Constructor = cast<CXXConstructorDecl>(Constructor->getFirstDecl());
18349 if (Constructor->isDefaulted() && !Constructor->isDeleted()) {
18350 if (Constructor->isDefaultConstructor()) {
18351 if (Constructor->isTrivial() &&
18352 !Constructor->hasAttr<DLLExportAttr>())
18353 return;
18354 DefineImplicitDefaultConstructor(Loc, Constructor);
18355 } else if (Constructor->isCopyConstructor()) {
18356 DefineImplicitCopyConstructor(Loc, Constructor);
18357 } else if (Constructor->isMoveConstructor()) {
18358 DefineImplicitMoveConstructor(Loc, Constructor);
18359 }
18360 } else if (Constructor->getInheritedConstructor()) {
18361 DefineInheritingConstructor(Loc, Constructor);
18362 }
18363 } else if (CXXDestructorDecl *Destructor =
18364 dyn_cast<CXXDestructorDecl>(Func)) {
18365 Destructor = cast<CXXDestructorDecl>(Destructor->getFirstDecl());
18366 if (Destructor->isDefaulted() && !Destructor->isDeleted()) {
18367 if (Destructor->isTrivial() && !Destructor->hasAttr<DLLExportAttr>())
18368 return;
18369 DefineImplicitDestructor(Loc, Destructor);
18370 }
18371 if (Destructor->isVirtual() && getLangOpts().AppleKext)
18372 MarkVTableUsed(Loc, Destructor->getParent());
18373 } else if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(Func)) {
18374 if (MethodDecl->isOverloadedOperator() &&
18375 MethodDecl->getOverloadedOperator() == OO_Equal) {
18376 MethodDecl = cast<CXXMethodDecl>(MethodDecl->getFirstDecl());
18377 if (MethodDecl->isDefaulted() && !MethodDecl->isDeleted()) {
18378 if (MethodDecl->isCopyAssignmentOperator())
18379 DefineImplicitCopyAssignment(Loc, MethodDecl);
18380 else if (MethodDecl->isMoveAssignmentOperator())
18381 DefineImplicitMoveAssignment(Loc, MethodDecl);
18382 }
18383 } else if (isa<CXXConversionDecl>(MethodDecl) &&
18384 MethodDecl->getParent()->isLambda()) {
18385 CXXConversionDecl *Conversion =
18386 cast<CXXConversionDecl>(MethodDecl->getFirstDecl());
18387 if (Conversion->isLambdaToBlockPointerConversion())
18388 DefineImplicitLambdaToBlockPointerConversion(Loc, Conversion);
18389 else
18390 DefineImplicitLambdaToFunctionPointerConversion(Loc, Conversion);
18391 } else if (MethodDecl->isVirtual() && getLangOpts().AppleKext)
18392 MarkVTableUsed(Loc, MethodDecl->getParent());
18393 }
18394
18395 if (Func->isDefaulted() && !Func->isDeleted()) {
18396 DefaultedComparisonKind DCK = getDefaultedComparisonKind(Func);
18397 if (DCK != DefaultedComparisonKind::None)
18398 DefineDefaultedComparison(Loc, Func, DCK);
18399 }
18400
18401 // Implicit instantiation of function templates and member functions of
18402 // class templates.
18403 if (Func->isImplicitlyInstantiable()) {
18404 TemplateSpecializationKind TSK =
18405 Func->getTemplateSpecializationKindForInstantiation();
18406 SourceLocation PointOfInstantiation = Func->getPointOfInstantiation();
18407 bool FirstInstantiation = PointOfInstantiation.isInvalid();
18408 if (FirstInstantiation) {
18409 PointOfInstantiation = Loc;
18410 if (auto *MSI = Func->getMemberSpecializationInfo())
18411 MSI->setPointOfInstantiation(Loc);
18412 // FIXME: Notify listener.
18413 else
18414 Func->setTemplateSpecializationKind(TSK, PointOfInstantiation);
18415 } else if (TSK != TSK_ImplicitInstantiation) {
18416 // Use the point of use as the point of instantiation, instead of the
18417 // point of explicit instantiation (which we track as the actual point
18418 // of instantiation). This gives better backtraces in diagnostics.
18419 PointOfInstantiation = Loc;
18420 }
18421
18422 if (FirstInstantiation || TSK != TSK_ImplicitInstantiation ||
18423 Func->isConstexpr()) {
18424 if (isa<CXXRecordDecl>(Func->getDeclContext()) &&
18425 cast<CXXRecordDecl>(Func->getDeclContext())->isLocalClass() &&
18426 CodeSynthesisContexts.size())
18427 PendingLocalImplicitInstantiations.push_back(
18428 std::make_pair(Func, PointOfInstantiation));
18429 else if (Func->isConstexpr())
18430 // Do not defer instantiations of constexpr functions, to avoid the
18431 // expression evaluator needing to call back into Sema if it sees a
18432 // call to such a function.
18433 InstantiateFunctionDefinition(PointOfInstantiation, Func);
18434 else {
18435 Func->setInstantiationIsPending(true);
18436 PendingInstantiations.push_back(
18437 std::make_pair(Func, PointOfInstantiation));
18438 // Notify the consumer that a function was implicitly instantiated.
18439 Consumer.HandleCXXImplicitFunctionInstantiation(Func);
18440 }
18441 }
18442 } else {
18443 // Walk redefinitions, as some of them may be instantiable.
18444 for (auto *i : Func->redecls()) {
18445 if (!i->isUsed(false) && i->isImplicitlyInstantiable())
18446 MarkFunctionReferenced(Loc, i, MightBeOdrUse);
18447 }
18448 }
18449 });
18450 }
18451
18452 // If a constructor was defined in the context of a default parameter
18453 // or of another default member initializer (ie a PotentiallyEvaluatedIfUsed
18454 // context), its initializers may not be referenced yet.
18455 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Func)) {
18456 for (CXXCtorInitializer *Init : Constructor->inits()) {
18457 if (Init->isInClassMemberInitializer())
18458 MarkDeclarationsReferencedInExpr(Init->getInit());
18459 }
18460 }
18461
18462 // C++14 [except.spec]p17:
18463 // An exception-specification is considered to be needed when:
18464 // - the function is odr-used or, if it appears in an unevaluated operand,
18465 // would be odr-used if the expression were potentially-evaluated;
18466 //
18467 // Note, we do this even if MightBeOdrUse is false. That indicates that the
18468 // function is a pure virtual function we're calling, and in that case the
18469 // function was selected by overload resolution and we need to resolve its
18470 // exception specification for a different reason.
18471 const FunctionProtoType *FPT = Func->getType()->getAs<FunctionProtoType>();
18472 if (FPT && isUnresolvedExceptionSpec(FPT->getExceptionSpecType()))
18473 ResolveExceptionSpec(Loc, FPT);
18474
18475 // If this is the first "real" use, act on that.
18476 if (OdrUse == OdrUseContext::Used && !Func->isUsed(/*CheckUsedAttr=*/false)) {
18477 // Keep track of used but undefined functions.
18478 if (!Func->isDefined()) {
18479 if (mightHaveNonExternalLinkage(Func))
18480 UndefinedButUsed.insert(std::make_pair(Func->getCanonicalDecl(), Loc));
18481 else if (Func->getMostRecentDecl()->isInlined() &&
18482 !LangOpts.GNUInline &&
18483 !Func->getMostRecentDecl()->hasAttr<GNUInlineAttr>())
18484 UndefinedButUsed.insert(std::make_pair(Func->getCanonicalDecl(), Loc));
18485 else if (isExternalWithNoLinkageType(Func))
18486 UndefinedButUsed.insert(std::make_pair(Func->getCanonicalDecl(), Loc));
18487 }
18488
18489 // Some x86 Windows calling conventions mangle the size of the parameter
18490 // pack into the name. Computing the size of the parameters requires the
18491 // parameter types to be complete. Check that now.
18492 if (funcHasParameterSizeMangling(*this, Func))
18493 CheckCompleteParameterTypesForMangler(*this, Func, Loc);
18494
18495 // In the MS C++ ABI, the compiler emits destructor variants where they are
18496 // used. If the destructor is used here but defined elsewhere, mark the
18497 // virtual base destructors referenced. If those virtual base destructors
18498 // are inline, this will ensure they are defined when emitting the complete
18499 // destructor variant. This checking may be redundant if the destructor is
18500 // provided later in this TU.
18501 if (Context.getTargetInfo().getCXXABI().isMicrosoft()) {
18502 if (auto *Dtor = dyn_cast<CXXDestructorDecl>(Func)) {
18503 CXXRecordDecl *Parent = Dtor->getParent();
18504 if (Parent->getNumVBases() > 0 && !Dtor->getBody())
18505 CheckCompleteDestructorVariant(Loc, Dtor);
18506 }
18507 }
18508
18509 Func->markUsed(Context);
18510 }
18511}
18512
18513/// Directly mark a variable odr-used. Given a choice, prefer to use
18514/// MarkVariableReferenced since it does additional checks and then
18515/// calls MarkVarDeclODRUsed.
18516/// If the variable must be captured:
18517/// - if FunctionScopeIndexToStopAt is null, capture it in the CurContext
18518/// - else capture it in the DeclContext that maps to the
18519/// *FunctionScopeIndexToStopAt on the FunctionScopeInfo stack.
18520static void
18521MarkVarDeclODRUsed(ValueDecl *V, SourceLocation Loc, Sema &SemaRef,
18522 const unsigned *const FunctionScopeIndexToStopAt = nullptr) {
18523 // Keep track of used but undefined variables.
18524 // FIXME: We shouldn't suppress this warning for static data members.
18525 VarDecl *Var = V->getPotentiallyDecomposedVarDecl();
18526 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", 18526, __extension__ __PRETTY_FUNCTION__
))
;
18527
18528 if (Var->hasDefinition(SemaRef.Context) == VarDecl::DeclarationOnly &&
18529 (!Var->isExternallyVisible() || Var->isInline() ||
18530 SemaRef.isExternalWithNoLinkageType(Var)) &&
18531 !(Var->isStaticDataMember() && Var->hasInit())) {
18532 SourceLocation &old = SemaRef.UndefinedButUsed[Var->getCanonicalDecl()];
18533 if (old.isInvalid())
18534 old = Loc;
18535 }
18536 QualType CaptureType, DeclRefType;
18537 if (SemaRef.LangOpts.OpenMP)
18538 SemaRef.tryCaptureOpenMPLambdas(V);
18539 SemaRef.tryCaptureVariable(V, Loc, Sema::TryCapture_Implicit,
18540 /*EllipsisLoc*/ SourceLocation(),
18541 /*BuildAndDiagnose*/ true, CaptureType,
18542 DeclRefType, FunctionScopeIndexToStopAt);
18543
18544 if (SemaRef.LangOpts.CUDA && Var->hasGlobalStorage()) {
18545 auto *FD = dyn_cast_or_null<FunctionDecl>(SemaRef.CurContext);
18546 auto VarTarget = SemaRef.IdentifyCUDATarget(Var);
18547 auto UserTarget = SemaRef.IdentifyCUDATarget(FD);
18548 if (VarTarget == Sema::CVT_Host &&
18549 (UserTarget == Sema::CFT_Device || UserTarget == Sema::CFT_HostDevice ||
18550 UserTarget == Sema::CFT_Global)) {
18551 // Diagnose ODR-use of host global variables in device functions.
18552 // Reference of device global variables in host functions is allowed
18553 // through shadow variables therefore it is not diagnosed.
18554 if (SemaRef.LangOpts.CUDAIsDevice) {
18555 SemaRef.targetDiag(Loc, diag::err_ref_bad_target)
18556 << /*host*/ 2 << /*variable*/ 1 << Var << UserTarget;
18557 SemaRef.targetDiag(Var->getLocation(),
18558 Var->getType().isConstQualified()
18559 ? diag::note_cuda_const_var_unpromoted
18560 : diag::note_cuda_host_var);
18561 }
18562 } else if (VarTarget == Sema::CVT_Device &&
18563 (UserTarget == Sema::CFT_Host ||
18564 UserTarget == Sema::CFT_HostDevice)) {
18565 // Record a CUDA/HIP device side variable if it is ODR-used
18566 // by host code. This is done conservatively, when the variable is
18567 // referenced in any of the following contexts:
18568 // - a non-function context
18569 // - a host function
18570 // - a host device function
18571 // This makes the ODR-use of the device side variable by host code to
18572 // be visible in the device compilation for the compiler to be able to
18573 // emit template variables instantiated by host code only and to
18574 // externalize the static device side variable ODR-used by host code.
18575 if (!Var->hasExternalStorage())
18576 SemaRef.getASTContext().CUDADeviceVarODRUsedByHost.insert(Var);
18577 else if (SemaRef.LangOpts.GPURelocatableDeviceCode)
18578 SemaRef.getASTContext().CUDAExternalDeviceDeclODRUsedByHost.insert(Var);
18579 }
18580 }
18581
18582 V->markUsed(SemaRef.Context);
18583}
18584
18585void Sema::MarkCaptureUsedInEnclosingContext(ValueDecl *Capture,
18586 SourceLocation Loc,
18587 unsigned CapturingScopeIndex) {
18588 MarkVarDeclODRUsed(Capture, Loc, *this, &CapturingScopeIndex);
18589}
18590
18591void diagnoseUncapturableValueReferenceOrBinding(Sema &S, SourceLocation loc,
18592 ValueDecl *var) {
18593 DeclContext *VarDC = var->getDeclContext();
18594
18595 // If the parameter still belongs to the translation unit, then
18596 // we're actually just using one parameter in the declaration of
18597 // the next.
18598 if (isa<ParmVarDecl>(var) &&
18599 isa<TranslationUnitDecl>(VarDC))
18600 return;
18601
18602 // For C code, don't diagnose about capture if we're not actually in code
18603 // right now; it's impossible to write a non-constant expression outside of
18604 // function context, so we'll get other (more useful) diagnostics later.
18605 //
18606 // For C++, things get a bit more nasty... it would be nice to suppress this
18607 // diagnostic for certain cases like using a local variable in an array bound
18608 // for a member of a local class, but the correct predicate is not obvious.
18609 if (!S.getLangOpts().CPlusPlus && !S.CurContext->isFunctionOrMethod())
18610 return;
18611
18612 unsigned ValueKind = isa<BindingDecl>(var) ? 1 : 0;
18613 unsigned ContextKind = 3; // unknown
18614 if (isa<CXXMethodDecl>(VarDC) &&
18615 cast<CXXRecordDecl>(VarDC->getParent())->isLambda()) {
18616 ContextKind = 2;
18617 } else if (isa<FunctionDecl>(VarDC)) {
18618 ContextKind = 0;
18619 } else if (isa<BlockDecl>(VarDC)) {
18620 ContextKind = 1;
18621 }
18622
18623 S.Diag(loc, diag::err_reference_to_local_in_enclosing_context)
18624 << var << ValueKind << ContextKind << VarDC;
18625 S.Diag(var->getLocation(), diag::note_entity_declared_at)
18626 << var;
18627
18628 // FIXME: Add additional diagnostic info about class etc. which prevents
18629 // capture.
18630}
18631
18632static bool isVariableAlreadyCapturedInScopeInfo(CapturingScopeInfo *CSI,
18633 ValueDecl *Var,
18634 bool &SubCapturesAreNested,
18635 QualType &CaptureType,
18636 QualType &DeclRefType) {
18637 // Check whether we've already captured it.
18638 if (CSI->CaptureMap.count(Var)) {
18639 // If we found a capture, any subcaptures are nested.
18640 SubCapturesAreNested = true;
18641
18642 // Retrieve the capture type for this variable.
18643 CaptureType = CSI->getCapture(Var).getCaptureType();
18644
18645 // Compute the type of an expression that refers to this variable.
18646 DeclRefType = CaptureType.getNonReferenceType();
18647
18648 // Similarly to mutable captures in lambda, all the OpenMP captures by copy
18649 // are mutable in the sense that user can change their value - they are
18650 // private instances of the captured declarations.
18651 const Capture &Cap = CSI->getCapture(Var);
18652 if (Cap.isCopyCapture() &&
18653 !(isa<LambdaScopeInfo>(CSI) && cast<LambdaScopeInfo>(CSI)->Mutable) &&
18654 !(isa<CapturedRegionScopeInfo>(CSI) &&
18655 cast<CapturedRegionScopeInfo>(CSI)->CapRegionKind == CR_OpenMP))
18656 DeclRefType.addConst();
18657 return true;
18658 }
18659 return false;
18660}
18661
18662// Only block literals, captured statements, and lambda expressions can
18663// capture; other scopes don't work.
18664static DeclContext *getParentOfCapturingContextOrNull(DeclContext *DC,
18665 ValueDecl *Var,
18666 SourceLocation Loc,
18667 const bool Diagnose,
18668 Sema &S) {
18669 if (isa<BlockDecl>(DC) || isa<CapturedDecl>(DC) || isLambdaCallOperator(DC))
18670 return getLambdaAwareParentOfDeclContext(DC);
18671
18672 VarDecl *Underlying = Var->getPotentiallyDecomposedVarDecl();
18673 if (Underlying) {
18674 if (Underlying->hasLocalStorage() && Diagnose)
18675 diagnoseUncapturableValueReferenceOrBinding(S, Loc, Var);
18676 }
18677 return nullptr;
18678}
18679
18680// Certain capturing entities (lambdas, blocks etc.) are not allowed to capture
18681// certain types of variables (unnamed, variably modified types etc.)
18682// so check for eligibility.
18683static bool isVariableCapturable(CapturingScopeInfo *CSI, ValueDecl *Var,
18684 SourceLocation Loc, const bool Diagnose,
18685 Sema &S) {
18686
18687 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", 18688, __extension__ __PRETTY_FUNCTION__
))
18688 "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", 18688, __extension__ __PRETTY_FUNCTION__
))
;
18689
18690 bool IsBlock = isa<BlockScopeInfo>(CSI);
18691 bool IsLambda = isa<LambdaScopeInfo>(CSI);
18692
18693 // Lambdas are not allowed to capture unnamed variables
18694 // (e.g. anonymous unions).
18695 // FIXME: The C++11 rule don't actually state this explicitly, but I'm
18696 // assuming that's the intent.
18697 if (IsLambda && !Var->getDeclName()) {
18698 if (Diagnose) {
18699 S.Diag(Loc, diag::err_lambda_capture_anonymous_var);
18700 S.Diag(Var->getLocation(), diag::note_declared_at);
18701 }
18702 return false;
18703 }
18704
18705 // Prohibit variably-modified types in blocks; they're difficult to deal with.
18706 if (Var->getType()->isVariablyModifiedType() && IsBlock) {
18707 if (Diagnose) {
18708 S.Diag(Loc, diag::err_ref_vm_type);
18709 S.Diag(Var->getLocation(), diag::note_previous_decl) << Var;
18710 }
18711 return false;
18712 }
18713 // Prohibit structs with flexible array members too.
18714 // We cannot capture what is in the tail end of the struct.
18715 if (const RecordType *VTTy = Var->getType()->getAs<RecordType>()) {
18716 if (VTTy->getDecl()->hasFlexibleArrayMember()) {
18717 if (Diagnose) {
18718 if (IsBlock)
18719 S.Diag(Loc, diag::err_ref_flexarray_type);
18720 else
18721 S.Diag(Loc, diag::err_lambda_capture_flexarray_type) << Var;
18722 S.Diag(Var->getLocation(), diag::note_previous_decl) << Var;
18723 }
18724 return false;
18725 }
18726 }
18727 const bool HasBlocksAttr = Var->hasAttr<BlocksAttr>();
18728 // Lambdas and captured statements are not allowed to capture __block
18729 // variables; they don't support the expected semantics.
18730 if (HasBlocksAttr && (IsLambda || isa<CapturedRegionScopeInfo>(CSI))) {
18731 if (Diagnose) {
18732 S.Diag(Loc, diag::err_capture_block_variable) << Var << !IsLambda;
18733 S.Diag(Var->getLocation(), diag::note_previous_decl) << Var;
18734 }
18735 return false;
18736 }
18737 // OpenCL v2.0 s6.12.5: Blocks cannot reference/capture other blocks
18738 if (S.getLangOpts().OpenCL && IsBlock &&
18739 Var->getType()->isBlockPointerType()) {
18740 if (Diagnose)
18741 S.Diag(Loc, diag::err_opencl_block_ref_block);
18742 return false;
18743 }
18744
18745 if (isa<BindingDecl>(Var)) {
18746 if (!IsLambda || !S.getLangOpts().CPlusPlus) {
18747 if (Diagnose)
18748 diagnoseUncapturableValueReferenceOrBinding(S, Loc, Var);
18749 return false;
18750 } else if (Diagnose && S.getLangOpts().CPlusPlus) {
18751 S.Diag(Loc, S.LangOpts.CPlusPlus20
18752 ? diag::warn_cxx17_compat_capture_binding
18753 : diag::ext_capture_binding)
18754 << Var;
18755 S.Diag(Var->getLocation(), diag::note_entity_declared_at) << Var;
18756 }
18757 }
18758
18759 return true;
18760}
18761
18762// Returns true if the capture by block was successful.
18763static bool captureInBlock(BlockScopeInfo *BSI, ValueDecl *Var,
18764 SourceLocation Loc, const bool BuildAndDiagnose,
18765 QualType &CaptureType, QualType &DeclRefType,
18766 const bool Nested, Sema &S, bool Invalid) {
18767 bool ByRef = false;
18768
18769 // Blocks are not allowed to capture arrays, excepting OpenCL.
18770 // OpenCL v2.0 s1.12.5 (revision 40): arrays are captured by reference
18771 // (decayed to pointers).
18772 if (!Invalid && !S.getLangOpts().OpenCL && CaptureType->isArrayType()) {
18773 if (BuildAndDiagnose) {
18774 S.Diag(Loc, diag::err_ref_array_type);
18775 S.Diag(Var->getLocation(), diag::note_previous_decl) << Var;
18776 Invalid = true;
18777 } else {
18778 return false;
18779 }
18780 }
18781
18782 // Forbid the block-capture of autoreleasing variables.
18783 if (!Invalid &&
18784 CaptureType.getObjCLifetime() == Qualifiers::OCL_Autoreleasing) {
18785 if (BuildAndDiagnose) {
18786 S.Diag(Loc, diag::err_arc_autoreleasing_capture)
18787 << /*block*/ 0;
18788 S.Diag(Var->getLocation(), diag::note_previous_decl) << Var;
18789 Invalid = true;
18790 } else {
18791 return false;
18792 }
18793 }
18794
18795 // Warn about implicitly autoreleasing indirect parameters captured by blocks.
18796 if (const auto *PT = CaptureType->getAs<PointerType>()) {
18797 QualType PointeeTy = PT->getPointeeType();
18798
18799 if (!Invalid && PointeeTy->getAs<ObjCObjectPointerType>() &&
18800 PointeeTy.getObjCLifetime() == Qualifiers::OCL_Autoreleasing &&
18801 !S.Context.hasDirectOwnershipQualifier(PointeeTy)) {
18802 if (BuildAndDiagnose) {
18803 SourceLocation VarLoc = Var->getLocation();
18804 S.Diag(Loc, diag::warn_block_capture_autoreleasing);
18805 S.Diag(VarLoc, diag::note_declare_parameter_strong);
18806 }
18807 }
18808 }
18809
18810 const bool HasBlocksAttr = Var->hasAttr<BlocksAttr>();
18811 if (HasBlocksAttr || CaptureType->isReferenceType() ||
18812 (S.getLangOpts().OpenMP && S.isOpenMPCapturedDecl(Var))) {
18813 // Block capture by reference does not change the capture or
18814 // declaration reference types.
18815 ByRef = true;
18816 } else {
18817 // Block capture by copy introduces 'const'.
18818 CaptureType = CaptureType.getNonReferenceType().withConst();
18819 DeclRefType = CaptureType;
18820 }
18821
18822 // Actually capture the variable.
18823 if (BuildAndDiagnose)
18824 BSI->addCapture(Var, HasBlocksAttr, ByRef, Nested, Loc, SourceLocation(),
18825 CaptureType, Invalid);
18826
18827 return !Invalid;
18828}
18829
18830/// Capture the given variable in the captured region.
18831static bool captureInCapturedRegion(
18832 CapturedRegionScopeInfo *RSI, ValueDecl *Var, SourceLocation Loc,
18833 const bool BuildAndDiagnose, QualType &CaptureType, QualType &DeclRefType,
18834 const bool RefersToCapturedVariable, Sema::TryCaptureKind Kind,
18835 bool IsTopScope, Sema &S, bool Invalid) {
18836 // By default, capture variables by reference.
18837 bool ByRef = true;
18838 if (IsTopScope && Kind != Sema::TryCapture_Implicit) {
18839 ByRef = (Kind == Sema::TryCapture_ExplicitByRef);
18840 } else if (S.getLangOpts().OpenMP && RSI->CapRegionKind == CR_OpenMP) {
18841 // Using an LValue reference type is consistent with Lambdas (see below).
18842 if (S.isOpenMPCapturedDecl(Var)) {
18843 bool HasConst = DeclRefType.isConstQualified();
18844 DeclRefType = DeclRefType.getUnqualifiedType();
18845 // Don't lose diagnostics about assignments to const.
18846 if (HasConst)
18847 DeclRefType.addConst();
18848 }
18849 // Do not capture firstprivates in tasks.
18850 if (S.isOpenMPPrivateDecl(Var, RSI->OpenMPLevel, RSI->OpenMPCaptureLevel) !=
18851 OMPC_unknown)
18852 return true;
18853 ByRef = S.isOpenMPCapturedByRef(Var, RSI->OpenMPLevel,
18854 RSI->OpenMPCaptureLevel);
18855 }
18856
18857 if (ByRef)
18858 CaptureType = S.Context.getLValueReferenceType(DeclRefType);
18859 else
18860 CaptureType = DeclRefType;
18861
18862 // Actually capture the variable.
18863 if (BuildAndDiagnose)
18864 RSI->addCapture(Var, /*isBlock*/ false, ByRef, RefersToCapturedVariable,
18865 Loc, SourceLocation(), CaptureType, Invalid);
18866
18867 return !Invalid;
18868}
18869
18870/// Capture the given variable in the lambda.
18871static bool captureInLambda(LambdaScopeInfo *LSI, ValueDecl *Var,
18872 SourceLocation Loc, const bool BuildAndDiagnose,
18873 QualType &CaptureType, QualType &DeclRefType,
18874 const bool RefersToCapturedVariable,
18875 const Sema::TryCaptureKind Kind,
18876 SourceLocation EllipsisLoc, const bool IsTopScope,
18877 Sema &S, bool Invalid) {
18878 // Determine whether we are capturing by reference or by value.
18879 bool ByRef = false;
18880 if (IsTopScope && Kind != Sema::TryCapture_Implicit) {
18881 ByRef = (Kind == Sema::TryCapture_ExplicitByRef);
18882 } else {
18883 ByRef = (LSI->ImpCaptureStyle == LambdaScopeInfo::ImpCap_LambdaByref);
18884 }
18885
18886 BindingDecl *BD = dyn_cast<BindingDecl>(Var);
18887 // FIXME: We should support capturing structured bindings in OpenMP.
18888 if (!Invalid && BD && S.LangOpts.OpenMP) {
18889 if (BuildAndDiagnose) {
18890 S.Diag(Loc, diag::err_capture_binding_openmp) << Var;
18891 S.Diag(Var->getLocation(), diag::note_entity_declared_at) << Var;
18892 }
18893 Invalid = true;
18894 }
18895
18896 if (BuildAndDiagnose && S.Context.getTargetInfo().getTriple().isWasm() &&
18897 CaptureType.getNonReferenceType()->isWebAssemblyReferenceType()) {
18898 S.Diag(Loc, diag::err_wasm_ca_reference) << 0;
18899 Invalid = true;
18900 }
18901
18902 // Compute the type of the field that will capture this variable.
18903 if (ByRef) {
18904 // C++11 [expr.prim.lambda]p15:
18905 // An entity is captured by reference if it is implicitly or
18906 // explicitly captured but not captured by copy. It is
18907 // unspecified whether additional unnamed non-static data
18908 // members are declared in the closure type for entities
18909 // captured by reference.
18910 //
18911 // FIXME: It is not clear whether we want to build an lvalue reference
18912 // to the DeclRefType or to CaptureType.getNonReferenceType(). GCC appears
18913 // to do the former, while EDG does the latter. Core issue 1249 will
18914 // clarify, but for now we follow GCC because it's a more permissive and
18915 // easily defensible position.
18916 CaptureType = S.Context.getLValueReferenceType(DeclRefType);
18917 } else {
18918 // C++11 [expr.prim.lambda]p14:
18919 // For each entity captured by copy, an unnamed non-static
18920 // data member is declared in the closure type. The
18921 // declaration order of these members is unspecified. The type
18922 // of such a data member is the type of the corresponding
18923 // captured entity if the entity is not a reference to an
18924 // object, or the referenced type otherwise. [Note: If the
18925 // captured entity is a reference to a function, the
18926 // corresponding data member is also a reference to a
18927 // function. - end note ]
18928 if (const ReferenceType *RefType = CaptureType->getAs<ReferenceType>()){
18929 if (!RefType->getPointeeType()->isFunctionType())
18930 CaptureType = RefType->getPointeeType();
18931 }
18932
18933 // Forbid the lambda copy-capture of autoreleasing variables.
18934 if (!Invalid &&
18935 CaptureType.getObjCLifetime() == Qualifiers::OCL_Autoreleasing) {
18936 if (BuildAndDiagnose) {
18937 S.Diag(Loc, diag::err_arc_autoreleasing_capture) << /*lambda*/ 1;
18938 S.Diag(Var->getLocation(), diag::note_previous_decl)
18939 << Var->getDeclName();
18940 Invalid = true;
18941 } else {
18942 return false;
18943 }
18944 }
18945
18946 // Make sure that by-copy captures are of a complete and non-abstract type.
18947 if (!Invalid && BuildAndDiagnose) {
18948 if (!CaptureType->isDependentType() &&
18949 S.RequireCompleteSizedType(
18950 Loc, CaptureType,
18951 diag::err_capture_of_incomplete_or_sizeless_type,
18952 Var->getDeclName()))
18953 Invalid = true;
18954 else if (S.RequireNonAbstractType(Loc, CaptureType,
18955 diag::err_capture_of_abstract_type))
18956 Invalid = true;
18957 }
18958 }
18959
18960 // Compute the type of a reference to this captured variable.
18961 if (ByRef)
18962 DeclRefType = CaptureType.getNonReferenceType();
18963 else {
18964 // C++ [expr.prim.lambda]p5:
18965 // The closure type for a lambda-expression has a public inline
18966 // function call operator [...]. This function call operator is
18967 // declared const (9.3.1) if and only if the lambda-expression's
18968 // parameter-declaration-clause is not followed by mutable.
18969 DeclRefType = CaptureType.getNonReferenceType();
18970 if (!LSI->Mutable && !CaptureType->isReferenceType())
18971 DeclRefType.addConst();
18972 }
18973
18974 // Add the capture.
18975 if (BuildAndDiagnose)
18976 LSI->addCapture(Var, /*isBlock=*/false, ByRef, RefersToCapturedVariable,
18977 Loc, EllipsisLoc, CaptureType, Invalid);
18978
18979 return !Invalid;
18980}
18981
18982static bool canCaptureVariableByCopy(ValueDecl *Var,
18983 const ASTContext &Context) {
18984 // Offer a Copy fix even if the type is dependent.
18985 if (Var->getType()->isDependentType())
18986 return true;
18987 QualType T = Var->getType().getNonReferenceType();
18988 if (T.isTriviallyCopyableType(Context))
18989 return true;
18990 if (CXXRecordDecl *RD = T->getAsCXXRecordDecl()) {
18991
18992 if (!(RD = RD->getDefinition()))
18993 return false;
18994 if (RD->hasSimpleCopyConstructor())
18995 return true;
18996 if (RD->hasUserDeclaredCopyConstructor())
18997 for (CXXConstructorDecl *Ctor : RD->ctors())
18998 if (Ctor->isCopyConstructor())
18999 return !Ctor->isDeleted();
19000 }
19001 return false;
19002}
19003
19004/// Create up to 4 fix-its for explicit reference and value capture of \p Var or
19005/// default capture. Fixes may be omitted if they aren't allowed by the
19006/// standard, for example we can't emit a default copy capture fix-it if we
19007/// already explicitly copy capture capture another variable.
19008static void buildLambdaCaptureFixit(Sema &Sema, LambdaScopeInfo *LSI,
19009 ValueDecl *Var) {
19010 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", 19010, __extension__ __PRETTY_FUNCTION__
))
;
19011 // Don't offer Capture by copy of default capture by copy fixes if Var is
19012 // known not to be copy constructible.
19013 bool ShouldOfferCopyFix = canCaptureVariableByCopy(Var, Sema.getASTContext());
19014
19015 SmallString<32> FixBuffer;
19016 StringRef Separator = LSI->NumExplicitCaptures > 0 ? ", " : "";
19017 if (Var->getDeclName().isIdentifier() && !Var->getName().empty()) {
19018 SourceLocation VarInsertLoc = LSI->IntroducerRange.getEnd();
19019 if (ShouldOfferCopyFix) {
19020 // Offer fixes to insert an explicit capture for the variable.
19021 // [] -> [VarName]
19022 // [OtherCapture] -> [OtherCapture, VarName]
19023 FixBuffer.assign({Separator, Var->getName()});
19024 Sema.Diag(VarInsertLoc, diag::note_lambda_variable_capture_fixit)
19025 << Var << /*value*/ 0
19026 << FixItHint::CreateInsertion(VarInsertLoc, FixBuffer);
19027 }
19028 // As above but capture by reference.
19029 FixBuffer.assign({Separator, "&", Var->getName()});
19030 Sema.Diag(VarInsertLoc, diag::note_lambda_variable_capture_fixit)
19031 << Var << /*reference*/ 1
19032 << FixItHint::CreateInsertion(VarInsertLoc, FixBuffer);
19033 }
19034
19035 // Only try to offer default capture if there are no captures excluding this
19036 // and init captures.
19037 // [this]: OK.
19038 // [X = Y]: OK.
19039 // [&A, &B]: Don't offer.
19040 // [A, B]: Don't offer.
19041 if (llvm::any_of(LSI->Captures, [](Capture &C) {
19042 return !C.isThisCapture() && !C.isInitCapture();
19043 }))
19044 return;
19045
19046 // The default capture specifiers, '=' or '&', must appear first in the
19047 // capture body.
19048 SourceLocation DefaultInsertLoc =
19049 LSI->IntroducerRange.getBegin().getLocWithOffset(1);
19050
19051 if (ShouldOfferCopyFix) {
19052 bool CanDefaultCopyCapture = true;
19053 // [=, *this] OK since c++17
19054 // [=, this] OK since c++20
19055 if (LSI->isCXXThisCaptured() && !Sema.getLangOpts().CPlusPlus20)
19056 CanDefaultCopyCapture = Sema.getLangOpts().CPlusPlus17
19057 ? LSI->getCXXThisCapture().isCopyCapture()
19058 : false;
19059 // We can't use default capture by copy if any captures already specified
19060 // capture by copy.
19061 if (CanDefaultCopyCapture && llvm::none_of(LSI->Captures, [](Capture &C) {
19062 return !C.isThisCapture() && !C.isInitCapture() && C.isCopyCapture();
19063 })) {
19064 FixBuffer.assign({"=", Separator});
19065 Sema.Diag(DefaultInsertLoc, diag::note_lambda_default_capture_fixit)
19066 << /*value*/ 0
19067 << FixItHint::CreateInsertion(DefaultInsertLoc, FixBuffer);
19068 }
19069 }
19070
19071 // We can't use default capture by reference if any captures already specified
19072 // capture by reference.
19073 if (llvm::none_of(LSI->Captures, [](Capture &C) {
19074 return !C.isInitCapture() && C.isReferenceCapture() &&
19075 !C.isThisCapture();
19076 })) {
19077 FixBuffer.assign({"&", Separator});
19078 Sema.Diag(DefaultInsertLoc, diag::note_lambda_default_capture_fixit)
19079 << /*reference*/ 1
19080 << FixItHint::CreateInsertion(DefaultInsertLoc, FixBuffer);
19081 }
19082}
19083
19084bool Sema::tryCaptureVariable(
19085 ValueDecl *Var, SourceLocation ExprLoc, TryCaptureKind Kind,
19086 SourceLocation EllipsisLoc, bool BuildAndDiagnose, QualType &CaptureType,
19087 QualType &DeclRefType, const unsigned *const FunctionScopeIndexToStopAt) {
19088 // An init-capture is notionally from the context surrounding its
19089 // declaration, but its parent DC is the lambda class.
19090 DeclContext *VarDC = Var->getDeclContext();
19091 const auto *VD = dyn_cast<VarDecl>(Var);
19092 if (VD) {
19093 if (VD->isInitCapture())
19094 VarDC = VarDC->getParent();
19095 } else {
19096 VD = Var->getPotentiallyDecomposedVarDecl();
19097 }
19098 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", 19098, __extension__ __PRETTY_FUNCTION__
))
;
19099
19100 DeclContext *DC = CurContext;
19101 const unsigned MaxFunctionScopesIndex = FunctionScopeIndexToStopAt
19102 ? *FunctionScopeIndexToStopAt : FunctionScopes.size() - 1;
19103 // We need to sync up the Declaration Context with the
19104 // FunctionScopeIndexToStopAt
19105 if (FunctionScopeIndexToStopAt) {
19106 unsigned FSIndex = FunctionScopes.size() - 1;
19107 while (FSIndex != MaxFunctionScopesIndex) {
19108 DC = getLambdaAwareParentOfDeclContext(DC);
19109 --FSIndex;
19110 }
19111 }
19112
19113 // Capture global variables if it is required to use private copy of this
19114 // variable.
19115 bool IsGlobal = !VD->hasLocalStorage();
19116 if (IsGlobal &&
19117 !(LangOpts.OpenMP && isOpenMPCapturedDecl(Var, /*CheckScopeInfo=*/true,
19118 MaxFunctionScopesIndex)))
19119 return true;
19120
19121 if (isa<VarDecl>(Var))
19122 Var = cast<VarDecl>(Var->getCanonicalDecl());
19123
19124 // Walk up the stack to determine whether we can capture the variable,
19125 // performing the "simple" checks that don't depend on type. We stop when
19126 // we've either hit the declared scope of the variable or find an existing
19127 // capture of that variable. We start from the innermost capturing-entity
19128 // (the DC) and ensure that all intervening capturing-entities
19129 // (blocks/lambdas etc.) between the innermost capturer and the variable`s
19130 // declcontext can either capture the variable or have already captured
19131 // the variable.
19132 CaptureType = Var->getType();
19133 DeclRefType = CaptureType.getNonReferenceType();
19134 bool Nested = false;
19135 bool Explicit = (Kind != TryCapture_Implicit);
19136 unsigned FunctionScopesIndex = MaxFunctionScopesIndex;
19137 do {
19138
19139 LambdaScopeInfo *LSI = nullptr;
19140 if (!FunctionScopes.empty())
19141 LSI = dyn_cast_or_null<LambdaScopeInfo>(
19142 FunctionScopes[FunctionScopesIndex]);
19143
19144 bool IsInScopeDeclarationContext =
19145 !LSI || LSI->AfterParameterList || CurContext == LSI->CallOperator;
19146
19147 if (LSI && !LSI->AfterParameterList) {
19148 // This allows capturing parameters from a default value which does not
19149 // seems correct
19150 if (isa<ParmVarDecl>(Var) && !Var->getDeclContext()->isFunctionOrMethod())
19151 return true;
19152 }
19153 // If the variable is declared in the current context, there is no need to
19154 // capture it.
19155 if (IsInScopeDeclarationContext &&
19156 FunctionScopesIndex == MaxFunctionScopesIndex && VarDC == DC)
19157 return true;
19158
19159 // When evaluating some attributes (like enable_if) we might refer to a
19160 // function parameter appertaining to the same declaration as that
19161 // attribute.
19162 if (const auto *Parm = dyn_cast<ParmVarDecl>(Var);
19163 Parm && Parm->getDeclContext() == DC)
19164 return true;
19165
19166 // Only block literals, captured statements, and lambda expressions can
19167 // capture; other scopes don't work.
19168 DeclContext *ParentDC =
19169 !IsInScopeDeclarationContext
19170 ? DC->getParent()
19171 : getParentOfCapturingContextOrNull(DC, Var, ExprLoc,
19172 BuildAndDiagnose, *this);
19173 // We need to check for the parent *first* because, if we *have*
19174 // private-captured a global variable, we need to recursively capture it in
19175 // intermediate blocks, lambdas, etc.
19176 if (!ParentDC) {
19177 if (IsGlobal) {
19178 FunctionScopesIndex = MaxFunctionScopesIndex - 1;
19179 break;
19180 }
19181 return true;
19182 }
19183
19184 FunctionScopeInfo *FSI = FunctionScopes[FunctionScopesIndex];
19185 CapturingScopeInfo *CSI = cast<CapturingScopeInfo>(FSI);
19186
19187 // Check whether we've already captured it.
19188 if (isVariableAlreadyCapturedInScopeInfo(CSI, Var, Nested, CaptureType,
19189 DeclRefType)) {
19190 CSI->getCapture(Var).markUsed(BuildAndDiagnose);
19191 break;
19192 }
19193 // If we are instantiating a generic lambda call operator body,
19194 // we do not want to capture new variables. What was captured
19195 // during either a lambdas transformation or initial parsing
19196 // should be used.
19197 if (isGenericLambdaCallOperatorSpecialization(DC)) {
19198 if (BuildAndDiagnose) {
19199 LambdaScopeInfo *LSI = cast<LambdaScopeInfo>(CSI);
19200 if (LSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_None) {
19201 Diag(ExprLoc, diag::err_lambda_impcap) << Var;
19202 Diag(Var->getLocation(), diag::note_previous_decl) << Var;
19203 Diag(LSI->Lambda->getBeginLoc(), diag::note_lambda_decl);
19204 buildLambdaCaptureFixit(*this, LSI, Var);
19205 } else
19206 diagnoseUncapturableValueReferenceOrBinding(*this, ExprLoc, Var);
19207 }
19208 return true;
19209 }
19210
19211 // Try to capture variable-length arrays types.
19212 if (Var->getType()->isVariablyModifiedType()) {
19213 // We're going to walk down into the type and look for VLA
19214 // expressions.
19215 QualType QTy = Var->getType();
19216 if (ParmVarDecl *PVD = dyn_cast_or_null<ParmVarDecl>(Var))
19217 QTy = PVD->getOriginalType();
19218 captureVariablyModifiedType(Context, QTy, CSI);
19219 }
19220
19221 if (getLangOpts().OpenMP) {
19222 if (auto *RSI = dyn_cast<CapturedRegionScopeInfo>(CSI)) {
19223 // OpenMP private variables should not be captured in outer scope, so
19224 // just break here. Similarly, global variables that are captured in a
19225 // target region should not be captured outside the scope of the region.
19226 if (RSI->CapRegionKind == CR_OpenMP) {
19227 OpenMPClauseKind IsOpenMPPrivateDecl = isOpenMPPrivateDecl(
19228 Var, RSI->OpenMPLevel, RSI->OpenMPCaptureLevel);
19229 // If the variable is private (i.e. not captured) and has variably
19230 // modified type, we still need to capture the type for correct
19231 // codegen in all regions, associated with the construct. Currently,
19232 // it is captured in the innermost captured region only.
19233 if (IsOpenMPPrivateDecl != OMPC_unknown &&
19234 Var->getType()->isVariablyModifiedType()) {
19235 QualType QTy = Var->getType();
19236 if (ParmVarDecl *PVD = dyn_cast_or_null<ParmVarDecl>(Var))
19237 QTy = PVD->getOriginalType();
19238 for (int I = 1, E = getNumberOfConstructScopes(RSI->OpenMPLevel);
19239 I < E; ++I) {
19240 auto *OuterRSI = cast<CapturedRegionScopeInfo>(
19241 FunctionScopes[FunctionScopesIndex - I]);
19242 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", 19244, __extension__ __PRETTY_FUNCTION__
))
19243 "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", 19244, __extension__ __PRETTY_FUNCTION__
))
19244 "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", 19244, __extension__ __PRETTY_FUNCTION__
))
;
19245 captureVariablyModifiedType(Context, QTy, OuterRSI);
19246 }
19247 }
19248 bool IsTargetCap =
19249 IsOpenMPPrivateDecl != OMPC_private &&
19250 isOpenMPTargetCapturedDecl(Var, RSI->OpenMPLevel,
19251 RSI->OpenMPCaptureLevel);
19252 // Do not capture global if it is not privatized in outer regions.
19253 bool IsGlobalCap =
19254 IsGlobal && isOpenMPGlobalCapturedDecl(Var, RSI->OpenMPLevel,
19255 RSI->OpenMPCaptureLevel);
19256
19257 // When we detect target captures we are looking from inside the
19258 // target region, therefore we need to propagate the capture from the
19259 // enclosing region. Therefore, the capture is not initially nested.
19260 if (IsTargetCap)
19261 adjustOpenMPTargetScopeIndex(FunctionScopesIndex, RSI->OpenMPLevel);
19262
19263 if (IsTargetCap || IsOpenMPPrivateDecl == OMPC_private ||
19264 (IsGlobal && !IsGlobalCap)) {
19265 Nested = !IsTargetCap;
19266 bool HasConst = DeclRefType.isConstQualified();
19267 DeclRefType = DeclRefType.getUnqualifiedType();
19268 // Don't lose diagnostics about assignments to const.
19269 if (HasConst)
19270 DeclRefType.addConst();
19271 CaptureType = Context.getLValueReferenceType(DeclRefType);
19272 break;
19273 }
19274 }
19275 }
19276 }
19277 if (CSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_None && !Explicit) {
19278 // No capture-default, and this is not an explicit capture
19279 // so cannot capture this variable.
19280 if (BuildAndDiagnose) {
19281 Diag(ExprLoc, diag::err_lambda_impcap) << Var;
19282 Diag(Var->getLocation(), diag::note_previous_decl) << Var;
19283 auto *LSI = cast<LambdaScopeInfo>(CSI);
19284 if (LSI->Lambda) {
19285 Diag(LSI->Lambda->getBeginLoc(), diag::note_lambda_decl);
19286 buildLambdaCaptureFixit(*this, LSI, Var);
19287 }
19288 // FIXME: If we error out because an outer lambda can not implicitly
19289 // capture a variable that an inner lambda explicitly captures, we
19290 // should have the inner lambda do the explicit capture - because
19291 // it makes for cleaner diagnostics later. This would purely be done
19292 // so that the diagnostic does not misleadingly claim that a variable
19293 // can not be captured by a lambda implicitly even though it is captured
19294 // explicitly. Suggestion:
19295 // - create const bool VariableCaptureWasInitiallyExplicit = Explicit
19296 // at the function head
19297 // - cache the StartingDeclContext - this must be a lambda
19298 // - captureInLambda in the innermost lambda the variable.
19299 }
19300 return true;
19301 }
19302 Explicit = false;
19303 FunctionScopesIndex--;
19304 if (IsInScopeDeclarationContext)
19305 DC = ParentDC;
19306 } while (!VarDC->Equals(DC));
19307
19308 // Walk back down the scope stack, (e.g. from outer lambda to inner lambda)
19309 // computing the type of the capture at each step, checking type-specific
19310 // requirements, and adding captures if requested.
19311 // If the variable had already been captured previously, we start capturing
19312 // at the lambda nested within that one.
19313 bool Invalid = false;
19314 for (unsigned I = ++FunctionScopesIndex, N = MaxFunctionScopesIndex + 1; I != N;
19315 ++I) {
19316 CapturingScopeInfo *CSI = cast<CapturingScopeInfo>(FunctionScopes[I]);
19317
19318 // Certain capturing entities (lambdas, blocks etc.) are not allowed to capture
19319 // certain types of variables (unnamed, variably modified types etc.)
19320 // so check for eligibility.
19321 if (!Invalid)
19322 Invalid =
19323 !isVariableCapturable(CSI, Var, ExprLoc, BuildAndDiagnose, *this);
19324
19325 // After encountering an error, if we're actually supposed to capture, keep
19326 // capturing in nested contexts to suppress any follow-on diagnostics.
19327 if (Invalid && !BuildAndDiagnose)
19328 return true;
19329
19330 if (BlockScopeInfo *BSI = dyn_cast<BlockScopeInfo>(CSI)) {
19331 Invalid = !captureInBlock(BSI, Var, ExprLoc, BuildAndDiagnose, CaptureType,
19332 DeclRefType, Nested, *this, Invalid);
19333 Nested = true;
19334 } else if (CapturedRegionScopeInfo *RSI = dyn_cast<CapturedRegionScopeInfo>(CSI)) {
19335 Invalid = !captureInCapturedRegion(
19336 RSI, Var, ExprLoc, BuildAndDiagnose, CaptureType, DeclRefType, Nested,
19337 Kind, /*IsTopScope*/ I == N - 1, *this, Invalid);
19338 Nested = true;
19339 } else {
19340 LambdaScopeInfo *LSI = cast<LambdaScopeInfo>(CSI);
19341 Invalid =
19342 !captureInLambda(LSI, Var, ExprLoc, BuildAndDiagnose, CaptureType,
19343 DeclRefType, Nested, Kind, EllipsisLoc,
19344 /*IsTopScope*/ I == N - 1, *this, Invalid);
19345 Nested = true;
19346 }
19347
19348 if (Invalid && !BuildAndDiagnose)
19349 return true;
19350 }
19351 return Invalid;
19352}
19353
19354bool Sema::tryCaptureVariable(ValueDecl *Var, SourceLocation Loc,
19355 TryCaptureKind Kind, SourceLocation EllipsisLoc) {
19356 QualType CaptureType;
19357 QualType DeclRefType;
19358 return tryCaptureVariable(Var, Loc, Kind, EllipsisLoc,
19359 /*BuildAndDiagnose=*/true, CaptureType,
19360 DeclRefType, nullptr);
19361}
19362
19363bool Sema::NeedToCaptureVariable(ValueDecl *Var, SourceLocation Loc) {
19364 QualType CaptureType;
19365 QualType DeclRefType;
19366 return !tryCaptureVariable(Var, Loc, TryCapture_Implicit, SourceLocation(),
19367 /*BuildAndDiagnose=*/false, CaptureType,
19368 DeclRefType, nullptr);
19369}
19370
19371QualType Sema::getCapturedDeclRefType(ValueDecl *Var, SourceLocation Loc) {
19372 QualType CaptureType;
19373 QualType DeclRefType;
19374
19375 // Determine whether we can capture this variable.
19376 if (tryCaptureVariable(Var, Loc, TryCapture_Implicit, SourceLocation(),
19377 /*BuildAndDiagnose=*/false, CaptureType,
19378 DeclRefType, nullptr))
19379 return QualType();
19380
19381 return DeclRefType;
19382}
19383
19384namespace {
19385// Helper to copy the template arguments from a DeclRefExpr or MemberExpr.
19386// The produced TemplateArgumentListInfo* points to data stored within this
19387// object, so should only be used in contexts where the pointer will not be
19388// used after the CopiedTemplateArgs object is destroyed.
19389class CopiedTemplateArgs {
19390 bool HasArgs;
19391 TemplateArgumentListInfo TemplateArgStorage;
19392public:
19393 template<typename RefExpr>
19394 CopiedTemplateArgs(RefExpr *E) : HasArgs(E->hasExplicitTemplateArgs()) {
19395 if (HasArgs)
19396 E->copyTemplateArgumentsInto(TemplateArgStorage);
19397 }
19398 operator TemplateArgumentListInfo*()
19399#ifdef __has_cpp_attribute
19400#if0 __has_cpp_attribute(clang::lifetimebound)1
19401 [[clang::lifetimebound]]
19402#endif
19403#endif
19404 {
19405 return HasArgs ? &TemplateArgStorage : nullptr;
19406 }
19407};
19408}
19409
19410/// Walk the set of potential results of an expression and mark them all as
19411/// non-odr-uses if they satisfy the side-conditions of the NonOdrUseReason.
19412///
19413/// \return A new expression if we found any potential results, ExprEmpty() if
19414/// not, and ExprError() if we diagnosed an error.
19415static ExprResult rebuildPotentialResultsAsNonOdrUsed(Sema &S, Expr *E,
19416 NonOdrUseReason NOUR) {
19417 // Per C++11 [basic.def.odr], a variable is odr-used "unless it is
19418 // an object that satisfies the requirements for appearing in a
19419 // constant expression (5.19) and the lvalue-to-rvalue conversion (4.1)
19420 // is immediately applied." This function handles the lvalue-to-rvalue
19421 // conversion part.
19422 //
19423 // If we encounter a node that claims to be an odr-use but shouldn't be, we
19424 // transform it into the relevant kind of non-odr-use node and rebuild the
19425 // tree of nodes leading to it.
19426 //
19427 // This is a mini-TreeTransform that only transforms a restricted subset of
19428 // nodes (and only certain operands of them).
19429
19430 // Rebuild a subexpression.
19431 auto Rebuild = [&](Expr *Sub) {
19432 return rebuildPotentialResultsAsNonOdrUsed(S, Sub, NOUR);
19433 };
19434
19435 // Check whether a potential result satisfies the requirements of NOUR.
19436 auto IsPotentialResultOdrUsed = [&](NamedDecl *D) {
19437 // Any entity other than a VarDecl is always odr-used whenever it's named
19438 // in a potentially-evaluated expression.
19439 auto *VD = dyn_cast<VarDecl>(D);
19440 if (!VD)
19441 return true;
19442
19443 // C++2a [basic.def.odr]p4:
19444 // A variable x whose name appears as a potentially-evalauted expression
19445 // e is odr-used by e unless
19446 // -- x is a reference that is usable in constant expressions, or
19447 // -- x is a variable of non-reference type that is usable in constant
19448 // expressions and has no mutable subobjects, and e is an element of
19449 // the set of potential results of an expression of
19450 // non-volatile-qualified non-class type to which the lvalue-to-rvalue
19451 // conversion is applied, or
19452 // -- x is a variable of non-reference type, and e is an element of the
19453 // set of potential results of a discarded-value expression to which
19454 // the lvalue-to-rvalue conversion is not applied
19455 //
19456 // We check the first bullet and the "potentially-evaluated" condition in
19457 // BuildDeclRefExpr. We check the type requirements in the second bullet
19458 // in CheckLValueToRValueConversionOperand below.
19459 switch (NOUR) {
19460 case NOUR_None:
19461 case NOUR_Unevaluated:
19462 llvm_unreachable("unexpected non-odr-use-reason")::llvm::llvm_unreachable_internal("unexpected non-odr-use-reason"
, "clang/lib/Sema/SemaExpr.cpp", 19462)
;
19463
19464 case NOUR_Constant:
19465 // Constant references were handled when they were built.
19466 if (VD->getType()->isReferenceType())
19467 return true;
19468 if (auto *RD = VD->getType()->getAsCXXRecordDecl())
19469 if (RD->hasMutableFields())
19470 return true;
19471 if (!VD->isUsableInConstantExpressions(S.Context))
19472 return true;
19473 break;
19474
19475 case NOUR_Discarded:
19476 if (VD->getType()->isReferenceType())
19477 return true;
19478 break;
19479 }
19480 return false;
19481 };
19482
19483 // Mark that this expression does not constitute an odr-use.
19484 auto MarkNotOdrUsed = [&] {
19485 S.MaybeODRUseExprs.remove(E);
19486 if (LambdaScopeInfo *LSI = S.getCurLambda())
19487 LSI->markVariableExprAsNonODRUsed(E);
19488 };
19489
19490 // C++2a [basic.def.odr]p2:
19491 // The set of potential results of an expression e is defined as follows:
19492 switch (E->getStmtClass()) {
19493 // -- If e is an id-expression, ...
19494 case Expr::DeclRefExprClass: {
19495 auto *DRE = cast<DeclRefExpr>(E);
19496 if (DRE->isNonOdrUse() || IsPotentialResultOdrUsed(DRE->getDecl()))
19497 break;
19498
19499 // Rebuild as a non-odr-use DeclRefExpr.
19500 MarkNotOdrUsed();
19501 return DeclRefExpr::Create(
19502 S.Context, DRE->getQualifierLoc(), DRE->getTemplateKeywordLoc(),
19503 DRE->getDecl(), DRE->refersToEnclosingVariableOrCapture(),
19504 DRE->getNameInfo(), DRE->getType(), DRE->getValueKind(),
19505 DRE->getFoundDecl(), CopiedTemplateArgs(DRE), NOUR);
19506 }
19507
19508 case Expr::FunctionParmPackExprClass: {
19509 auto *FPPE = cast<FunctionParmPackExpr>(E);
19510 // If any of the declarations in the pack is odr-used, then the expression
19511 // as a whole constitutes an odr-use.
19512 for (VarDecl *D : *FPPE)
19513 if (IsPotentialResultOdrUsed(D))
19514 return ExprEmpty();
19515
19516 // FIXME: Rebuild as a non-odr-use FunctionParmPackExpr? In practice,
19517 // nothing cares about whether we marked this as an odr-use, but it might
19518 // be useful for non-compiler tools.
19519 MarkNotOdrUsed();
19520 break;
19521 }
19522
19523 // -- If e is a subscripting operation with an array operand...
19524 case Expr::ArraySubscriptExprClass: {
19525 auto *ASE = cast<ArraySubscriptExpr>(E);
19526 Expr *OldBase = ASE->getBase()->IgnoreImplicit();
19527 if (!OldBase->getType()->isArrayType())
19528 break;
19529 ExprResult Base = Rebuild(OldBase);
19530 if (!Base.isUsable())
19531 return Base;
19532 Expr *LHS = ASE->getBase() == ASE->getLHS() ? Base.get() : ASE->getLHS();
19533 Expr *RHS = ASE->getBase() == ASE->getRHS() ? Base.get() : ASE->getRHS();
19534 SourceLocation LBracketLoc = ASE->getBeginLoc(); // FIXME: Not stored.
19535 return S.ActOnArraySubscriptExpr(nullptr, LHS, LBracketLoc, RHS,
19536 ASE->getRBracketLoc());
19537 }
19538
19539 case Expr::MemberExprClass: {
19540 auto *ME = cast<MemberExpr>(E);
19541 // -- If e is a class member access expression [...] naming a non-static
19542 // data member...
19543 if (isa<FieldDecl>(ME->getMemberDecl())) {
19544 ExprResult Base = Rebuild(ME->getBase());
19545 if (!Base.isUsable())
19546 return Base;
19547 return MemberExpr::Create(
19548 S.Context, Base.get(), ME->isArrow(), ME->getOperatorLoc(),
19549 ME->getQualifierLoc(), ME->getTemplateKeywordLoc(),
19550 ME->getMemberDecl(), ME->getFoundDecl(), ME->getMemberNameInfo(),
19551 CopiedTemplateArgs(ME), ME->getType(), ME->getValueKind(),
19552 ME->getObjectKind(), ME->isNonOdrUse());
19553 }
19554
19555 if (ME->getMemberDecl()->isCXXInstanceMember())
19556 break;
19557
19558 // -- If e is a class member access expression naming a static data member,
19559 // ...
19560 if (ME->isNonOdrUse() || IsPotentialResultOdrUsed(ME->getMemberDecl()))
19561 break;
19562
19563 // Rebuild as a non-odr-use MemberExpr.
19564 MarkNotOdrUsed();
19565 return MemberExpr::Create(
19566 S.Context, ME->getBase(), ME->isArrow(), ME->getOperatorLoc(),
19567 ME->getQualifierLoc(), ME->getTemplateKeywordLoc(), ME->getMemberDecl(),
19568 ME->getFoundDecl(), ME->getMemberNameInfo(), CopiedTemplateArgs(ME),
19569 ME->getType(), ME->getValueKind(), ME->getObjectKind(), NOUR);
19570 }
19571
19572 case Expr::BinaryOperatorClass: {
19573 auto *BO = cast<BinaryOperator>(E);
19574 Expr *LHS = BO->getLHS();
19575 Expr *RHS = BO->getRHS();
19576 // -- If e is a pointer-to-member expression of the form e1 .* e2 ...
19577 if (BO->getOpcode() == BO_PtrMemD) {
19578 ExprResult Sub = Rebuild(LHS);
19579 if (!Sub.isUsable())
19580 return Sub;
19581 LHS = Sub.get();
19582 // -- If e is a comma expression, ...
19583 } else if (BO->getOpcode() == BO_Comma) {
19584 ExprResult Sub = Rebuild(RHS);
19585 if (!Sub.isUsable())
19586 return Sub;
19587 RHS = Sub.get();
19588 } else {
19589 break;
19590 }
19591 return S.BuildBinOp(nullptr, BO->getOperatorLoc(), BO->getOpcode(),
19592 LHS, RHS);
19593 }
19594
19595 // -- If e has the form (e1)...
19596 case Expr::ParenExprClass: {
19597 auto *PE = cast<ParenExpr>(E);
19598 ExprResult Sub = Rebuild(PE->getSubExpr());
19599 if (!Sub.isUsable())
19600 return Sub;
19601 return S.ActOnParenExpr(PE->getLParen(), PE->getRParen(), Sub.get());
19602 }
19603
19604 // -- If e is a glvalue conditional expression, ...
19605 // We don't apply this to a binary conditional operator. FIXME: Should we?
19606 case Expr::ConditionalOperatorClass: {
19607 auto *CO = cast<ConditionalOperator>(E);
19608 ExprResult LHS = Rebuild(CO->getLHS());
19609 if (LHS.isInvalid())
19610 return ExprError();
19611 ExprResult RHS = Rebuild(CO->getRHS());
19612 if (RHS.isInvalid())
19613 return ExprError();
19614 if (!LHS.isUsable() && !RHS.isUsable())
19615 return ExprEmpty();
19616 if (!LHS.isUsable())
19617 LHS = CO->getLHS();
19618 if (!RHS.isUsable())
19619 RHS = CO->getRHS();
19620 return S.ActOnConditionalOp(CO->getQuestionLoc(), CO->getColonLoc(),
19621 CO->getCond(), LHS.get(), RHS.get());
19622 }
19623
19624 // [Clang extension]
19625 // -- If e has the form __extension__ e1...
19626 case Expr::UnaryOperatorClass: {
19627 auto *UO = cast<UnaryOperator>(E);
19628 if (UO->getOpcode() != UO_Extension)
19629 break;
19630 ExprResult Sub = Rebuild(UO->getSubExpr());
19631 if (!Sub.isUsable())
19632 return Sub;
19633 return S.BuildUnaryOp(nullptr, UO->getOperatorLoc(), UO_Extension,
19634 Sub.get());
19635 }
19636
19637 // [Clang extension]
19638 // -- If e has the form _Generic(...), the set of potential results is the
19639 // union of the sets of potential results of the associated expressions.
19640 case Expr::GenericSelectionExprClass: {
19641 auto *GSE = cast<GenericSelectionExpr>(E);
19642
19643 SmallVector<Expr *, 4> AssocExprs;
19644 bool AnyChanged = false;
19645 for (Expr *OrigAssocExpr : GSE->getAssocExprs()) {
19646 ExprResult AssocExpr = Rebuild(OrigAssocExpr);
19647 if (AssocExpr.isInvalid())
19648 return ExprError();
19649 if (AssocExpr.isUsable()) {
19650 AssocExprs.push_back(AssocExpr.get());
19651 AnyChanged = true;
19652 } else {
19653 AssocExprs.push_back(OrigAssocExpr);
19654 }
19655 }
19656
19657 return AnyChanged ? S.CreateGenericSelectionExpr(
19658 GSE->getGenericLoc(), GSE->getDefaultLoc(),
19659 GSE->getRParenLoc(), GSE->getControllingExpr(),
19660 GSE->getAssocTypeSourceInfos(), AssocExprs)
19661 : ExprEmpty();
19662 }
19663
19664 // [Clang extension]
19665 // -- If e has the form __builtin_choose_expr(...), the set of potential
19666 // results is the union of the sets of potential results of the
19667 // second and third subexpressions.
19668 case Expr::ChooseExprClass: {
19669 auto *CE = cast<ChooseExpr>(E);
19670
19671 ExprResult LHS = Rebuild(CE->getLHS());
19672 if (LHS.isInvalid())
19673 return ExprError();
19674
19675 ExprResult RHS = Rebuild(CE->getLHS());
19676 if (RHS.isInvalid())
19677 return ExprError();
19678
19679 if (!LHS.get() && !RHS.get())
19680 return ExprEmpty();
19681 if (!LHS.isUsable())
19682 LHS = CE->getLHS();
19683 if (!RHS.isUsable())
19684 RHS = CE->getRHS();
19685
19686 return S.ActOnChooseExpr(CE->getBuiltinLoc(), CE->getCond(), LHS.get(),
19687 RHS.get(), CE->getRParenLoc());
19688 }
19689
19690 // Step through non-syntactic nodes.
19691 case Expr::ConstantExprClass: {
19692 auto *CE = cast<ConstantExpr>(E);
19693 ExprResult Sub = Rebuild(CE->getSubExpr());
19694 if (!Sub.isUsable())
19695 return Sub;
19696 return ConstantExpr::Create(S.Context, Sub.get());
19697 }
19698
19699 // We could mostly rely on the recursive rebuilding to rebuild implicit
19700 // casts, but not at the top level, so rebuild them here.
19701 case Expr::ImplicitCastExprClass: {
19702 auto *ICE = cast<ImplicitCastExpr>(E);
19703 // Only step through the narrow set of cast kinds we expect to encounter.
19704 // Anything else suggests we've left the region in which potential results
19705 // can be found.
19706 switch (ICE->getCastKind()) {
19707 case CK_NoOp:
19708 case CK_DerivedToBase:
19709 case CK_UncheckedDerivedToBase: {
19710 ExprResult Sub = Rebuild(ICE->getSubExpr());
19711 if (!Sub.isUsable())
19712 return Sub;
19713 CXXCastPath Path(ICE->path());
19714 return S.ImpCastExprToType(Sub.get(), ICE->getType(), ICE->getCastKind(),
19715 ICE->getValueKind(), &Path);
19716 }
19717
19718 default:
19719 break;
19720 }
19721 break;
19722 }
19723
19724 default:
19725 break;
19726 }
19727
19728 // Can't traverse through this node. Nothing to do.
19729 return ExprEmpty();
19730}
19731
19732ExprResult Sema::CheckLValueToRValueConversionOperand(Expr *E) {
19733 // Check whether the operand is or contains an object of non-trivial C union
19734 // type.
19735 if (E->getType().isVolatileQualified() &&
19736 (E->getType().hasNonTrivialToPrimitiveDestructCUnion() ||
19737 E->getType().hasNonTrivialToPrimitiveCopyCUnion()))
19738 checkNonTrivialCUnion(E->getType(), E->getExprLoc(),
19739 Sema::NTCUC_LValueToRValueVolatile,
19740 NTCUK_Destruct|NTCUK_Copy);
19741
19742 // C++2a [basic.def.odr]p4:
19743 // [...] an expression of non-volatile-qualified non-class type to which
19744 // the lvalue-to-rvalue conversion is applied [...]
19745 if (E->getType().isVolatileQualified() || E->getType()->getAs<RecordType>())
19746 return E;
19747
19748 ExprResult Result =
19749 rebuildPotentialResultsAsNonOdrUsed(*this, E, NOUR_Constant);
19750 if (Result.isInvalid())
19751 return ExprError();
19752 return Result.get() ? Result : E;
19753}
19754
19755ExprResult Sema::ActOnConstantExpression(ExprResult Res) {
19756 Res = CorrectDelayedTyposInExpr(Res);
19757
19758 if (!Res.isUsable())
19759 return Res;
19760
19761 // If a constant-expression is a reference to a variable where we delay
19762 // deciding whether it is an odr-use, just assume we will apply the
19763 // lvalue-to-rvalue conversion. In the one case where this doesn't happen
19764 // (a non-type template argument), we have special handling anyway.
19765 return CheckLValueToRValueConversionOperand(Res.get());
19766}
19767
19768void Sema::CleanupVarDeclMarking() {
19769 // Iterate through a local copy in case MarkVarDeclODRUsed makes a recursive
19770 // call.
19771 MaybeODRUseExprSet LocalMaybeODRUseExprs;
19772 std::swap(LocalMaybeODRUseExprs, MaybeODRUseExprs);
19773
19774 for (Expr *E : LocalMaybeODRUseExprs) {
19775 if (auto *DRE = dyn_cast<DeclRefExpr>(E)) {
19776 MarkVarDeclODRUsed(cast<VarDecl>(DRE->getDecl()),
19777 DRE->getLocation(), *this);
19778 } else if (auto *ME = dyn_cast<MemberExpr>(E)) {
19779 MarkVarDeclODRUsed(cast<VarDecl>(ME->getMemberDecl()), ME->getMemberLoc(),
19780 *this);
19781 } else if (auto *FP = dyn_cast<FunctionParmPackExpr>(E)) {
19782 for (VarDecl *VD : *FP)
19783 MarkVarDeclODRUsed(VD, FP->getParameterPackLocation(), *this);
19784 } else {
19785 llvm_unreachable("Unexpected expression")::llvm::llvm_unreachable_internal("Unexpected expression", "clang/lib/Sema/SemaExpr.cpp"
, 19785)
;
19786 }
19787 }
19788
19789 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", 19790, __extension__ __PRETTY_FUNCTION__
))
19790 "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", 19790, __extension__ __PRETTY_FUNCTION__
))
;
19791}
19792
19793static void DoMarkPotentialCapture(Sema &SemaRef, SourceLocation Loc,
19794 ValueDecl *Var, Expr *E) {
19795 VarDecl *VD = Var->getPotentiallyDecomposedVarDecl();
19796 if (!VD)
19797 return;
19798
19799 const bool RefersToEnclosingScope =
19800 (SemaRef.CurContext != VD->getDeclContext() &&
19801 VD->getDeclContext()->isFunctionOrMethod() && VD->hasLocalStorage());
19802 if (RefersToEnclosingScope) {
19803 LambdaScopeInfo *const LSI =
19804 SemaRef.getCurLambda(/*IgnoreNonLambdaCapturingScope=*/true);
19805 if (LSI && (!LSI->CallOperator ||
19806 !LSI->CallOperator->Encloses(Var->getDeclContext()))) {
19807 // If a variable could potentially be odr-used, defer marking it so
19808 // until we finish analyzing the full expression for any
19809 // lvalue-to-rvalue
19810 // or discarded value conversions that would obviate odr-use.
19811 // Add it to the list of potential captures that will be analyzed
19812 // later (ActOnFinishFullExpr) for eventual capture and odr-use marking
19813 // unless the variable is a reference that was initialized by a constant
19814 // expression (this will never need to be captured or odr-used).
19815 //
19816 // FIXME: We can simplify this a lot after implementing P0588R1.
19817 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", 19817, __extension__ __PRETTY_FUNCTION__
))
;
19818 if (!Var->getType()->isReferenceType() ||
19819 !VD->isUsableInConstantExpressions(SemaRef.Context))
19820 LSI->addPotentialCapture(E->IgnoreParens());
19821 }
19822 }
19823}
19824
19825static void DoMarkVarDeclReferenced(
19826 Sema &SemaRef, SourceLocation Loc, VarDecl *Var, Expr *E,
19827 llvm::DenseMap<const VarDecl *, int> &RefsMinusAssignments) {
19828 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", 19830, __extension__ __PRETTY_FUNCTION__
))
19829 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", 19830, __extension__ __PRETTY_FUNCTION__
))
19830 "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", 19830, __extension__ __PRETTY_FUNCTION__
))
;
19831 Var->setReferenced();
19832
19833 if (Var->isInvalidDecl())
19834 return;
19835
19836 auto *MSI = Var->getMemberSpecializationInfo();
19837 TemplateSpecializationKind TSK = MSI ? MSI->getTemplateSpecializationKind()
19838 : Var->getTemplateSpecializationKind();
19839
19840 OdrUseContext OdrUse = isOdrUseContext(SemaRef);
19841 bool UsableInConstantExpr =
19842 Var->mightBeUsableInConstantExpressions(SemaRef.Context);
19843
19844 if (Var->isLocalVarDeclOrParm() && !Var->hasExternalStorage()) {
19845 RefsMinusAssignments.insert({Var, 0}).first->getSecond()++;
19846 }
19847
19848 // C++20 [expr.const]p12:
19849 // A variable [...] is needed for constant evaluation if it is [...] a
19850 // variable whose name appears as a potentially constant evaluated
19851 // expression that is either a contexpr variable or is of non-volatile
19852 // const-qualified integral type or of reference type
19853 bool NeededForConstantEvaluation =
19854 isPotentiallyConstantEvaluatedContext(SemaRef) && UsableInConstantExpr;
19855
19856 bool NeedDefinition =
19857 OdrUse == OdrUseContext::Used || NeededForConstantEvaluation;
19858
19859 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", 19860, __extension__ __PRETTY_FUNCTION__
))
19860 "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", 19860, __extension__ __PRETTY_FUNCTION__
))
;
19861
19862 // If this might be a member specialization of a static data member, check
19863 // the specialization is visible. We already did the checks for variable
19864 // template specializations when we created them.
19865 if (NeedDefinition && TSK != TSK_Undeclared &&
19866 !isa<VarTemplateSpecializationDecl>(Var))
19867 SemaRef.checkSpecializationVisibility(Loc, Var);
19868
19869 // Perform implicit instantiation of static data members, static data member
19870 // templates of class templates, and variable template specializations. Delay
19871 // instantiations of variable templates, except for those that could be used
19872 // in a constant expression.
19873 if (NeedDefinition && isTemplateInstantiation(TSK)) {
19874 // Per C++17 [temp.explicit]p10, we may instantiate despite an explicit
19875 // instantiation declaration if a variable is usable in a constant
19876 // expression (among other cases).
19877 bool TryInstantiating =
19878 TSK == TSK_ImplicitInstantiation ||
19879 (TSK == TSK_ExplicitInstantiationDeclaration && UsableInConstantExpr);
19880
19881 if (TryInstantiating) {
19882 SourceLocation PointOfInstantiation =
19883 MSI ? MSI->getPointOfInstantiation() : Var->getPointOfInstantiation();
19884 bool FirstInstantiation = PointOfInstantiation.isInvalid();
19885 if (FirstInstantiation) {
19886 PointOfInstantiation = Loc;
19887 if (MSI)
19888 MSI->setPointOfInstantiation(PointOfInstantiation);
19889 // FIXME: Notify listener.
19890 else
19891 Var->setTemplateSpecializationKind(TSK, PointOfInstantiation);
19892 }
19893
19894 if (UsableInConstantExpr) {
19895 // Do not defer instantiations of variables that could be used in a
19896 // constant expression.
19897 SemaRef.runWithSufficientStackSpace(PointOfInstantiation, [&] {
19898 SemaRef.InstantiateVariableDefinition(PointOfInstantiation, Var);
19899 });
19900
19901 // Re-set the member to trigger a recomputation of the dependence bits
19902 // for the expression.
19903 if (auto *DRE = dyn_cast_or_null<DeclRefExpr>(E))
19904 DRE->setDecl(DRE->getDecl());
19905 else if (auto *ME = dyn_cast_or_null<MemberExpr>(E))
19906 ME->setMemberDecl(ME->getMemberDecl());
19907 } else if (FirstInstantiation) {
19908 SemaRef.PendingInstantiations
19909 .push_back(std::make_pair(Var, PointOfInstantiation));
19910 } else {
19911 bool Inserted = false;
19912 for (auto &I : SemaRef.SavedPendingInstantiations) {
19913 auto Iter = llvm::find_if(
19914 I, [Var](const Sema::PendingImplicitInstantiation &P) {
19915 return P.first == Var;
19916 });
19917 if (Iter != I.end()) {
19918 SemaRef.PendingInstantiations.push_back(*Iter);
19919 I.erase(Iter);
19920 Inserted = true;
19921 break;
19922 }
19923 }
19924
19925 // FIXME: For a specialization of a variable template, we don't
19926 // distinguish between "declaration and type implicitly instantiated"
19927 // and "implicit instantiation of definition requested", so we have
19928 // no direct way to avoid enqueueing the pending instantiation
19929 // multiple times.
19930 if (isa<VarTemplateSpecializationDecl>(Var) && !Inserted)
19931 SemaRef.PendingInstantiations
19932 .push_back(std::make_pair(Var, PointOfInstantiation));
19933 }
19934 }
19935 }
19936
19937 // C++2a [basic.def.odr]p4:
19938 // A variable x whose name appears as a potentially-evaluated expression e
19939 // is odr-used by e unless
19940 // -- x is a reference that is usable in constant expressions
19941 // -- x is a variable of non-reference type that is usable in constant
19942 // expressions and has no mutable subobjects [FIXME], and e is an
19943 // element of the set of potential results of an expression of
19944 // non-volatile-qualified non-class type to which the lvalue-to-rvalue
19945 // conversion is applied
19946 // -- x is a variable of non-reference type, and e is an element of the set
19947 // of potential results of a discarded-value expression to which the
19948 // lvalue-to-rvalue conversion is not applied [FIXME]
19949 //
19950 // We check the first part of the second bullet here, and
19951 // Sema::CheckLValueToRValueConversionOperand deals with the second part.
19952 // FIXME: To get the third bullet right, we need to delay this even for
19953 // variables that are not usable in constant expressions.
19954
19955 // If we already know this isn't an odr-use, there's nothing more to do.
19956 if (DeclRefExpr *DRE = dyn_cast_or_null<DeclRefExpr>(E))
19957 if (DRE->isNonOdrUse())
19958 return;
19959 if (MemberExpr *ME = dyn_cast_or_null<MemberExpr>(E))
19960 if (ME->isNonOdrUse())
19961 return;
19962
19963 switch (OdrUse) {
19964 case OdrUseContext::None:
19965 // In some cases, a variable may not have been marked unevaluated, if it
19966 // appears in a defaukt initializer.
19967 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", 19969, __extension__ __PRETTY_FUNCTION__
))
19968 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", 19969, __extension__ __PRETTY_FUNCTION__
))
19969 "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", 19969, __extension__ __PRETTY_FUNCTION__
))
;
19970 break;
19971
19972 case OdrUseContext::FormallyOdrUsed:
19973 // FIXME: Ignoring formal odr-uses results in incorrect lambda capture
19974 // behavior.
19975 break;
19976
19977 case OdrUseContext::Used:
19978 // If we might later find that this expression isn't actually an odr-use,
19979 // delay the marking.
19980 if (E && Var->isUsableInConstantExpressions(SemaRef.Context))
19981 SemaRef.MaybeODRUseExprs.insert(E);
19982 else
19983 MarkVarDeclODRUsed(Var, Loc, SemaRef);
19984 break;
19985
19986 case OdrUseContext::Dependent:
19987 // If this is a dependent context, we don't need to mark variables as
19988 // odr-used, but we may still need to track them for lambda capture.
19989 // FIXME: Do we also need to do this inside dependent typeid expressions
19990 // (which are modeled as unevaluated at this point)?
19991 DoMarkPotentialCapture(SemaRef, Loc, Var, E);
19992 break;
19993 }
19994}
19995
19996static void DoMarkBindingDeclReferenced(Sema &SemaRef, SourceLocation Loc,
19997 BindingDecl *BD, Expr *E) {
19998 BD->setReferenced();
19999
20000 if (BD->isInvalidDecl())
20001 return;
20002
20003 OdrUseContext OdrUse = isOdrUseContext(SemaRef);
20004 if (OdrUse == OdrUseContext::Used) {
20005 QualType CaptureType, DeclRefType;
20006 SemaRef.tryCaptureVariable(BD, Loc, Sema::TryCapture_Implicit,
20007 /*EllipsisLoc*/ SourceLocation(),
20008 /*BuildAndDiagnose*/ true, CaptureType,
20009 DeclRefType,
20010 /*FunctionScopeIndexToStopAt*/ nullptr);
20011 } else if (OdrUse == OdrUseContext::Dependent) {
20012 DoMarkPotentialCapture(SemaRef, Loc, BD, E);
20013 }
20014}
20015
20016/// Mark a variable referenced, and check whether it is odr-used
20017/// (C++ [basic.def.odr]p2, C99 6.9p3). Note that this should not be
20018/// used directly for normal expressions referring to VarDecl.
20019void Sema::MarkVariableReferenced(SourceLocation Loc, VarDecl *Var) {
20020 DoMarkVarDeclReferenced(*this, Loc, Var, nullptr, RefsMinusAssignments);
20021}
20022
20023static void
20024MarkExprReferenced(Sema &SemaRef, SourceLocation Loc, Decl *D, Expr *E,
20025 bool MightBeOdrUse,
20026 llvm::DenseMap<const VarDecl *, int> &RefsMinusAssignments) {
20027 if (SemaRef.isInOpenMPDeclareTargetContext())
20028 SemaRef.checkDeclIsAllowedInOpenMPTarget(E, D);
20029
20030 if (VarDecl *Var = dyn_cast<VarDecl>(D)) {
20031 DoMarkVarDeclReferenced(SemaRef, Loc, Var, E, RefsMinusAssignments);
20032 return;
20033 }
20034
20035 if (BindingDecl *Decl = dyn_cast<BindingDecl>(D)) {
20036 DoMarkBindingDeclReferenced(SemaRef, Loc, Decl, E);
20037 return;
20038 }
20039
20040 SemaRef.MarkAnyDeclReferenced(Loc, D, MightBeOdrUse);
20041
20042 // If this is a call to a method via a cast, also mark the method in the
20043 // derived class used in case codegen can devirtualize the call.
20044 const MemberExpr *ME = dyn_cast<MemberExpr>(E);
20045 if (!ME)
20046 return;
20047 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ME->getMemberDecl());
20048 if (!MD)
20049 return;
20050 // Only attempt to devirtualize if this is truly a virtual call.
20051 bool IsVirtualCall = MD->isVirtual() &&
20052 ME->performsVirtualDispatch(SemaRef.getLangOpts());
20053 if (!IsVirtualCall)
20054 return;
20055
20056 // If it's possible to devirtualize the call, mark the called function
20057 // referenced.
20058 CXXMethodDecl *DM = MD->getDevirtualizedMethod(
20059 ME->getBase(), SemaRef.getLangOpts().AppleKext);
20060 if (DM)
20061 SemaRef.MarkAnyDeclReferenced(Loc, DM, MightBeOdrUse);
20062}
20063
20064/// Perform reference-marking and odr-use handling for a DeclRefExpr.
20065///
20066/// Note, this may change the dependence of the DeclRefExpr, and so needs to be
20067/// handled with care if the DeclRefExpr is not newly-created.
20068void Sema::MarkDeclRefReferenced(DeclRefExpr *E, const Expr *Base) {
20069 // TODO: update this with DR# once a defect report is filed.
20070 // C++11 defect. The address of a pure member should not be an ODR use, even
20071 // if it's a qualified reference.
20072 bool OdrUse = true;
20073 if (const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(E->getDecl()))
20074 if (Method->isVirtual() &&
20075 !Method->getDevirtualizedMethod(Base, getLangOpts().AppleKext))
20076 OdrUse = false;
20077
20078 if (auto *FD = dyn_cast<FunctionDecl>(E->getDecl()))
20079 if (!isUnevaluatedContext() && !isConstantEvaluated() &&
20080 !isImmediateFunctionContext() &&
20081 !isCheckingDefaultArgumentOrInitializer() && FD->isConsteval() &&
20082 !RebuildingImmediateInvocation && !FD->isDependentContext())
20083 ExprEvalContexts.back().ReferenceToConsteval.insert(E);
20084 MarkExprReferenced(*this, E->getLocation(), E->getDecl(), E, OdrUse,
20085 RefsMinusAssignments);
20086}
20087
20088/// Perform reference-marking and odr-use handling for a MemberExpr.
20089void Sema::MarkMemberReferenced(MemberExpr *E) {
20090 // C++11 [basic.def.odr]p2:
20091 // A non-overloaded function whose name appears as a potentially-evaluated
20092 // expression or a member of a set of candidate functions, if selected by
20093 // overload resolution when referred to from a potentially-evaluated
20094 // expression, is odr-used, unless it is a pure virtual function and its
20095 // name is not explicitly qualified.
20096 bool MightBeOdrUse = true;
20097 if (E->performsVirtualDispatch(getLangOpts())) {
20098 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(E->getMemberDecl()))
20099 if (Method->isPure())
20100 MightBeOdrUse = false;
20101 }
20102 SourceLocation Loc =
20103 E->getMemberLoc().isValid() ? E->getMemberLoc() : E->getBeginLoc();
20104 MarkExprReferenced(*this, Loc, E->getMemberDecl(), E, MightBeOdrUse,
20105 RefsMinusAssignments);
20106}
20107
20108/// Perform reference-marking and odr-use handling for a FunctionParmPackExpr.
20109void Sema::MarkFunctionParmPackReferenced(FunctionParmPackExpr *E) {
20110 for (VarDecl *VD : *E)
20111 MarkExprReferenced(*this, E->getParameterPackLocation(), VD, E, true,
20112 RefsMinusAssignments);
20113}
20114
20115/// Perform marking for a reference to an arbitrary declaration. It
20116/// marks the declaration referenced, and performs odr-use checking for
20117/// functions and variables. This method should not be used when building a
20118/// normal expression which refers to a variable.
20119void Sema::MarkAnyDeclReferenced(SourceLocation Loc, Decl *D,
20120 bool MightBeOdrUse) {
20121 if (MightBeOdrUse) {
20122 if (auto *VD = dyn_cast<VarDecl>(D)) {
20123 MarkVariableReferenced(Loc, VD);
20124 return;
20125 }
20126 }
20127 if (auto *FD = dyn_cast<FunctionDecl>(D)) {
20128 MarkFunctionReferenced(Loc, FD, MightBeOdrUse);
20129 return;
20130 }
20131 D->setReferenced();
20132}
20133
20134namespace {
20135 // Mark all of the declarations used by a type as referenced.
20136 // FIXME: Not fully implemented yet! We need to have a better understanding
20137 // of when we're entering a context we should not recurse into.
20138 // FIXME: This is and EvaluatedExprMarker are more-or-less equivalent to
20139 // TreeTransforms rebuilding the type in a new context. Rather than
20140 // duplicating the TreeTransform logic, we should consider reusing it here.
20141 // Currently that causes problems when rebuilding LambdaExprs.
20142 class MarkReferencedDecls : public RecursiveASTVisitor<MarkReferencedDecls> {
20143 Sema &S;
20144 SourceLocation Loc;
20145
20146 public:
20147 typedef RecursiveASTVisitor<MarkReferencedDecls> Inherited;
20148
20149 MarkReferencedDecls(Sema &S, SourceLocation Loc) : S(S), Loc(Loc) { }
20150
20151 bool TraverseTemplateArgument(const TemplateArgument &Arg);
20152 };
20153}
20154
20155bool MarkReferencedDecls::TraverseTemplateArgument(
20156 const TemplateArgument &Arg) {
20157 {
20158 // A non-type template argument is a constant-evaluated context.
20159 EnterExpressionEvaluationContext Evaluated(
20160 S, Sema::ExpressionEvaluationContext::ConstantEvaluated);
20161 if (Arg.getKind() == TemplateArgument::Declaration) {
20162 if (Decl *D = Arg.getAsDecl())
20163 S.MarkAnyDeclReferenced(Loc, D, true);
20164 } else if (Arg.getKind() == TemplateArgument::Expression) {
20165 S.MarkDeclarationsReferencedInExpr(Arg.getAsExpr(), false);
20166 }
20167 }
20168
20169 return Inherited::TraverseTemplateArgument(Arg);
20170}
20171
20172void Sema::MarkDeclarationsReferencedInType(SourceLocation Loc, QualType T) {
20173 MarkReferencedDecls Marker(*this, Loc);
20174 Marker.TraverseType(T);
20175}
20176
20177namespace {
20178/// Helper class that marks all of the declarations referenced by
20179/// potentially-evaluated subexpressions as "referenced".
20180class EvaluatedExprMarker : public UsedDeclVisitor<EvaluatedExprMarker> {
20181public:
20182 typedef UsedDeclVisitor<EvaluatedExprMarker> Inherited;
20183 bool SkipLocalVariables;
20184 ArrayRef<const Expr *> StopAt;
20185
20186 EvaluatedExprMarker(Sema &S, bool SkipLocalVariables,
20187 ArrayRef<const Expr *> StopAt)
20188 : Inherited(S), SkipLocalVariables(SkipLocalVariables), StopAt(StopAt) {}
20189
20190 void visitUsedDecl(SourceLocation Loc, Decl *D) {
20191 S.MarkFunctionReferenced(Loc, cast<FunctionDecl>(D));
20192 }
20193
20194 void Visit(Expr *E) {
20195 if (llvm::is_contained(StopAt, E))
20196 return;
20197 Inherited::Visit(E);
20198 }
20199
20200 void VisitConstantExpr(ConstantExpr *E) {
20201 // Don't mark declarations within a ConstantExpression, as this expression
20202 // will be evaluated and folded to a value.
20203 }
20204
20205 void VisitDeclRefExpr(DeclRefExpr *E) {
20206 // If we were asked not to visit local variables, don't.
20207 if (SkipLocalVariables) {
20208 if (VarDecl *VD = dyn_cast<VarDecl>(E->getDecl()))
20209 if (VD->hasLocalStorage())
20210 return;
20211 }
20212
20213 // FIXME: This can trigger the instantiation of the initializer of a
20214 // variable, which can cause the expression to become value-dependent
20215 // or error-dependent. Do we need to propagate the new dependence bits?
20216 S.MarkDeclRefReferenced(E);
20217 }
20218
20219 void VisitMemberExpr(MemberExpr *E) {
20220 S.MarkMemberReferenced(E);
20221 Visit(E->getBase());
20222 }
20223};
20224} // namespace
20225
20226/// Mark any declarations that appear within this expression or any
20227/// potentially-evaluated subexpressions as "referenced".
20228///
20229/// \param SkipLocalVariables If true, don't mark local variables as
20230/// 'referenced'.
20231/// \param StopAt Subexpressions that we shouldn't recurse into.
20232void Sema::MarkDeclarationsReferencedInExpr(Expr *E,
20233 bool SkipLocalVariables,
20234 ArrayRef<const Expr*> StopAt) {
20235 EvaluatedExprMarker(*this, SkipLocalVariables, StopAt).Visit(E);
20236}
20237
20238/// Emit a diagnostic when statements are reachable.
20239/// FIXME: check for reachability even in expressions for which we don't build a
20240/// CFG (eg, in the initializer of a global or in a constant expression).
20241/// For example,
20242/// namespace { auto *p = new double[3][false ? (1, 2) : 3]; }
20243bool Sema::DiagIfReachable(SourceLocation Loc, ArrayRef<const Stmt *> Stmts,
20244 const PartialDiagnostic &PD) {
20245 if (!Stmts.empty() && getCurFunctionOrMethodDecl()) {
20246 if (!FunctionScopes.empty())
20247 FunctionScopes.back()->PossiblyUnreachableDiags.push_back(
20248 sema::PossiblyUnreachableDiag(PD, Loc, Stmts));
20249 return true;
20250 }
20251
20252 // The initializer of a constexpr variable or of the first declaration of a
20253 // static data member is not syntactically a constant evaluated constant,
20254 // but nonetheless is always required to be a constant expression, so we
20255 // can skip diagnosing.
20256 // FIXME: Using the mangling context here is a hack.
20257 if (auto *VD = dyn_cast_or_null<VarDecl>(
20258 ExprEvalContexts.back().ManglingContextDecl)) {
20259 if (VD->isConstexpr() ||
20260 (VD->isStaticDataMember() && VD->isFirstDecl() && !VD->isInline()))
20261 return false;
20262 // FIXME: For any other kind of variable, we should build a CFG for its
20263 // initializer and check whether the context in question is reachable.
20264 }
20265
20266 Diag(Loc, PD);
20267 return true;
20268}
20269
20270/// Emit a diagnostic that describes an effect on the run-time behavior
20271/// of the program being compiled.
20272///
20273/// This routine emits the given diagnostic when the code currently being
20274/// type-checked is "potentially evaluated", meaning that there is a
20275/// possibility that the code will actually be executable. Code in sizeof()
20276/// expressions, code used only during overload resolution, etc., are not
20277/// potentially evaluated. This routine will suppress such diagnostics or,
20278/// in the absolutely nutty case of potentially potentially evaluated
20279/// expressions (C++ typeid), queue the diagnostic to potentially emit it
20280/// later.
20281///
20282/// This routine should be used for all diagnostics that describe the run-time
20283/// behavior of a program, such as passing a non-POD value through an ellipsis.
20284/// Failure to do so will likely result in spurious diagnostics or failures
20285/// during overload resolution or within sizeof/alignof/typeof/typeid.
20286bool Sema::DiagRuntimeBehavior(SourceLocation Loc, ArrayRef<const Stmt*> Stmts,
20287 const PartialDiagnostic &PD) {
20288
20289 if (ExprEvalContexts.back().isDiscardedStatementContext())
20290 return false;
20291
20292 switch (ExprEvalContexts.back().Context) {
20293 case ExpressionEvaluationContext::Unevaluated:
20294 case ExpressionEvaluationContext::UnevaluatedList:
20295 case ExpressionEvaluationContext::UnevaluatedAbstract:
20296 case ExpressionEvaluationContext::DiscardedStatement:
20297 // The argument will never be evaluated, so don't complain.
20298 break;
20299
20300 case ExpressionEvaluationContext::ConstantEvaluated:
20301 case ExpressionEvaluationContext::ImmediateFunctionContext:
20302 // Relevant diagnostics should be produced by constant evaluation.
20303 break;
20304
20305 case ExpressionEvaluationContext::PotentiallyEvaluated:
20306 case ExpressionEvaluationContext::PotentiallyEvaluatedIfUsed:
20307 return DiagIfReachable(Loc, Stmts, PD);
20308 }
20309
20310 return false;
20311}
20312
20313bool Sema::DiagRuntimeBehavior(SourceLocation Loc, const Stmt *Statement,
20314 const PartialDiagnostic &PD) {
20315 return DiagRuntimeBehavior(
20316 Loc, Statement ? llvm::ArrayRef(Statement) : std::nullopt, PD);
20317}
20318
20319bool Sema::CheckCallReturnType(QualType ReturnType, SourceLocation Loc,
20320 CallExpr *CE, FunctionDecl *FD) {
20321 if (ReturnType->isVoidType() || !ReturnType->isIncompleteType())
20322 return false;
20323
20324 // If we're inside a decltype's expression, don't check for a valid return
20325 // type or construct temporaries until we know whether this is the last call.
20326 if (ExprEvalContexts.back().ExprContext ==
20327 ExpressionEvaluationContextRecord::EK_Decltype) {
20328 ExprEvalContexts.back().DelayedDecltypeCalls.push_back(CE);
20329 return false;
20330 }
20331
20332 class CallReturnIncompleteDiagnoser : public TypeDiagnoser {
20333 FunctionDecl *FD;
20334 CallExpr *CE;
20335
20336 public:
20337 CallReturnIncompleteDiagnoser(FunctionDecl *FD, CallExpr *CE)
20338 : FD(FD), CE(CE) { }
20339
20340 void diagnose(Sema &S, SourceLocation Loc, QualType T) override {
20341 if (!FD) {
20342 S.Diag(Loc, diag::err_call_incomplete_return)
20343 << T << CE->getSourceRange();
20344 return;
20345 }
20346
20347 S.Diag(Loc, diag::err_call_function_incomplete_return)
20348 << CE->getSourceRange() << FD << T;
20349 S.Diag(FD->getLocation(), diag::note_entity_declared_at)
20350 << FD->getDeclName();
20351 }
20352 } Diagnoser(FD, CE);
20353
20354 if (RequireCompleteType(Loc, ReturnType, Diagnoser))
20355 return true;
20356
20357 return false;
20358}
20359
20360// Diagnose the s/=/==/ and s/\|=/!=/ typos. Note that adding parentheses
20361// will prevent this condition from triggering, which is what we want.
20362void Sema::DiagnoseAssignmentAsCondition(Expr *E) {
20363 SourceLocation Loc;
20364
20365 unsigned diagnostic = diag::warn_condition_is_assignment;
20366 bool IsOrAssign = false;
20367
20368 if (BinaryOperator *Op = dyn_cast<BinaryOperator>(E)) {
20369 if (Op->getOpcode() != BO_Assign && Op->getOpcode() != BO_OrAssign)
20370 return;
20371
20372 IsOrAssign = Op->getOpcode() == BO_OrAssign;
20373
20374 // Greylist some idioms by putting them into a warning subcategory.
20375 if (ObjCMessageExpr *ME
20376 = dyn_cast<ObjCMessageExpr>(Op->getRHS()->IgnoreParenCasts())) {
20377 Selector Sel = ME->getSelector();
20378
20379 // self = [<foo> init...]
20380 if (isSelfExpr(Op->getLHS()) && ME->getMethodFamily() == OMF_init)
20381 diagnostic = diag::warn_condition_is_idiomatic_assignment;
20382
20383 // <foo> = [<bar> nextObject]
20384 else if (Sel.isUnarySelector() && Sel.getNameForSlot(0) == "nextObject")
20385 diagnostic = diag::warn_condition_is_idiomatic_assignment;
20386 }
20387
20388 Loc = Op->getOperatorLoc();
20389 } else if (CXXOperatorCallExpr *Op = dyn_cast<CXXOperatorCallExpr>(E)) {
20390 if (Op->getOperator() != OO_Equal && Op->getOperator() != OO_PipeEqual)
20391 return;
20392
20393 IsOrAssign = Op->getOperator() == OO_PipeEqual;
20394 Loc = Op->getOperatorLoc();
20395 } else if (PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(E))
20396 return DiagnoseAssignmentAsCondition(POE->getSyntacticForm());
20397 else {
20398 // Not an assignment.
20399 return;
20400 }
20401
20402 Diag(Loc, diagnostic) << E->getSourceRange();
20403
20404 SourceLocation Open = E->getBeginLoc();
20405 SourceLocation Close = getLocForEndOfToken(E->getSourceRange().getEnd());
20406 Diag(Loc, diag::note_condition_assign_silence)
20407 << FixItHint::CreateInsertion(Open, "(")
20408 << FixItHint::CreateInsertion(Close, ")");
20409
20410 if (IsOrAssign)
20411 Diag(Loc, diag::note_condition_or_assign_to_comparison)
20412 << FixItHint::CreateReplacement(Loc, "!=");
20413 else
20414 Diag(Loc, diag::note_condition_assign_to_comparison)
20415 << FixItHint::CreateReplacement(Loc, "==");
20416}
20417
20418/// Redundant parentheses over an equality comparison can indicate
20419/// that the user intended an assignment used as condition.
20420void Sema::DiagnoseEqualityWithExtraParens(ParenExpr *ParenE) {
20421 // Don't warn if the parens came from a macro.
20422 SourceLocation parenLoc = ParenE->getBeginLoc();
20423 if (parenLoc.isInvalid() || parenLoc.isMacroID())
20424 return;
20425 // Don't warn for dependent expressions.
20426 if (ParenE->isTypeDependent())
20427 return;
20428
20429 Expr *E = ParenE->IgnoreParens();
20430
20431 if (BinaryOperator *opE = dyn_cast<BinaryOperator>(E))
20432 if (opE->getOpcode() == BO_EQ &&
20433 opE->getLHS()->IgnoreParenImpCasts()->isModifiableLvalue(Context)
20434 == Expr::MLV_Valid) {
20435 SourceLocation Loc = opE->getOperatorLoc();
20436
20437 Diag(Loc, diag::warn_equality_with_extra_parens) << E->getSourceRange();
20438 SourceRange ParenERange = ParenE->getSourceRange();
20439 Diag(Loc, diag::note_equality_comparison_silence)
20440 << FixItHint::CreateRemoval(ParenERange.getBegin())
20441 << FixItHint::CreateRemoval(ParenERange.getEnd());
20442 Diag(Loc, diag::note_equality_comparison_to_assign)
20443 << FixItHint::CreateReplacement(Loc, "=");
20444 }
20445}
20446
20447ExprResult Sema::CheckBooleanCondition(SourceLocation Loc, Expr *E,
20448 bool IsConstexpr) {
20449 DiagnoseAssignmentAsCondition(E);
20450 if (ParenExpr *parenE = dyn_cast<ParenExpr>(E))
20451 DiagnoseEqualityWithExtraParens(parenE);
20452
20453 ExprResult result = CheckPlaceholderExpr(E);
20454 if (result.isInvalid()) return ExprError();
20455 E = result.get();
20456
20457 if (!E->isTypeDependent()) {
20458 if (getLangOpts().CPlusPlus)
20459 return CheckCXXBooleanCondition(E, IsConstexpr); // C++ 6.4p4
20460
20461 ExprResult ERes = DefaultFunctionArrayLvalueConversion(E);
20462 if (ERes.isInvalid())
20463 return ExprError();
20464 E = ERes.get();
20465
20466 QualType T = E->getType();
20467 if (!T->isScalarType()) { // C99 6.8.4.1p1
20468 Diag(Loc, diag::err_typecheck_statement_requires_scalar)
20469 << T << E->getSourceRange();
20470 return ExprError();
20471 }
20472 CheckBoolLikeConversion(E, Loc);
20473 }
20474
20475 return E;
20476}
20477
20478Sema::ConditionResult Sema::ActOnCondition(Scope *S, SourceLocation Loc,
20479 Expr *SubExpr, ConditionKind CK,
20480 bool MissingOK) {
20481 // MissingOK indicates whether having no condition expression is valid
20482 // (for loop) or invalid (e.g. while loop).
20483 if (!SubExpr)
20484 return MissingOK ? ConditionResult() : ConditionError();
20485
20486 ExprResult Cond;
20487 switch (CK) {
20488 case ConditionKind::Boolean:
20489 Cond = CheckBooleanCondition(Loc, SubExpr);
20490 break;
20491
20492 case ConditionKind::ConstexprIf:
20493 Cond = CheckBooleanCondition(Loc, SubExpr, true);
20494 break;
20495
20496 case ConditionKind::Switch:
20497 Cond = CheckSwitchCondition(Loc, SubExpr);
20498 break;
20499 }
20500 if (Cond.isInvalid()) {
20501 Cond = CreateRecoveryExpr(SubExpr->getBeginLoc(), SubExpr->getEndLoc(),
20502 {SubExpr}, PreferredConditionType(CK));
20503 if (!Cond.get())
20504 return ConditionError();
20505 }
20506 // FIXME: FullExprArg doesn't have an invalid bit, so check nullness instead.
20507 FullExprArg FullExpr = MakeFullExpr(Cond.get(), Loc);
20508 if (!FullExpr.get())
20509 return ConditionError();
20510
20511 return ConditionResult(*this, nullptr, FullExpr,
20512 CK == ConditionKind::ConstexprIf);
20513}
20514
20515namespace {
20516 /// A visitor for rebuilding a call to an __unknown_any expression
20517 /// to have an appropriate type.
20518 struct RebuildUnknownAnyFunction
20519 : StmtVisitor<RebuildUnknownAnyFunction, ExprResult> {
20520
20521 Sema &S;
20522
20523 RebuildUnknownAnyFunction(Sema &S) : S(S) {}
20524
20525 ExprResult VisitStmt(Stmt *S) {
20526 llvm_unreachable("unexpected statement!")::llvm::llvm_unreachable_internal("unexpected statement!", "clang/lib/Sema/SemaExpr.cpp"
, 20526)
;
20527 }
20528
20529 ExprResult VisitExpr(Expr *E) {
20530 S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_call)
20531 << E->getSourceRange();
20532 return ExprError();
20533 }
20534
20535 /// Rebuild an expression which simply semantically wraps another
20536 /// expression which it shares the type and value kind of.
20537 template <class T> ExprResult rebuildSugarExpr(T *E) {
20538 ExprResult SubResult = Visit(E->getSubExpr());
20539 if (SubResult.isInvalid()) return ExprError();
20540
20541 Expr *SubExpr = SubResult.get();
20542 E->setSubExpr(SubExpr);
20543 E->setType(SubExpr->getType());
20544 E->setValueKind(SubExpr->getValueKind());
20545 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", 20545, __extension__ __PRETTY_FUNCTION__
))
;
20546 return E;
20547 }
20548
20549 ExprResult VisitParenExpr(ParenExpr *E) {
20550 return rebuildSugarExpr(E);
20551 }
20552
20553 ExprResult VisitUnaryExtension(UnaryOperator *E) {
20554 return rebuildSugarExpr(E);
20555 }
20556
20557 ExprResult VisitUnaryAddrOf(UnaryOperator *E) {
20558 ExprResult SubResult = Visit(E->getSubExpr());
20559 if (SubResult.isInvalid()) return ExprError();
20560
20561 Expr *SubExpr = SubResult.get();
20562 E->setSubExpr(SubExpr);
20563 E->setType(S.Context.getPointerType(SubExpr->getType()));
20564 assert(E->isPRValue())(static_cast <bool> (E->isPRValue()) ? void (0) : __assert_fail
("E->isPRValue()", "clang/lib/Sema/SemaExpr.cpp", 20564, __extension__
__PRETTY_FUNCTION__))
;
20565 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", 20565, __extension__ __PRETTY_FUNCTION__
))
;
20566 return E;
20567 }
20568
20569 ExprResult resolveDecl(Expr *E, ValueDecl *VD) {
20570 if (!isa<FunctionDecl>(VD)) return VisitExpr(E);
20571
20572 E->setType(VD->getType());
20573
20574 assert(E->isPRValue())(static_cast <bool> (E->isPRValue()) ? void (0) : __assert_fail
("E->isPRValue()", "clang/lib/Sema/SemaExpr.cpp", 20574, __extension__
__PRETTY_FUNCTION__))
;
20575 if (S.getLangOpts().CPlusPlus &&
20576 !(isa<CXXMethodDecl>(VD) &&
20577 cast<CXXMethodDecl>(VD)->isInstance()))
20578 E->setValueKind(VK_LValue);
20579
20580 return E;
20581 }
20582
20583 ExprResult VisitMemberExpr(MemberExpr *E) {
20584 return resolveDecl(E, E->getMemberDecl());
20585 }
20586
20587 ExprResult VisitDeclRefExpr(DeclRefExpr *E) {
20588 return resolveDecl(E, E->getDecl());
20589 }
20590 };
20591}
20592
20593/// Given a function expression of unknown-any type, try to rebuild it
20594/// to have a function type.
20595static ExprResult rebuildUnknownAnyFunction(Sema &S, Expr *FunctionExpr) {
20596 ExprResult Result = RebuildUnknownAnyFunction(S).Visit(FunctionExpr);
20597 if (Result.isInvalid()) return ExprError();
20598 return S.DefaultFunctionArrayConversion(Result.get());
20599}
20600
20601namespace {
20602 /// A visitor for rebuilding an expression of type __unknown_anytype
20603 /// into one which resolves the type directly on the referring
20604 /// expression. Strict preservation of the original source
20605 /// structure is not a goal.
20606 struct RebuildUnknownAnyExpr
20607 : StmtVisitor<RebuildUnknownAnyExpr, ExprResult> {
20608
20609 Sema &S;
20610
20611 /// The current destination type.
20612 QualType DestType;
20613
20614 RebuildUnknownAnyExpr(Sema &S, QualType CastType)
20615 : S(S), DestType(CastType) {}
20616
20617 ExprResult VisitStmt(Stmt *S) {
20618 llvm_unreachable("unexpected statement!")::llvm::llvm_unreachable_internal("unexpected statement!", "clang/lib/Sema/SemaExpr.cpp"
, 20618)
;
20619 }
20620
20621 ExprResult VisitExpr(Expr *E) {
20622 S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_expr)
20623 << E->getSourceRange();
20624 return ExprError();
20625 }
20626
20627 ExprResult VisitCallExpr(CallExpr *E);
20628 ExprResult VisitObjCMessageExpr(ObjCMessageExpr *E);
20629
20630 /// Rebuild an expression which simply semantically wraps another
20631 /// expression which it shares the type and value kind of.
20632 template <class T> ExprResult rebuildSugarExpr(T *E) {
20633 ExprResult SubResult = Visit(E->getSubExpr());
20634 if (SubResult.isInvalid()) return ExprError();
20635 Expr *SubExpr = SubResult.get();
20636 E->setSubExpr(SubExpr);
20637 E->setType(SubExpr->getType());
20638 E->setValueKind(SubExpr->getValueKind());
20639 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", 20639, __extension__ __PRETTY_FUNCTION__
))
;
20640 return E;
20641 }
20642
20643 ExprResult VisitParenExpr(ParenExpr *E) {
20644 return rebuildSugarExpr(E);
20645 }
20646
20647 ExprResult VisitUnaryExtension(UnaryOperator *E) {
20648 return rebuildSugarExpr(E);
20649 }
20650
20651 ExprResult VisitUnaryAddrOf(UnaryOperator *E) {
20652 const PointerType *Ptr = DestType->getAs<PointerType>();
20653 if (!Ptr) {
20654 S.Diag(E->getOperatorLoc(), diag::err_unknown_any_addrof)
20655 << E->getSourceRange();
20656 return ExprError();
20657 }
20658
20659 if (isa<CallExpr>(E->getSubExpr())) {
20660 S.Diag(E->getOperatorLoc(), diag::err_unknown_any_addrof_call)
20661 << E->getSourceRange();
20662 return ExprError();
20663 }
20664
20665 assert(E->isPRValue())(static_cast <bool> (E->isPRValue()) ? void (0) : __assert_fail
("E->isPRValue()", "clang/lib/Sema/SemaExpr.cpp", 20665, __extension__
__PRETTY_FUNCTION__))
;
20666 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", 20666, __extension__ __PRETTY_FUNCTION__
))
;
20667 E->setType(DestType);
20668
20669 // Build the sub-expression as if it were an object of the pointee type.
20670 DestType = Ptr->getPointeeType();
20671 ExprResult SubResult = Visit(E->getSubExpr());
20672 if (SubResult.isInvalid()) return ExprError();
20673 E->setSubExpr(SubResult.get());
20674 return E;
20675 }
20676
20677 ExprResult VisitImplicitCastExpr(ImplicitCastExpr *E);
20678
20679 ExprResult resolveDecl(Expr *E, ValueDecl *VD);
20680
20681 ExprResult VisitMemberExpr(MemberExpr *E) {
20682 return resolveDecl(E, E->getMemberDecl());
20683 }
20684
20685 ExprResult VisitDeclRefExpr(DeclRefExpr *E) {
20686 return resolveDecl(E, E->getDecl());
20687 }
20688 };
20689}
20690
20691/// Rebuilds a call expression which yielded __unknown_anytype.
20692ExprResult RebuildUnknownAnyExpr::VisitCallExpr(CallExpr *E) {
20693 Expr *CalleeExpr = E->getCallee();
20694
20695 enum FnKind {
20696 FK_MemberFunction,
20697 FK_FunctionPointer,
20698 FK_BlockPointer
20699 };
20700
20701 FnKind Kind;
20702 QualType CalleeType = CalleeExpr->getType();
20703 if (CalleeType == S.Context.BoundMemberTy) {
20704 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", 20704, __extension__ __PRETTY_FUNCTION__
))
;
20705 Kind = FK_MemberFunction;
20706 CalleeType = Expr::findBoundMemberType(CalleeExpr);
20707 } else if (const PointerType *Ptr = CalleeType->getAs<PointerType>()) {
20708 CalleeType = Ptr->getPointeeType();
20709 Kind = FK_FunctionPointer;
20710 } else {
20711 CalleeType = CalleeType->castAs<BlockPointerType>()->getPointeeType();
20712 Kind = FK_BlockPointer;
20713 }
20714 const FunctionType *FnType = CalleeType->castAs<FunctionType>();
20715
20716 // Verify that this is a legal result type of a function.
20717 if (DestType->isArrayType() || DestType->isFunctionType()) {
20718 unsigned diagID = diag::err_func_returning_array_function;
20719 if (Kind == FK_BlockPointer)
20720 diagID = diag::err_block_returning_array_function;
20721
20722 S.Diag(E->getExprLoc(), diagID)
20723 << DestType->isFunctionType() << DestType;
20724 return ExprError();
20725 }
20726
20727 // Otherwise, go ahead and set DestType as the call's result.
20728 E->setType(DestType.getNonLValueExprType(S.Context));
20729 E->setValueKind(Expr::getValueKindForType(DestType));
20730 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", 20730, __extension__ __PRETTY_FUNCTION__
))
;
20731
20732 // Rebuild the function type, replacing the result type with DestType.
20733 const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FnType);
20734 if (Proto) {
20735 // __unknown_anytype(...) is a special case used by the debugger when
20736 // it has no idea what a function's signature is.
20737 //
20738 // We want to build this call essentially under the K&R
20739 // unprototyped rules, but making a FunctionNoProtoType in C++
20740 // would foul up all sorts of assumptions. However, we cannot
20741 // simply pass all arguments as variadic arguments, nor can we
20742 // portably just call the function under a non-variadic type; see
20743 // the comment on IR-gen's TargetInfo::isNoProtoCallVariadic.
20744 // However, it turns out that in practice it is generally safe to
20745 // call a function declared as "A foo(B,C,D);" under the prototype
20746 // "A foo(B,C,D,...);". The only known exception is with the
20747 // Windows ABI, where any variadic function is implicitly cdecl
20748 // regardless of its normal CC. Therefore we change the parameter
20749 // types to match the types of the arguments.
20750 //
20751 // This is a hack, but it is far superior to moving the
20752 // corresponding target-specific code from IR-gen to Sema/AST.
20753
20754 ArrayRef<QualType> ParamTypes = Proto->getParamTypes();
20755 SmallVector<QualType, 8> ArgTypes;
20756 if (ParamTypes.empty() && Proto->isVariadic()) { // the special case
20757 ArgTypes.reserve(E->getNumArgs());
20758 for (unsigned i = 0, e = E->getNumArgs(); i != e; ++i) {
20759 ArgTypes.push_back(S.Context.getReferenceQualifiedType(E->getArg(i)));
20760 }
20761 ParamTypes = ArgTypes;
20762 }
20763 DestType = S.Context.getFunctionType(DestType, ParamTypes,
20764 Proto->getExtProtoInfo());
20765 } else {
20766 DestType = S.Context.getFunctionNoProtoType(DestType,
20767 FnType->getExtInfo());
20768 }
20769
20770 // Rebuild the appropriate pointer-to-function type.
20771 switch (Kind) {
20772 case FK_MemberFunction:
20773 // Nothing to do.
20774 break;
20775
20776 case FK_FunctionPointer:
20777 DestType = S.Context.getPointerType(DestType);
20778 break;
20779
20780 case FK_BlockPointer:
20781 DestType = S.Context.getBlockPointerType(DestType);
20782 break;
20783 }
20784
20785 // Finally, we can recurse.
20786 ExprResult CalleeResult = Visit(CalleeExpr);
20787 if (!CalleeResult.isUsable()) return ExprError();
20788 E->setCallee(CalleeResult.get());
20789
20790 // Bind a temporary if necessary.
20791 return S.MaybeBindToTemporary(E);
20792}
20793
20794ExprResult RebuildUnknownAnyExpr::VisitObjCMessageExpr(ObjCMessageExpr *E) {
20795 // Verify that this is a legal result type of a call.
20796 if (DestType->isArrayType() || DestType->isFunctionType()) {
20797 S.Diag(E->getExprLoc(), diag::err_func_returning_array_function)
20798 << DestType->isFunctionType() << DestType;
20799 return ExprError();
20800 }
20801
20802 // Rewrite the method result type if available.
20803 if (ObjCMethodDecl *Method = E->getMethodDecl()) {
20804 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", 20804, __extension__ __PRETTY_FUNCTION__
))
;
20805 Method->setReturnType(DestType);
20806 }
20807
20808 // Change the type of the message.
20809 E->setType(DestType.getNonReferenceType());
20810 E->setValueKind(Expr::getValueKindForType(DestType));
20811
20812 return S.MaybeBindToTemporary(E);
20813}
20814
20815ExprResult RebuildUnknownAnyExpr::VisitImplicitCastExpr(ImplicitCastExpr *E) {
20816 // The only case we should ever see here is a function-to-pointer decay.
20817 if (E->getCastKind() == CK_FunctionToPointerDecay) {
20818 assert(E->isPRValue())(static_cast <bool> (E->isPRValue()) ? void (0) : __assert_fail
("E->isPRValue()", "clang/lib/Sema/SemaExpr.cpp", 20818, __extension__
__PRETTY_FUNCTION__))
;
20819 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", 20819, __extension__ __PRETTY_FUNCTION__
))
;
20820
20821 E->setType(DestType);
20822
20823 // Rebuild the sub-expression as the pointee (function) type.
20824 DestType = DestType->castAs<PointerType>()->getPointeeType();
20825
20826 ExprResult Result = Visit(E->getSubExpr());
20827 if (!Result.isUsable()) return ExprError();
20828
20829 E->setSubExpr(Result.get());
20830 return E;
20831 } else if (E->getCastKind() == CK_LValueToRValue) {
20832 assert(E->isPRValue())(static_cast <bool> (E->isPRValue()) ? void (0) : __assert_fail
("E->isPRValue()", "clang/lib/Sema/SemaExpr.cpp", 20832, __extension__
__PRETTY_FUNCTION__))
;
20833 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", 20833, __extension__ __PRETTY_FUNCTION__
))
;
20834
20835 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", 20835, __extension__ __PRETTY_FUNCTION__
))
;
20836
20837 E->setType(DestType);
20838
20839 // The sub-expression has to be a lvalue reference, so rebuild it as such.
20840 DestType = S.Context.getLValueReferenceType(DestType);
20841
20842 ExprResult Result = Visit(E->getSubExpr());
20843 if (!Result.isUsable()) return ExprError();
20844
20845 E->setSubExpr(Result.get());
20846 return E;
20847 } else {
20848 llvm_unreachable("Unhandled cast type!")::llvm::llvm_unreachable_internal("Unhandled cast type!", "clang/lib/Sema/SemaExpr.cpp"
, 20848)
;
20849 }
20850}
20851
20852ExprResult RebuildUnknownAnyExpr::resolveDecl(Expr *E, ValueDecl *VD) {
20853 ExprValueKind ValueKind = VK_LValue;
20854 QualType Type = DestType;
20855
20856 // We know how to make this work for certain kinds of decls:
20857
20858 // - functions
20859 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(VD)) {
20860 if (const PointerType *Ptr = Type->getAs<PointerType>()) {
20861 DestType = Ptr->getPointeeType();
20862 ExprResult Result = resolveDecl(E, VD);
20863 if (Result.isInvalid()) return ExprError();
20864 return S.ImpCastExprToType(Result.get(), Type, CK_FunctionToPointerDecay,
20865 VK_PRValue);
20866 }
20867
20868 if (!Type->isFunctionType()) {
20869 S.Diag(E->getExprLoc(), diag::err_unknown_any_function)
20870 << VD << E->getSourceRange();
20871 return ExprError();
20872 }
20873 if (const FunctionProtoType *FT = Type->getAs<FunctionProtoType>()) {
20874 // We must match the FunctionDecl's type to the hack introduced in
20875 // RebuildUnknownAnyExpr::VisitCallExpr to vararg functions of unknown
20876 // type. See the lengthy commentary in that routine.
20877 QualType FDT = FD->getType();
20878 const FunctionType *FnType = FDT->castAs<FunctionType>();
20879 const FunctionProtoType *Proto = dyn_cast_or_null<FunctionProtoType>(FnType);
20880 DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E);
20881 if (DRE && Proto && Proto->getParamTypes().empty() && Proto->isVariadic()) {
20882 SourceLocation Loc = FD->getLocation();
20883 FunctionDecl *NewFD = FunctionDecl::Create(
20884 S.Context, FD->getDeclContext(), Loc, Loc,
20885 FD->getNameInfo().getName(), DestType, FD->getTypeSourceInfo(),
20886 SC_None, S.getCurFPFeatures().isFPConstrained(),
20887 false /*isInlineSpecified*/, FD->hasPrototype(),
20888 /*ConstexprKind*/ ConstexprSpecKind::Unspecified);
20889
20890 if (FD->getQualifier())
20891 NewFD->setQualifierInfo(FD->getQualifierLoc());
20892
20893 SmallVector<ParmVarDecl*, 16> Params;
20894 for (const auto &AI : FT->param_types()) {
20895 ParmVarDecl *Param =
20896 S.BuildParmVarDeclForTypedef(FD, Loc, AI);
20897 Param->setScopeInfo(0, Params.size());
20898 Params.push_back(Param);
20899 }
20900 NewFD->setParams(Params);
20901 DRE->setDecl(NewFD);
20902 VD = DRE->getDecl();
20903 }
20904 }
20905
20906 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD))
20907 if (MD->isInstance()) {
20908 ValueKind = VK_PRValue;
20909 Type = S.Context.BoundMemberTy;
20910 }
20911
20912 // Function references aren't l-values in C.
20913 if (!S.getLangOpts().CPlusPlus)
20914 ValueKind = VK_PRValue;
20915
20916 // - variables
20917 } else if (isa<VarDecl>(VD)) {
20918 if (const ReferenceType *RefTy = Type->getAs<ReferenceType>()) {
20919 Type = RefTy->getPointeeType();
20920 } else if (Type->isFunctionType()) {
20921 S.Diag(E->getExprLoc(), diag::err_unknown_any_var_function_type)
20922 << VD << E->getSourceRange();
20923 return ExprError();
20924 }
20925
20926 // - nothing else
20927 } else {
20928 S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_decl)
20929 << VD << E->getSourceRange();
20930 return ExprError();
20931 }
20932
20933 // Modifying the declaration like this is friendly to IR-gen but
20934 // also really dangerous.
20935 VD->setType(DestType);
20936 E->setType(Type);
20937 E->setValueKind(ValueKind);
20938 return E;
20939}
20940
20941/// Check a cast of an unknown-any type. We intentionally only
20942/// trigger this for C-style casts.
20943ExprResult Sema::checkUnknownAnyCast(SourceRange TypeRange, QualType CastType,
20944 Expr *CastExpr, CastKind &CastKind,
20945 ExprValueKind &VK, CXXCastPath &Path) {
20946 // The type we're casting to must be either void or complete.
20947 if (!CastType->isVoidType() &&
20948 RequireCompleteType(TypeRange.getBegin(), CastType,
20949 diag::err_typecheck_cast_to_incomplete))
20950 return ExprError();
20951
20952 // Rewrite the casted expression from scratch.
20953 ExprResult result = RebuildUnknownAnyExpr(*this, CastType).Visit(CastExpr);
20954 if (!result.isUsable()) return ExprError();
20955
20956 CastExpr = result.get();
20957 VK = CastExpr->getValueKind();
20958 CastKind = CK_NoOp;
20959
20960 return CastExpr;
20961}
20962
20963ExprResult Sema::forceUnknownAnyToType(Expr *E, QualType ToType) {
20964 return RebuildUnknownAnyExpr(*this, ToType).Visit(E);
20965}
20966
20967ExprResult Sema::checkUnknownAnyArg(SourceLocation callLoc,
20968 Expr *arg, QualType &paramType) {
20969 // If the syntactic form of the argument is not an explicit cast of
20970 // any sort, just do default argument promotion.
20971 ExplicitCastExpr *castArg = dyn_cast<ExplicitCastExpr>(arg->IgnoreParens());
20972 if (!castArg) {
20973 ExprResult result = DefaultArgumentPromotion(arg);
20974 if (result.isInvalid()) return ExprError();
20975 paramType = result.get()->getType();
20976 return result;
20977 }
20978
20979 // Otherwise, use the type that was written in the explicit cast.
20980 assert(!arg->hasPlaceholderType())(static_cast <bool> (!arg->hasPlaceholderType()) ? void
(0) : __assert_fail ("!arg->hasPlaceholderType()", "clang/lib/Sema/SemaExpr.cpp"
, 20980, __extension__ __PRETTY_FUNCTION__))
;
20981 paramType = castArg->getTypeAsWritten();
20982
20983 // Copy-initialize a parameter of that type.
20984 InitializedEntity entity =
20985 InitializedEntity::InitializeParameter(Context, paramType,
20986 /*consumed*/ false);
20987 return PerformCopyInitialization(entity, callLoc, arg);
20988}
20989
20990static ExprResult diagnoseUnknownAnyExpr(Sema &S, Expr *E) {
20991 Expr *orig = E;
20992 unsigned diagID = diag::err_uncasted_use_of_unknown_any;
20993 while (true) {
20994 E = E->IgnoreParenImpCasts();
20995 if (CallExpr *call = dyn_cast<CallExpr>(E)) {
20996 E = call->getCallee();
20997 diagID = diag::err_uncasted_call_of_unknown_any;
20998 } else {
20999 break;
21000 }
21001 }
21002
21003 SourceLocation loc;
21004 NamedDecl *d;
21005 if (DeclRefExpr *ref = dyn_cast<DeclRefExpr>(E)) {
21006 loc = ref->getLocation();
21007 d = ref->getDecl();
21008 } else if (MemberExpr *mem = dyn_cast<MemberExpr>(E)) {
21009 loc = mem->getMemberLoc();
21010 d = mem->getMemberDecl();
21011 } else if (ObjCMessageExpr *msg = dyn_cast<ObjCMessageExpr>(E)) {
21012 diagID = diag::err_uncasted_call_of_unknown_any;
21013 loc = msg->getSelectorStartLoc();
21014 d = msg->getMethodDecl();
21015 if (!d) {
21016 S.Diag(loc, diag::err_uncasted_send_to_unknown_any_method)
21017 << static_cast<unsigned>(msg->isClassMessage()) << msg->getSelector()
21018 << orig->getSourceRange();
21019 return ExprError();
21020 }
21021 } else {
21022 S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_expr)
21023 << E->getSourceRange();
21024 return ExprError();
21025 }
21026
21027 S.Diag(loc, diagID) << d << orig->getSourceRange();
21028
21029 // Never recoverable.
21030 return ExprError();
21031}
21032
21033/// Check for operands with placeholder types and complain if found.
21034/// Returns ExprError() if there was an error and no recovery was possible.
21035ExprResult Sema::CheckPlaceholderExpr(Expr *E) {
21036 if (!Context.isDependenceAllowed()) {
21037 // C cannot handle TypoExpr nodes on either side of a binop because it
21038 // doesn't handle dependent types properly, so make sure any TypoExprs have
21039 // been dealt with before checking the operands.
21040 ExprResult Result = CorrectDelayedTyposInExpr(E);
21041 if (!Result.isUsable()) return ExprError();
21042 E = Result.get();
21043 }
21044
21045 const BuiltinType *placeholderType = E->getType()->getAsPlaceholderType();
21046 if (!placeholderType) return E;
21047
21048 switch (placeholderType->getKind()) {
21049
21050 // Overloaded expressions.
21051 case BuiltinType::Overload: {
21052 // Try to resolve a single function template specialization.
21053 // This is obligatory.
21054 ExprResult Result = E;
21055 if (ResolveAndFixSingleFunctionTemplateSpecialization(Result, false))
21056 return Result;
21057
21058 // No guarantees that ResolveAndFixSingleFunctionTemplateSpecialization
21059 // leaves Result unchanged on failure.
21060 Result = E;
21061 if (resolveAndFixAddressOfSingleOverloadCandidate(Result))
21062 return Result;
21063
21064 // If that failed, try to recover with a call.
21065 tryToRecoverWithCall(Result, PDiag(diag::err_ovl_unresolvable),
21066 /*complain*/ true);
21067 return Result;
21068 }
21069
21070 // Bound member functions.
21071 case BuiltinType::BoundMember: {
21072 ExprResult result = E;
21073 const Expr *BME = E->IgnoreParens();
21074 PartialDiagnostic PD = PDiag(diag::err_bound_member_function);
21075 // Try to give a nicer diagnostic if it is a bound member that we recognize.
21076 if (isa<CXXPseudoDestructorExpr>(BME)) {
21077 PD = PDiag(diag::err_dtor_expr_without_call) << /*pseudo-destructor*/ 1;
21078 } else if (const auto *ME = dyn_cast<MemberExpr>(BME)) {
21079 if (ME->getMemberNameInfo().getName().getNameKind() ==
21080 DeclarationName::CXXDestructorName)
21081 PD = PDiag(diag::err_dtor_expr_without_call) << /*destructor*/ 0;
21082 }
21083 tryToRecoverWithCall(result, PD,
21084 /*complain*/ true);
21085 return result;
21086 }
21087
21088 // ARC unbridged casts.
21089 case BuiltinType::ARCUnbridgedCast: {
21090 Expr *realCast = stripARCUnbridgedCast(E);
21091 diagnoseARCUnbridgedCast(realCast);
21092 return realCast;
21093 }
21094
21095 // Expressions of unknown type.
21096 case BuiltinType::UnknownAny:
21097 return diagnoseUnknownAnyExpr(*this, E);
21098
21099 // Pseudo-objects.
21100 case BuiltinType::PseudoObject:
21101 return checkPseudoObjectRValue(E);
21102
21103 case BuiltinType::BuiltinFn: {
21104 // Accept __noop without parens by implicitly converting it to a call expr.
21105 auto *DRE = dyn_cast<DeclRefExpr>(E->IgnoreParenImpCasts());
21106 if (DRE) {
21107 auto *FD = cast<FunctionDecl>(DRE->getDecl());
21108 unsigned BuiltinID = FD->getBuiltinID();
21109 if (BuiltinID == Builtin::BI__noop) {
21110 E = ImpCastExprToType(E, Context.getPointerType(FD->getType()),
21111 CK_BuiltinFnToFnPtr)
21112 .get();
21113 return CallExpr::Create(Context, E, /*Args=*/{}, Context.IntTy,
21114 VK_PRValue, SourceLocation(),
21115 FPOptionsOverride());
21116 }
21117
21118 if (Context.BuiltinInfo.isInStdNamespace(BuiltinID)) {
21119 // Any use of these other than a direct call is ill-formed as of C++20,
21120 // because they are not addressable functions. In earlier language
21121 // modes, warn and force an instantiation of the real body.
21122 Diag(E->getBeginLoc(),
21123 getLangOpts().CPlusPlus20
21124 ? diag::err_use_of_unaddressable_function
21125 : diag::warn_cxx20_compat_use_of_unaddressable_function);
21126 if (FD->isImplicitlyInstantiable()) {
21127 // Require a definition here because a normal attempt at
21128 // instantiation for a builtin will be ignored, and we won't try
21129 // again later. We assume that the definition of the template
21130 // precedes this use.
21131 InstantiateFunctionDefinition(E->getBeginLoc(), FD,
21132 /*Recursive=*/false,
21133 /*DefinitionRequired=*/true,
21134 /*AtEndOfTU=*/false);
21135 }
21136 // Produce a properly-typed reference to the function.
21137 CXXScopeSpec SS;
21138 SS.Adopt(DRE->getQualifierLoc());
21139 TemplateArgumentListInfo TemplateArgs;
21140 DRE->copyTemplateArgumentsInto(TemplateArgs);
21141 return BuildDeclRefExpr(
21142 FD, FD->getType(), VK_LValue, DRE->getNameInfo(),
21143 DRE->hasQualifier() ? &SS : nullptr, DRE->getFoundDecl(),
21144 DRE->getTemplateKeywordLoc(),
21145 DRE->hasExplicitTemplateArgs() ? &TemplateArgs : nullptr);
21146 }
21147 }
21148
21149 Diag(E->getBeginLoc(), diag::err_builtin_fn_use);
21150 return ExprError();
21151 }
21152
21153 case BuiltinType::IncompleteMatrixIdx:
21154 Diag(cast<MatrixSubscriptExpr>(E->IgnoreParens())
21155 ->getRowIdx()
21156 ->getBeginLoc(),
21157 diag::err_matrix_incomplete_index);
21158 return ExprError();
21159
21160 // Expressions of unknown type.
21161 case BuiltinType::OMPArraySection:
21162 Diag(E->getBeginLoc(), diag::err_omp_array_section_use);
21163 return ExprError();
21164
21165 // Expressions of unknown type.
21166 case BuiltinType::OMPArrayShaping:
21167 return ExprError(Diag(E->getBeginLoc(), diag::err_omp_array_shaping_use));
21168
21169 case BuiltinType::OMPIterator:
21170 return ExprError(Diag(E->getBeginLoc(), diag::err_omp_iterator_use));
21171
21172 // Everything else should be impossible.
21173#define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
21174 case BuiltinType::Id:
21175#include "clang/Basic/OpenCLImageTypes.def"
21176#define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \
21177 case BuiltinType::Id:
21178#include "clang/Basic/OpenCLExtensionTypes.def"
21179#define SVE_TYPE(Name, Id, SingletonId) \
21180 case BuiltinType::Id:
21181#include "clang/Basic/AArch64SVEACLETypes.def"
21182#define PPC_VECTOR_TYPE(Name, Id, Size) \
21183 case BuiltinType::Id:
21184#include "clang/Basic/PPCTypes.def"
21185#define RVV_TYPE(Name, Id, SingletonId) case BuiltinType::Id:
21186#include "clang/Basic/RISCVVTypes.def"
21187#define WASM_TYPE(Name, Id, SingletonId) case BuiltinType::Id:
21188#include "clang/Basic/WebAssemblyReferenceTypes.def"
21189#define BUILTIN_TYPE(Id, SingletonId) case BuiltinType::Id:
21190#define PLACEHOLDER_TYPE(Id, SingletonId)
21191#include "clang/AST/BuiltinTypes.def"
21192 break;
21193 }
21194
21195 llvm_unreachable("invalid placeholder type!")::llvm::llvm_unreachable_internal("invalid placeholder type!"
, "clang/lib/Sema/SemaExpr.cpp", 21195)
;
21196}
21197
21198bool Sema::CheckCaseExpression(Expr *E) {
21199 if (E->isTypeDependent())
21200 return true;
21201 if (E->isValueDependent() || E->isIntegerConstantExpr(Context))
21202 return E->getType()->isIntegralOrEnumerationType();
21203 return false;
21204}
21205
21206/// ActOnObjCBoolLiteral - Parse {__objc_yes,__objc_no} literals.
21207ExprResult
21208Sema::ActOnObjCBoolLiteral(SourceLocation OpLoc, tok::TokenKind Kind) {
21209 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", 21210, __extension__ __PRETTY_FUNCTION__
))
21210 "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", 21210, __extension__ __PRETTY_FUNCTION__
))
;
21211 QualType BoolT = Context.ObjCBuiltinBoolTy;
21212 if (!Context.getBOOLDecl()) {
21213 LookupResult Result(*this, &Context.Idents.get("BOOL"), OpLoc,
21214 Sema::LookupOrdinaryName);
21215 if (LookupName(Result, getCurScope()) && Result.isSingleResult()) {
21216 NamedDecl *ND = Result.getFoundDecl();
21217 if (TypedefDecl *TD = dyn_cast<TypedefDecl>(ND))
21218 Context.setBOOLDecl(TD);
21219 }
21220 }
21221 if (Context.getBOOLDecl())
21222 BoolT = Context.getBOOLType();
21223 return new (Context)
21224 ObjCBoolLiteralExpr(Kind == tok::kw___objc_yes, BoolT, OpLoc);
21225}
21226
21227ExprResult Sema::ActOnObjCAvailabilityCheckExpr(
21228 llvm::ArrayRef<AvailabilitySpec> AvailSpecs, SourceLocation AtLoc,
21229 SourceLocation RParen) {
21230 auto FindSpecVersion =
21231 [&](StringRef Platform) -> std::optional<VersionTuple> {
21232 auto Spec = llvm::find_if(AvailSpecs, [&](const AvailabilitySpec &Spec) {
21233 return Spec.getPlatform() == Platform;
21234 });
21235 // Transcribe the "ios" availability check to "maccatalyst" when compiling
21236 // for "maccatalyst" if "maccatalyst" is not specified.
21237 if (Spec == AvailSpecs.end() && Platform == "maccatalyst") {
21238 Spec = llvm::find_if(AvailSpecs, [&](const AvailabilitySpec &Spec) {
21239 return Spec.getPlatform() == "ios";
21240 });
21241 }
21242 if (Spec == AvailSpecs.end())
21243 return std::nullopt;
21244 return Spec->getVersion();
21245 };
21246
21247 VersionTuple Version;
21248 if (auto MaybeVersion =
21249 FindSpecVersion(Context.getTargetInfo().getPlatformName()))
21250 Version = *MaybeVersion;
21251
21252 // The use of `@available` in the enclosing context should be analyzed to
21253 // warn when it's used inappropriately (i.e. not if(@available)).
21254 if (FunctionScopeInfo *Context = getCurFunctionAvailabilityContext())
21255 Context->HasPotentialAvailabilityViolations = true;
21256
21257 return new (Context)
21258 ObjCAvailabilityCheckExpr(Version, AtLoc, RParen, Context.BoolTy);
21259}
21260
21261ExprResult Sema::CreateRecoveryExpr(SourceLocation Begin, SourceLocation End,
21262 ArrayRef<Expr *> SubExprs, QualType T) {
21263 if (!Context.getLangOpts().RecoveryAST)
21264 return ExprError();
21265
21266 if (isSFINAEContext())
21267 return ExprError();
21268
21269 if (T.isNull() || T->isUndeducedType() ||
21270 !Context.getLangOpts().RecoveryASTType)
21271 // We don't know the concrete type, fallback to dependent type.
21272 T = Context.DependentTy;
21273
21274 return RecoveryExpr::Create(Context, T, Begin, End, SubExprs);
21275}

/build/source/llvm/include/llvm/Support/Casting.h

1//===- llvm/Support/Casting.h - Allow flexible, checked, casts --*- C++ -*-===//
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 defines the isa<X>(), cast<X>(), dyn_cast<X>(),
10// cast_if_present<X>(), and dyn_cast_if_present<X>() templates.
11//
12//===----------------------------------------------------------------------===//
13
14#ifndef LLVM_SUPPORT_CASTING_H
15#define LLVM_SUPPORT_CASTING_H
16
17#include "llvm/Support/Compiler.h"
18#include "llvm/Support/type_traits.h"
19#include <cassert>
20#include <memory>
21#include <optional>
22#include <type_traits>
23
24namespace llvm {
25
26//===----------------------------------------------------------------------===//
27// simplify_type
28//===----------------------------------------------------------------------===//
29
30/// Define a template that can be specialized by smart pointers to reflect the
31/// fact that they are automatically dereferenced, and are not involved with the
32/// template selection process... the default implementation is a noop.
33// TODO: rename this and/or replace it with other cast traits.
34template <typename From> struct simplify_type {
35 using SimpleType = From; // The real type this represents...
36
37 // An accessor to get the real value...
38 static SimpleType &getSimplifiedValue(From &Val) { return Val; }
45
Returning without writing to 'Val', which participates in a condition later
39};
40
41template <typename From> struct simplify_type<const From> {
42 using NonConstSimpleType = typename simplify_type<From>::SimpleType;
43 using SimpleType = typename add_const_past_pointer<NonConstSimpleType>::type;
44 using RetType =
45 typename add_lvalue_reference_if_not_pointer<SimpleType>::type;
46
47 static RetType getSimplifiedValue(const From &Val) {
48 return simplify_type<From>::getSimplifiedValue(const_cast<From &>(Val));
44
Calling 'simplify_type::getSimplifiedValue'
46
Returning from 'simplify_type::getSimplifiedValue'
49 }
50};
51
52// TODO: add this namespace once everyone is switched to using the new
53// interface.
54// namespace detail {
55
56//===----------------------------------------------------------------------===//
57// isa_impl
58//===----------------------------------------------------------------------===//
59
60// The core of the implementation of isa<X> is here; To and From should be
61// the names of classes. This template can be specialized to customize the
62// implementation of isa<> without rewriting it from scratch.
63template <typename To, typename From, typename Enabler = void> struct isa_impl {
64 static inline bool doit(const From &Val) { return To::classof(&Val); }
65};
66
67// Always allow upcasts, and perform no dynamic check for them.
68template <typename To, typename From>
69struct isa_impl<To, From, std::enable_if_t<std::is_base_of<To, From>::value>> {
70 static inline bool doit(const From &) { return true; }
71};
72
73template <typename To, typename From> struct isa_impl_cl {
74 static inline bool doit(const From &Val) {
75 return isa_impl<To, From>::doit(Val);
76 }
77};
78
79template <typename To, typename From> struct isa_impl_cl<To, const From> {
80 static inline bool doit(const From &Val) {
81 return isa_impl<To, From>::doit(Val);
82 }
83};
84
85template <typename To, typename From>
86struct isa_impl_cl<To, const std::unique_ptr<From>> {
87 static inline bool doit(const std::unique_ptr<From> &Val) {
88 assert(Val && "isa<> used on a null pointer")(static_cast <bool> (Val && "isa<> used on a null pointer"
) ? void (0) : __assert_fail ("Val && \"isa<> used on a null pointer\""
, "llvm/include/llvm/Support/Casting.h", 88, __extension__ __PRETTY_FUNCTION__
))
;
89 return isa_impl_cl<To, From>::doit(*Val);
90 }
91};
92
93template <typename To, typename From> struct isa_impl_cl<To, From *> {
94 static inline bool doit(const From *Val) {
95 assert(Val && "isa<> used on a null pointer")(static_cast <bool> (Val && "isa<> used on a null pointer"
) ? void (0) : __assert_fail ("Val && \"isa<> used on a null pointer\""
, "llvm/include/llvm/Support/Casting.h", 95, __extension__ __PRETTY_FUNCTION__
))
;
96 return isa_impl<To, From>::doit(*Val);
97 }
98};
99
100template <typename To, typename From> struct isa_impl_cl<To, From *const> {
101 static inline bool doit(const From *Val) {
102 assert(Val && "isa<> used on a null pointer")(static_cast <bool> (Val && "isa<> used on a null pointer"
) ? void (0) : __assert_fail ("Val && \"isa<> used on a null pointer\""
, "llvm/include/llvm/Support/Casting.h", 102, __extension__ __PRETTY_FUNCTION__
))
;
103 return isa_impl<To, From>::doit(*Val);
104 }
105};
106
107template <typename To, typename From> struct isa_impl_cl<To, const From *> {
108 static inline bool doit(const From *Val) {
109 assert(Val && "isa<> used on a null pointer")(static_cast <bool> (Val && "isa<> used on a null pointer"
) ? void (0) : __assert_fail ("Val && \"isa<> used on a null pointer\""
, "llvm/include/llvm/Support/Casting.h", 109, __extension__ __PRETTY_FUNCTION__
))
;
50
Assuming 'Val' is non-null, which participates in a condition later
51
'?' condition is true
110 return isa_impl<To, From>::doit(*Val);
111 }
112};
113
114template <typename To, typename From>
115struct isa_impl_cl<To, const From *const> {
116 static inline bool doit(const From *Val) {
117 assert(Val && "isa<> used on a null pointer")(static_cast <bool> (Val && "isa<> used on a null pointer"
) ? void (0) : __assert_fail ("Val && \"isa<> used on a null pointer\""
, "llvm/include/llvm/Support/Casting.h", 117, __extension__ __PRETTY_FUNCTION__
))
;
118 return isa_impl<To, From>::doit(*Val);
119 }
120};
121
122template <typename To, typename From, typename SimpleFrom>
123struct isa_impl_wrap {
124 // When From != SimplifiedType, we can simplify the type some more by using
125 // the simplify_type template.
126 static bool doit(const From &Val) {
127 return isa_impl_wrap<To, SimpleFrom,
48
Calling 'isa_impl_wrap::doit'
53
Returning from 'isa_impl_wrap::doit'
128 typename simplify_type<SimpleFrom>::SimpleType>::
129 doit(simplify_type<const From>::getSimplifiedValue(Val));
43
Calling 'simplify_type::getSimplifiedValue'
47
Returning from 'simplify_type::getSimplifiedValue'
130 }
131};
132
133template <typename To, typename FromTy>
134struct isa_impl_wrap<To, FromTy, FromTy> {
135 // When From == SimpleType, we are as simple as we are going to get.
136 static bool doit(const FromTy &Val) {
137 return isa_impl_cl<To, FromTy>::doit(Val);
49
Calling 'isa_impl_cl::doit'
52
Returning from 'isa_impl_cl::doit'
138 }
139};
140
141//===----------------------------------------------------------------------===//
142// cast_retty + cast_retty_impl
143//===----------------------------------------------------------------------===//
144
145template <class To, class From> struct cast_retty;
146
147// Calculate what type the 'cast' function should return, based on a requested
148// type of To and a source type of From.
149template <class To, class From> struct cast_retty_impl {
150 using ret_type = To &; // Normal case, return Ty&
151};
152template <class To, class From> struct cast_retty_impl<To, const From> {
153 using ret_type = const To &; // Normal case, return Ty&
154};
155
156template <class To, class From> struct cast_retty_impl<To, From *> {
157 using ret_type = To *; // Pointer arg case, return Ty*
158};
159
160template <class To, class From> struct cast_retty_impl<To, const From *> {
161 using ret_type = const To *; // Constant pointer arg case, return const Ty*
162};
163
164template <class To, class From> struct cast_retty_impl<To, const From *const> {
165 using ret_type = const To *; // Constant pointer arg case, return const Ty*
166};
167
168template <class To, class From>
169struct cast_retty_impl<To, std::unique_ptr<From>> {
170private:
171 using PointerType = typename cast_retty_impl<To, From *>::ret_type;
172 using ResultType = std::remove_pointer_t<PointerType>;
173
174public:
175 using ret_type = std::unique_ptr<ResultType>;
176};
177
178template <class To, class From, class SimpleFrom> struct cast_retty_wrap {
179 // When the simplified type and the from type are not the same, use the type
180 // simplifier to reduce the type, then reuse cast_retty_impl to get the
181 // resultant type.
182 using ret_type = typename cast_retty<To, SimpleFrom>::ret_type;
183};
184
185template <class To, class FromTy> struct cast_retty_wrap<To, FromTy, FromTy> {
186 // When the simplified type is equal to the from type, use it directly.
187 using ret_type = typename cast_retty_impl<To, FromTy>::ret_type;
188};
189
190template <class To, class From> struct cast_retty {
191 using ret_type = typename cast_retty_wrap<
192 To, From, typename simplify_type<From>::SimpleType>::ret_type;
193};
194
195//===----------------------------------------------------------------------===//
196// cast_convert_val
197//===----------------------------------------------------------------------===//
198
199// Ensure the non-simple values are converted using the simplify_type template
200// that may be specialized by smart pointers...
201//
202template <class To, class From, class SimpleFrom> struct cast_convert_val {
203 // This is not a simple type, use the template to simplify it...
204 static typename cast_retty<To, From>::ret_type doit(const From &Val) {
205 return cast_convert_val<To, SimpleFrom,
206 typename simplify_type<SimpleFrom>::SimpleType>::
207 doit(simplify_type<From>::getSimplifiedValue(const_cast<From &>(Val)));
208 }
209};
210
211template <class To, class FromTy> struct cast_convert_val<To, FromTy, FromTy> {
212 // If it's a reference, switch to a pointer to do the cast and then deref it.
213 static typename cast_retty<To, FromTy>::ret_type doit(const FromTy &Val) {
214 return *(std::remove_reference_t<typename cast_retty<To, FromTy>::ret_type>
215 *)&const_cast<FromTy &>(Val);
216 }
217};
218
219template <class To, class FromTy>
220struct cast_convert_val<To, FromTy *, FromTy *> {
221 // If it's a pointer, we can use c-style casting directly.
222 static typename cast_retty<To, FromTy *>::ret_type doit(const FromTy *Val) {
223 return (typename cast_retty<To, FromTy *>::ret_type) const_cast<FromTy *>(
224 Val);
225 }
226};
227
228//===----------------------------------------------------------------------===//
229// is_simple_type
230//===----------------------------------------------------------------------===//
231
232template <class X> struct is_simple_type {
233 static const bool value =
234 std::is_same<X, typename simplify_type<X>::SimpleType>::value;
235};
236
237// } // namespace detail
238
239//===----------------------------------------------------------------------===//
240// CastIsPossible
241//===----------------------------------------------------------------------===//
242
243/// This struct provides a way to check if a given cast is possible. It provides
244/// a static function called isPossible that is used to check if a cast can be
245/// performed. It should be overridden like this:
246///
247/// template<> struct CastIsPossible<foo, bar> {
248/// static inline bool isPossible(const bar &b) {
249/// return bar.isFoo();
250/// }
251/// };
252template <typename To, typename From, typename Enable = void>
253struct CastIsPossible {
254 static inline bool isPossible(const From &f) {
255 return isa_impl_wrap<
42
Calling 'isa_impl_wrap::doit'
54
Returning from 'isa_impl_wrap::doit'
256 To, const From,
257 typename simplify_type<const From>::SimpleType>::doit(f);
258 }
259};
260
261// Needed for optional unwrapping. This could be implemented with isa_impl, but
262// we want to implement things in the new method and move old implementations
263// over. In fact, some of the isa_impl templates should be moved over to
264// CastIsPossible.
265template <typename To, typename From>
266struct CastIsPossible<To, std::optional<From>> {
267 static inline bool isPossible(const std::optional<From> &f) {
268 assert(f && "CastIsPossible::isPossible called on a nullopt!")(static_cast <bool> (f && "CastIsPossible::isPossible called on a nullopt!"
) ? void (0) : __assert_fail ("f && \"CastIsPossible::isPossible called on a nullopt!\""
, "llvm/include/llvm/Support/Casting.h", 268, __extension__ __PRETTY_FUNCTION__
))
;
269 return isa_impl_wrap<
270 To, const From,
271 typename simplify_type<const From>::SimpleType>::doit(*f);
272 }
273};
274
275/// Upcasting (from derived to base) and casting from a type to itself should
276/// always be possible.
277template <typename To, typename From>
278struct CastIsPossible<To, From,
279 std::enable_if_t<std::is_base_of<To, From>::value>> {
280 static inline bool isPossible(const From &f) { return true; }
281};
282
283//===----------------------------------------------------------------------===//
284// Cast traits
285//===----------------------------------------------------------------------===//
286
287/// All of these cast traits are meant to be implementations for useful casts
288/// that users may want to use that are outside the standard behavior. An
289/// example of how to use a special cast called `CastTrait` is:
290///
291/// template<> struct CastInfo<foo, bar> : public CastTrait<foo, bar> {};
292///
293/// Essentially, if your use case falls directly into one of the use cases
294/// supported by a given cast trait, simply inherit your special CastInfo
295/// directly from one of these to avoid having to reimplement the boilerplate
296/// `isPossible/castFailed/doCast/doCastIfPossible`. A cast trait can also
297/// provide a subset of those functions.
298
299/// This cast trait just provides castFailed for the specified `To` type to make
300/// CastInfo specializations more declarative. In order to use this, the target
301/// result type must be `To` and `To` must be constructible from `nullptr`.
302template <typename To> struct NullableValueCastFailed {
303 static To castFailed() { return To(nullptr); }
304};
305
306/// This cast trait just provides the default implementation of doCastIfPossible
307/// to make CastInfo specializations more declarative. The `Derived` template
308/// parameter *must* be provided for forwarding castFailed and doCast.
309template <typename To, typename From, typename Derived>
310struct DefaultDoCastIfPossible {
311 static To doCastIfPossible(From f) {
312 if (!Derived::isPossible(f))
313 return Derived::castFailed();
314 return Derived::doCast(f);
315 }
316};
317
318namespace detail {
319/// A helper to derive the type to use with `Self` for cast traits, when the
320/// provided CRTP derived type is allowed to be void.
321template <typename OptionalDerived, typename Default>
322using SelfType = std::conditional_t<std::is_same<OptionalDerived, void>::value,
323 Default, OptionalDerived>;
324} // namespace detail
325
326/// This cast trait provides casting for the specific case of casting to a
327/// value-typed object from a pointer-typed object. Note that `To` must be
328/// nullable/constructible from a pointer to `From` to use this cast.
329template <typename To, typename From, typename Derived = void>
330struct ValueFromPointerCast
331 : public CastIsPossible<To, From *>,
332 public NullableValueCastFailed<To>,
333 public DefaultDoCastIfPossible<
334 To, From *,
335 detail::SelfType<Derived, ValueFromPointerCast<To, From>>> {
336 static inline To doCast(From *f) { return To(f); }
337};
338
339/// This cast trait provides std::unique_ptr casting. It has the semantics of
340/// moving the contents of the input unique_ptr into the output unique_ptr
341/// during the cast. It's also a good example of how to implement a move-only
342/// cast.
343template <typename To, typename From, typename Derived = void>
344struct UniquePtrCast : public CastIsPossible<To, From *> {
345 using Self = detail::SelfType<Derived, UniquePtrCast<To, From>>;
346 using CastResultType = std::unique_ptr<
347 std::remove_reference_t<typename cast_retty<To, From>::ret_type>>;
348
349 static inline CastResultType doCast(std::unique_ptr<From> &&f) {
350 return CastResultType((typename CastResultType::element_type *)f.release());
351 }
352
353 static inline CastResultType castFailed() { return CastResultType(nullptr); }
354
355 static inline CastResultType doCastIfPossible(std::unique_ptr<From> &&f) {
356 if (!Self::isPossible(f))
357 return castFailed();
358 return doCast(f);
359 }
360};
361
362/// This cast trait provides std::optional<T> casting. This means that if you
363/// have a value type, you can cast it to another value type and have dyn_cast
364/// return an std::optional<T>.
365template <typename To, typename From, typename Derived = void>
366struct OptionalValueCast
367 : public CastIsPossible<To, From>,
368 public DefaultDoCastIfPossible<
369 std::optional<To>, From,
370 detail::SelfType<Derived, OptionalValueCast<To, From>>> {
371 static inline std::optional<To> castFailed() { return std::optional<To>{}; }
372
373 static inline std::optional<To> doCast(const From &f) { return To(f); }
374};
375
376/// Provides a cast trait that strips `const` from types to make it easier to
377/// implement a const-version of a non-const cast. It just removes boilerplate
378/// and reduces the amount of code you as the user need to implement. You can
379/// use it like this:
380///
381/// template<> struct CastInfo<foo, bar> {
382/// ...verbose implementation...
383/// };
384///
385/// template<> struct CastInfo<foo, const bar> : public
386/// ConstStrippingForwardingCast<foo, const bar, CastInfo<foo, bar>> {};
387///
388template <typename To, typename From, typename ForwardTo>
389struct ConstStrippingForwardingCast {
390 // Remove the pointer if it exists, then we can get rid of consts/volatiles.
391 using DecayedFrom = std::remove_cv_t<std::remove_pointer_t<From>>;
392 // Now if it's a pointer, add it back. Otherwise, we want a ref.
393 using NonConstFrom = std::conditional_t<std::is_pointer<From>::value,
394 DecayedFrom *, DecayedFrom &>;
395
396 static inline bool isPossible(const From &f) {
397 return ForwardTo::isPossible(const_cast<NonConstFrom>(f));
398 }
399
400 static inline decltype(auto) castFailed() { return ForwardTo::castFailed(); }
401
402 static inline decltype(auto) doCast(const From &f) {
403 return ForwardTo::doCast(const_cast<NonConstFrom>(f));
404 }
405
406 static inline decltype(auto) doCastIfPossible(const From &f) {
407 return ForwardTo::doCastIfPossible(const_cast<NonConstFrom>(f));
408 }
409};
410
411/// Provides a cast trait that uses a defined pointer to pointer cast as a base
412/// for reference-to-reference casts. Note that it does not provide castFailed
413/// and doCastIfPossible because a pointer-to-pointer cast would likely just
414/// return `nullptr` which could cause nullptr dereference. You can use it like
415/// this:
416///
417/// template <> struct CastInfo<foo, bar *> { ... verbose implementation... };
418///
419/// template <>
420/// struct CastInfo<foo, bar>
421/// : public ForwardToPointerCast<foo, bar, CastInfo<foo, bar *>> {};
422///
423template <typename To, typename From, typename ForwardTo>
424struct ForwardToPointerCast {
425 static inline bool isPossible(const From &f) {
426 return ForwardTo::isPossible(&f);
427 }
428
429 static inline decltype(auto) doCast(const From &f) {
430 return *ForwardTo::doCast(&f);
431 }
432};
433
434//===----------------------------------------------------------------------===//
435// CastInfo
436//===----------------------------------------------------------------------===//
437
438/// This struct provides a method for customizing the way a cast is performed.
439/// It inherits from CastIsPossible, to support the case of declaring many
440/// CastIsPossible specializations without having to specialize the full
441/// CastInfo.
442///
443/// In order to specialize different behaviors, specify different functions in
444/// your CastInfo specialization.
445/// For isa<> customization, provide:
446///
447/// `static bool isPossible(const From &f)`
448///
449/// For cast<> customization, provide:
450///
451/// `static To doCast(const From &f)`
452///
453/// For dyn_cast<> and the *_if_present<> variants' customization, provide:
454///
455/// `static To castFailed()` and `static To doCastIfPossible(const From &f)`
456///
457/// Your specialization might look something like this:
458///
459/// template<> struct CastInfo<foo, bar> : public CastIsPossible<foo, bar> {
460/// static inline foo doCast(const bar &b) {
461/// return foo(const_cast<bar &>(b));
462/// }
463/// static inline foo castFailed() { return foo(); }
464/// static inline foo doCastIfPossible(const bar &b) {
465/// if (!CastInfo<foo, bar>::isPossible(b))
466/// return castFailed();
467/// return doCast(b);
468/// }
469/// };
470
471// The default implementations of CastInfo don't use cast traits for now because
472// we need to specify types all over the place due to the current expected
473// casting behavior and the way cast_retty works. New use cases can and should
474// take advantage of the cast traits whenever possible!
475
476template <typename To, typename From, typename Enable = void>
477struct CastInfo : public CastIsPossible<To, From> {
478 using Self = CastInfo<To, From, Enable>;
479
480 using CastReturnType = typename cast_retty<To, From>::ret_type;
481
482 static inline CastReturnType doCast(const From &f) {
483 return cast_convert_val<
484 To, From,
485 typename simplify_type<From>::SimpleType>::doit(const_cast<From &>(f));
486 }
487
488 // This assumes that you can construct the cast return type from `nullptr`.
489 // This is largely to support legacy use cases - if you don't want this
490 // behavior you should specialize CastInfo for your use case.
491 static inline CastReturnType castFailed() { return CastReturnType(nullptr); }
8
Returning null pointer, which participates in a condition later
23
Returning null pointer, which participates in a condition later
492
493 static inline CastReturnType doCastIfPossible(const From &f) {
494 if (!Self::isPossible(f))
6
Taking true branch
21
Taking true branch
41
Calling 'CastIsPossible::isPossible'
55
Returning from 'CastIsPossible::isPossible'
56
Taking false branch
495 return castFailed();
7
Calling 'CastInfo::castFailed'
9
Returning from 'CastInfo::castFailed'
10
Returning null pointer, which participates in a condition later
22
Calling 'CastInfo::castFailed'
24
Returning from 'CastInfo::castFailed'
25
Returning null pointer, which participates in a condition later
496 return doCast(f);
57
Returning pointer, which participates in a condition later
497 }
498};
499
500/// This struct provides an overload for CastInfo where From has simplify_type
501/// defined. This simply forwards to the appropriate CastInfo with the
502/// simplified type/value, so you don't have to implement both.
503template <typename To, typename From>
504struct CastInfo<To, From, std::enable_if_t<!is_simple_type<From>::value>> {
505 using Self = CastInfo<To, From>;
506 using SimpleFrom = typename simplify_type<From>::SimpleType;
507 using SimplifiedSelf = CastInfo<To, SimpleFrom>;
508
509 static inline bool isPossible(From &f) {
510 return SimplifiedSelf::isPossible(
511 simplify_type<From>::getSimplifiedValue(f));
512 }
513
514 static inline decltype(auto) doCast(From &f) {
515 return SimplifiedSelf::doCast(simplify_type<From>::getSimplifiedValue(f));
516 }
517
518 static inline decltype(auto) castFailed() {
519 return SimplifiedSelf::castFailed();
520 }
521
522 static inline decltype(auto) doCastIfPossible(From &f) {
523 return SimplifiedSelf::doCastIfPossible(
5
Calling 'CastInfo::doCastIfPossible'
11
Returning from 'CastInfo::doCastIfPossible'
12
Returning null pointer, which participates in a condition later
20
Calling 'CastInfo::doCastIfPossible'
26
Returning from 'CastInfo::doCastIfPossible'
27
Returning null pointer, which participates in a condition later
40
Calling 'CastInfo::doCastIfPossible'
58
Returning from 'CastInfo::doCastIfPossible'
59
Returning pointer, which participates in a condition later
524 simplify_type<From>::getSimplifiedValue(f));
525 }
526};
527
528//===----------------------------------------------------------------------===//
529// Pre-specialized CastInfo
530//===----------------------------------------------------------------------===//
531
532/// Provide a CastInfo specialized for std::unique_ptr.
533template <typename To, typename From>
534struct CastInfo<To, std::unique_ptr<From>> : public UniquePtrCast<To, From> {};
535
536/// Provide a CastInfo specialized for std::optional<From>. It's assumed that if
537/// the input is std::optional<From> that the output can be std::optional<To>.
538/// If that's not the case, specialize CastInfo for your use case.
539template <typename To, typename From>
540struct CastInfo<To, std::optional<From>> : public OptionalValueCast<To, From> {
541};
542
543/// isa<X> - Return true if the parameter to the template is an instance of one
544/// of the template type arguments. Used like this:
545///
546/// if (isa<Type>(myVal)) { ... }
547/// if (isa<Type0, Type1, Type2>(myVal)) { ... }
548template <typename To, typename From>
549[[nodiscard]] inline bool isa(const From &Val) {
550 return CastInfo<To, const From>::isPossible(Val);
551}
552
553template <typename First, typename Second, typename... Rest, typename From>
554[[nodiscard]] inline bool isa(const From &Val) {
555 return isa<First>(Val) || isa<Second, Rest...>(Val);
556}
557
558/// cast<X> - Return the argument parameter cast to the specified type. This
559/// casting operator asserts that the type is correct, so it does not return
560/// null on failure. It does not allow a null argument (use cast_if_present for
561/// that). It is typically used like this:
562///
563/// cast<Instruction>(myVal)->getParent()
564
565template <typename To, typename From>
566[[nodiscard]] inline decltype(auto) cast(const From &Val) {
567 assert(isa<To>(Val) && "cast<Ty>() argument of incompatible type!")(static_cast <bool> (isa<To>(Val) && "cast<Ty>() argument of incompatible type!"
) ? void (0) : __assert_fail ("isa<To>(Val) && \"cast<Ty>() argument of incompatible type!\""
, "llvm/include/llvm/Support/Casting.h", 567, __extension__ __PRETTY_FUNCTION__
))
;
568 return CastInfo<To, const From>::doCast(Val);
569}
570
571template <typename To, typename From>
572[[nodiscard]] inline decltype(auto) cast(From &Val) {
573 assert(isa<To>(Val) && "cast<Ty>() argument of incompatible type!")(static_cast <bool> (isa<To>(Val) && "cast<Ty>() argument of incompatible type!"
) ? void (0) : __assert_fail ("isa<To>(Val) && \"cast<Ty>() argument of incompatible type!\""
, "llvm/include/llvm/Support/Casting.h", 573, __extension__ __PRETTY_FUNCTION__
))
;
574 return CastInfo<To, From>::doCast(Val);
575}
576
577template <typename To, typename From>
578[[nodiscard]] inline decltype(auto) cast(From *Val) {
579 assert(isa<To>(Val) && "cast<Ty>() argument of incompatible type!")(static_cast <bool> (isa<To>(Val) && "cast<Ty>() argument of incompatible type!"
) ? void (0) : __assert_fail ("isa<To>(Val) && \"cast<Ty>() argument of incompatible type!\""
, "llvm/include/llvm/Support/Casting.h", 579, __extension__ __PRETTY_FUNCTION__
))
;
580 return CastInfo<To, From *>::doCast(Val);
581}
582
583template <typename To, typename From>
584[[nodiscard]] inline decltype(auto) cast(std::unique_ptr<From> &&Val) {
585 assert(isa<To>(Val) && "cast<Ty>() argument of incompatible type!")(static_cast <bool> (isa<To>(Val) && "cast<Ty>() argument of incompatible type!"
) ? void (0) : __assert_fail ("isa<To>(Val) && \"cast<Ty>() argument of incompatible type!\""
, "llvm/include/llvm/Support/Casting.h", 585, __extension__ __PRETTY_FUNCTION__
))
;
586 return CastInfo<To, std::unique_ptr<From>>::doCast(std::move(Val));
587}
588
589//===----------------------------------------------------------------------===//
590// ValueIsPresent
591//===----------------------------------------------------------------------===//
592
593template <typename T>
594constexpr bool IsNullable =
595 std::is_pointer_v<T> || std::is_constructible_v<T, std::nullptr_t>;
596
597/// ValueIsPresent provides a way to check if a value is, well, present. For
598/// pointers, this is the equivalent of checking against nullptr, for Optionals
599/// this is the equivalent of checking hasValue(). It also provides a method for
600/// unwrapping a value (think calling .value() on an optional).
601
602// Generic values can't *not* be present.
603template <typename T, typename Enable = void> struct ValueIsPresent {
604 using UnwrappedType = T;
605 static inline bool isPresent(const T &t) { return true; }
606 static inline decltype(auto) unwrapValue(T &t) { return t; }
607};
608
609// Optional provides its own way to check if something is present.
610template <typename T> struct ValueIsPresent<std::optional<T>> {
611 using UnwrappedType = T;
612 static inline bool isPresent(const std::optional<T> &t) {
613 return t.has_value();
614 }
615 static inline decltype(auto) unwrapValue(std::optional<T> &t) { return *t; }
616};
617
618// If something is "nullable" then we just compare it to nullptr to see if it
619// exists.
620template <typename T>
621struct ValueIsPresent<T, std::enable_if_t<IsNullable<T>>> {
622 using UnwrappedType = T;
623 static inline bool isPresent(const T &t) { return t != T(nullptr); }
624 static inline decltype(auto) unwrapValue(T &t) { return t; }
625};
626
627namespace detail {
628// Convenience function we can use to check if a value is present. Because of
629// simplify_type, we have to call it on the simplified type for now.
630template <typename T> inline bool isPresent(const T &t) {
631 return ValueIsPresent<typename simplify_type<T>::SimpleType>::isPresent(
632 simplify_type<T>::getSimplifiedValue(const_cast<T &>(t)));
633}
634
635// Convenience function we can use to unwrap a value.
636template <typename T> inline decltype(auto) unwrapValue(T &t) {
637 return ValueIsPresent<T>::unwrapValue(t);
638}
639} // namespace detail
640
641/// dyn_cast<X> - Return the argument parameter cast to the specified type. This
642/// casting operator returns null if the argument is of the wrong type, so it
643/// can be used to test for a type as well as cast if successful. The value
644/// passed in must be present, if not, use dyn_cast_if_present. This should be
645/// used in the context of an if statement like this:
646///
647/// if (const Instruction *I = dyn_cast<Instruction>(myVal)) { ... }
648
649template <typename To, typename From>
650[[nodiscard]] inline decltype(auto) dyn_cast(const From &Val) {
651 assert(detail::isPresent(Val) && "dyn_cast on a non-existent value")(static_cast <bool> (detail::isPresent(Val) && "dyn_cast on a non-existent value"
) ? void (0) : __assert_fail ("detail::isPresent(Val) && \"dyn_cast on a non-existent value\""
, "llvm/include/llvm/Support/Casting.h", 651, __extension__ __PRETTY_FUNCTION__
))
;
652 return CastInfo<To, const From>::doCastIfPossible(Val);
653}
654
655template <typename To, typename From>
656[[nodiscard]] inline decltype(auto) dyn_cast(From &Val) {
657 assert(detail::isPresent(Val) && "dyn_cast on a non-existent value")(static_cast <bool> (detail::isPresent(Val) && "dyn_cast on a non-existent value"
) ? void (0) : __assert_fail ("detail::isPresent(Val) && \"dyn_cast on a non-existent value\""
, "llvm/include/llvm/Support/Casting.h", 657, __extension__ __PRETTY_FUNCTION__
))
;
3
'?' condition is true
18
'?' condition is true
38
'?' condition is true
658 return CastInfo<To, From>::doCastIfPossible(Val);
4
Calling 'CastInfo::doCastIfPossible'
13
Returning from 'CastInfo::doCastIfPossible'
14
Returning null pointer, which participates in a condition later
19
Calling 'CastInfo::doCastIfPossible'
28
Returning from 'CastInfo::doCastIfPossible'
29
Returning null pointer, which participates in a condition later
39
Calling 'CastInfo::doCastIfPossible'
60
Returning from 'CastInfo::doCastIfPossible'
61
Returning pointer, which participates in a condition later
659}
660
661template <typename To, typename From>
662[[nodiscard]] inline decltype(auto) dyn_cast(From *Val) {
663 assert(detail::isPresent(Val) && "dyn_cast on a non-existent value")(static_cast <bool> (detail::isPresent(Val) && "dyn_cast on a non-existent value"
) ? void (0) : __assert_fail ("detail::isPresent(Val) && \"dyn_cast on a non-existent value\""
, "llvm/include/llvm/Support/Casting.h", 663, __extension__ __PRETTY_FUNCTION__
))
;
664 return CastInfo<To, From *>::doCastIfPossible(Val);
665}
666
667template <typename To, typename From>
668[[nodiscard]] inline decltype(auto) dyn_cast(std::unique_ptr<From> &&Val) {
669 assert(detail::isPresent(Val) && "dyn_cast on a non-existent value")(static_cast <bool> (detail::isPresent(Val) && "dyn_cast on a non-existent value"
) ? void (0) : __assert_fail ("detail::isPresent(Val) && \"dyn_cast on a non-existent value\""
, "llvm/include/llvm/Support/Casting.h", 669, __extension__ __PRETTY_FUNCTION__
))
;
670 return CastInfo<To, std::unique_ptr<From>>::doCastIfPossible(
671 std::forward<std::unique_ptr<From> &&>(Val));
672}
673
674/// isa_and_present<X> - Functionally identical to isa, except that a null value
675/// is accepted.
676template <typename... X, class Y>
677[[nodiscard]] inline bool isa_and_present(const Y &Val) {
678 if (!detail::isPresent(Val))
679 return false;
680 return isa<X...>(Val);
681}
682
683template <typename... X, class Y>
684[[nodiscard]] inline bool isa_and_nonnull(const Y &Val) {
685 return isa_and_present<X...>(Val);
686}
687
688/// cast_if_present<X> - Functionally identical to cast, except that a null
689/// value is accepted.
690template <class X, class Y>
691[[nodiscard]] inline auto cast_if_present(const Y &Val) {
692 if (!detail::isPresent(Val))
693 return CastInfo<X, const Y>::castFailed();
694 assert(isa<X>(Val) && "cast_if_present<Ty>() argument of incompatible type!")(static_cast <bool> (isa<X>(Val) && "cast_if_present<Ty>() argument of incompatible type!"
) ? void (0) : __assert_fail ("isa<X>(Val) && \"cast_if_present<Ty>() argument of incompatible type!\""
, "llvm/include/llvm/Support/Casting.h", 694, __extension__ __PRETTY_FUNCTION__
))
;
695 return cast<X>(detail::unwrapValue(Val));
696}
697
698template <class X, class Y> [[nodiscard]] inline auto cast_if_present(Y &Val) {
699 if (!detail::isPresent(Val))
700 return CastInfo<X, Y>::castFailed();
701 assert(isa<X>(Val) && "cast_if_present<Ty>() argument of incompatible type!")(static_cast <bool> (isa<X>(Val) && "cast_if_present<Ty>() argument of incompatible type!"
) ? void (0) : __assert_fail ("isa<X>(Val) && \"cast_if_present<Ty>() argument of incompatible type!\""
, "llvm/include/llvm/Support/Casting.h", 701, __extension__ __PRETTY_FUNCTION__
))
;
702 return cast<X>(detail::unwrapValue(Val));
703}
704
705template <class X, class Y> [[nodiscard]] inline auto cast_if_present(Y *Val) {
706 if (!detail::isPresent(Val))
707 return CastInfo<X, Y *>::castFailed();
708 assert(isa<X>(Val) && "cast_if_present<Ty>() argument of incompatible type!")(static_cast <bool> (isa<X>(Val) && "cast_if_present<Ty>() argument of incompatible type!"
) ? void (0) : __assert_fail ("isa<X>(Val) && \"cast_if_present<Ty>() argument of incompatible type!\""
, "llvm/include/llvm/Support/Casting.h", 708, __extension__ __PRETTY_FUNCTION__
))
;
709 return cast<X>(detail::unwrapValue(Val));
710}
711
712template <class X, class Y>
713[[nodiscard]] inline auto cast_if_present(std::unique_ptr<Y> &&Val) {
714 if (!detail::isPresent(Val))
715 return UniquePtrCast<X, Y>::castFailed();
716 return UniquePtrCast<X, Y>::doCast(std::move(Val));
717}
718
719// Provide a forwarding from cast_or_null to cast_if_present for current
720// users. This is deprecated and will be removed in a future patch, use
721// cast_if_present instead.
722template <class X, class Y> auto cast_or_null(const Y &Val) {
723 return cast_if_present<X>(Val);
724}
725
726template <class X, class Y> auto cast_or_null(Y &Val) {
727 return cast_if_present<X>(Val);
728}
729
730template <class X, class Y> auto cast_or_null(Y *Val) {
731 return cast_if_present<X>(Val);
732}
733
734template <class X, class Y> auto cast_or_null(std::unique_ptr<Y> &&Val) {
735 return cast_if_present<X>(std::move(Val));
736}
737
738/// dyn_cast_if_present<X> - Functionally identical to dyn_cast, except that a
739/// null (or none in the case of optionals) value is accepted.
740template <class X, class Y> auto dyn_cast_if_present(const Y &Val) {
741 if (!detail::isPresent(Val))
742 return CastInfo<X, const Y>::castFailed();
743 return CastInfo<X, const Y>::doCastIfPossible(detail::unwrapValue(Val));
744}
745
746template <class X, class Y> auto dyn_cast_if_present(Y &Val) {
747 if (!detail::isPresent(Val))
748 return CastInfo<X, Y>::castFailed();
749 return CastInfo<X, Y>::doCastIfPossible(detail::unwrapValue(Val));
750}
751
752template <class X, class Y> auto dyn_cast_if_present(Y *Val) {
753 if (!detail::isPresent(Val))
754 return CastInfo<X, Y *>::castFailed();
755 return CastInfo<X, Y *>::doCastIfPossible(detail::unwrapValue(Val));
756}
757
758// Forwards to dyn_cast_if_present to avoid breaking current users. This is
759// deprecated and will be removed in a future patch, use
760// cast_if_present instead.
761template <class X, class Y> auto dyn_cast_or_null(const Y &Val) {
762 return dyn_cast_if_present<X>(Val);
763}
764
765template <class X, class Y> auto dyn_cast_or_null(Y &Val) {
766 return dyn_cast_if_present<X>(Val);
767}
768
769template <class X, class Y> auto dyn_cast_or_null(Y *Val) {
770 return dyn_cast_if_present<X>(Val);
771}
772
773/// unique_dyn_cast<X> - Given a unique_ptr<Y>, try to return a unique_ptr<X>,
774/// taking ownership of the input pointer iff isa<X>(Val) is true. If the
775/// cast is successful, From refers to nullptr on exit and the casted value
776/// is returned. If the cast is unsuccessful, the function returns nullptr
777/// and From is unchanged.
778template <class X, class Y>
779[[nodiscard]] inline typename CastInfo<X, std::unique_ptr<Y>>::CastResultType
780unique_dyn_cast(std::unique_ptr<Y> &Val) {
781 if (!isa<X>(Val))
782 return nullptr;
783 return cast<X>(std::move(Val));
784}
785
786template <class X, class Y>
787[[nodiscard]] inline auto unique_dyn_cast(std::unique_ptr<Y> &&Val) {
788 return unique_dyn_cast<X, Y>(Val);
789}
790
791// unique_dyn_cast_or_null<X> - Functionally identical to unique_dyn_cast,
792// except that a null value is accepted.
793template <class X, class Y>
794[[nodiscard]] inline typename CastInfo<X, std::unique_ptr<Y>>::CastResultType
795unique_dyn_cast_or_null(std::unique_ptr<Y> &Val) {
796 if (!Val)
797 return nullptr;
798 return unique_dyn_cast<X, Y>(Val);
799}
800
801template <class X, class Y>
802[[nodiscard]] inline auto unique_dyn_cast_or_null(std::unique_ptr<Y> &&Val) {
803 return unique_dyn_cast_or_null<X, Y>(Val);
804}
805
806} // end namespace llvm
807
808#endif // LLVM_SUPPORT_CASTING_H