Bug Summary

File:build/llvm-toolchain-snapshot-15~++20220420111733+e13d2efed663/clang/lib/Sema/SemaExpr.cpp
Warning:line 7692, column 10
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-store=region -analyzer-opt-analyze-nested-blocks -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/llvm-toolchain-snapshot-15~++20220420111733+e13d2efed663/build-llvm -resource-dir /usr/lib/llvm-15/lib/clang/15.0.0 -D _DEBUG -D _GNU_SOURCE -D __STDC_CONSTANT_MACROS -D __STDC_FORMAT_MACROS -D __STDC_LIMIT_MACROS -I tools/clang/lib/Sema -I /build/llvm-toolchain-snapshot-15~++20220420111733+e13d2efed663/clang/lib/Sema -I /build/llvm-toolchain-snapshot-15~++20220420111733+e13d2efed663/clang/include -I tools/clang/include -I include -I /build/llvm-toolchain-snapshot-15~++20220420111733+e13d2efed663/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-15/lib/clang/15.0.0/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/llvm-toolchain-snapshot-15~++20220420111733+e13d2efed663/build-llvm=build-llvm -fmacro-prefix-map=/build/llvm-toolchain-snapshot-15~++20220420111733+e13d2efed663/= -fcoverage-prefix-map=/build/llvm-toolchain-snapshot-15~++20220420111733+e13d2efed663/build-llvm=build-llvm -fcoverage-prefix-map=/build/llvm-toolchain-snapshot-15~++20220420111733+e13d2efed663/= -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 -std=c++14 -fdeprecated-macro -fdebug-compilation-dir=/build/llvm-toolchain-snapshot-15~++20220420111733+e13d2efed663/build-llvm -fdebug-prefix-map=/build/llvm-toolchain-snapshot-15~++20220420111733+e13d2efed663/build-llvm=build-llvm -fdebug-prefix-map=/build/llvm-toolchain-snapshot-15~++20220420111733+e13d2efed663/= -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-2022-04-20-140412-16051-1 -x c++ /build/llvm-toolchain-snapshot-15~++20220420111733+e13d2efed663/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
60using namespace clang;
61using namespace sema;
62
63/// Determine whether the use of this declaration is valid, without
64/// emitting diagnostics.
65bool Sema::CanUseDecl(NamedDecl *D, bool TreatUnavailableAsInvalid) {
66 // See if this is an auto-typed variable whose initializer we are parsing.
67 if (ParsingInitForAutoVars.count(D))
68 return false;
69
70 // See if this is a deleted function.
71 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
72 if (FD->isDeleted())
73 return false;
74
75 // If the function has a deduced return type, and we can't deduce it,
76 // then we can't use it either.
77 if (getLangOpts().CPlusPlus14 && FD->getReturnType()->isUndeducedType() &&
78 DeduceReturnType(FD, SourceLocation(), /*Diagnose*/ false))
79 return false;
80
81 // See if this is an aligned allocation/deallocation function that is
82 // unavailable.
83 if (TreatUnavailableAsInvalid &&
84 isUnavailableAlignedAllocationFunction(*FD))
85 return false;
86 }
87
88 // See if this function is unavailable.
89 if (TreatUnavailableAsInvalid && D->getAvailability() == AR_Unavailable &&
90 cast<Decl>(CurContext)->getAvailability() != AR_Unavailable)
91 return false;
92
93 if (isa<UnresolvedUsingIfExistsDecl>(D))
94 return false;
95
96 return true;
97}
98
99static void DiagnoseUnusedOfDecl(Sema &S, NamedDecl *D, SourceLocation Loc) {
100 // Warn if this is used but marked unused.
101 if (const auto *A = D->getAttr<UnusedAttr>()) {
102 // [[maybe_unused]] should not diagnose uses, but __attribute__((unused))
103 // should diagnose them.
104 if (A->getSemanticSpelling() != UnusedAttr::CXX11_maybe_unused &&
105 A->getSemanticSpelling() != UnusedAttr::C2x_maybe_unused) {
106 const Decl *DC = cast_or_null<Decl>(S.getCurObjCLexicalContext());
107 if (DC && !DC->hasAttr<UnusedAttr>())
108 S.Diag(Loc, diag::warn_used_but_marked_unused) << D;
109 }
110 }
111}
112
113/// Emit a note explaining that this function is deleted.
114void Sema::NoteDeletedFunction(FunctionDecl *Decl) {
115 assert(Decl && Decl->isDeleted())(static_cast <bool> (Decl && Decl->isDeleted
()) ? void (0) : __assert_fail ("Decl && Decl->isDeleted()"
, "clang/lib/Sema/SemaExpr.cpp", 115, __extension__ __PRETTY_FUNCTION__
))
;
116
117 if (Decl->isDefaulted()) {
118 // If the method was explicitly defaulted, point at that declaration.
119 if (!Decl->isImplicit())
120 Diag(Decl->getLocation(), diag::note_implicitly_deleted);
121
122 // Try to diagnose why this special member function was implicitly
123 // deleted. This might fail, if that reason no longer applies.
124 DiagnoseDeletedDefaultedFunction(Decl);
125 return;
126 }
127
128 auto *Ctor = dyn_cast<CXXConstructorDecl>(Decl);
129 if (Ctor && Ctor->isInheritingConstructor())
130 return NoteDeletedInheritingConstructor(Ctor);
131
132 Diag(Decl->getLocation(), diag::note_availability_specified_here)
133 << Decl << 1;
134}
135
136/// Determine whether a FunctionDecl was ever declared with an
137/// explicit storage class.
138static bool hasAnyExplicitStorageClass(const FunctionDecl *D) {
139 for (auto I : D->redecls()) {
140 if (I->getStorageClass() != SC_None)
141 return true;
142 }
143 return false;
144}
145
146/// Check whether we're in an extern inline function and referring to a
147/// variable or function with internal linkage (C11 6.7.4p3).
148///
149/// This is only a warning because we used to silently accept this code, but
150/// in many cases it will not behave correctly. This is not enabled in C++ mode
151/// because the restriction language is a bit weaker (C++11 [basic.def.odr]p6)
152/// and so while there may still be user mistakes, most of the time we can't
153/// prove that there are errors.
154static void diagnoseUseOfInternalDeclInInlineFunction(Sema &S,
155 const NamedDecl *D,
156 SourceLocation Loc) {
157 // This is disabled under C++; there are too many ways for this to fire in
158 // contexts where the warning is a false positive, or where it is technically
159 // correct but benign.
160 if (S.getLangOpts().CPlusPlus)
161 return;
162
163 // Check if this is an inlined function or method.
164 FunctionDecl *Current = S.getCurFunctionDecl();
165 if (!Current)
166 return;
167 if (!Current->isInlined())
168 return;
169 if (!Current->isExternallyVisible())
170 return;
171
172 // Check if the decl has internal linkage.
173 if (D->getFormalLinkage() != InternalLinkage)
174 return;
175
176 // Downgrade from ExtWarn to Extension if
177 // (1) the supposedly external inline function is in the main file,
178 // and probably won't be included anywhere else.
179 // (2) the thing we're referencing is a pure function.
180 // (3) the thing we're referencing is another inline function.
181 // This last can give us false negatives, but it's better than warning on
182 // wrappers for simple C library functions.
183 const FunctionDecl *UsedFn = dyn_cast<FunctionDecl>(D);
184 bool DowngradeWarning = S.getSourceManager().isInMainFile(Loc);
185 if (!DowngradeWarning && UsedFn)
186 DowngradeWarning = UsedFn->isInlined() || UsedFn->hasAttr<ConstAttr>();
187
188 S.Diag(Loc, DowngradeWarning ? diag::ext_internal_in_extern_inline_quiet
189 : diag::ext_internal_in_extern_inline)
190 << /*IsVar=*/!UsedFn << D;
191
192 S.MaybeSuggestAddingStaticToDecl(Current);
193
194 S.Diag(D->getCanonicalDecl()->getLocation(), diag::note_entity_declared_at)
195 << D;
196}
197
198void Sema::MaybeSuggestAddingStaticToDecl(const FunctionDecl *Cur) {
199 const FunctionDecl *First = Cur->getFirstDecl();
200
201 // Suggest "static" on the function, if possible.
202 if (!hasAnyExplicitStorageClass(First)) {
203 SourceLocation DeclBegin = First->getSourceRange().getBegin();
204 Diag(DeclBegin, diag::note_convert_inline_to_static)
205 << Cur << FixItHint::CreateInsertion(DeclBegin, "static ");
206 }
207}
208
209/// Determine whether the use of this declaration is valid, and
210/// emit any corresponding diagnostics.
211///
212/// This routine diagnoses various problems with referencing
213/// declarations that can occur when using a declaration. For example,
214/// it might warn if a deprecated or unavailable declaration is being
215/// used, or produce an error (and return true) if a C++0x deleted
216/// function is being used.
217///
218/// \returns true if there was an error (this declaration cannot be
219/// referenced), false otherwise.
220///
221bool Sema::DiagnoseUseOfDecl(NamedDecl *D, ArrayRef<SourceLocation> Locs,
222 const ObjCInterfaceDecl *UnknownObjCClass,
223 bool ObjCPropertyAccess,
224 bool AvoidPartialAvailabilityChecks,
225 ObjCInterfaceDecl *ClassReceiver) {
226 SourceLocation Loc = Locs.front();
227 if (getLangOpts().CPlusPlus && isa<FunctionDecl>(D)) {
228 // If there were any diagnostics suppressed by template argument deduction,
229 // emit them now.
230 auto Pos = SuppressedDiagnostics.find(D->getCanonicalDecl());
231 if (Pos != SuppressedDiagnostics.end()) {
232 for (const PartialDiagnosticAt &Suppressed : Pos->second)
233 Diag(Suppressed.first, Suppressed.second);
234
235 // Clear out the list of suppressed diagnostics, so that we don't emit
236 // them again for this specialization. However, we don't obsolete this
237 // entry from the table, because we want to avoid ever emitting these
238 // diagnostics again.
239 Pos->second.clear();
240 }
241
242 // C++ [basic.start.main]p3:
243 // The function 'main' shall not be used within a program.
244 if (cast<FunctionDecl>(D)->isMain())
245 Diag(Loc, diag::ext_main_used);
246
247 diagnoseUnavailableAlignedAllocation(*cast<FunctionDecl>(D), Loc);
248 }
249
250 // See if this is an auto-typed variable whose initializer we are parsing.
251 if (ParsingInitForAutoVars.count(D)) {
252 if (isa<BindingDecl>(D)) {
253 Diag(Loc, diag::err_binding_cannot_appear_in_own_initializer)
254 << D->getDeclName();
255 } else {
256 Diag(Loc, diag::err_auto_variable_cannot_appear_in_own_initializer)
257 << D->getDeclName() << cast<VarDecl>(D)->getType();
258 }
259 return true;
260 }
261
262 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
263 // See if this is a deleted function.
264 if (FD->isDeleted()) {
265 auto *Ctor = dyn_cast<CXXConstructorDecl>(FD);
266 if (Ctor && Ctor->isInheritingConstructor())
267 Diag(Loc, diag::err_deleted_inherited_ctor_use)
268 << Ctor->getParent()
269 << Ctor->getInheritedConstructor().getConstructor()->getParent();
270 else
271 Diag(Loc, diag::err_deleted_function_use);
272 NoteDeletedFunction(FD);
273 return true;
274 }
275
276 // [expr.prim.id]p4
277 // A program that refers explicitly or implicitly to a function with a
278 // trailing requires-clause whose constraint-expression is not satisfied,
279 // other than to declare it, is ill-formed. [...]
280 //
281 // See if this is a function with constraints that need to be satisfied.
282 // Check this before deducing the return type, as it might instantiate the
283 // definition.
284 if (FD->getTrailingRequiresClause()) {
285 ConstraintSatisfaction Satisfaction;
286 if (CheckFunctionConstraints(FD, Satisfaction, Loc))
287 // A diagnostic will have already been generated (non-constant
288 // constraint expression, for example)
289 return true;
290 if (!Satisfaction.IsSatisfied) {
291 Diag(Loc,
292 diag::err_reference_to_function_with_unsatisfied_constraints)
293 << D;
294 DiagnoseUnsatisfiedConstraint(Satisfaction);
295 return true;
296 }
297 }
298
299 // If the function has a deduced return type, and we can't deduce it,
300 // then we can't use it either.
301 if (getLangOpts().CPlusPlus14 && FD->getReturnType()->isUndeducedType() &&
302 DeduceReturnType(FD, Loc))
303 return true;
304
305 if (getLangOpts().CUDA && !CheckCUDACall(Loc, FD))
306 return true;
307
308 if (getLangOpts().SYCLIsDevice && !checkSYCLDeviceFunction(Loc, FD))
309 return true;
310 }
311
312 if (auto *MD = dyn_cast<CXXMethodDecl>(D)) {
313 // Lambdas are only default-constructible or assignable in C++2a onwards.
314 if (MD->getParent()->isLambda() &&
315 ((isa<CXXConstructorDecl>(MD) &&
316 cast<CXXConstructorDecl>(MD)->isDefaultConstructor()) ||
317 MD->isCopyAssignmentOperator() || MD->isMoveAssignmentOperator())) {
318 Diag(Loc, diag::warn_cxx17_compat_lambda_def_ctor_assign)
319 << !isa<CXXConstructorDecl>(MD);
320 }
321 }
322
323 auto getReferencedObjCProp = [](const NamedDecl *D) ->
324 const ObjCPropertyDecl * {
325 if (const auto *MD = dyn_cast<ObjCMethodDecl>(D))
326 return MD->findPropertyDecl();
327 return nullptr;
328 };
329 if (const ObjCPropertyDecl *ObjCPDecl = getReferencedObjCProp(D)) {
330 if (diagnoseArgIndependentDiagnoseIfAttrs(ObjCPDecl, Loc))
331 return true;
332 } else if (diagnoseArgIndependentDiagnoseIfAttrs(D, Loc)) {
333 return true;
334 }
335
336 // [OpenMP 4.0], 2.15 declare reduction Directive, Restrictions
337 // Only the variables omp_in and omp_out are allowed in the combiner.
338 // Only the variables omp_priv and omp_orig are allowed in the
339 // initializer-clause.
340 auto *DRD = dyn_cast<OMPDeclareReductionDecl>(CurContext);
341 if (LangOpts.OpenMP && DRD && !CurContext->containsDecl(D) &&
342 isa<VarDecl>(D)) {
343 Diag(Loc, diag::err_omp_wrong_var_in_declare_reduction)
344 << getCurFunction()->HasOMPDeclareReductionCombiner;
345 Diag(D->getLocation(), diag::note_entity_declared_at) << D;
346 return true;
347 }
348
349 // [OpenMP 5.0], 2.19.7.3. declare mapper Directive, Restrictions
350 // List-items in map clauses on this construct may only refer to the declared
351 // variable var and entities that could be referenced by a procedure defined
352 // at the same location
353 if (LangOpts.OpenMP && isa<VarDecl>(D) &&
354 !isOpenMPDeclareMapperVarDeclAllowed(cast<VarDecl>(D))) {
355 Diag(Loc, diag::err_omp_declare_mapper_wrong_var)
356 << getOpenMPDeclareMapperVarName();
357 Diag(D->getLocation(), diag::note_entity_declared_at) << D;
358 return true;
359 }
360
361 if (const auto *EmptyD = dyn_cast<UnresolvedUsingIfExistsDecl>(D)) {
362 Diag(Loc, diag::err_use_of_empty_using_if_exists);
363 Diag(EmptyD->getLocation(), diag::note_empty_using_if_exists_here);
364 return true;
365 }
366
367 DiagnoseAvailabilityOfDecl(D, Locs, UnknownObjCClass, ObjCPropertyAccess,
368 AvoidPartialAvailabilityChecks, ClassReceiver);
369
370 DiagnoseUnusedOfDecl(*this, D, Loc);
371
372 diagnoseUseOfInternalDeclInInlineFunction(*this, D, Loc);
373
374 if (auto *VD = dyn_cast<ValueDecl>(D))
375 checkTypeSupport(VD->getType(), Loc, VD);
376
377 if (LangOpts.SYCLIsDevice || (LangOpts.OpenMP && LangOpts.OpenMPIsDevice)) {
378 if (!Context.getTargetInfo().isTLSSupported())
379 if (const auto *VD = dyn_cast<VarDecl>(D))
380 if (VD->getTLSKind() != VarDecl::TLS_None)
381 targetDiag(*Locs.begin(), diag::err_thread_unsupported);
382 }
383
384 if (isa<ParmVarDecl>(D) && isa<RequiresExprBodyDecl>(D->getDeclContext()) &&
385 !isUnevaluatedContext()) {
386 // C++ [expr.prim.req.nested] p3
387 // A local parameter shall only appear as an unevaluated operand
388 // (Clause 8) within the constraint-expression.
389 Diag(Loc, diag::err_requires_expr_parameter_referenced_in_evaluated_context)
390 << D;
391 Diag(D->getLocation(), diag::note_entity_declared_at) << D;
392 return true;
393 }
394
395 return false;
396}
397
398/// DiagnoseSentinelCalls - This routine checks whether a call or
399/// message-send is to a declaration with the sentinel attribute, and
400/// if so, it checks that the requirements of the sentinel are
401/// satisfied.
402void Sema::DiagnoseSentinelCalls(NamedDecl *D, SourceLocation Loc,
403 ArrayRef<Expr *> Args) {
404 const SentinelAttr *attr = D->getAttr<SentinelAttr>();
405 if (!attr)
406 return;
407
408 // The number of formal parameters of the declaration.
409 unsigned numFormalParams;
410
411 // The kind of declaration. This is also an index into a %select in
412 // the diagnostic.
413 enum CalleeType { CT_Function, CT_Method, CT_Block } calleeType;
414
415 if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) {
416 numFormalParams = MD->param_size();
417 calleeType = CT_Method;
418 } else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
419 numFormalParams = FD->param_size();
420 calleeType = CT_Function;
421 } else if (isa<VarDecl>(D)) {
422 QualType type = cast<ValueDecl>(D)->getType();
423 const FunctionType *fn = nullptr;
424 if (const PointerType *ptr = type->getAs<PointerType>()) {
425 fn = ptr->getPointeeType()->getAs<FunctionType>();
426 if (!fn) return;
427 calleeType = CT_Function;
428 } else if (const BlockPointerType *ptr = type->getAs<BlockPointerType>()) {
429 fn = ptr->getPointeeType()->castAs<FunctionType>();
430 calleeType = CT_Block;
431 } else {
432 return;
433 }
434
435 if (const FunctionProtoType *proto = dyn_cast<FunctionProtoType>(fn)) {
436 numFormalParams = proto->getNumParams();
437 } else {
438 numFormalParams = 0;
439 }
440 } else {
441 return;
442 }
443
444 // "nullPos" is the number of formal parameters at the end which
445 // effectively count as part of the variadic arguments. This is
446 // useful if you would prefer to not have *any* formal parameters,
447 // but the language forces you to have at least one.
448 unsigned nullPos = attr->getNullPos();
449 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", 449, __extension__ __PRETTY_FUNCTION__
))
;
450 numFormalParams = (nullPos > numFormalParams ? 0 : numFormalParams - nullPos);
451
452 // The number of arguments which should follow the sentinel.
453 unsigned numArgsAfterSentinel = attr->getSentinel();
454
455 // If there aren't enough arguments for all the formal parameters,
456 // the sentinel, and the args after the sentinel, complain.
457 if (Args.size() < numFormalParams + numArgsAfterSentinel + 1) {
458 Diag(Loc, diag::warn_not_enough_argument) << D->getDeclName();
459 Diag(D->getLocation(), diag::note_sentinel_here) << int(calleeType);
460 return;
461 }
462
463 // Otherwise, find the sentinel expression.
464 Expr *sentinelExpr = Args[Args.size() - numArgsAfterSentinel - 1];
465 if (!sentinelExpr) return;
466 if (sentinelExpr->isValueDependent()) return;
467 if (Context.isSentinelNullExpr(sentinelExpr)) return;
468
469 // Pick a reasonable string to insert. Optimistically use 'nil', 'nullptr',
470 // or 'NULL' if those are actually defined in the context. Only use
471 // 'nil' for ObjC methods, where it's much more likely that the
472 // variadic arguments form a list of object pointers.
473 SourceLocation MissingNilLoc = getLocForEndOfToken(sentinelExpr->getEndLoc());
474 std::string NullValue;
475 if (calleeType == CT_Method && PP.isMacroDefined("nil"))
476 NullValue = "nil";
477 else if (getLangOpts().CPlusPlus11)
478 NullValue = "nullptr";
479 else if (PP.isMacroDefined("NULL"))
480 NullValue = "NULL";
481 else
482 NullValue = "(void*) 0";
483
484 if (MissingNilLoc.isInvalid())
485 Diag(Loc, diag::warn_missing_sentinel) << int(calleeType);
486 else
487 Diag(MissingNilLoc, diag::warn_missing_sentinel)
488 << int(calleeType)
489 << FixItHint::CreateInsertion(MissingNilLoc, ", " + NullValue);
490 Diag(D->getLocation(), diag::note_sentinel_here) << int(calleeType);
491}
492
493SourceRange Sema::getExprRange(Expr *E) const {
494 return E ? E->getSourceRange() : SourceRange();
495}
496
497//===----------------------------------------------------------------------===//
498// Standard Promotions and Conversions
499//===----------------------------------------------------------------------===//
500
501/// DefaultFunctionArrayConversion (C99 6.3.2.1p3, C99 6.3.2.1p4).
502ExprResult Sema::DefaultFunctionArrayConversion(Expr *E, bool Diagnose) {
503 // Handle any placeholder expressions which made it here.
504 if (E->hasPlaceholderType()) {
505 ExprResult result = CheckPlaceholderExpr(E);
506 if (result.isInvalid()) return ExprError();
507 E = result.get();
508 }
509
510 QualType Ty = E->getType();
511 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", 511, __extension__ __PRETTY_FUNCTION__
))
;
512
513 if (Ty->isFunctionType()) {
514 if (auto *DRE = dyn_cast<DeclRefExpr>(E->IgnoreParenCasts()))
515 if (auto *FD = dyn_cast<FunctionDecl>(DRE->getDecl()))
516 if (!checkAddressOfFunctionIsAvailable(FD, Diagnose, E->getExprLoc()))
517 return ExprError();
518
519 E = ImpCastExprToType(E, Context.getPointerType(Ty),
520 CK_FunctionToPointerDecay).get();
521 } else if (Ty->isArrayType()) {
522 // In C90 mode, arrays only promote to pointers if the array expression is
523 // an lvalue. The relevant legalese is C90 6.2.2.1p3: "an lvalue that has
524 // type 'array of type' is converted to an expression that has type 'pointer
525 // to type'...". In C99 this was changed to: C99 6.3.2.1p3: "an expression
526 // that has type 'array of type' ...". The relevant change is "an lvalue"
527 // (C90) to "an expression" (C99).
528 //
529 // C++ 4.2p1:
530 // An lvalue or rvalue of type "array of N T" or "array of unknown bound of
531 // T" can be converted to an rvalue of type "pointer to T".
532 //
533 if (getLangOpts().C99 || getLangOpts().CPlusPlus || E->isLValue()) {
534 ExprResult Res = ImpCastExprToType(E, Context.getArrayDecayedType(Ty),
535 CK_ArrayToPointerDecay);
536 if (Res.isInvalid())
537 return ExprError();
538 E = Res.get();
539 }
540 }
541 return E;
542}
543
544static void CheckForNullPointerDereference(Sema &S, Expr *E) {
545 // Check to see if we are dereferencing a null pointer. If so,
546 // and if not volatile-qualified, this is undefined behavior that the
547 // optimizer will delete, so warn about it. People sometimes try to use this
548 // to get a deterministic trap and are surprised by clang's behavior. This
549 // only handles the pattern "*null", which is a very syntactic check.
550 const auto *UO = dyn_cast<UnaryOperator>(E->IgnoreParenCasts());
551 if (UO && UO->getOpcode() == UO_Deref &&
552 UO->getSubExpr()->getType()->isPointerType()) {
553 const LangAS AS =
554 UO->getSubExpr()->getType()->getPointeeType().getAddressSpace();
555 if ((!isTargetAddressSpace(AS) ||
556 (isTargetAddressSpace(AS) && toTargetAddressSpace(AS) == 0)) &&
557 UO->getSubExpr()->IgnoreParenCasts()->isNullPointerConstant(
558 S.Context, Expr::NPC_ValueDependentIsNotNull) &&
559 !UO->getType().isVolatileQualified()) {
560 S.DiagRuntimeBehavior(UO->getOperatorLoc(), UO,
561 S.PDiag(diag::warn_indirection_through_null)
562 << UO->getSubExpr()->getSourceRange());
563 S.DiagRuntimeBehavior(UO->getOperatorLoc(), UO,
564 S.PDiag(diag::note_indirection_through_null));
565 }
566 }
567}
568
569static void DiagnoseDirectIsaAccess(Sema &S, const ObjCIvarRefExpr *OIRE,
570 SourceLocation AssignLoc,
571 const Expr* RHS) {
572 const ObjCIvarDecl *IV = OIRE->getDecl();
573 if (!IV)
574 return;
575
576 DeclarationName MemberName = IV->getDeclName();
577 IdentifierInfo *Member = MemberName.getAsIdentifierInfo();
578 if (!Member || !Member->isStr("isa"))
579 return;
580
581 const Expr *Base = OIRE->getBase();
582 QualType BaseType = Base->getType();
583 if (OIRE->isArrow())
584 BaseType = BaseType->getPointeeType();
585 if (const ObjCObjectType *OTy = BaseType->getAs<ObjCObjectType>())
586 if (ObjCInterfaceDecl *IDecl = OTy->getInterface()) {
587 ObjCInterfaceDecl *ClassDeclared = nullptr;
588 ObjCIvarDecl *IV = IDecl->lookupInstanceVariable(Member, ClassDeclared);
589 if (!ClassDeclared->getSuperClass()
590 && (*ClassDeclared->ivar_begin()) == IV) {
591 if (RHS) {
592 NamedDecl *ObjectSetClass =
593 S.LookupSingleName(S.TUScope,
594 &S.Context.Idents.get("object_setClass"),
595 SourceLocation(), S.LookupOrdinaryName);
596 if (ObjectSetClass) {
597 SourceLocation RHSLocEnd = S.getLocForEndOfToken(RHS->getEndLoc());
598 S.Diag(OIRE->getExprLoc(), diag::warn_objc_isa_assign)
599 << FixItHint::CreateInsertion(OIRE->getBeginLoc(),
600 "object_setClass(")
601 << FixItHint::CreateReplacement(
602 SourceRange(OIRE->getOpLoc(), AssignLoc), ",")
603 << FixItHint::CreateInsertion(RHSLocEnd, ")");
604 }
605 else
606 S.Diag(OIRE->getLocation(), diag::warn_objc_isa_assign);
607 } else {
608 NamedDecl *ObjectGetClass =
609 S.LookupSingleName(S.TUScope,
610 &S.Context.Idents.get("object_getClass"),
611 SourceLocation(), S.LookupOrdinaryName);
612 if (ObjectGetClass)
613 S.Diag(OIRE->getExprLoc(), diag::warn_objc_isa_use)
614 << FixItHint::CreateInsertion(OIRE->getBeginLoc(),
615 "object_getClass(")
616 << FixItHint::CreateReplacement(
617 SourceRange(OIRE->getOpLoc(), OIRE->getEndLoc()), ")");
618 else
619 S.Diag(OIRE->getLocation(), diag::warn_objc_isa_use);
620 }
621 S.Diag(IV->getLocation(), diag::note_ivar_decl);
622 }
623 }
624}
625
626ExprResult Sema::DefaultLvalueConversion(Expr *E) {
627 // Handle any placeholder expressions which made it here.
628 if (E->hasPlaceholderType()) {
629 ExprResult result = CheckPlaceholderExpr(E);
630 if (result.isInvalid()) return ExprError();
631 E = result.get();
632 }
633
634 // C++ [conv.lval]p1:
635 // A glvalue of a non-function, non-array type T can be
636 // converted to a prvalue.
637 if (!E->isGLValue()) return E;
638
639 QualType T = E->getType();
640 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", 640, __extension__ __PRETTY_FUNCTION__
))
;
641
642 // lvalue-to-rvalue conversion cannot be applied to function or array types.
643 if (T->isFunctionType() || T->isArrayType())
644 return E;
645
646 // We don't want to throw lvalue-to-rvalue casts on top of
647 // expressions of certain types in C++.
648 if (getLangOpts().CPlusPlus &&
649 (E->getType() == Context.OverloadTy ||
650 T->isDependentType() ||
651 T->isRecordType()))
652 return E;
653
654 // The C standard is actually really unclear on this point, and
655 // DR106 tells us what the result should be but not why. It's
656 // generally best to say that void types just doesn't undergo
657 // lvalue-to-rvalue at all. Note that expressions of unqualified
658 // 'void' type are never l-values, but qualified void can be.
659 if (T->isVoidType())
660 return E;
661
662 // OpenCL usually rejects direct accesses to values of 'half' type.
663 if (getLangOpts().OpenCL &&
664 !getOpenCLOptions().isAvailableOption("cl_khr_fp16", getLangOpts()) &&
665 T->isHalfType()) {
666 Diag(E->getExprLoc(), diag::err_opencl_half_load_store)
667 << 0 << T;
668 return ExprError();
669 }
670
671 CheckForNullPointerDereference(*this, E);
672 if (const ObjCIsaExpr *OISA = dyn_cast<ObjCIsaExpr>(E->IgnoreParenCasts())) {
673 NamedDecl *ObjectGetClass = LookupSingleName(TUScope,
674 &Context.Idents.get("object_getClass"),
675 SourceLocation(), LookupOrdinaryName);
676 if (ObjectGetClass)
677 Diag(E->getExprLoc(), diag::warn_objc_isa_use)
678 << FixItHint::CreateInsertion(OISA->getBeginLoc(), "object_getClass(")
679 << FixItHint::CreateReplacement(
680 SourceRange(OISA->getOpLoc(), OISA->getIsaMemberLoc()), ")");
681 else
682 Diag(E->getExprLoc(), diag::warn_objc_isa_use);
683 }
684 else if (const ObjCIvarRefExpr *OIRE =
685 dyn_cast<ObjCIvarRefExpr>(E->IgnoreParenCasts()))
686 DiagnoseDirectIsaAccess(*this, OIRE, SourceLocation(), /* Expr*/nullptr);
687
688 // C++ [conv.lval]p1:
689 // [...] If T is a non-class type, the type of the prvalue is the
690 // cv-unqualified version of T. Otherwise, the type of the
691 // rvalue is T.
692 //
693 // C99 6.3.2.1p2:
694 // If the lvalue has qualified type, the value has the unqualified
695 // version of the type of the lvalue; otherwise, the value has the
696 // type of the lvalue.
697 if (T.hasQualifiers())
698 T = T.getUnqualifiedType();
699
700 // Under the MS ABI, lock down the inheritance model now.
701 if (T->isMemberPointerType() &&
702 Context.getTargetInfo().getCXXABI().isMicrosoft())
703 (void)isCompleteType(E->getExprLoc(), T);
704
705 ExprResult Res = CheckLValueToRValueConversionOperand(E);
706 if (Res.isInvalid())
707 return Res;
708 E = Res.get();
709
710 // Loading a __weak object implicitly retains the value, so we need a cleanup to
711 // balance that.
712 if (E->getType().getObjCLifetime() == Qualifiers::OCL_Weak)
713 Cleanup.setExprNeedsCleanups(true);
714
715 if (E->getType().isDestructedType() == QualType::DK_nontrivial_c_struct)
716 Cleanup.setExprNeedsCleanups(true);
717
718 // C++ [conv.lval]p3:
719 // If T is cv std::nullptr_t, the result is a null pointer constant.
720 CastKind CK = T->isNullPtrType() ? CK_NullToPointer : CK_LValueToRValue;
721 Res = ImplicitCastExpr::Create(Context, T, CK, E, nullptr, VK_PRValue,
722 CurFPFeatureOverrides());
723
724 // C11 6.3.2.1p2:
725 // ... if the lvalue has atomic type, the value has the non-atomic version
726 // of the type of the lvalue ...
727 if (const AtomicType *Atomic = T->getAs<AtomicType>()) {
728 T = Atomic->getValueType().getUnqualifiedType();
729 Res = ImplicitCastExpr::Create(Context, T, CK_AtomicToNonAtomic, Res.get(),
730 nullptr, VK_PRValue, FPOptionsOverride());
731 }
732
733 return Res;
734}
735
736ExprResult Sema::DefaultFunctionArrayLvalueConversion(Expr *E, bool Diagnose) {
737 ExprResult Res = DefaultFunctionArrayConversion(E, Diagnose);
738 if (Res.isInvalid())
739 return ExprError();
740 Res = DefaultLvalueConversion(Res.get());
741 if (Res.isInvalid())
742 return ExprError();
743 return Res;
744}
745
746/// CallExprUnaryConversions - a special case of an unary conversion
747/// performed on a function designator of a call expression.
748ExprResult Sema::CallExprUnaryConversions(Expr *E) {
749 QualType Ty = E->getType();
750 ExprResult Res = E;
751 // Only do implicit cast for a function type, but not for a pointer
752 // to function type.
753 if (Ty->isFunctionType()) {
754 Res = ImpCastExprToType(E, Context.getPointerType(Ty),
755 CK_FunctionToPointerDecay);
756 if (Res.isInvalid())
757 return ExprError();
758 }
759 Res = DefaultLvalueConversion(Res.get());
760 if (Res.isInvalid())
761 return ExprError();
762 return Res.get();
763}
764
765/// UsualUnaryConversions - Performs various conversions that are common to most
766/// operators (C99 6.3). The conversions of array and function types are
767/// sometimes suppressed. For example, the array->pointer conversion doesn't
768/// apply if the array is an argument to the sizeof or address (&) operators.
769/// In these instances, this routine should *not* be called.
770ExprResult Sema::UsualUnaryConversions(Expr *E) {
771 // First, convert to an r-value.
772 ExprResult Res = DefaultFunctionArrayLvalueConversion(E);
773 if (Res.isInvalid())
774 return ExprError();
775 E = Res.get();
776
777 QualType Ty = E->getType();
778 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", 778, __extension__ __PRETTY_FUNCTION__
))
;
779
780 LangOptions::FPEvalMethodKind EvalMethod = CurFPFeatures.getFPEvalMethod();
781 if (EvalMethod != LangOptions::FEM_Source && Ty->isFloatingType() &&
782 (getLangOpts().getFPEvalMethod() !=
783 LangOptions::FPEvalMethodKind::FEM_UnsetOnCommandLine ||
784 PP.getLastFPEvalPragmaLocation().isValid())) {
785 switch (EvalMethod) {
786 default:
787 llvm_unreachable("Unrecognized float evaluation method")::llvm::llvm_unreachable_internal("Unrecognized float evaluation method"
, "clang/lib/Sema/SemaExpr.cpp", 787)
;
788 break;
789 case LangOptions::FEM_UnsetOnCommandLine:
790 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", 790)
;
791 break;
792 case LangOptions::FEM_Double:
793 if (Context.getFloatingTypeOrder(Context.DoubleTy, Ty) > 0)
794 // Widen the expression to double.
795 return Ty->isComplexType()
796 ? ImpCastExprToType(E,
797 Context.getComplexType(Context.DoubleTy),
798 CK_FloatingComplexCast)
799 : ImpCastExprToType(E, Context.DoubleTy, CK_FloatingCast);
800 break;
801 case LangOptions::FEM_Extended:
802 if (Context.getFloatingTypeOrder(Context.LongDoubleTy, Ty) > 0)
803 // Widen the expression to long double.
804 return Ty->isComplexType()
805 ? ImpCastExprToType(
806 E, Context.getComplexType(Context.LongDoubleTy),
807 CK_FloatingComplexCast)
808 : ImpCastExprToType(E, Context.LongDoubleTy,
809 CK_FloatingCast);
810 break;
811 }
812 }
813
814 // Half FP have to be promoted to float unless it is natively supported
815 if (Ty->isHalfType() && !getLangOpts().NativeHalfType)
816 return ImpCastExprToType(Res.get(), Context.FloatTy, CK_FloatingCast);
817
818 // Try to perform integral promotions if the object has a theoretically
819 // promotable type.
820 if (Ty->isIntegralOrUnscopedEnumerationType()) {
821 // C99 6.3.1.1p2:
822 //
823 // The following may be used in an expression wherever an int or
824 // unsigned int may be used:
825 // - an object or expression with an integer type whose integer
826 // conversion rank is less than or equal to the rank of int
827 // and unsigned int.
828 // - A bit-field of type _Bool, int, signed int, or unsigned int.
829 //
830 // If an int can represent all values of the original type, the
831 // value is converted to an int; otherwise, it is converted to an
832 // unsigned int. These are called the integer promotions. All
833 // other types are unchanged by the integer promotions.
834
835 QualType PTy = Context.isPromotableBitField(E);
836 if (!PTy.isNull()) {
837 E = ImpCastExprToType(E, PTy, CK_IntegralCast).get();
838 return E;
839 }
840 if (Ty->isPromotableIntegerType()) {
841 QualType PT = Context.getPromotedIntegerType(Ty);
842 E = ImpCastExprToType(E, PT, CK_IntegralCast).get();
843 return E;
844 }
845 }
846 return E;
847}
848
849/// DefaultArgumentPromotion (C99 6.5.2.2p6). Used for function calls that
850/// do not have a prototype. Arguments that have type float or __fp16
851/// are promoted to double. All other argument types are converted by
852/// UsualUnaryConversions().
853ExprResult Sema::DefaultArgumentPromotion(Expr *E) {
854 QualType Ty = E->getType();
855 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", 855, __extension__ __PRETTY_FUNCTION__
))
;
856
857 ExprResult Res = UsualUnaryConversions(E);
858 if (Res.isInvalid())
859 return ExprError();
860 E = Res.get();
861
862 // If this is a 'float' or '__fp16' (CVR qualified or typedef)
863 // promote to double.
864 // Note that default argument promotion applies only to float (and
865 // half/fp16); it does not apply to _Float16.
866 const BuiltinType *BTy = Ty->getAs<BuiltinType>();
867 if (BTy && (BTy->getKind() == BuiltinType::Half ||
868 BTy->getKind() == BuiltinType::Float)) {
869 if (getLangOpts().OpenCL &&
870 !getOpenCLOptions().isAvailableOption("cl_khr_fp64", getLangOpts())) {
871 if (BTy->getKind() == BuiltinType::Half) {
872 E = ImpCastExprToType(E, Context.FloatTy, CK_FloatingCast).get();
873 }
874 } else {
875 E = ImpCastExprToType(E, Context.DoubleTy, CK_FloatingCast).get();
876 }
877 }
878 if (BTy &&
879 getLangOpts().getExtendIntArgs() ==
880 LangOptions::ExtendArgsKind::ExtendTo64 &&
881 Context.getTargetInfo().supportsExtendIntArgs() && Ty->isIntegerType() &&
882 Context.getTypeSizeInChars(BTy) <
883 Context.getTypeSizeInChars(Context.LongLongTy)) {
884 E = (Ty->isUnsignedIntegerType())
885 ? ImpCastExprToType(E, Context.UnsignedLongLongTy, CK_IntegralCast)
886 .get()
887 : ImpCastExprToType(E, Context.LongLongTy, CK_IntegralCast).get();
888 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", 889, __extension__ __PRETTY_FUNCTION__
))
889 "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", 889, __extension__ __PRETTY_FUNCTION__
))
;
890 }
891
892 // C++ performs lvalue-to-rvalue conversion as a default argument
893 // promotion, even on class types, but note:
894 // C++11 [conv.lval]p2:
895 // When an lvalue-to-rvalue conversion occurs in an unevaluated
896 // operand or a subexpression thereof the value contained in the
897 // referenced object is not accessed. Otherwise, if the glvalue
898 // has a class type, the conversion copy-initializes a temporary
899 // of type T from the glvalue and the result of the conversion
900 // is a prvalue for the temporary.
901 // FIXME: add some way to gate this entire thing for correctness in
902 // potentially potentially evaluated contexts.
903 if (getLangOpts().CPlusPlus && E->isGLValue() && !isUnevaluatedContext()) {
904 ExprResult Temp = PerformCopyInitialization(
905 InitializedEntity::InitializeTemporary(E->getType()),
906 E->getExprLoc(), E);
907 if (Temp.isInvalid())
908 return ExprError();
909 E = Temp.get();
910 }
911
912 return E;
913}
914
915/// Determine the degree of POD-ness for an expression.
916/// Incomplete types are considered POD, since this check can be performed
917/// when we're in an unevaluated context.
918Sema::VarArgKind Sema::isValidVarArgType(const QualType &Ty) {
919 if (Ty->isIncompleteType()) {
920 // C++11 [expr.call]p7:
921 // After these conversions, if the argument does not have arithmetic,
922 // enumeration, pointer, pointer to member, or class type, the program
923 // is ill-formed.
924 //
925 // Since we've already performed array-to-pointer and function-to-pointer
926 // decay, the only such type in C++ is cv void. This also handles
927 // initializer lists as variadic arguments.
928 if (Ty->isVoidType())
929 return VAK_Invalid;
930
931 if (Ty->isObjCObjectType())
932 return VAK_Invalid;
933 return VAK_Valid;
934 }
935
936 if (Ty.isDestructedType() == QualType::DK_nontrivial_c_struct)
937 return VAK_Invalid;
938
939 if (Ty.isCXX98PODType(Context))
940 return VAK_Valid;
941
942 // C++11 [expr.call]p7:
943 // Passing a potentially-evaluated argument of class type (Clause 9)
944 // having a non-trivial copy constructor, a non-trivial move constructor,
945 // or a non-trivial destructor, with no corresponding parameter,
946 // is conditionally-supported with implementation-defined semantics.
947 if (getLangOpts().CPlusPlus11 && !Ty->isDependentType())
948 if (CXXRecordDecl *Record = Ty->getAsCXXRecordDecl())
949 if (!Record->hasNonTrivialCopyConstructor() &&
950 !Record->hasNonTrivialMoveConstructor() &&
951 !Record->hasNonTrivialDestructor())
952 return VAK_ValidInCXX11;
953
954 if (getLangOpts().ObjCAutoRefCount && Ty->isObjCLifetimeType())
955 return VAK_Valid;
956
957 if (Ty->isObjCObjectType())
958 return VAK_Invalid;
959
960 if (getLangOpts().MSVCCompat)
961 return VAK_MSVCUndefined;
962
963 // FIXME: In C++11, these cases are conditionally-supported, meaning we're
964 // permitted to reject them. We should consider doing so.
965 return VAK_Undefined;
966}
967
968void Sema::checkVariadicArgument(const Expr *E, VariadicCallType CT) {
969 // Don't allow one to pass an Objective-C interface to a vararg.
970 const QualType &Ty = E->getType();
971 VarArgKind VAK = isValidVarArgType(Ty);
972
973 // Complain about passing non-POD types through varargs.
974 switch (VAK) {
975 case VAK_ValidInCXX11:
976 DiagRuntimeBehavior(
977 E->getBeginLoc(), nullptr,
978 PDiag(diag::warn_cxx98_compat_pass_non_pod_arg_to_vararg) << Ty << CT);
979 LLVM_FALLTHROUGH[[gnu::fallthrough]];
980 case VAK_Valid:
981 if (Ty->isRecordType()) {
982 // This is unlikely to be what the user intended. If the class has a
983 // 'c_str' member function, the user probably meant to call that.
984 DiagRuntimeBehavior(E->getBeginLoc(), nullptr,
985 PDiag(diag::warn_pass_class_arg_to_vararg)
986 << Ty << CT << hasCStrMethod(E) << ".c_str()");
987 }
988 break;
989
990 case VAK_Undefined:
991 case VAK_MSVCUndefined:
992 DiagRuntimeBehavior(E->getBeginLoc(), nullptr,
993 PDiag(diag::warn_cannot_pass_non_pod_arg_to_vararg)
994 << getLangOpts().CPlusPlus11 << Ty << CT);
995 break;
996
997 case VAK_Invalid:
998 if (Ty.isDestructedType() == QualType::DK_nontrivial_c_struct)
999 Diag(E->getBeginLoc(),
1000 diag::err_cannot_pass_non_trivial_c_struct_to_vararg)
1001 << Ty << CT;
1002 else if (Ty->isObjCObjectType())
1003 DiagRuntimeBehavior(E->getBeginLoc(), nullptr,
1004 PDiag(diag::err_cannot_pass_objc_interface_to_vararg)
1005 << Ty << CT);
1006 else
1007 Diag(E->getBeginLoc(), diag::err_cannot_pass_to_vararg)
1008 << isa<InitListExpr>(E) << Ty << CT;
1009 break;
1010 }
1011}
1012
1013/// DefaultVariadicArgumentPromotion - Like DefaultArgumentPromotion, but
1014/// will create a trap if the resulting type is not a POD type.
1015ExprResult Sema::DefaultVariadicArgumentPromotion(Expr *E, VariadicCallType CT,
1016 FunctionDecl *FDecl) {
1017 if (const BuiltinType *PlaceholderTy = E->getType()->getAsPlaceholderType()) {
1018 // Strip the unbridged-cast placeholder expression off, if applicable.
1019 if (PlaceholderTy->getKind() == BuiltinType::ARCUnbridgedCast &&
1020 (CT == VariadicMethod ||
1021 (FDecl && FDecl->hasAttr<CFAuditedTransferAttr>()))) {
1022 E = stripARCUnbridgedCast(E);
1023
1024 // Otherwise, do normal placeholder checking.
1025 } else {
1026 ExprResult ExprRes = CheckPlaceholderExpr(E);
1027 if (ExprRes.isInvalid())
1028 return ExprError();
1029 E = ExprRes.get();
1030 }
1031 }
1032
1033 ExprResult ExprRes = DefaultArgumentPromotion(E);
1034 if (ExprRes.isInvalid())
1035 return ExprError();
1036
1037 // Copy blocks to the heap.
1038 if (ExprRes.get()->getType()->isBlockPointerType())
1039 maybeExtendBlockObject(ExprRes);
1040
1041 E = ExprRes.get();
1042
1043 // Diagnostics regarding non-POD argument types are
1044 // emitted along with format string checking in Sema::CheckFunctionCall().
1045 if (isValidVarArgType(E->getType()) == VAK_Undefined) {
1046 // Turn this into a trap.
1047 CXXScopeSpec SS;
1048 SourceLocation TemplateKWLoc;
1049 UnqualifiedId Name;
1050 Name.setIdentifier(PP.getIdentifierInfo("__builtin_trap"),
1051 E->getBeginLoc());
1052 ExprResult TrapFn = ActOnIdExpression(TUScope, SS, TemplateKWLoc, Name,
1053 /*HasTrailingLParen=*/true,
1054 /*IsAddressOfOperand=*/false);
1055 if (TrapFn.isInvalid())
1056 return ExprError();
1057
1058 ExprResult Call = BuildCallExpr(TUScope, TrapFn.get(), E->getBeginLoc(),
1059 None, E->getEndLoc());
1060 if (Call.isInvalid())
1061 return ExprError();
1062
1063 ExprResult Comma =
1064 ActOnBinOp(TUScope, E->getBeginLoc(), tok::comma, Call.get(), E);
1065 if (Comma.isInvalid())
1066 return ExprError();
1067 return Comma.get();
1068 }
1069
1070 if (!getLangOpts().CPlusPlus &&
1071 RequireCompleteType(E->getExprLoc(), E->getType(),
1072 diag::err_call_incomplete_argument))
1073 return ExprError();
1074
1075 return E;
1076}
1077
1078/// Converts an integer to complex float type. Helper function of
1079/// UsualArithmeticConversions()
1080///
1081/// \return false if the integer expression is an integer type and is
1082/// successfully converted to the complex type.
1083static bool handleIntegerToComplexFloatConversion(Sema &S, ExprResult &IntExpr,
1084 ExprResult &ComplexExpr,
1085 QualType IntTy,
1086 QualType ComplexTy,
1087 bool SkipCast) {
1088 if (IntTy->isComplexType() || IntTy->isRealFloatingType()) return true;
1089 if (SkipCast) return false;
1090 if (IntTy->isIntegerType()) {
1091 QualType fpTy = cast<ComplexType>(ComplexTy)->getElementType();
1092 IntExpr = S.ImpCastExprToType(IntExpr.get(), fpTy, CK_IntegralToFloating);
1093 IntExpr = S.ImpCastExprToType(IntExpr.get(), ComplexTy,
1094 CK_FloatingRealToComplex);
1095 } else {
1096 assert(IntTy->isComplexIntegerType())(static_cast <bool> (IntTy->isComplexIntegerType()) ?
void (0) : __assert_fail ("IntTy->isComplexIntegerType()"
, "clang/lib/Sema/SemaExpr.cpp", 1096, __extension__ __PRETTY_FUNCTION__
))
;
1097 IntExpr = S.ImpCastExprToType(IntExpr.get(), ComplexTy,
1098 CK_IntegralComplexToFloatingComplex);
1099 }
1100 return false;
1101}
1102
1103/// Handle arithmetic conversion with complex types. Helper function of
1104/// UsualArithmeticConversions()
1105static QualType handleComplexFloatConversion(Sema &S, ExprResult &LHS,
1106 ExprResult &RHS, QualType LHSType,
1107 QualType RHSType,
1108 bool IsCompAssign) {
1109 // if we have an integer operand, the result is the complex type.
1110 if (!handleIntegerToComplexFloatConversion(S, RHS, LHS, RHSType, LHSType,
1111 /*skipCast*/false))
1112 return LHSType;
1113 if (!handleIntegerToComplexFloatConversion(S, LHS, RHS, LHSType, RHSType,
1114 /*skipCast*/IsCompAssign))
1115 return RHSType;
1116
1117 // This handles complex/complex, complex/float, or float/complex.
1118 // When both operands are complex, the shorter operand is converted to the
1119 // type of the longer, and that is the type of the result. This corresponds
1120 // to what is done when combining two real floating-point operands.
1121 // The fun begins when size promotion occur across type domains.
1122 // From H&S 6.3.4: When one operand is complex and the other is a real
1123 // floating-point type, the less precise type is converted, within it's
1124 // real or complex domain, to the precision of the other type. For example,
1125 // when combining a "long double" with a "double _Complex", the
1126 // "double _Complex" is promoted to "long double _Complex".
1127
1128 // Compute the rank of the two types, regardless of whether they are complex.
1129 int Order = S.Context.getFloatingTypeOrder(LHSType, RHSType);
1130
1131 auto *LHSComplexType = dyn_cast<ComplexType>(LHSType);
1132 auto *RHSComplexType = dyn_cast<ComplexType>(RHSType);
1133 QualType LHSElementType =
1134 LHSComplexType ? LHSComplexType->getElementType() : LHSType;
1135 QualType RHSElementType =
1136 RHSComplexType ? RHSComplexType->getElementType() : RHSType;
1137
1138 QualType ResultType = S.Context.getComplexType(LHSElementType);
1139 if (Order < 0) {
1140 // Promote the precision of the LHS if not an assignment.
1141 ResultType = S.Context.getComplexType(RHSElementType);
1142 if (!IsCompAssign) {
1143 if (LHSComplexType)
1144 LHS =
1145 S.ImpCastExprToType(LHS.get(), ResultType, CK_FloatingComplexCast);
1146 else
1147 LHS = S.ImpCastExprToType(LHS.get(), RHSElementType, CK_FloatingCast);
1148 }
1149 } else if (Order > 0) {
1150 // Promote the precision of the RHS.
1151 if (RHSComplexType)
1152 RHS = S.ImpCastExprToType(RHS.get(), ResultType, CK_FloatingComplexCast);
1153 else
1154 RHS = S.ImpCastExprToType(RHS.get(), LHSElementType, CK_FloatingCast);
1155 }
1156 return ResultType;
1157}
1158
1159/// Handle arithmetic conversion from integer to float. Helper function
1160/// of UsualArithmeticConversions()
1161static QualType handleIntToFloatConversion(Sema &S, ExprResult &FloatExpr,
1162 ExprResult &IntExpr,
1163 QualType FloatTy, QualType IntTy,
1164 bool ConvertFloat, bool ConvertInt) {
1165 if (IntTy->isIntegerType()) {
1166 if (ConvertInt)
1167 // Convert intExpr to the lhs floating point type.
1168 IntExpr = S.ImpCastExprToType(IntExpr.get(), FloatTy,
1169 CK_IntegralToFloating);
1170 return FloatTy;
1171 }
1172
1173 // Convert both sides to the appropriate complex float.
1174 assert(IntTy->isComplexIntegerType())(static_cast <bool> (IntTy->isComplexIntegerType()) ?
void (0) : __assert_fail ("IntTy->isComplexIntegerType()"
, "clang/lib/Sema/SemaExpr.cpp", 1174, __extension__ __PRETTY_FUNCTION__
))
;
1175 QualType result = S.Context.getComplexType(FloatTy);
1176
1177 // _Complex int -> _Complex float
1178 if (ConvertInt)
1179 IntExpr = S.ImpCastExprToType(IntExpr.get(), result,
1180 CK_IntegralComplexToFloatingComplex);
1181
1182 // float -> _Complex float
1183 if (ConvertFloat)
1184 FloatExpr = S.ImpCastExprToType(FloatExpr.get(), result,
1185 CK_FloatingRealToComplex);
1186
1187 return result;
1188}
1189
1190/// Handle arithmethic conversion with floating point types. Helper
1191/// function of UsualArithmeticConversions()
1192static QualType handleFloatConversion(Sema &S, ExprResult &LHS,
1193 ExprResult &RHS, QualType LHSType,
1194 QualType RHSType, bool IsCompAssign) {
1195 bool LHSFloat = LHSType->isRealFloatingType();
1196 bool RHSFloat = RHSType->isRealFloatingType();
1197
1198 // N1169 4.1.4: If one of the operands has a floating type and the other
1199 // operand has a fixed-point type, the fixed-point operand
1200 // is converted to the floating type [...]
1201 if (LHSType->isFixedPointType() || RHSType->isFixedPointType()) {
1202 if (LHSFloat)
1203 RHS = S.ImpCastExprToType(RHS.get(), LHSType, CK_FixedPointToFloating);
1204 else if (!IsCompAssign)
1205 LHS = S.ImpCastExprToType(LHS.get(), RHSType, CK_FixedPointToFloating);
1206 return LHSFloat ? LHSType : RHSType;
1207 }
1208
1209 // If we have two real floating types, convert the smaller operand
1210 // to the bigger result.
1211 if (LHSFloat && RHSFloat) {
1212 int order = S.Context.getFloatingTypeOrder(LHSType, RHSType);
1213 if (order > 0) {
1214 RHS = S.ImpCastExprToType(RHS.get(), LHSType, CK_FloatingCast);
1215 return LHSType;
1216 }
1217
1218 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", 1218, __extension__ __PRETTY_FUNCTION__
))
;
1219 if (!IsCompAssign)
1220 LHS = S.ImpCastExprToType(LHS.get(), RHSType, CK_FloatingCast);
1221 return RHSType;
1222 }
1223
1224 if (LHSFloat) {
1225 // Half FP has to be promoted to float unless it is natively supported
1226 if (LHSType->isHalfType() && !S.getLangOpts().NativeHalfType)
1227 LHSType = S.Context.FloatTy;
1228
1229 return handleIntToFloatConversion(S, LHS, RHS, LHSType, RHSType,
1230 /*ConvertFloat=*/!IsCompAssign,
1231 /*ConvertInt=*/ true);
1232 }
1233 assert(RHSFloat)(static_cast <bool> (RHSFloat) ? void (0) : __assert_fail
("RHSFloat", "clang/lib/Sema/SemaExpr.cpp", 1233, __extension__
__PRETTY_FUNCTION__))
;
1234 return handleIntToFloatConversion(S, RHS, LHS, RHSType, LHSType,
1235 /*ConvertFloat=*/ true,
1236 /*ConvertInt=*/!IsCompAssign);
1237}
1238
1239/// Diagnose attempts to convert between __float128, __ibm128 and
1240/// long double if there is no support for such conversion.
1241/// Helper function of UsualArithmeticConversions().
1242static bool unsupportedTypeConversion(const Sema &S, QualType LHSType,
1243 QualType RHSType) {
1244 // No issue if either is not a floating point type.
1245 if (!LHSType->isFloatingType() || !RHSType->isFloatingType())
1246 return false;
1247
1248 // No issue if both have the same 128-bit float semantics.
1249 auto *LHSComplex = LHSType->getAs<ComplexType>();
1250 auto *RHSComplex = RHSType->getAs<ComplexType>();
1251
1252 QualType LHSElem = LHSComplex ? LHSComplex->getElementType() : LHSType;
1253 QualType RHSElem = RHSComplex ? RHSComplex->getElementType() : RHSType;
1254
1255 const llvm::fltSemantics &LHSSem = S.Context.getFloatTypeSemantics(LHSElem);
1256 const llvm::fltSemantics &RHSSem = S.Context.getFloatTypeSemantics(RHSElem);
1257
1258 if ((&LHSSem != &llvm::APFloat::PPCDoubleDouble() ||
1259 &RHSSem != &llvm::APFloat::IEEEquad()) &&
1260 (&LHSSem != &llvm::APFloat::IEEEquad() ||
1261 &RHSSem != &llvm::APFloat::PPCDoubleDouble()))
1262 return false;
1263
1264 return true;
1265}
1266
1267typedef ExprResult PerformCastFn(Sema &S, Expr *operand, QualType toType);
1268
1269namespace {
1270/// These helper callbacks are placed in an anonymous namespace to
1271/// permit their use as function template parameters.
1272ExprResult doIntegralCast(Sema &S, Expr *op, QualType toType) {
1273 return S.ImpCastExprToType(op, toType, CK_IntegralCast);
1274}
1275
1276ExprResult doComplexIntegralCast(Sema &S, Expr *op, QualType toType) {
1277 return S.ImpCastExprToType(op, S.Context.getComplexType(toType),
1278 CK_IntegralComplexCast);
1279}
1280}
1281
1282/// Handle integer arithmetic conversions. Helper function of
1283/// UsualArithmeticConversions()
1284template <PerformCastFn doLHSCast, PerformCastFn doRHSCast>
1285static QualType handleIntegerConversion(Sema &S, ExprResult &LHS,
1286 ExprResult &RHS, QualType LHSType,
1287 QualType RHSType, bool IsCompAssign) {
1288 // The rules for this case are in C99 6.3.1.8
1289 int order = S.Context.getIntegerTypeOrder(LHSType, RHSType);
1290 bool LHSSigned = LHSType->hasSignedIntegerRepresentation();
1291 bool RHSSigned = RHSType->hasSignedIntegerRepresentation();
1292 if (LHSSigned == RHSSigned) {
1293 // Same signedness; use the higher-ranked type
1294 if (order >= 0) {
1295 RHS = (*doRHSCast)(S, RHS.get(), LHSType);
1296 return LHSType;
1297 } else if (!IsCompAssign)
1298 LHS = (*doLHSCast)(S, LHS.get(), RHSType);
1299 return RHSType;
1300 } else if (order != (LHSSigned ? 1 : -1)) {
1301 // The unsigned type has greater than or equal rank to the
1302 // signed type, so use the unsigned type
1303 if (RHSSigned) {
1304 RHS = (*doRHSCast)(S, RHS.get(), LHSType);
1305 return LHSType;
1306 } else if (!IsCompAssign)
1307 LHS = (*doLHSCast)(S, LHS.get(), RHSType);
1308 return RHSType;
1309 } else if (S.Context.getIntWidth(LHSType) != S.Context.getIntWidth(RHSType)) {
1310 // The two types are different widths; if we are here, that
1311 // means the signed type is larger than the unsigned type, so
1312 // use the signed type.
1313 if (LHSSigned) {
1314 RHS = (*doRHSCast)(S, RHS.get(), LHSType);
1315 return LHSType;
1316 } else if (!IsCompAssign)
1317 LHS = (*doLHSCast)(S, LHS.get(), RHSType);
1318 return RHSType;
1319 } else {
1320 // The signed type is higher-ranked than the unsigned type,
1321 // but isn't actually any bigger (like unsigned int and long
1322 // on most 32-bit systems). Use the unsigned type corresponding
1323 // to the signed type.
1324 QualType result =
1325 S.Context.getCorrespondingUnsignedType(LHSSigned ? LHSType : RHSType);
1326 RHS = (*doRHSCast)(S, RHS.get(), result);
1327 if (!IsCompAssign)
1328 LHS = (*doLHSCast)(S, LHS.get(), result);
1329 return result;
1330 }
1331}
1332
1333/// Handle conversions with GCC complex int extension. Helper function
1334/// of UsualArithmeticConversions()
1335static QualType handleComplexIntConversion(Sema &S, ExprResult &LHS,
1336 ExprResult &RHS, QualType LHSType,
1337 QualType RHSType,
1338 bool IsCompAssign) {
1339 const ComplexType *LHSComplexInt = LHSType->getAsComplexIntegerType();
1340 const ComplexType *RHSComplexInt = RHSType->getAsComplexIntegerType();
1341
1342 if (LHSComplexInt && RHSComplexInt) {
1343 QualType LHSEltType = LHSComplexInt->getElementType();
1344 QualType RHSEltType = RHSComplexInt->getElementType();
1345 QualType ScalarType =
1346 handleIntegerConversion<doComplexIntegralCast, doComplexIntegralCast>
1347 (S, LHS, RHS, LHSEltType, RHSEltType, IsCompAssign);
1348
1349 return S.Context.getComplexType(ScalarType);
1350 }
1351
1352 if (LHSComplexInt) {
1353 QualType LHSEltType = LHSComplexInt->getElementType();
1354 QualType ScalarType =
1355 handleIntegerConversion<doComplexIntegralCast, doIntegralCast>
1356 (S, LHS, RHS, LHSEltType, RHSType, IsCompAssign);
1357 QualType ComplexType = S.Context.getComplexType(ScalarType);
1358 RHS = S.ImpCastExprToType(RHS.get(), ComplexType,
1359 CK_IntegralRealToComplex);
1360
1361 return ComplexType;
1362 }
1363
1364 assert(RHSComplexInt)(static_cast <bool> (RHSComplexInt) ? void (0) : __assert_fail
("RHSComplexInt", "clang/lib/Sema/SemaExpr.cpp", 1364, __extension__
__PRETTY_FUNCTION__))
;
1365
1366 QualType RHSEltType = RHSComplexInt->getElementType();
1367 QualType ScalarType =
1368 handleIntegerConversion<doIntegralCast, doComplexIntegralCast>
1369 (S, LHS, RHS, LHSType, RHSEltType, IsCompAssign);
1370 QualType ComplexType = S.Context.getComplexType(ScalarType);
1371
1372 if (!IsCompAssign)
1373 LHS = S.ImpCastExprToType(LHS.get(), ComplexType,
1374 CK_IntegralRealToComplex);
1375 return ComplexType;
1376}
1377
1378/// Return the rank of a given fixed point or integer type. The value itself
1379/// doesn't matter, but the values must be increasing with proper increasing
1380/// rank as described in N1169 4.1.1.
1381static unsigned GetFixedPointRank(QualType Ty) {
1382 const auto *BTy = Ty->getAs<BuiltinType>();
1383 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", 1383, __extension__ __PRETTY_FUNCTION__
))
;
1384
1385 switch (BTy->getKind()) {
1386 case BuiltinType::ShortFract:
1387 case BuiltinType::UShortFract:
1388 case BuiltinType::SatShortFract:
1389 case BuiltinType::SatUShortFract:
1390 return 1;
1391 case BuiltinType::Fract:
1392 case BuiltinType::UFract:
1393 case BuiltinType::SatFract:
1394 case BuiltinType::SatUFract:
1395 return 2;
1396 case BuiltinType::LongFract:
1397 case BuiltinType::ULongFract:
1398 case BuiltinType::SatLongFract:
1399 case BuiltinType::SatULongFract:
1400 return 3;
1401 case BuiltinType::ShortAccum:
1402 case BuiltinType::UShortAccum:
1403 case BuiltinType::SatShortAccum:
1404 case BuiltinType::SatUShortAccum:
1405 return 4;
1406 case BuiltinType::Accum:
1407 case BuiltinType::UAccum:
1408 case BuiltinType::SatAccum:
1409 case BuiltinType::SatUAccum:
1410 return 5;
1411 case BuiltinType::LongAccum:
1412 case BuiltinType::ULongAccum:
1413 case BuiltinType::SatLongAccum:
1414 case BuiltinType::SatULongAccum:
1415 return 6;
1416 default:
1417 if (BTy->isInteger())
1418 return 0;
1419 llvm_unreachable("Unexpected fixed point or integer type")::llvm::llvm_unreachable_internal("Unexpected fixed point or integer type"
, "clang/lib/Sema/SemaExpr.cpp", 1419)
;
1420 }
1421}
1422
1423/// handleFixedPointConversion - Fixed point operations between fixed
1424/// point types and integers or other fixed point types do not fall under
1425/// usual arithmetic conversion since these conversions could result in loss
1426/// of precsision (N1169 4.1.4). These operations should be calculated with
1427/// the full precision of their result type (N1169 4.1.6.2.1).
1428static QualType handleFixedPointConversion(Sema &S, QualType LHSTy,
1429 QualType RHSTy) {
1430 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", 1431, __extension__ __PRETTY_FUNCTION__
))
1431 "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", 1431, __extension__ __PRETTY_FUNCTION__
))
;
1432 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", 1435, __extension__ __PRETTY_FUNCTION__
))
1433 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", 1435, __extension__ __PRETTY_FUNCTION__
))
1434 "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", 1435, __extension__ __PRETTY_FUNCTION__
))
1435 "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", 1435, __extension__ __PRETTY_FUNCTION__
))
;
1436
1437 // If one operand has signed fixed-point type and the other operand has
1438 // unsigned fixed-point type, then the unsigned fixed-point operand is
1439 // converted to its corresponding signed fixed-point type and the resulting
1440 // type is the type of the converted operand.
1441 if (RHSTy->isSignedFixedPointType() && LHSTy->isUnsignedFixedPointType())
1442 LHSTy = S.Context.getCorrespondingSignedFixedPointType(LHSTy);
1443 else if (RHSTy->isUnsignedFixedPointType() && LHSTy->isSignedFixedPointType())
1444 RHSTy = S.Context.getCorrespondingSignedFixedPointType(RHSTy);
1445
1446 // The result type is the type with the highest rank, whereby a fixed-point
1447 // conversion rank is always greater than an integer conversion rank; if the
1448 // type of either of the operands is a saturating fixedpoint type, the result
1449 // type shall be the saturating fixed-point type corresponding to the type
1450 // with the highest rank; the resulting value is converted (taking into
1451 // account rounding and overflow) to the precision of the resulting type.
1452 // Same ranks between signed and unsigned types are resolved earlier, so both
1453 // types are either signed or both unsigned at this point.
1454 unsigned LHSTyRank = GetFixedPointRank(LHSTy);
1455 unsigned RHSTyRank = GetFixedPointRank(RHSTy);
1456
1457 QualType ResultTy = LHSTyRank > RHSTyRank ? LHSTy : RHSTy;
1458
1459 if (LHSTy->isSaturatedFixedPointType() || RHSTy->isSaturatedFixedPointType())
1460 ResultTy = S.Context.getCorrespondingSaturatedType(ResultTy);
1461
1462 return ResultTy;
1463}
1464
1465/// Check that the usual arithmetic conversions can be performed on this pair of
1466/// expressions that might be of enumeration type.
1467static void checkEnumArithmeticConversions(Sema &S, Expr *LHS, Expr *RHS,
1468 SourceLocation Loc,
1469 Sema::ArithConvKind ACK) {
1470 // C++2a [expr.arith.conv]p1:
1471 // If one operand is of enumeration type and the other operand is of a
1472 // different enumeration type or a floating-point type, this behavior is
1473 // deprecated ([depr.arith.conv.enum]).
1474 //
1475 // Warn on this in all language modes. Produce a deprecation warning in C++20.
1476 // Eventually we will presumably reject these cases (in C++23 onwards?).
1477 QualType L = LHS->getType(), R = RHS->getType();
1478 bool LEnum = L->isUnscopedEnumerationType(),
1479 REnum = R->isUnscopedEnumerationType();
1480 bool IsCompAssign = ACK == Sema::ACK_CompAssign;
1481 if ((!IsCompAssign && LEnum && R->isFloatingType()) ||
1482 (REnum && L->isFloatingType())) {
1483 S.Diag(Loc, S.getLangOpts().CPlusPlus20
1484 ? diag::warn_arith_conv_enum_float_cxx20
1485 : diag::warn_arith_conv_enum_float)
1486 << LHS->getSourceRange() << RHS->getSourceRange()
1487 << (int)ACK << LEnum << L << R;
1488 } else if (!IsCompAssign && LEnum && REnum &&
1489 !S.Context.hasSameUnqualifiedType(L, R)) {
1490 unsigned DiagID;
1491 if (!L->castAs<EnumType>()->getDecl()->hasNameForLinkage() ||
1492 !R->castAs<EnumType>()->getDecl()->hasNameForLinkage()) {
1493 // If either enumeration type is unnamed, it's less likely that the
1494 // user cares about this, but this situation is still deprecated in
1495 // C++2a. Use a different warning group.
1496 DiagID = S.getLangOpts().CPlusPlus20
1497 ? diag::warn_arith_conv_mixed_anon_enum_types_cxx20
1498 : diag::warn_arith_conv_mixed_anon_enum_types;
1499 } else if (ACK == Sema::ACK_Conditional) {
1500 // Conditional expressions are separated out because they have
1501 // historically had a different warning flag.
1502 DiagID = S.getLangOpts().CPlusPlus20
1503 ? diag::warn_conditional_mixed_enum_types_cxx20
1504 : diag::warn_conditional_mixed_enum_types;
1505 } else if (ACK == Sema::ACK_Comparison) {
1506 // Comparison expressions are separated out because they have
1507 // historically had a different warning flag.
1508 DiagID = S.getLangOpts().CPlusPlus20
1509 ? diag::warn_comparison_mixed_enum_types_cxx20
1510 : diag::warn_comparison_mixed_enum_types;
1511 } else {
1512 DiagID = S.getLangOpts().CPlusPlus20
1513 ? diag::warn_arith_conv_mixed_enum_types_cxx20
1514 : diag::warn_arith_conv_mixed_enum_types;
1515 }
1516 S.Diag(Loc, DiagID) << LHS->getSourceRange() << RHS->getSourceRange()
1517 << (int)ACK << L << R;
1518 }
1519}
1520
1521/// UsualArithmeticConversions - Performs various conversions that are common to
1522/// binary operators (C99 6.3.1.8). If both operands aren't arithmetic, this
1523/// routine returns the first non-arithmetic type found. The client is
1524/// responsible for emitting appropriate error diagnostics.
1525QualType Sema::UsualArithmeticConversions(ExprResult &LHS, ExprResult &RHS,
1526 SourceLocation Loc,
1527 ArithConvKind ACK) {
1528 checkEnumArithmeticConversions(*this, LHS.get(), RHS.get(), Loc, ACK);
1529
1530 if (ACK != ACK_CompAssign) {
1531 LHS = UsualUnaryConversions(LHS.get());
1532 if (LHS.isInvalid())
1533 return QualType();
1534 }
1535
1536 RHS = UsualUnaryConversions(RHS.get());
1537 if (RHS.isInvalid())
1538 return QualType();
1539
1540 // For conversion purposes, we ignore any qualifiers.
1541 // For example, "const float" and "float" are equivalent.
1542 QualType LHSType =
1543 Context.getCanonicalType(LHS.get()->getType()).getUnqualifiedType();
1544 QualType RHSType =
1545 Context.getCanonicalType(RHS.get()->getType()).getUnqualifiedType();
1546
1547 // For conversion purposes, we ignore any atomic qualifier on the LHS.
1548 if (const AtomicType *AtomicLHS = LHSType->getAs<AtomicType>())
1549 LHSType = AtomicLHS->getValueType();
1550
1551 // If both types are identical, no conversion is needed.
1552 if (LHSType == RHSType)
1553 return LHSType;
1554
1555 // If either side is a non-arithmetic type (e.g. a pointer), we are done.
1556 // The caller can deal with this (e.g. pointer + int).
1557 if (!LHSType->isArithmeticType() || !RHSType->isArithmeticType())
1558 return QualType();
1559
1560 // Apply unary and bitfield promotions to the LHS's type.
1561 QualType LHSUnpromotedType = LHSType;
1562 if (LHSType->isPromotableIntegerType())
1563 LHSType = Context.getPromotedIntegerType(LHSType);
1564 QualType LHSBitfieldPromoteTy = Context.isPromotableBitField(LHS.get());
1565 if (!LHSBitfieldPromoteTy.isNull())
1566 LHSType = LHSBitfieldPromoteTy;
1567 if (LHSType != LHSUnpromotedType && ACK != ACK_CompAssign)
1568 LHS = ImpCastExprToType(LHS.get(), LHSType, CK_IntegralCast);
1569
1570 // If both types are identical, no conversion is needed.
1571 if (LHSType == RHSType)
1572 return LHSType;
1573
1574 // At this point, we have two different arithmetic types.
1575
1576 // Diagnose attempts to convert between __ibm128, __float128 and long double
1577 // where such conversions currently can't be handled.
1578 if (unsupportedTypeConversion(*this, LHSType, RHSType))
1579 return QualType();
1580
1581 // Handle complex types first (C99 6.3.1.8p1).
1582 if (LHSType->isComplexType() || RHSType->isComplexType())
1583 return handleComplexFloatConversion(*this, LHS, RHS, LHSType, RHSType,
1584 ACK == ACK_CompAssign);
1585
1586 // Now handle "real" floating types (i.e. float, double, long double).
1587 if (LHSType->isRealFloatingType() || RHSType->isRealFloatingType())
1588 return handleFloatConversion(*this, LHS, RHS, LHSType, RHSType,
1589 ACK == ACK_CompAssign);
1590
1591 // Handle GCC complex int extension.
1592 if (LHSType->isComplexIntegerType() || RHSType->isComplexIntegerType())
1593 return handleComplexIntConversion(*this, LHS, RHS, LHSType, RHSType,
1594 ACK == ACK_CompAssign);
1595
1596 if (LHSType->isFixedPointType() || RHSType->isFixedPointType())
1597 return handleFixedPointConversion(*this, LHSType, RHSType);
1598
1599 // Finally, we have two differing integer types.
1600 return handleIntegerConversion<doIntegralCast, doIntegralCast>
1601 (*this, LHS, RHS, LHSType, RHSType, ACK == ACK_CompAssign);
1602}
1603
1604//===----------------------------------------------------------------------===//
1605// Semantic Analysis for various Expression Types
1606//===----------------------------------------------------------------------===//
1607
1608
1609ExprResult
1610Sema::ActOnGenericSelectionExpr(SourceLocation KeyLoc,
1611 SourceLocation DefaultLoc,
1612 SourceLocation RParenLoc,
1613 Expr *ControllingExpr,
1614 ArrayRef<ParsedType> ArgTypes,
1615 ArrayRef<Expr *> ArgExprs) {
1616 unsigned NumAssocs = ArgTypes.size();
1617 assert(NumAssocs == ArgExprs.size())(static_cast <bool> (NumAssocs == ArgExprs.size()) ? void
(0) : __assert_fail ("NumAssocs == ArgExprs.size()", "clang/lib/Sema/SemaExpr.cpp"
, 1617, __extension__ __PRETTY_FUNCTION__))
;
1618
1619 TypeSourceInfo **Types = new TypeSourceInfo*[NumAssocs];
1620 for (unsigned i = 0; i < NumAssocs; ++i) {
1621 if (ArgTypes[i])
1622 (void) GetTypeFromParser(ArgTypes[i], &Types[i]);
1623 else
1624 Types[i] = nullptr;
1625 }
1626
1627 ExprResult ER = CreateGenericSelectionExpr(KeyLoc, DefaultLoc, RParenLoc,
1628 ControllingExpr,
1629 llvm::makeArrayRef(Types, NumAssocs),
1630 ArgExprs);
1631 delete [] Types;
1632 return ER;
1633}
1634
1635ExprResult
1636Sema::CreateGenericSelectionExpr(SourceLocation KeyLoc,
1637 SourceLocation DefaultLoc,
1638 SourceLocation RParenLoc,
1639 Expr *ControllingExpr,
1640 ArrayRef<TypeSourceInfo *> Types,
1641 ArrayRef<Expr *> Exprs) {
1642 unsigned NumAssocs = Types.size();
1643 assert(NumAssocs == Exprs.size())(static_cast <bool> (NumAssocs == Exprs.size()) ? void (
0) : __assert_fail ("NumAssocs == Exprs.size()", "clang/lib/Sema/SemaExpr.cpp"
, 1643, __extension__ __PRETTY_FUNCTION__))
;
1644
1645 // Decay and strip qualifiers for the controlling expression type, and handle
1646 // placeholder type replacement. See committee discussion from WG14 DR423.
1647 {
1648 EnterExpressionEvaluationContext Unevaluated(
1649 *this, Sema::ExpressionEvaluationContext::Unevaluated);
1650 ExprResult R = DefaultFunctionArrayLvalueConversion(ControllingExpr);
1651 if (R.isInvalid())
1652 return ExprError();
1653 ControllingExpr = R.get();
1654 }
1655
1656 // The controlling expression is an unevaluated operand, so side effects are
1657 // likely unintended.
1658 if (!inTemplateInstantiation() &&
1659 ControllingExpr->HasSideEffects(Context, false))
1660 Diag(ControllingExpr->getExprLoc(),
1661 diag::warn_side_effects_unevaluated_context);
1662
1663 bool TypeErrorFound = false,
1664 IsResultDependent = ControllingExpr->isTypeDependent(),
1665 ContainsUnexpandedParameterPack
1666 = ControllingExpr->containsUnexpandedParameterPack();
1667
1668 for (unsigned i = 0; i < NumAssocs; ++i) {
1669 if (Exprs[i]->containsUnexpandedParameterPack())
1670 ContainsUnexpandedParameterPack = true;
1671
1672 if (Types[i]) {
1673 if (Types[i]->getType()->containsUnexpandedParameterPack())
1674 ContainsUnexpandedParameterPack = true;
1675
1676 if (Types[i]->getType()->isDependentType()) {
1677 IsResultDependent = true;
1678 } else {
1679 // C11 6.5.1.1p2 "The type name in a generic association shall specify a
1680 // complete object type other than a variably modified type."
1681 unsigned D = 0;
1682 if (Types[i]->getType()->isIncompleteType())
1683 D = diag::err_assoc_type_incomplete;
1684 else if (!Types[i]->getType()->isObjectType())
1685 D = diag::err_assoc_type_nonobject;
1686 else if (Types[i]->getType()->isVariablyModifiedType())
1687 D = diag::err_assoc_type_variably_modified;
1688
1689 if (D != 0) {
1690 Diag(Types[i]->getTypeLoc().getBeginLoc(), D)
1691 << Types[i]->getTypeLoc().getSourceRange()
1692 << Types[i]->getType();
1693 TypeErrorFound = true;
1694 }
1695
1696 // C11 6.5.1.1p2 "No two generic associations in the same generic
1697 // selection shall specify compatible types."
1698 for (unsigned j = i+1; j < NumAssocs; ++j)
1699 if (Types[j] && !Types[j]->getType()->isDependentType() &&
1700 Context.typesAreCompatible(Types[i]->getType(),
1701 Types[j]->getType())) {
1702 Diag(Types[j]->getTypeLoc().getBeginLoc(),
1703 diag::err_assoc_compatible_types)
1704 << Types[j]->getTypeLoc().getSourceRange()
1705 << Types[j]->getType()
1706 << Types[i]->getType();
1707 Diag(Types[i]->getTypeLoc().getBeginLoc(),
1708 diag::note_compat_assoc)
1709 << Types[i]->getTypeLoc().getSourceRange()
1710 << Types[i]->getType();
1711 TypeErrorFound = true;
1712 }
1713 }
1714 }
1715 }
1716 if (TypeErrorFound)
1717 return ExprError();
1718
1719 // If we determined that the generic selection is result-dependent, don't
1720 // try to compute the result expression.
1721 if (IsResultDependent)
1722 return GenericSelectionExpr::Create(Context, KeyLoc, ControllingExpr, Types,
1723 Exprs, DefaultLoc, RParenLoc,
1724 ContainsUnexpandedParameterPack);
1725
1726 SmallVector<unsigned, 1> CompatIndices;
1727 unsigned DefaultIndex = -1U;
1728 for (unsigned i = 0; i < NumAssocs; ++i) {
1729 if (!Types[i])
1730 DefaultIndex = i;
1731 else if (Context.typesAreCompatible(ControllingExpr->getType(),
1732 Types[i]->getType()))
1733 CompatIndices.push_back(i);
1734 }
1735
1736 // C11 6.5.1.1p2 "The controlling expression of a generic selection shall have
1737 // type compatible with at most one of the types named in its generic
1738 // association list."
1739 if (CompatIndices.size() > 1) {
1740 // We strip parens here because the controlling expression is typically
1741 // parenthesized in macro definitions.
1742 ControllingExpr = ControllingExpr->IgnoreParens();
1743 Diag(ControllingExpr->getBeginLoc(), diag::err_generic_sel_multi_match)
1744 << ControllingExpr->getSourceRange() << ControllingExpr->getType()
1745 << (unsigned)CompatIndices.size();
1746 for (unsigned I : CompatIndices) {
1747 Diag(Types[I]->getTypeLoc().getBeginLoc(),
1748 diag::note_compat_assoc)
1749 << Types[I]->getTypeLoc().getSourceRange()
1750 << Types[I]->getType();
1751 }
1752 return ExprError();
1753 }
1754
1755 // C11 6.5.1.1p2 "If a generic selection has no default generic association,
1756 // its controlling expression shall have type compatible with exactly one of
1757 // the types named in its generic association list."
1758 if (DefaultIndex == -1U && CompatIndices.size() == 0) {
1759 // We strip parens here because the controlling expression is typically
1760 // parenthesized in macro definitions.
1761 ControllingExpr = ControllingExpr->IgnoreParens();
1762 Diag(ControllingExpr->getBeginLoc(), diag::err_generic_sel_no_match)
1763 << ControllingExpr->getSourceRange() << ControllingExpr->getType();
1764 return ExprError();
1765 }
1766
1767 // C11 6.5.1.1p3 "If a generic selection has a generic association with a
1768 // type name that is compatible with the type of the controlling expression,
1769 // then the result expression of the generic selection is the expression
1770 // in that generic association. Otherwise, the result expression of the
1771 // generic selection is the expression in the default generic association."
1772 unsigned ResultIndex =
1773 CompatIndices.size() ? CompatIndices[0] : DefaultIndex;
1774
1775 return GenericSelectionExpr::Create(
1776 Context, KeyLoc, ControllingExpr, Types, Exprs, DefaultLoc, RParenLoc,
1777 ContainsUnexpandedParameterPack, ResultIndex);
1778}
1779
1780/// getUDSuffixLoc - Create a SourceLocation for a ud-suffix, given the
1781/// location of the token and the offset of the ud-suffix within it.
1782static SourceLocation getUDSuffixLoc(Sema &S, SourceLocation TokLoc,
1783 unsigned Offset) {
1784 return Lexer::AdvanceToTokenCharacter(TokLoc, Offset, S.getSourceManager(),
1785 S.getLangOpts());
1786}
1787
1788/// BuildCookedLiteralOperatorCall - A user-defined literal was found. Look up
1789/// the corresponding cooked (non-raw) literal operator, and build a call to it.
1790static ExprResult BuildCookedLiteralOperatorCall(Sema &S, Scope *Scope,
1791 IdentifierInfo *UDSuffix,
1792 SourceLocation UDSuffixLoc,
1793 ArrayRef<Expr*> Args,
1794 SourceLocation LitEndLoc) {
1795 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", 1795, __extension__ __PRETTY_FUNCTION__
))
;
1796
1797 QualType ArgTy[2];
1798 for (unsigned ArgIdx = 0; ArgIdx != Args.size(); ++ArgIdx) {
1799 ArgTy[ArgIdx] = Args[ArgIdx]->getType();
1800 if (ArgTy[ArgIdx]->isArrayType())
1801 ArgTy[ArgIdx] = S.Context.getArrayDecayedType(ArgTy[ArgIdx]);
1802 }
1803
1804 DeclarationName OpName =
1805 S.Context.DeclarationNames.getCXXLiteralOperatorName(UDSuffix);
1806 DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc);
1807 OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc);
1808
1809 LookupResult R(S, OpName, UDSuffixLoc, Sema::LookupOrdinaryName);
1810 if (S.LookupLiteralOperator(Scope, R, llvm::makeArrayRef(ArgTy, Args.size()),
1811 /*AllowRaw*/ false, /*AllowTemplate*/ false,
1812 /*AllowStringTemplatePack*/ false,
1813 /*DiagnoseMissing*/ true) == Sema::LOLR_Error)
1814 return ExprError();
1815
1816 return S.BuildLiteralOperatorCall(R, OpNameInfo, Args, LitEndLoc);
1817}
1818
1819/// ActOnStringLiteral - The specified tokens were lexed as pasted string
1820/// fragments (e.g. "foo" "bar" L"baz"). The result string has to handle string
1821/// concatenation ([C99 5.1.1.2, translation phase #6]), so it may come from
1822/// multiple tokens. However, the common case is that StringToks points to one
1823/// string.
1824///
1825ExprResult
1826Sema::ActOnStringLiteral(ArrayRef<Token> StringToks, Scope *UDLScope) {
1827 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", 1827, __extension__ __PRETTY_FUNCTION__
))
;
1828
1829 StringLiteralParser Literal(StringToks, PP);
1830 if (Literal.hadError)
1831 return ExprError();
1832
1833 SmallVector<SourceLocation, 4> StringTokLocs;
1834 for (const Token &Tok : StringToks)
1835 StringTokLocs.push_back(Tok.getLocation());
1836
1837 QualType CharTy = Context.CharTy;
1838 StringLiteral::StringKind Kind = StringLiteral::Ascii;
1839 if (Literal.isWide()) {
1840 CharTy = Context.getWideCharType();
1841 Kind = StringLiteral::Wide;
1842 } else if (Literal.isUTF8()) {
1843 if (getLangOpts().Char8)
1844 CharTy = Context.Char8Ty;
1845 Kind = StringLiteral::UTF8;
1846 } else if (Literal.isUTF16()) {
1847 CharTy = Context.Char16Ty;
1848 Kind = StringLiteral::UTF16;
1849 } else if (Literal.isUTF32()) {
1850 CharTy = Context.Char32Ty;
1851 Kind = StringLiteral::UTF32;
1852 } else if (Literal.isPascal()) {
1853 CharTy = Context.UnsignedCharTy;
1854 }
1855
1856 // Warn on initializing an array of char from a u8 string literal; this
1857 // becomes ill-formed in C++2a.
1858 if (getLangOpts().CPlusPlus && !getLangOpts().CPlusPlus20 &&
1859 !getLangOpts().Char8 && Kind == StringLiteral::UTF8) {
1860 Diag(StringTokLocs.front(), diag::warn_cxx20_compat_utf8_string);
1861
1862 // Create removals for all 'u8' prefixes in the string literal(s). This
1863 // ensures C++2a compatibility (but may change the program behavior when
1864 // built by non-Clang compilers for which the execution character set is
1865 // not always UTF-8).
1866 auto RemovalDiag = PDiag(diag::note_cxx20_compat_utf8_string_remove_u8);
1867 SourceLocation RemovalDiagLoc;
1868 for (const Token &Tok : StringToks) {
1869 if (Tok.getKind() == tok::utf8_string_literal) {
1870 if (RemovalDiagLoc.isInvalid())
1871 RemovalDiagLoc = Tok.getLocation();
1872 RemovalDiag << FixItHint::CreateRemoval(CharSourceRange::getCharRange(
1873 Tok.getLocation(),
1874 Lexer::AdvanceToTokenCharacter(Tok.getLocation(), 2,
1875 getSourceManager(), getLangOpts())));
1876 }
1877 }
1878 Diag(RemovalDiagLoc, RemovalDiag);
1879 }
1880
1881 QualType StrTy =
1882 Context.getStringLiteralArrayType(CharTy, Literal.GetNumStringChars());
1883
1884 // Pass &StringTokLocs[0], StringTokLocs.size() to factory!
1885 StringLiteral *Lit = StringLiteral::Create(Context, Literal.GetString(),
1886 Kind, Literal.Pascal, StrTy,
1887 &StringTokLocs[0],
1888 StringTokLocs.size());
1889 if (Literal.getUDSuffix().empty())
1890 return Lit;
1891
1892 // We're building a user-defined literal.
1893 IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix());
1894 SourceLocation UDSuffixLoc =
1895 getUDSuffixLoc(*this, StringTokLocs[Literal.getUDSuffixToken()],
1896 Literal.getUDSuffixOffset());
1897
1898 // Make sure we're allowed user-defined literals here.
1899 if (!UDLScope)
1900 return ExprError(Diag(UDSuffixLoc, diag::err_invalid_string_udl));
1901
1902 // C++11 [lex.ext]p5: The literal L is treated as a call of the form
1903 // operator "" X (str, len)
1904 QualType SizeType = Context.getSizeType();
1905
1906 DeclarationName OpName =
1907 Context.DeclarationNames.getCXXLiteralOperatorName(UDSuffix);
1908 DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc);
1909 OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc);
1910
1911 QualType ArgTy[] = {
1912 Context.getArrayDecayedType(StrTy), SizeType
1913 };
1914
1915 LookupResult R(*this, OpName, UDSuffixLoc, LookupOrdinaryName);
1916 switch (LookupLiteralOperator(UDLScope, R, ArgTy,
1917 /*AllowRaw*/ false, /*AllowTemplate*/ true,
1918 /*AllowStringTemplatePack*/ true,
1919 /*DiagnoseMissing*/ true, Lit)) {
1920
1921 case LOLR_Cooked: {
1922 llvm::APInt Len(Context.getIntWidth(SizeType), Literal.GetNumStringChars());
1923 IntegerLiteral *LenArg = IntegerLiteral::Create(Context, Len, SizeType,
1924 StringTokLocs[0]);
1925 Expr *Args[] = { Lit, LenArg };
1926
1927 return BuildLiteralOperatorCall(R, OpNameInfo, Args, StringTokLocs.back());
1928 }
1929
1930 case LOLR_Template: {
1931 TemplateArgumentListInfo ExplicitArgs;
1932 TemplateArgument Arg(Lit);
1933 TemplateArgumentLocInfo ArgInfo(Lit);
1934 ExplicitArgs.addArgument(TemplateArgumentLoc(Arg, ArgInfo));
1935 return BuildLiteralOperatorCall(R, OpNameInfo, None, StringTokLocs.back(),
1936 &ExplicitArgs);
1937 }
1938
1939 case LOLR_StringTemplatePack: {
1940 TemplateArgumentListInfo ExplicitArgs;
1941
1942 unsigned CharBits = Context.getIntWidth(CharTy);
1943 bool CharIsUnsigned = CharTy->isUnsignedIntegerType();
1944 llvm::APSInt Value(CharBits, CharIsUnsigned);
1945
1946 TemplateArgument TypeArg(CharTy);
1947 TemplateArgumentLocInfo TypeArgInfo(Context.getTrivialTypeSourceInfo(CharTy));
1948 ExplicitArgs.addArgument(TemplateArgumentLoc(TypeArg, TypeArgInfo));
1949
1950 for (unsigned I = 0, N = Lit->getLength(); I != N; ++I) {
1951 Value = Lit->getCodeUnit(I);
1952 TemplateArgument Arg(Context, Value, CharTy);
1953 TemplateArgumentLocInfo ArgInfo;
1954 ExplicitArgs.addArgument(TemplateArgumentLoc(Arg, ArgInfo));
1955 }
1956 return BuildLiteralOperatorCall(R, OpNameInfo, None, StringTokLocs.back(),
1957 &ExplicitArgs);
1958 }
1959 case LOLR_Raw:
1960 case LOLR_ErrorNoDiagnostic:
1961 llvm_unreachable("unexpected literal operator lookup result")::llvm::llvm_unreachable_internal("unexpected literal operator lookup result"
, "clang/lib/Sema/SemaExpr.cpp", 1961)
;
1962 case LOLR_Error:
1963 return ExprError();
1964 }
1965 llvm_unreachable("unexpected literal operator lookup result")::llvm::llvm_unreachable_internal("unexpected literal operator lookup result"
, "clang/lib/Sema/SemaExpr.cpp", 1965)
;
1966}
1967
1968DeclRefExpr *
1969Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK,
1970 SourceLocation Loc,
1971 const CXXScopeSpec *SS) {
1972 DeclarationNameInfo NameInfo(D->getDeclName(), Loc);
1973 return BuildDeclRefExpr(D, Ty, VK, NameInfo, SS);
1974}
1975
1976DeclRefExpr *
1977Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK,
1978 const DeclarationNameInfo &NameInfo,
1979 const CXXScopeSpec *SS, NamedDecl *FoundD,
1980 SourceLocation TemplateKWLoc,
1981 const TemplateArgumentListInfo *TemplateArgs) {
1982 NestedNameSpecifierLoc NNS =
1983 SS ? SS->getWithLocInContext(Context) : NestedNameSpecifierLoc();
1984 return BuildDeclRefExpr(D, Ty, VK, NameInfo, NNS, FoundD, TemplateKWLoc,
1985 TemplateArgs);
1986}
1987
1988// CUDA/HIP: Check whether a captured reference variable is referencing a
1989// host variable in a device or host device lambda.
1990static bool isCapturingReferenceToHostVarInCUDADeviceLambda(const Sema &S,
1991 VarDecl *VD) {
1992 if (!S.getLangOpts().CUDA || !VD->hasInit())
1993 return false;
1994 assert(VD->getType()->isReferenceType())(static_cast <bool> (VD->getType()->isReferenceType
()) ? void (0) : __assert_fail ("VD->getType()->isReferenceType()"
, "clang/lib/Sema/SemaExpr.cpp", 1994, __extension__ __PRETTY_FUNCTION__
))
;
1995
1996 // Check whether the reference variable is referencing a host variable.
1997 auto *DRE = dyn_cast<DeclRefExpr>(VD->getInit());
1998 if (!DRE)
1999 return false;
2000 auto *Referee = dyn_cast<VarDecl>(DRE->getDecl());
2001 if (!Referee || !Referee->hasGlobalStorage() ||
2002 Referee->hasAttr<CUDADeviceAttr>())
2003 return false;
2004
2005 // Check whether the current function is a device or host device lambda.
2006 // Check whether the reference variable is a capture by getDeclContext()
2007 // since refersToEnclosingVariableOrCapture() is not ready at this point.
2008 auto *MD = dyn_cast_or_null<CXXMethodDecl>(S.CurContext);
2009 if (MD && MD->getParent()->isLambda() &&
2010 MD->getOverloadedOperator() == OO_Call && MD->hasAttr<CUDADeviceAttr>() &&
2011 VD->getDeclContext() != MD)
2012 return true;
2013
2014 return false;
2015}
2016
2017NonOdrUseReason Sema::getNonOdrUseReasonInCurrentContext(ValueDecl *D) {
2018 // A declaration named in an unevaluated operand never constitutes an odr-use.
2019 if (isUnevaluatedContext())
2020 return NOUR_Unevaluated;
2021
2022 // C++2a [basic.def.odr]p4:
2023 // A variable x whose name appears as a potentially-evaluated expression e
2024 // is odr-used by e unless [...] x is a reference that is usable in
2025 // constant expressions.
2026 // CUDA/HIP:
2027 // If a reference variable referencing a host variable is captured in a
2028 // device or host device lambda, the value of the referee must be copied
2029 // to the capture and the reference variable must be treated as odr-use
2030 // since the value of the referee is not known at compile time and must
2031 // be loaded from the captured.
2032 if (VarDecl *VD = dyn_cast<VarDecl>(D)) {
2033 if (VD->getType()->isReferenceType() &&
2034 !(getLangOpts().OpenMP && isOpenMPCapturedDecl(D)) &&
2035 !isCapturingReferenceToHostVarInCUDADeviceLambda(*this, VD) &&
2036 VD->isUsableInConstantExpressions(Context))
2037 return NOUR_Constant;
2038 }
2039
2040 // All remaining non-variable cases constitute an odr-use. For variables, we
2041 // need to wait and see how the expression is used.
2042 return NOUR_None;
2043}
2044
2045/// BuildDeclRefExpr - Build an expression that references a
2046/// declaration that does not require a closure capture.
2047DeclRefExpr *
2048Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK,
2049 const DeclarationNameInfo &NameInfo,
2050 NestedNameSpecifierLoc NNS, NamedDecl *FoundD,
2051 SourceLocation TemplateKWLoc,
2052 const TemplateArgumentListInfo *TemplateArgs) {
2053 bool RefersToCapturedVariable =
2054 isa<VarDecl>(D) &&
2055 NeedToCaptureVariable(cast<VarDecl>(D), NameInfo.getLoc());
2056
2057 DeclRefExpr *E = DeclRefExpr::Create(
2058 Context, NNS, TemplateKWLoc, D, RefersToCapturedVariable, NameInfo, Ty,
2059 VK, FoundD, TemplateArgs, getNonOdrUseReasonInCurrentContext(D));
2060 MarkDeclRefReferenced(E);
2061
2062 // C++ [except.spec]p17:
2063 // An exception-specification is considered to be needed when:
2064 // - in an expression, the function is the unique lookup result or
2065 // the selected member of a set of overloaded functions.
2066 //
2067 // We delay doing this until after we've built the function reference and
2068 // marked it as used so that:
2069 // a) if the function is defaulted, we get errors from defining it before /
2070 // instead of errors from computing its exception specification, and
2071 // b) if the function is a defaulted comparison, we can use the body we
2072 // build when defining it as input to the exception specification
2073 // computation rather than computing a new body.
2074 if (auto *FPT = Ty->getAs<FunctionProtoType>()) {
2075 if (isUnresolvedExceptionSpec(FPT->getExceptionSpecType())) {
2076 if (auto *NewFPT = ResolveExceptionSpec(NameInfo.getLoc(), FPT))
2077 E->setType(Context.getQualifiedType(NewFPT, Ty.getQualifiers()));
2078 }
2079 }
2080
2081 if (getLangOpts().ObjCWeak && isa<VarDecl>(D) &&
2082 Ty.getObjCLifetime() == Qualifiers::OCL_Weak && !isUnevaluatedContext() &&
2083 !Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, E->getBeginLoc()))
2084 getCurFunction()->recordUseOfWeak(E);
2085
2086 FieldDecl *FD = dyn_cast<FieldDecl>(D);
2087 if (IndirectFieldDecl *IFD = dyn_cast<IndirectFieldDecl>(D))
2088 FD = IFD->getAnonField();
2089 if (FD) {
2090 UnusedPrivateFields.remove(FD);
2091 // Just in case we're building an illegal pointer-to-member.
2092 if (FD->isBitField())
2093 E->setObjectKind(OK_BitField);
2094 }
2095
2096 // C++ [expr.prim]/8: The expression [...] is a bit-field if the identifier
2097 // designates a bit-field.
2098 if (auto *BD = dyn_cast<BindingDecl>(D))
2099 if (auto *BE = BD->getBinding())
2100 E->setObjectKind(BE->getObjectKind());
2101
2102 return E;
2103}
2104
2105/// Decomposes the given name into a DeclarationNameInfo, its location, and
2106/// possibly a list of template arguments.
2107///
2108/// If this produces template arguments, it is permitted to call
2109/// DecomposeTemplateName.
2110///
2111/// This actually loses a lot of source location information for
2112/// non-standard name kinds; we should consider preserving that in
2113/// some way.
2114void
2115Sema::DecomposeUnqualifiedId(const UnqualifiedId &Id,
2116 TemplateArgumentListInfo &Buffer,
2117 DeclarationNameInfo &NameInfo,
2118 const TemplateArgumentListInfo *&TemplateArgs) {
2119 if (Id.getKind() == UnqualifiedIdKind::IK_TemplateId) {
2120 Buffer.setLAngleLoc(Id.TemplateId->LAngleLoc);
2121 Buffer.setRAngleLoc(Id.TemplateId->RAngleLoc);
2122
2123 ASTTemplateArgsPtr TemplateArgsPtr(Id.TemplateId->getTemplateArgs(),
2124 Id.TemplateId->NumArgs);
2125 translateTemplateArguments(TemplateArgsPtr, Buffer);
2126
2127 TemplateName TName = Id.TemplateId->Template.get();
2128 SourceLocation TNameLoc = Id.TemplateId->TemplateNameLoc;
2129 NameInfo = Context.getNameForTemplate(TName, TNameLoc);
2130 TemplateArgs = &Buffer;
2131 } else {
2132 NameInfo = GetNameFromUnqualifiedId(Id);
2133 TemplateArgs = nullptr;
2134 }
2135}
2136
2137static void emitEmptyLookupTypoDiagnostic(
2138 const TypoCorrection &TC, Sema &SemaRef, const CXXScopeSpec &SS,
2139 DeclarationName Typo, SourceLocation TypoLoc, ArrayRef<Expr *> Args,
2140 unsigned DiagnosticID, unsigned DiagnosticSuggestID) {
2141 DeclContext *Ctx =
2142 SS.isEmpty() ? nullptr : SemaRef.computeDeclContext(SS, false);
2143 if (!TC) {
2144 // Emit a special diagnostic for failed member lookups.
2145 // FIXME: computing the declaration context might fail here (?)
2146 if (Ctx)
2147 SemaRef.Diag(TypoLoc, diag::err_no_member) << Typo << Ctx
2148 << SS.getRange();
2149 else
2150 SemaRef.Diag(TypoLoc, DiagnosticID) << Typo;
2151 return;
2152 }
2153
2154 std::string CorrectedStr = TC.getAsString(SemaRef.getLangOpts());
2155 bool DroppedSpecifier =
2156 TC.WillReplaceSpecifier() && Typo.getAsString() == CorrectedStr;
2157 unsigned NoteID = TC.getCorrectionDeclAs<ImplicitParamDecl>()
2158 ? diag::note_implicit_param_decl
2159 : diag::note_previous_decl;
2160 if (!Ctx)
2161 SemaRef.diagnoseTypo(TC, SemaRef.PDiag(DiagnosticSuggestID) << Typo,
2162 SemaRef.PDiag(NoteID));
2163 else
2164 SemaRef.diagnoseTypo(TC, SemaRef.PDiag(diag::err_no_member_suggest)
2165 << Typo << Ctx << DroppedSpecifier
2166 << SS.getRange(),
2167 SemaRef.PDiag(NoteID));
2168}
2169
2170/// Diagnose a lookup that found results in an enclosing class during error
2171/// recovery. This usually indicates that the results were found in a dependent
2172/// base class that could not be searched as part of a template definition.
2173/// Always issues a diagnostic (though this may be only a warning in MS
2174/// compatibility mode).
2175///
2176/// Return \c true if the error is unrecoverable, or \c false if the caller
2177/// should attempt to recover using these lookup results.
2178bool Sema::DiagnoseDependentMemberLookup(LookupResult &R) {
2179 // During a default argument instantiation the CurContext points
2180 // to a CXXMethodDecl; but we can't apply a this-> fixit inside a
2181 // function parameter list, hence add an explicit check.
2182 bool isDefaultArgument =
2183 !CodeSynthesisContexts.empty() &&
2184 CodeSynthesisContexts.back().Kind ==
2185 CodeSynthesisContext::DefaultFunctionArgumentInstantiation;
2186 CXXMethodDecl *CurMethod = dyn_cast<CXXMethodDecl>(CurContext);
2187 bool isInstance = CurMethod && CurMethod->isInstance() &&
2188 R.getNamingClass() == CurMethod->getParent() &&
2189 !isDefaultArgument;
2190
2191 // There are two ways we can find a class-scope declaration during template
2192 // instantiation that we did not find in the template definition: if it is a
2193 // member of a dependent base class, or if it is declared after the point of
2194 // use in the same class. Distinguish these by comparing the class in which
2195 // the member was found to the naming class of the lookup.
2196 unsigned DiagID = diag::err_found_in_dependent_base;
2197 unsigned NoteID = diag::note_member_declared_at;
2198 if (R.getRepresentativeDecl()->getDeclContext()->Equals(R.getNamingClass())) {
2199 DiagID = getLangOpts().MSVCCompat ? diag::ext_found_later_in_class
2200 : diag::err_found_later_in_class;
2201 } else if (getLangOpts().MSVCCompat) {
2202 DiagID = diag::ext_found_in_dependent_base;
2203 NoteID = diag::note_dependent_member_use;
2204 }
2205
2206 if (isInstance) {
2207 // Give a code modification hint to insert 'this->'.
2208 Diag(R.getNameLoc(), DiagID)
2209 << R.getLookupName()
2210 << FixItHint::CreateInsertion(R.getNameLoc(), "this->");
2211 CheckCXXThisCapture(R.getNameLoc());
2212 } else {
2213 // FIXME: Add a FixItHint to insert 'Base::' or 'Derived::' (assuming
2214 // they're not shadowed).
2215 Diag(R.getNameLoc(), DiagID) << R.getLookupName();
2216 }
2217
2218 for (NamedDecl *D : R)
2219 Diag(D->getLocation(), NoteID);
2220
2221 // Return true if we are inside a default argument instantiation
2222 // and the found name refers to an instance member function, otherwise
2223 // the caller will try to create an implicit member call and this is wrong
2224 // for default arguments.
2225 //
2226 // FIXME: Is this special case necessary? We could allow the caller to
2227 // diagnose this.
2228 if (isDefaultArgument && ((*R.begin())->isCXXInstanceMember())) {
2229 Diag(R.getNameLoc(), diag::err_member_call_without_object);
2230 return true;
2231 }
2232
2233 // Tell the callee to try to recover.
2234 return false;
2235}
2236
2237/// Diagnose an empty lookup.
2238///
2239/// \return false if new lookup candidates were found
2240bool Sema::DiagnoseEmptyLookup(Scope *S, CXXScopeSpec &SS, LookupResult &R,
2241 CorrectionCandidateCallback &CCC,
2242 TemplateArgumentListInfo *ExplicitTemplateArgs,
2243 ArrayRef<Expr *> Args, TypoExpr **Out) {
2244 DeclarationName Name = R.getLookupName();
2245
2246 unsigned diagnostic = diag::err_undeclared_var_use;
2247 unsigned diagnostic_suggest = diag::err_undeclared_var_use_suggest;
2248 if (Name.getNameKind() == DeclarationName::CXXOperatorName ||
2249 Name.getNameKind() == DeclarationName::CXXLiteralOperatorName ||
2250 Name.getNameKind() == DeclarationName::CXXConversionFunctionName) {
2251 diagnostic = diag::err_undeclared_use;
2252 diagnostic_suggest = diag::err_undeclared_use_suggest;
2253 }
2254
2255 // If the original lookup was an unqualified lookup, fake an
2256 // unqualified lookup. This is useful when (for example) the
2257 // original lookup would not have found something because it was a
2258 // dependent name.
2259 DeclContext *DC = SS.isEmpty() ? CurContext : nullptr;
2260 while (DC) {
2261 if (isa<CXXRecordDecl>(DC)) {
2262 LookupQualifiedName(R, DC);
2263
2264 if (!R.empty()) {
2265 // Don't give errors about ambiguities in this lookup.
2266 R.suppressDiagnostics();
2267
2268 // If there's a best viable function among the results, only mention
2269 // that one in the notes.
2270 OverloadCandidateSet Candidates(R.getNameLoc(),
2271 OverloadCandidateSet::CSK_Normal);
2272 AddOverloadedCallCandidates(R, ExplicitTemplateArgs, Args, Candidates);
2273 OverloadCandidateSet::iterator Best;
2274 if (Candidates.BestViableFunction(*this, R.getNameLoc(), Best) ==
2275 OR_Success) {
2276 R.clear();
2277 R.addDecl(Best->FoundDecl.getDecl(), Best->FoundDecl.getAccess());
2278 R.resolveKind();
2279 }
2280
2281 return DiagnoseDependentMemberLookup(R);
2282 }
2283
2284 R.clear();
2285 }
2286
2287 DC = DC->getLookupParent();
2288 }
2289
2290 // We didn't find anything, so try to correct for a typo.
2291 TypoCorrection Corrected;
2292 if (S && Out) {
2293 SourceLocation TypoLoc = R.getNameLoc();
2294 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", 2295, __extension__ __PRETTY_FUNCTION__
))
2295 "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", 2295, __extension__ __PRETTY_FUNCTION__
))
;
2296 *Out = CorrectTypoDelayed(
2297 R.getLookupNameInfo(), R.getLookupKind(), S, &SS, CCC,
2298 [=](const TypoCorrection &TC) {
2299 emitEmptyLookupTypoDiagnostic(TC, *this, SS, Name, TypoLoc, Args,
2300 diagnostic, diagnostic_suggest);
2301 },
2302 nullptr, CTK_ErrorRecovery);
2303 if (*Out)
2304 return true;
2305 } else if (S &&
2306 (Corrected = CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(),
2307 S, &SS, CCC, CTK_ErrorRecovery))) {
2308 std::string CorrectedStr(Corrected.getAsString(getLangOpts()));
2309 bool DroppedSpecifier =
2310 Corrected.WillReplaceSpecifier() && Name.getAsString() == CorrectedStr;
2311 R.setLookupName(Corrected.getCorrection());
2312
2313 bool AcceptableWithRecovery = false;
2314 bool AcceptableWithoutRecovery = false;
2315 NamedDecl *ND = Corrected.getFoundDecl();
2316 if (ND) {
2317 if (Corrected.isOverloaded()) {
2318 OverloadCandidateSet OCS(R.getNameLoc(),
2319 OverloadCandidateSet::CSK_Normal);
2320 OverloadCandidateSet::iterator Best;
2321 for (NamedDecl *CD : Corrected) {
2322 if (FunctionTemplateDecl *FTD =
2323 dyn_cast<FunctionTemplateDecl>(CD))
2324 AddTemplateOverloadCandidate(
2325 FTD, DeclAccessPair::make(FTD, AS_none), ExplicitTemplateArgs,
2326 Args, OCS);
2327 else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(CD))
2328 if (!ExplicitTemplateArgs || ExplicitTemplateArgs->size() == 0)
2329 AddOverloadCandidate(FD, DeclAccessPair::make(FD, AS_none),
2330 Args, OCS);
2331 }
2332 switch (OCS.BestViableFunction(*this, R.getNameLoc(), Best)) {
2333 case OR_Success:
2334 ND = Best->FoundDecl;
2335 Corrected.setCorrectionDecl(ND);
2336 break;
2337 default:
2338 // FIXME: Arbitrarily pick the first declaration for the note.
2339 Corrected.setCorrectionDecl(ND);
2340 break;
2341 }
2342 }
2343 R.addDecl(ND);
2344 if (getLangOpts().CPlusPlus && ND->isCXXClassMember()) {
2345 CXXRecordDecl *Record = nullptr;
2346 if (Corrected.getCorrectionSpecifier()) {
2347 const Type *Ty = Corrected.getCorrectionSpecifier()->getAsType();
2348 Record = Ty->getAsCXXRecordDecl();
2349 }
2350 if (!Record)
2351 Record = cast<CXXRecordDecl>(
2352 ND->getDeclContext()->getRedeclContext());
2353 R.setNamingClass(Record);
2354 }
2355
2356 auto *UnderlyingND = ND->getUnderlyingDecl();
2357 AcceptableWithRecovery = isa<ValueDecl>(UnderlyingND) ||
2358 isa<FunctionTemplateDecl>(UnderlyingND);
2359 // FIXME: If we ended up with a typo for a type name or
2360 // Objective-C class name, we're in trouble because the parser
2361 // is in the wrong place to recover. Suggest the typo
2362 // correction, but don't make it a fix-it since we're not going
2363 // to recover well anyway.
2364 AcceptableWithoutRecovery = isa<TypeDecl>(UnderlyingND) ||
2365 getAsTypeTemplateDecl(UnderlyingND) ||
2366 isa<ObjCInterfaceDecl>(UnderlyingND);
2367 } else {
2368 // FIXME: We found a keyword. Suggest it, but don't provide a fix-it
2369 // because we aren't able to recover.
2370 AcceptableWithoutRecovery = true;
2371 }
2372
2373 if (AcceptableWithRecovery || AcceptableWithoutRecovery) {
2374 unsigned NoteID = Corrected.getCorrectionDeclAs<ImplicitParamDecl>()
2375 ? diag::note_implicit_param_decl
2376 : diag::note_previous_decl;
2377 if (SS.isEmpty())
2378 diagnoseTypo(Corrected, PDiag(diagnostic_suggest) << Name,
2379 PDiag(NoteID), AcceptableWithRecovery);
2380 else
2381 diagnoseTypo(Corrected, PDiag(diag::err_no_member_suggest)
2382 << Name << computeDeclContext(SS, false)
2383 << DroppedSpecifier << SS.getRange(),
2384 PDiag(NoteID), AcceptableWithRecovery);
2385
2386 // Tell the callee whether to try to recover.
2387 return !AcceptableWithRecovery;
2388 }
2389 }
2390 R.clear();
2391
2392 // Emit a special diagnostic for failed member lookups.
2393 // FIXME: computing the declaration context might fail here (?)
2394 if (!SS.isEmpty()) {
2395 Diag(R.getNameLoc(), diag::err_no_member)
2396 << Name << computeDeclContext(SS, false)
2397 << SS.getRange();
2398 return true;
2399 }
2400
2401 // Give up, we can't recover.
2402 Diag(R.getNameLoc(), diagnostic) << Name;
2403 return true;
2404}
2405
2406/// In Microsoft mode, if we are inside a template class whose parent class has
2407/// dependent base classes, and we can't resolve an unqualified identifier, then
2408/// assume the identifier is a member of a dependent base class. We can only
2409/// recover successfully in static methods, instance methods, and other contexts
2410/// where 'this' is available. This doesn't precisely match MSVC's
2411/// instantiation model, but it's close enough.
2412static Expr *
2413recoverFromMSUnqualifiedLookup(Sema &S, ASTContext &Context,
2414 DeclarationNameInfo &NameInfo,
2415 SourceLocation TemplateKWLoc,
2416 const TemplateArgumentListInfo *TemplateArgs) {
2417 // Only try to recover from lookup into dependent bases in static methods or
2418 // contexts where 'this' is available.
2419 QualType ThisType = S.getCurrentThisType();
2420 const CXXRecordDecl *RD = nullptr;
2421 if (!ThisType.isNull())
2422 RD = ThisType->getPointeeType()->getAsCXXRecordDecl();
2423 else if (auto *MD = dyn_cast<CXXMethodDecl>(S.CurContext))
2424 RD = MD->getParent();
2425 if (!RD || !RD->hasAnyDependentBases())
2426 return nullptr;
2427
2428 // Diagnose this as unqualified lookup into a dependent base class. If 'this'
2429 // is available, suggest inserting 'this->' as a fixit.
2430 SourceLocation Loc = NameInfo.getLoc();
2431 auto DB = S.Diag(Loc, diag::ext_undeclared_unqual_id_with_dependent_base);
2432 DB << NameInfo.getName() << RD;
2433
2434 if (!ThisType.isNull()) {
2435 DB << FixItHint::CreateInsertion(Loc, "this->");
2436 return CXXDependentScopeMemberExpr::Create(
2437 Context, /*This=*/nullptr, ThisType, /*IsArrow=*/true,
2438 /*Op=*/SourceLocation(), NestedNameSpecifierLoc(), TemplateKWLoc,
2439 /*FirstQualifierFoundInScope=*/nullptr, NameInfo, TemplateArgs);
2440 }
2441
2442 // Synthesize a fake NNS that points to the derived class. This will
2443 // perform name lookup during template instantiation.
2444 CXXScopeSpec SS;
2445 auto *NNS =
2446 NestedNameSpecifier::Create(Context, nullptr, true, RD->getTypeForDecl());
2447 SS.MakeTrivial(Context, NNS, SourceRange(Loc, Loc));
2448 return DependentScopeDeclRefExpr::Create(
2449 Context, SS.getWithLocInContext(Context), TemplateKWLoc, NameInfo,
2450 TemplateArgs);
2451}
2452
2453ExprResult
2454Sema::ActOnIdExpression(Scope *S, CXXScopeSpec &SS,
2455 SourceLocation TemplateKWLoc, UnqualifiedId &Id,
2456 bool HasTrailingLParen, bool IsAddressOfOperand,
2457 CorrectionCandidateCallback *CCC,
2458 bool IsInlineAsmIdentifier, Token *KeywordReplacement) {
2459 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", 2460, __extension__ __PRETTY_FUNCTION__
))
2460 "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", 2460, __extension__ __PRETTY_FUNCTION__
))
;
2461 if (SS.isInvalid())
2462 return ExprError();
2463
2464 TemplateArgumentListInfo TemplateArgsBuffer;
2465
2466 // Decompose the UnqualifiedId into the following data.
2467 DeclarationNameInfo NameInfo;
2468 const TemplateArgumentListInfo *TemplateArgs;
2469 DecomposeUnqualifiedId(Id, TemplateArgsBuffer, NameInfo, TemplateArgs);
2470
2471 DeclarationName Name = NameInfo.getName();
2472 IdentifierInfo *II = Name.getAsIdentifierInfo();
2473 SourceLocation NameLoc = NameInfo.getLoc();
2474
2475 if (II && II->isEditorPlaceholder()) {
2476 // FIXME: When typed placeholders are supported we can create a typed
2477 // placeholder expression node.
2478 return ExprError();
2479 }
2480
2481 // C++ [temp.dep.expr]p3:
2482 // An id-expression is type-dependent if it contains:
2483 // -- an identifier that was declared with a dependent type,
2484 // (note: handled after lookup)
2485 // -- a template-id that is dependent,
2486 // (note: handled in BuildTemplateIdExpr)
2487 // -- a conversion-function-id that specifies a dependent type,
2488 // -- a nested-name-specifier that contains a class-name that
2489 // names a dependent type.
2490 // Determine whether this is a member of an unknown specialization;
2491 // we need to handle these differently.
2492 bool DependentID = false;
2493 if (Name.getNameKind() == DeclarationName::CXXConversionFunctionName &&
2494 Name.getCXXNameType()->isDependentType()) {
2495 DependentID = true;
2496 } else if (SS.isSet()) {
2497 if (DeclContext *DC = computeDeclContext(SS, false)) {
2498 if (RequireCompleteDeclContext(SS, DC))
2499 return ExprError();
2500 } else {
2501 DependentID = true;
2502 }
2503 }
2504
2505 if (DependentID)
2506 return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo,
2507 IsAddressOfOperand, TemplateArgs);
2508
2509 // Perform the required lookup.
2510 LookupResult R(*this, NameInfo,
2511 (Id.getKind() == UnqualifiedIdKind::IK_ImplicitSelfParam)
2512 ? LookupObjCImplicitSelfParam
2513 : LookupOrdinaryName);
2514 if (TemplateKWLoc.isValid() || TemplateArgs) {
2515 // Lookup the template name again to correctly establish the context in
2516 // which it was found. This is really unfortunate as we already did the
2517 // lookup to determine that it was a template name in the first place. If
2518 // this becomes a performance hit, we can work harder to preserve those
2519 // results until we get here but it's likely not worth it.
2520 bool MemberOfUnknownSpecialization;
2521 AssumedTemplateKind AssumedTemplate;
2522 if (LookupTemplateName(R, S, SS, QualType(), /*EnteringContext=*/false,
2523 MemberOfUnknownSpecialization, TemplateKWLoc,
2524 &AssumedTemplate))
2525 return ExprError();
2526
2527 if (MemberOfUnknownSpecialization ||
2528 (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation))
2529 return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo,
2530 IsAddressOfOperand, TemplateArgs);
2531 } else {
2532 bool IvarLookupFollowUp = II && !SS.isSet() && getCurMethodDecl();
2533 LookupParsedName(R, S, &SS, !IvarLookupFollowUp);
2534
2535 // If the result might be in a dependent base class, this is a dependent
2536 // id-expression.
2537 if (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation)
2538 return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo,
2539 IsAddressOfOperand, TemplateArgs);
2540
2541 // If this reference is in an Objective-C method, then we need to do
2542 // some special Objective-C lookup, too.
2543 if (IvarLookupFollowUp) {
2544 ExprResult E(LookupInObjCMethod(R, S, II, true));
2545 if (E.isInvalid())
2546 return ExprError();
2547
2548 if (Expr *Ex = E.getAs<Expr>())
2549 return Ex;
2550 }
2551 }
2552
2553 if (R.isAmbiguous())
2554 return ExprError();
2555
2556 // This could be an implicitly declared function reference (legal in C90,
2557 // extension in C99, forbidden in C++).
2558 if (R.empty() && HasTrailingLParen && II && !getLangOpts().CPlusPlus) {
2559 NamedDecl *D = ImplicitlyDefineFunction(NameLoc, *II, S);
2560 if (D) R.addDecl(D);
2561 }
2562
2563 // Determine whether this name might be a candidate for
2564 // argument-dependent lookup.
2565 bool ADL = UseArgumentDependentLookup(SS, R, HasTrailingLParen);
2566
2567 if (R.empty() && !ADL) {
2568 if (SS.isEmpty() && getLangOpts().MSVCCompat) {
2569 if (Expr *E = recoverFromMSUnqualifiedLookup(*this, Context, NameInfo,
2570 TemplateKWLoc, TemplateArgs))
2571 return E;
2572 }
2573
2574 // Don't diagnose an empty lookup for inline assembly.
2575 if (IsInlineAsmIdentifier)
2576 return ExprError();
2577
2578 // If this name wasn't predeclared and if this is not a function
2579 // call, diagnose the problem.
2580 TypoExpr *TE = nullptr;
2581 DefaultFilterCCC DefaultValidator(II, SS.isValid() ? SS.getScopeRep()
2582 : nullptr);
2583 DefaultValidator.IsAddressOfOperand = IsAddressOfOperand;
2584 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", 2585, __extension__ __PRETTY_FUNCTION__
))
2585 "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", 2585, __extension__ __PRETTY_FUNCTION__
))
;
2586 if (CCC) {
2587 // Make sure the callback knows what the typo being diagnosed is.
2588 CCC->setTypoName(II);
2589 if (SS.isValid())
2590 CCC->setTypoNNS(SS.getScopeRep());
2591 }
2592 // FIXME: DiagnoseEmptyLookup produces bad diagnostics if we're looking for
2593 // a template name, but we happen to have always already looked up the name
2594 // before we get here if it must be a template name.
2595 if (DiagnoseEmptyLookup(S, SS, R, CCC ? *CCC : DefaultValidator, nullptr,
2596 None, &TE)) {
2597 if (TE && KeywordReplacement) {
2598 auto &State = getTypoExprState(TE);
2599 auto BestTC = State.Consumer->getNextCorrection();
2600 if (BestTC.isKeyword()) {
2601 auto *II = BestTC.getCorrectionAsIdentifierInfo();
2602 if (State.DiagHandler)
2603 State.DiagHandler(BestTC);
2604 KeywordReplacement->startToken();
2605 KeywordReplacement->setKind(II->getTokenID());
2606 KeywordReplacement->setIdentifierInfo(II);
2607 KeywordReplacement->setLocation(BestTC.getCorrectionRange().getBegin());
2608 // Clean up the state associated with the TypoExpr, since it has
2609 // now been diagnosed (without a call to CorrectDelayedTyposInExpr).
2610 clearDelayedTypo(TE);
2611 // Signal that a correction to a keyword was performed by returning a
2612 // valid-but-null ExprResult.
2613 return (Expr*)nullptr;
2614 }
2615 State.Consumer->resetCorrectionStream();
2616 }
2617 return TE ? TE : ExprError();
2618 }
2619
2620 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", 2621, __extension__ __PRETTY_FUNCTION__
))
2621 "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", 2621, __extension__ __PRETTY_FUNCTION__
))
;
2622
2623 // If we found an Objective-C instance variable, let
2624 // LookupInObjCMethod build the appropriate expression to
2625 // reference the ivar.
2626 if (ObjCIvarDecl *Ivar = R.getAsSingle<ObjCIvarDecl>()) {
2627 R.clear();
2628 ExprResult E(LookupInObjCMethod(R, S, Ivar->getIdentifier()));
2629 // In a hopelessly buggy code, Objective-C instance variable
2630 // lookup fails and no expression will be built to reference it.
2631 if (!E.isInvalid() && !E.get())
2632 return ExprError();
2633 return E;
2634 }
2635 }
2636
2637 // This is guaranteed from this point on.
2638 assert(!R.empty() || ADL)(static_cast <bool> (!R.empty() || ADL) ? void (0) : __assert_fail
("!R.empty() || ADL", "clang/lib/Sema/SemaExpr.cpp", 2638, __extension__
__PRETTY_FUNCTION__))
;
2639
2640 // Check whether this might be a C++ implicit instance member access.
2641 // C++ [class.mfct.non-static]p3:
2642 // When an id-expression that is not part of a class member access
2643 // syntax and not used to form a pointer to member is used in the
2644 // body of a non-static member function of class X, if name lookup
2645 // resolves the name in the id-expression to a non-static non-type
2646 // member of some class C, the id-expression is transformed into a
2647 // class member access expression using (*this) as the
2648 // postfix-expression to the left of the . operator.
2649 //
2650 // But we don't actually need to do this for '&' operands if R
2651 // resolved to a function or overloaded function set, because the
2652 // expression is ill-formed if it actually works out to be a
2653 // non-static member function:
2654 //
2655 // C++ [expr.ref]p4:
2656 // Otherwise, if E1.E2 refers to a non-static member function. . .
2657 // [t]he expression can be used only as the left-hand operand of a
2658 // member function call.
2659 //
2660 // There are other safeguards against such uses, but it's important
2661 // to get this right here so that we don't end up making a
2662 // spuriously dependent expression if we're inside a dependent
2663 // instance method.
2664 if (!R.empty() && (*R.begin())->isCXXClassMember()) {
2665 bool MightBeImplicitMember;
2666 if (!IsAddressOfOperand)
2667 MightBeImplicitMember = true;
2668 else if (!SS.isEmpty())
2669 MightBeImplicitMember = false;
2670 else if (R.isOverloadedResult())
2671 MightBeImplicitMember = false;
2672 else if (R.isUnresolvableResult())
2673 MightBeImplicitMember = true;
2674 else
2675 MightBeImplicitMember = isa<FieldDecl>(R.getFoundDecl()) ||
2676 isa<IndirectFieldDecl>(R.getFoundDecl()) ||
2677 isa<MSPropertyDecl>(R.getFoundDecl());
2678
2679 if (MightBeImplicitMember)
2680 return BuildPossibleImplicitMemberExpr(SS, TemplateKWLoc,
2681 R, TemplateArgs, S);
2682 }
2683
2684 if (TemplateArgs || TemplateKWLoc.isValid()) {
2685
2686 // In C++1y, if this is a variable template id, then check it
2687 // in BuildTemplateIdExpr().
2688 // The single lookup result must be a variable template declaration.
2689 if (Id.getKind() == UnqualifiedIdKind::IK_TemplateId && Id.TemplateId &&
2690 Id.TemplateId->Kind == TNK_Var_template) {
2691 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", 2692, __extension__ __PRETTY_FUNCTION__
))
2692 "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", 2692, __extension__ __PRETTY_FUNCTION__
))
;
2693 }
2694
2695 return BuildTemplateIdExpr(SS, TemplateKWLoc, R, ADL, TemplateArgs);
2696 }
2697
2698 return BuildDeclarationNameExpr(SS, R, ADL);
2699}
2700
2701ExprResult Sema::ActOnMutableAgnosticIdExpression(Scope *S, CXXScopeSpec &SS,
2702 UnqualifiedId &Id) {
2703 MutableAgnosticContextRAII Ctx(*this);
2704 return ActOnIdExpression(S, SS, /*TemplateKwLoc*/
2705 SourceLocation(), Id,
2706 /*HasTrailingLParen*/ false,
2707 /*IsAddressOfOperand*/ false,
2708 /*CorrectionCandidateCallback*/ nullptr,
2709 /*IsInlineAsmIdentifier*/ false,
2710 /*KeywordReplacement*/ nullptr);
2711}
2712
2713/// BuildQualifiedDeclarationNameExpr - Build a C++ qualified
2714/// declaration name, generally during template instantiation.
2715/// There's a large number of things which don't need to be done along
2716/// this path.
2717ExprResult Sema::BuildQualifiedDeclarationNameExpr(
2718 CXXScopeSpec &SS, const DeclarationNameInfo &NameInfo,
2719 bool IsAddressOfOperand, const Scope *S, TypeSourceInfo **RecoveryTSI) {
2720 DeclContext *DC = computeDeclContext(SS, false);
2721 if (!DC)
2722 return BuildDependentDeclRefExpr(SS, /*TemplateKWLoc=*/SourceLocation(),
2723 NameInfo, /*TemplateArgs=*/nullptr);
2724
2725 if (RequireCompleteDeclContext(SS, DC))
2726 return ExprError();
2727
2728 LookupResult R(*this, NameInfo, LookupOrdinaryName);
2729 LookupQualifiedName(R, DC);
2730
2731 if (R.isAmbiguous())
2732 return ExprError();
2733
2734 if (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation)
2735 return BuildDependentDeclRefExpr(SS, /*TemplateKWLoc=*/SourceLocation(),
2736 NameInfo, /*TemplateArgs=*/nullptr);
2737
2738 if (R.empty()) {
2739 // Don't diagnose problems with invalid record decl, the secondary no_member
2740 // diagnostic during template instantiation is likely bogus, e.g. if a class
2741 // is invalid because it's derived from an invalid base class, then missing
2742 // members were likely supposed to be inherited.
2743 if (const auto *CD = dyn_cast<CXXRecordDecl>(DC))
2744 if (CD->isInvalidDecl())
2745 return ExprError();
2746 Diag(NameInfo.getLoc(), diag::err_no_member)
2747 << NameInfo.getName() << DC << SS.getRange();
2748 return ExprError();
2749 }
2750
2751 if (const TypeDecl *TD = R.getAsSingle<TypeDecl>()) {
2752 // Diagnose a missing typename if this resolved unambiguously to a type in
2753 // a dependent context. If we can recover with a type, downgrade this to
2754 // a warning in Microsoft compatibility mode.
2755 unsigned DiagID = diag::err_typename_missing;
2756 if (RecoveryTSI && getLangOpts().MSVCCompat)
2757 DiagID = diag::ext_typename_missing;
2758 SourceLocation Loc = SS.getBeginLoc();
2759 auto D = Diag(Loc, DiagID);
2760 D << SS.getScopeRep() << NameInfo.getName().getAsString()
2761 << SourceRange(Loc, NameInfo.getEndLoc());
2762
2763 // Don't recover if the caller isn't expecting us to or if we're in a SFINAE
2764 // context.
2765 if (!RecoveryTSI)
2766 return ExprError();
2767
2768 // Only issue the fixit if we're prepared to recover.
2769 D << FixItHint::CreateInsertion(Loc, "typename ");
2770
2771 // Recover by pretending this was an elaborated type.
2772 QualType Ty = Context.getTypeDeclType(TD);
2773 TypeLocBuilder TLB;
2774 TLB.pushTypeSpec(Ty).setNameLoc(NameInfo.getLoc());
2775
2776 QualType ET = getElaboratedType(ETK_None, SS, Ty);
2777 ElaboratedTypeLoc QTL = TLB.push<ElaboratedTypeLoc>(ET);
2778 QTL.setElaboratedKeywordLoc(SourceLocation());
2779 QTL.setQualifierLoc(SS.getWithLocInContext(Context));
2780
2781 *RecoveryTSI = TLB.getTypeSourceInfo(Context, ET);
2782
2783 return ExprEmpty();
2784 }
2785
2786 // Defend against this resolving to an implicit member access. We usually
2787 // won't get here if this might be a legitimate a class member (we end up in
2788 // BuildMemberReferenceExpr instead), but this can be valid if we're forming
2789 // a pointer-to-member or in an unevaluated context in C++11.
2790 if (!R.empty() && (*R.begin())->isCXXClassMember() && !IsAddressOfOperand)
2791 return BuildPossibleImplicitMemberExpr(SS,
2792 /*TemplateKWLoc=*/SourceLocation(),
2793 R, /*TemplateArgs=*/nullptr, S);
2794
2795 return BuildDeclarationNameExpr(SS, R, /* ADL */ false);
2796}
2797
2798/// The parser has read a name in, and Sema has detected that we're currently
2799/// inside an ObjC method. Perform some additional checks and determine if we
2800/// should form a reference to an ivar.
2801///
2802/// Ideally, most of this would be done by lookup, but there's
2803/// actually quite a lot of extra work involved.
2804DeclResult Sema::LookupIvarInObjCMethod(LookupResult &Lookup, Scope *S,
2805 IdentifierInfo *II) {
2806 SourceLocation Loc = Lookup.getNameLoc();
2807 ObjCMethodDecl *CurMethod = getCurMethodDecl();
2808
2809 // Check for error condition which is already reported.
2810 if (!CurMethod)
2811 return DeclResult(true);
2812
2813 // There are two cases to handle here. 1) scoped lookup could have failed,
2814 // in which case we should look for an ivar. 2) scoped lookup could have
2815 // found a decl, but that decl is outside the current instance method (i.e.
2816 // a global variable). In these two cases, we do a lookup for an ivar with
2817 // this name, if the lookup sucedes, we replace it our current decl.
2818
2819 // If we're in a class method, we don't normally want to look for
2820 // ivars. But if we don't find anything else, and there's an
2821 // ivar, that's an error.
2822 bool IsClassMethod = CurMethod->isClassMethod();
2823
2824 bool LookForIvars;
2825 if (Lookup.empty())
2826 LookForIvars = true;
2827 else if (IsClassMethod)
2828 LookForIvars = false;
2829 else
2830 LookForIvars = (Lookup.isSingleResult() &&
2831 Lookup.getFoundDecl()->isDefinedOutsideFunctionOrMethod());
2832 ObjCInterfaceDecl *IFace = nullptr;
2833 if (LookForIvars) {
2834 IFace = CurMethod->getClassInterface();
2835 ObjCInterfaceDecl *ClassDeclared;
2836 ObjCIvarDecl *IV = nullptr;
2837 if (IFace && (IV = IFace->lookupInstanceVariable(II, ClassDeclared))) {
2838 // Diagnose using an ivar in a class method.
2839 if (IsClassMethod) {
2840 Diag(Loc, diag::err_ivar_use_in_class_method) << IV->getDeclName();
2841 return DeclResult(true);
2842 }
2843
2844 // Diagnose the use of an ivar outside of the declaring class.
2845 if (IV->getAccessControl() == ObjCIvarDecl::Private &&
2846 !declaresSameEntity(ClassDeclared, IFace) &&
2847 !getLangOpts().DebuggerSupport)
2848 Diag(Loc, diag::err_private_ivar_access) << IV->getDeclName();
2849
2850 // Success.
2851 return IV;
2852 }
2853 } else if (CurMethod->isInstanceMethod()) {
2854 // We should warn if a local variable hides an ivar.
2855 if (ObjCInterfaceDecl *IFace = CurMethod->getClassInterface()) {
2856 ObjCInterfaceDecl *ClassDeclared;
2857 if (ObjCIvarDecl *IV = IFace->lookupInstanceVariable(II, ClassDeclared)) {
2858 if (IV->getAccessControl() != ObjCIvarDecl::Private ||
2859 declaresSameEntity(IFace, ClassDeclared))
2860 Diag(Loc, diag::warn_ivar_use_hidden) << IV->getDeclName();
2861 }
2862 }
2863 } else if (Lookup.isSingleResult() &&
2864 Lookup.getFoundDecl()->isDefinedOutsideFunctionOrMethod()) {
2865 // If accessing a stand-alone ivar in a class method, this is an error.
2866 if (const ObjCIvarDecl *IV =
2867 dyn_cast<ObjCIvarDecl>(Lookup.getFoundDecl())) {
2868 Diag(Loc, diag::err_ivar_use_in_class_method) << IV->getDeclName();
2869 return DeclResult(true);
2870 }
2871 }
2872
2873 // Didn't encounter an error, didn't find an ivar.
2874 return DeclResult(false);
2875}
2876
2877ExprResult Sema::BuildIvarRefExpr(Scope *S, SourceLocation Loc,
2878 ObjCIvarDecl *IV) {
2879 ObjCMethodDecl *CurMethod = getCurMethodDecl();
2880 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", 2881, __extension__ __PRETTY_FUNCTION__
))
2881 "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", 2881, __extension__ __PRETTY_FUNCTION__
))
;
2882
2883 ObjCInterfaceDecl *IFace = CurMethod->getClassInterface();
2884 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", 2884, __extension__ __PRETTY_FUNCTION__
))
;
2885
2886 // If we're referencing an invalid decl, just return this as a silent
2887 // error node. The error diagnostic was already emitted on the decl.
2888 if (IV->isInvalidDecl())
2889 return ExprError();
2890
2891 // Check if referencing a field with __attribute__((deprecated)).
2892 if (DiagnoseUseOfDecl(IV, Loc))
2893 return ExprError();
2894
2895 // FIXME: This should use a new expr for a direct reference, don't
2896 // turn this into Self->ivar, just return a BareIVarExpr or something.
2897 IdentifierInfo &II = Context.Idents.get("self");
2898 UnqualifiedId SelfName;
2899 SelfName.setImplicitSelfParam(&II);
2900 CXXScopeSpec SelfScopeSpec;
2901 SourceLocation TemplateKWLoc;
2902 ExprResult SelfExpr =
2903 ActOnIdExpression(S, SelfScopeSpec, TemplateKWLoc, SelfName,
2904 /*HasTrailingLParen=*/false,
2905 /*IsAddressOfOperand=*/false);
2906 if (SelfExpr.isInvalid())
2907 return ExprError();
2908
2909 SelfExpr = DefaultLvalueConversion(SelfExpr.get());
2910 if (SelfExpr.isInvalid())
2911 return ExprError();
2912
2913 MarkAnyDeclReferenced(Loc, IV, true);
2914
2915 ObjCMethodFamily MF = CurMethod->getMethodFamily();
2916 if (MF != OMF_init && MF != OMF_dealloc && MF != OMF_finalize &&
2917 !IvarBacksCurrentMethodAccessor(IFace, CurMethod, IV))
2918 Diag(Loc, diag::warn_direct_ivar_access) << IV->getDeclName();
2919
2920 ObjCIvarRefExpr *Result = new (Context)
2921 ObjCIvarRefExpr(IV, IV->getUsageType(SelfExpr.get()->getType()), Loc,
2922 IV->getLocation(), SelfExpr.get(), true, true);
2923
2924 if (IV->getType().getObjCLifetime() == Qualifiers::OCL_Weak) {
2925 if (!isUnevaluatedContext() &&
2926 !Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, Loc))
2927 getCurFunction()->recordUseOfWeak(Result);
2928 }
2929 if (getLangOpts().ObjCAutoRefCount)
2930 if (const BlockDecl *BD = CurContext->getInnermostBlockDecl())
2931 ImplicitlyRetainedSelfLocs.push_back({Loc, BD});
2932
2933 return Result;
2934}
2935
2936/// The parser has read a name in, and Sema has detected that we're currently
2937/// inside an ObjC method. Perform some additional checks and determine if we
2938/// should form a reference to an ivar. If so, build an expression referencing
2939/// that ivar.
2940ExprResult
2941Sema::LookupInObjCMethod(LookupResult &Lookup, Scope *S,
2942 IdentifierInfo *II, bool AllowBuiltinCreation) {
2943 // FIXME: Integrate this lookup step into LookupParsedName.
2944 DeclResult Ivar = LookupIvarInObjCMethod(Lookup, S, II);
2945 if (Ivar.isInvalid())
2946 return ExprError();
2947 if (Ivar.isUsable())
2948 return BuildIvarRefExpr(S, Lookup.getNameLoc(),
2949 cast<ObjCIvarDecl>(Ivar.get()));
2950
2951 if (Lookup.empty() && II && AllowBuiltinCreation)
2952 LookupBuiltin(Lookup);
2953
2954 // Sentinel value saying that we didn't do anything special.
2955 return ExprResult(false);
2956}
2957
2958/// Cast a base object to a member's actual type.
2959///
2960/// There are two relevant checks:
2961///
2962/// C++ [class.access.base]p7:
2963///
2964/// If a class member access operator [...] is used to access a non-static
2965/// data member or non-static member function, the reference is ill-formed if
2966/// the left operand [...] cannot be implicitly converted to a pointer to the
2967/// naming class of the right operand.
2968///
2969/// C++ [expr.ref]p7:
2970///
2971/// If E2 is a non-static data member or a non-static member function, the
2972/// program is ill-formed if the class of which E2 is directly a member is an
2973/// ambiguous base (11.8) of the naming class (11.9.3) of E2.
2974///
2975/// Note that the latter check does not consider access; the access of the
2976/// "real" base class is checked as appropriate when checking the access of the
2977/// member name.
2978ExprResult
2979Sema::PerformObjectMemberConversion(Expr *From,
2980 NestedNameSpecifier *Qualifier,
2981 NamedDecl *FoundDecl,
2982 NamedDecl *Member) {
2983 CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Member->getDeclContext());
2984 if (!RD)
2985 return From;
2986
2987 QualType DestRecordType;
2988 QualType DestType;
2989 QualType FromRecordType;
2990 QualType FromType = From->getType();
2991 bool PointerConversions = false;
2992 if (isa<FieldDecl>(Member)) {
2993 DestRecordType = Context.getCanonicalType(Context.getTypeDeclType(RD));
2994 auto FromPtrType = FromType->getAs<PointerType>();
2995 DestRecordType = Context.getAddrSpaceQualType(
2996 DestRecordType, FromPtrType
2997 ? FromType->getPointeeType().getAddressSpace()
2998 : FromType.getAddressSpace());
2999
3000 if (FromPtrType) {
3001 DestType = Context.getPointerType(DestRecordType);
3002 FromRecordType = FromPtrType->getPointeeType();
3003 PointerConversions = true;
3004 } else {
3005 DestType = DestRecordType;
3006 FromRecordType = FromType;
3007 }
3008 } else if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Member)) {
3009 if (Method->isStatic())
3010 return From;
3011
3012 DestType = Method->getThisType();
3013 DestRecordType = DestType->getPointeeType();
3014
3015 if (FromType->getAs<PointerType>()) {
3016 FromRecordType = FromType->getPointeeType();
3017 PointerConversions = true;
3018 } else {
3019 FromRecordType = FromType;
3020 DestType = DestRecordType;
3021 }
3022
3023 LangAS FromAS = FromRecordType.getAddressSpace();
3024 LangAS DestAS = DestRecordType.getAddressSpace();
3025 if (FromAS != DestAS) {
3026 QualType FromRecordTypeWithoutAS =
3027 Context.removeAddrSpaceQualType(FromRecordType);
3028 QualType FromTypeWithDestAS =
3029 Context.getAddrSpaceQualType(FromRecordTypeWithoutAS, DestAS);
3030 if (PointerConversions)
3031 FromTypeWithDestAS = Context.getPointerType(FromTypeWithDestAS);
3032 From = ImpCastExprToType(From, FromTypeWithDestAS,
3033 CK_AddressSpaceConversion, From->getValueKind())
3034 .get();
3035 }
3036 } else {
3037 // No conversion necessary.
3038 return From;
3039 }
3040
3041 if (DestType->isDependentType() || FromType->isDependentType())
3042 return From;
3043
3044 // If the unqualified types are the same, no conversion is necessary.
3045 if (Context.hasSameUnqualifiedType(FromRecordType, DestRecordType))
3046 return From;
3047
3048 SourceRange FromRange = From->getSourceRange();
3049 SourceLocation FromLoc = FromRange.getBegin();
3050
3051 ExprValueKind VK = From->getValueKind();
3052
3053 // C++ [class.member.lookup]p8:
3054 // [...] Ambiguities can often be resolved by qualifying a name with its
3055 // class name.
3056 //
3057 // If the member was a qualified name and the qualified referred to a
3058 // specific base subobject type, we'll cast to that intermediate type
3059 // first and then to the object in which the member is declared. That allows
3060 // one to resolve ambiguities in, e.g., a diamond-shaped hierarchy such as:
3061 //
3062 // class Base { public: int x; };
3063 // class Derived1 : public Base { };
3064 // class Derived2 : public Base { };
3065 // class VeryDerived : public Derived1, public Derived2 { void f(); };
3066 //
3067 // void VeryDerived::f() {
3068 // x = 17; // error: ambiguous base subobjects
3069 // Derived1::x = 17; // okay, pick the Base subobject of Derived1
3070 // }
3071 if (Qualifier && Qualifier->getAsType()) {
3072 QualType QType = QualType(Qualifier->getAsType(), 0);
3073 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", 3073, __extension__ __PRETTY_FUNCTION__
))
;
3074
3075 QualType QRecordType = QualType(QType->castAs<RecordType>(), 0);
3076
3077 // In C++98, the qualifier type doesn't actually have to be a base
3078 // type of the object type, in which case we just ignore it.
3079 // Otherwise build the appropriate casts.
3080 if (IsDerivedFrom(FromLoc, FromRecordType, QRecordType)) {
3081 CXXCastPath BasePath;
3082 if (CheckDerivedToBaseConversion(FromRecordType, QRecordType,
3083 FromLoc, FromRange, &BasePath))
3084 return ExprError();
3085
3086 if (PointerConversions)
3087 QType = Context.getPointerType(QType);
3088 From = ImpCastExprToType(From, QType, CK_UncheckedDerivedToBase,
3089 VK, &BasePath).get();
3090
3091 FromType = QType;
3092 FromRecordType = QRecordType;
3093
3094 // If the qualifier type was the same as the destination type,
3095 // we're done.
3096 if (Context.hasSameUnqualifiedType(FromRecordType, DestRecordType))
3097 return From;
3098 }
3099 }
3100
3101 CXXCastPath BasePath;
3102 if (CheckDerivedToBaseConversion(FromRecordType, DestRecordType,
3103 FromLoc, FromRange, &BasePath,
3104 /*IgnoreAccess=*/true))
3105 return ExprError();
3106
3107 return ImpCastExprToType(From, DestType, CK_UncheckedDerivedToBase,
3108 VK, &BasePath);
3109}
3110
3111bool Sema::UseArgumentDependentLookup(const CXXScopeSpec &SS,
3112 const LookupResult &R,
3113 bool HasTrailingLParen) {
3114 // Only when used directly as the postfix-expression of a call.
3115 if (!HasTrailingLParen)
3116 return false;
3117
3118 // Never if a scope specifier was provided.
3119 if (SS.isSet())
3120 return false;
3121
3122 // Only in C++ or ObjC++.
3123 if (!getLangOpts().CPlusPlus)
3124 return false;
3125
3126 // Turn off ADL when we find certain kinds of declarations during
3127 // normal lookup:
3128 for (NamedDecl *D : R) {
3129 // C++0x [basic.lookup.argdep]p3:
3130 // -- a declaration of a class member
3131 // Since using decls preserve this property, we check this on the
3132 // original decl.
3133 if (D->isCXXClassMember())
3134 return false;
3135
3136 // C++0x [basic.lookup.argdep]p3:
3137 // -- a block-scope function declaration that is not a
3138 // using-declaration
3139 // NOTE: we also trigger this for function templates (in fact, we
3140 // don't check the decl type at all, since all other decl types
3141 // turn off ADL anyway).
3142 if (isa<UsingShadowDecl>(D))
3143 D = cast<UsingShadowDecl>(D)->getTargetDecl();
3144 else if (D->getLexicalDeclContext()->isFunctionOrMethod())
3145 return false;
3146
3147 // C++0x [basic.lookup.argdep]p3:
3148 // -- a declaration that is neither a function or a function
3149 // template
3150 // And also for builtin functions.
3151 if (isa<FunctionDecl>(D)) {
3152 FunctionDecl *FDecl = cast<FunctionDecl>(D);
3153
3154 // But also builtin functions.
3155 if (FDecl->getBuiltinID() && FDecl->isImplicit())
3156 return false;
3157 } else if (!isa<FunctionTemplateDecl>(D))
3158 return false;
3159 }
3160
3161 return true;
3162}
3163
3164
3165/// Diagnoses obvious problems with the use of the given declaration
3166/// as an expression. This is only actually called for lookups that
3167/// were not overloaded, and it doesn't promise that the declaration
3168/// will in fact be used.
3169static bool CheckDeclInExpr(Sema &S, SourceLocation Loc, NamedDecl *D) {
3170 if (D->isInvalidDecl())
3171 return true;
3172
3173 if (isa<TypedefNameDecl>(D)) {
3174 S.Diag(Loc, diag::err_unexpected_typedef) << D->getDeclName();
3175 return true;
3176 }
3177
3178 if (isa<ObjCInterfaceDecl>(D)) {
3179 S.Diag(Loc, diag::err_unexpected_interface) << D->getDeclName();
3180 return true;
3181 }
3182
3183 if (isa<NamespaceDecl>(D)) {
3184 S.Diag(Loc, diag::err_unexpected_namespace) << D->getDeclName();
3185 return true;
3186 }
3187
3188 return false;
3189}
3190
3191// Certain multiversion types should be treated as overloaded even when there is
3192// only one result.
3193static bool ShouldLookupResultBeMultiVersionOverload(const LookupResult &R) {
3194 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", 3194, __extension__ __PRETTY_FUNCTION__
))
;
3195 const auto *FD = dyn_cast<FunctionDecl>(R.getFoundDecl());
3196 return FD &&
3197 (FD->isCPUDispatchMultiVersion() || FD->isCPUSpecificMultiVersion());
3198}
3199
3200ExprResult Sema::BuildDeclarationNameExpr(const CXXScopeSpec &SS,
3201 LookupResult &R, bool NeedsADL,
3202 bool AcceptInvalidDecl) {
3203 // If this is a single, fully-resolved result and we don't need ADL,
3204 // just build an ordinary singleton decl ref.
3205 if (!NeedsADL && R.isSingleResult() &&
3206 !R.getAsSingle<FunctionTemplateDecl>() &&
3207 !ShouldLookupResultBeMultiVersionOverload(R))
3208 return BuildDeclarationNameExpr(SS, R.getLookupNameInfo(), R.getFoundDecl(),
3209 R.getRepresentativeDecl(), nullptr,
3210 AcceptInvalidDecl);
3211
3212 // We only need to check the declaration if there's exactly one
3213 // result, because in the overloaded case the results can only be
3214 // functions and function templates.
3215 if (R.isSingleResult() && !ShouldLookupResultBeMultiVersionOverload(R) &&
3216 CheckDeclInExpr(*this, R.getNameLoc(), R.getFoundDecl()))
3217 return ExprError();
3218
3219 // Otherwise, just build an unresolved lookup expression. Suppress
3220 // any lookup-related diagnostics; we'll hash these out later, when
3221 // we've picked a target.
3222 R.suppressDiagnostics();
3223
3224 UnresolvedLookupExpr *ULE
3225 = UnresolvedLookupExpr::Create(Context, R.getNamingClass(),
3226 SS.getWithLocInContext(Context),
3227 R.getLookupNameInfo(),
3228 NeedsADL, R.isOverloadedResult(),
3229 R.begin(), R.end());
3230
3231 return ULE;
3232}
3233
3234static void diagnoseUncapturableValueReference(Sema &S, SourceLocation loc,
3235 ValueDecl *var);
3236
3237/// Complete semantic analysis for a reference to the given declaration.
3238ExprResult Sema::BuildDeclarationNameExpr(
3239 const CXXScopeSpec &SS, const DeclarationNameInfo &NameInfo, NamedDecl *D,
3240 NamedDecl *FoundD, const TemplateArgumentListInfo *TemplateArgs,
3241 bool AcceptInvalidDecl) {
3242 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", 3242, __extension__ __PRETTY_FUNCTION__
))
;
3243 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", 3244, __extension__ __PRETTY_FUNCTION__
))
3244 "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", 3244, __extension__ __PRETTY_FUNCTION__
))
;
3245
3246 SourceLocation Loc = NameInfo.getLoc();
3247 if (CheckDeclInExpr(*this, Loc, D)) {
3248 // Recovery from invalid cases (e.g. D is an invalid Decl).
3249 // We use the dependent type for the RecoveryExpr to prevent bogus follow-up
3250 // diagnostics, as invalid decls use int as a fallback type.
3251 return CreateRecoveryExpr(NameInfo.getBeginLoc(), NameInfo.getEndLoc(), {});
3252 }
3253
3254 if (TemplateDecl *Template = dyn_cast<TemplateDecl>(D)) {
3255 // Specifically diagnose references to class templates that are missing
3256 // a template argument list.
3257 diagnoseMissingTemplateArguments(TemplateName(Template), Loc);
3258 return ExprError();
3259 }
3260
3261 // Make sure that we're referring to a value.
3262 if (!isa<ValueDecl, UnresolvedUsingIfExistsDecl>(D)) {
3263 Diag(Loc, diag::err_ref_non_value) << D << SS.getRange();
3264 Diag(D->getLocation(), diag::note_declared_at);
3265 return ExprError();
3266 }
3267
3268 // Check whether this declaration can be used. Note that we suppress
3269 // this check when we're going to perform argument-dependent lookup
3270 // on this function name, because this might not be the function
3271 // that overload resolution actually selects.
3272 if (DiagnoseUseOfDecl(D, Loc))
3273 return ExprError();
3274
3275 auto *VD = cast<ValueDecl>(D);
3276
3277 // Only create DeclRefExpr's for valid Decl's.
3278 if (VD->isInvalidDecl() && !AcceptInvalidDecl)
3279 return ExprError();
3280
3281 // Handle members of anonymous structs and unions. If we got here,
3282 // and the reference is to a class member indirect field, then this
3283 // must be the subject of a pointer-to-member expression.
3284 if (IndirectFieldDecl *indirectField = dyn_cast<IndirectFieldDecl>(VD))
3285 if (!indirectField->isCXXClassMember())
3286 return BuildAnonymousStructUnionMemberReference(SS, NameInfo.getLoc(),
3287 indirectField);
3288
3289 QualType type = VD->getType();
3290 if (type.isNull())
3291 return ExprError();
3292 ExprValueKind valueKind = VK_PRValue;
3293
3294 // In 'T ...V;', the type of the declaration 'V' is 'T...', but the type of
3295 // a reference to 'V' is simply (unexpanded) 'T'. The type, like the value,
3296 // is expanded by some outer '...' in the context of the use.
3297 type = type.getNonPackExpansionType();
3298
3299 switch (D->getKind()) {
3300 // Ignore all the non-ValueDecl kinds.
3301#define ABSTRACT_DECL(kind)
3302#define VALUE(type, base)
3303#define DECL(type, base) case Decl::type:
3304#include "clang/AST/DeclNodes.inc"
3305 llvm_unreachable("invalid value decl kind")::llvm::llvm_unreachable_internal("invalid value decl kind", "clang/lib/Sema/SemaExpr.cpp"
, 3305)
;
3306
3307 // These shouldn't make it here.
3308 case Decl::ObjCAtDefsField:
3309 llvm_unreachable("forming non-member reference to ivar?")::llvm::llvm_unreachable_internal("forming non-member reference to ivar?"
, "clang/lib/Sema/SemaExpr.cpp", 3309)
;
3310
3311 // Enum constants are always r-values and never references.
3312 // Unresolved using declarations are dependent.
3313 case Decl::EnumConstant:
3314 case Decl::UnresolvedUsingValue:
3315 case Decl::OMPDeclareReduction:
3316 case Decl::OMPDeclareMapper:
3317 valueKind = VK_PRValue;
3318 break;
3319
3320 // Fields and indirect fields that got here must be for
3321 // pointer-to-member expressions; we just call them l-values for
3322 // internal consistency, because this subexpression doesn't really
3323 // exist in the high-level semantics.
3324 case Decl::Field:
3325 case Decl::IndirectField:
3326 case Decl::ObjCIvar:
3327 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", 3327, __extension__ __PRETTY_FUNCTION__
))
;
3328
3329 // These can't have reference type in well-formed programs, but
3330 // for internal consistency we do this anyway.
3331 type = type.getNonReferenceType();
3332 valueKind = VK_LValue;
3333 break;
3334
3335 // Non-type template parameters are either l-values or r-values
3336 // depending on the type.
3337 case Decl::NonTypeTemplateParm: {
3338 if (const ReferenceType *reftype = type->getAs<ReferenceType>()) {
3339 type = reftype->getPointeeType();
3340 valueKind = VK_LValue; // even if the parameter is an r-value reference
3341 break;
3342 }
3343
3344 // [expr.prim.id.unqual]p2:
3345 // If the entity is a template parameter object for a template
3346 // parameter of type T, the type of the expression is const T.
3347 // [...] The expression is an lvalue if the entity is a [...] template
3348 // parameter object.
3349 if (type->isRecordType()) {
3350 type = type.getUnqualifiedType().withConst();
3351 valueKind = VK_LValue;
3352 break;
3353 }
3354
3355 // For non-references, we need to strip qualifiers just in case
3356 // the template parameter was declared as 'const int' or whatever.
3357 valueKind = VK_PRValue;
3358 type = type.getUnqualifiedType();
3359 break;
3360 }
3361
3362 case Decl::Var:
3363 case Decl::VarTemplateSpecialization:
3364 case Decl::VarTemplatePartialSpecialization:
3365 case Decl::Decomposition:
3366 case Decl::OMPCapturedExpr:
3367 // In C, "extern void blah;" is valid and is an r-value.
3368 if (!getLangOpts().CPlusPlus && !type.hasQualifiers() &&
3369 type->isVoidType()) {
3370 valueKind = VK_PRValue;
3371 break;
3372 }
3373 LLVM_FALLTHROUGH[[gnu::fallthrough]];
3374
3375 case Decl::ImplicitParam:
3376 case Decl::ParmVar: {
3377 // These are always l-values.
3378 valueKind = VK_LValue;
3379 type = type.getNonReferenceType();
3380
3381 // FIXME: Does the addition of const really only apply in
3382 // potentially-evaluated contexts? Since the variable isn't actually
3383 // captured in an unevaluated context, it seems that the answer is no.
3384 if (!isUnevaluatedContext()) {
3385 QualType CapturedType = getCapturedDeclRefType(cast<VarDecl>(VD), Loc);
3386 if (!CapturedType.isNull())
3387 type = CapturedType;
3388 }
3389
3390 break;
3391 }
3392
3393 case Decl::Binding: {
3394 // These are always lvalues.
3395 valueKind = VK_LValue;
3396 type = type.getNonReferenceType();
3397 // FIXME: Support lambda-capture of BindingDecls, once CWG actually
3398 // decides how that's supposed to work.
3399 auto *BD = cast<BindingDecl>(VD);
3400 if (BD->getDeclContext() != CurContext && !isUnevaluatedContext()) {
3401 auto *DD = dyn_cast_or_null<VarDecl>(BD->getDecomposedDecl());
3402 if (DD && DD->hasLocalStorage())
3403 diagnoseUncapturableValueReference(*this, Loc, BD);
3404 }
3405 break;
3406 }
3407
3408 case Decl::Function: {
3409 if (unsigned BID = cast<FunctionDecl>(VD)->getBuiltinID()) {
3410 if (!Context.BuiltinInfo.isDirectlyAddressable(BID)) {
3411 type = Context.BuiltinFnTy;
3412 valueKind = VK_PRValue;
3413 break;
3414 }
3415 }
3416
3417 const FunctionType *fty = type->castAs<FunctionType>();
3418
3419 // If we're referring to a function with an __unknown_anytype
3420 // result type, make the entire expression __unknown_anytype.
3421 if (fty->getReturnType() == Context.UnknownAnyTy) {
3422 type = Context.UnknownAnyTy;
3423 valueKind = VK_PRValue;
3424 break;
3425 }
3426
3427 // Functions are l-values in C++.
3428 if (getLangOpts().CPlusPlus) {
3429 valueKind = VK_LValue;
3430 break;
3431 }
3432
3433 // C99 DR 316 says that, if a function type comes from a
3434 // function definition (without a prototype), that type is only
3435 // used for checking compatibility. Therefore, when referencing
3436 // the function, we pretend that we don't have the full function
3437 // type.
3438 if (!cast<FunctionDecl>(VD)->hasPrototype() && isa<FunctionProtoType>(fty))
3439 type = Context.getFunctionNoProtoType(fty->getReturnType(),
3440 fty->getExtInfo());
3441
3442 // Functions are r-values in C.
3443 valueKind = VK_PRValue;
3444 break;
3445 }
3446
3447 case Decl::CXXDeductionGuide:
3448 llvm_unreachable("building reference to deduction guide")::llvm::llvm_unreachable_internal("building reference to deduction guide"
, "clang/lib/Sema/SemaExpr.cpp", 3448)
;
3449
3450 case Decl::MSProperty:
3451 case Decl::MSGuid:
3452 case Decl::TemplateParamObject:
3453 // FIXME: Should MSGuidDecl and template parameter objects be subject to
3454 // capture in OpenMP, or duplicated between host and device?
3455 valueKind = VK_LValue;
3456 break;
3457
3458 case Decl::UnnamedGlobalConstant:
3459 valueKind = VK_LValue;
3460 break;
3461
3462 case Decl::CXXMethod:
3463 // If we're referring to a method with an __unknown_anytype
3464 // result type, make the entire expression __unknown_anytype.
3465 // This should only be possible with a type written directly.
3466 if (const FunctionProtoType *proto =
3467 dyn_cast<FunctionProtoType>(VD->getType()))
3468 if (proto->getReturnType() == Context.UnknownAnyTy) {
3469 type = Context.UnknownAnyTy;
3470 valueKind = VK_PRValue;
3471 break;
3472 }
3473
3474 // C++ methods are l-values if static, r-values if non-static.
3475 if (cast<CXXMethodDecl>(VD)->isStatic()) {
3476 valueKind = VK_LValue;
3477 break;
3478 }
3479 LLVM_FALLTHROUGH[[gnu::fallthrough]];
3480
3481 case Decl::CXXConversion:
3482 case Decl::CXXDestructor:
3483 case Decl::CXXConstructor:
3484 valueKind = VK_PRValue;
3485 break;
3486 }
3487
3488 return BuildDeclRefExpr(VD, type, valueKind, NameInfo, &SS, FoundD,
3489 /*FIXME: TemplateKWLoc*/ SourceLocation(),
3490 TemplateArgs);
3491}
3492
3493static void ConvertUTF8ToWideString(unsigned CharByteWidth, StringRef Source,
3494 SmallString<32> &Target) {
3495 Target.resize(CharByteWidth * (Source.size() + 1));
3496 char *ResultPtr = &Target[0];
3497 const llvm::UTF8 *ErrorPtr;
3498 bool success =
3499 llvm::ConvertUTF8toWide(CharByteWidth, Source, ResultPtr, ErrorPtr);
3500 (void)success;
3501 assert(success)(static_cast <bool> (success) ? void (0) : __assert_fail
("success", "clang/lib/Sema/SemaExpr.cpp", 3501, __extension__
__PRETTY_FUNCTION__))
;
3502 Target.resize(ResultPtr - &Target[0]);
3503}
3504
3505ExprResult Sema::BuildPredefinedExpr(SourceLocation Loc,
3506 PredefinedExpr::IdentKind IK) {
3507 // Pick the current block, lambda, captured statement or function.
3508 Decl *currentDecl = nullptr;
3509 if (const BlockScopeInfo *BSI = getCurBlock())
3510 currentDecl = BSI->TheDecl;
3511 else if (const LambdaScopeInfo *LSI = getCurLambda())
3512 currentDecl = LSI->CallOperator;
3513 else if (const CapturedRegionScopeInfo *CSI = getCurCapturedRegion())
3514 currentDecl = CSI->TheCapturedDecl;
3515 else
3516 currentDecl = getCurFunctionOrMethodDecl();
3517
3518 if (!currentDecl) {
3519 Diag(Loc, diag::ext_predef_outside_function);
3520 currentDecl = Context.getTranslationUnitDecl();
3521 }
3522
3523 QualType ResTy;
3524 StringLiteral *SL = nullptr;
3525 if (cast<DeclContext>(currentDecl)->isDependentContext())
3526 ResTy = Context.DependentTy;
3527 else {
3528 // Pre-defined identifiers are of type char[x], where x is the length of
3529 // the string.
3530 auto Str = PredefinedExpr::ComputeName(IK, currentDecl);
3531 unsigned Length = Str.length();
3532
3533 llvm::APInt LengthI(32, Length + 1);
3534 if (IK == PredefinedExpr::LFunction || IK == PredefinedExpr::LFuncSig) {
3535 ResTy =
3536 Context.adjustStringLiteralBaseType(Context.WideCharTy.withConst());
3537 SmallString<32> RawChars;
3538 ConvertUTF8ToWideString(Context.getTypeSizeInChars(ResTy).getQuantity(),
3539 Str, RawChars);
3540 ResTy = Context.getConstantArrayType(ResTy, LengthI, nullptr,
3541 ArrayType::Normal,
3542 /*IndexTypeQuals*/ 0);
3543 SL = StringLiteral::Create(Context, RawChars, StringLiteral::Wide,
3544 /*Pascal*/ false, ResTy, Loc);
3545 } else {
3546 ResTy = Context.adjustStringLiteralBaseType(Context.CharTy.withConst());
3547 ResTy = Context.getConstantArrayType(ResTy, LengthI, nullptr,
3548 ArrayType::Normal,
3549 /*IndexTypeQuals*/ 0);
3550 SL = StringLiteral::Create(Context, Str, StringLiteral::Ascii,
3551 /*Pascal*/ false, ResTy, Loc);
3552 }
3553 }
3554
3555 return PredefinedExpr::Create(Context, Loc, ResTy, IK, SL);
3556}
3557
3558ExprResult Sema::BuildSYCLUniqueStableNameExpr(SourceLocation OpLoc,
3559 SourceLocation LParen,
3560 SourceLocation RParen,
3561 TypeSourceInfo *TSI) {
3562 return SYCLUniqueStableNameExpr::Create(Context, OpLoc, LParen, RParen, TSI);
3563}
3564
3565ExprResult Sema::ActOnSYCLUniqueStableNameExpr(SourceLocation OpLoc,
3566 SourceLocation LParen,
3567 SourceLocation RParen,
3568 ParsedType ParsedTy) {
3569 TypeSourceInfo *TSI = nullptr;
3570 QualType Ty = GetTypeFromParser(ParsedTy, &TSI);
3571
3572 if (Ty.isNull())
3573 return ExprError();
3574 if (!TSI)
3575 TSI = Context.getTrivialTypeSourceInfo(Ty, LParen);
3576
3577 return BuildSYCLUniqueStableNameExpr(OpLoc, LParen, RParen, TSI);
3578}
3579
3580ExprResult Sema::ActOnPredefinedExpr(SourceLocation Loc, tok::TokenKind Kind) {
3581 PredefinedExpr::IdentKind IK;
3582
3583 switch (Kind) {
3584 default: llvm_unreachable("Unknown simple primary expr!")::llvm::llvm_unreachable_internal("Unknown simple primary expr!"
, "clang/lib/Sema/SemaExpr.cpp", 3584)
;
3585 case tok::kw___func__: IK = PredefinedExpr::Func; break; // [C99 6.4.2.2]
3586 case tok::kw___FUNCTION__: IK = PredefinedExpr::Function; break;
3587 case tok::kw___FUNCDNAME__: IK = PredefinedExpr::FuncDName; break; // [MS]
3588 case tok::kw___FUNCSIG__: IK = PredefinedExpr::FuncSig; break; // [MS]
3589 case tok::kw_L__FUNCTION__: IK = PredefinedExpr::LFunction; break; // [MS]
3590 case tok::kw_L__FUNCSIG__: IK = PredefinedExpr::LFuncSig; break; // [MS]
3591 case tok::kw___PRETTY_FUNCTION__: IK = PredefinedExpr::PrettyFunction; break;
3592 }
3593
3594 return BuildPredefinedExpr(Loc, IK);
3595}
3596
3597ExprResult Sema::ActOnCharacterConstant(const Token &Tok, Scope *UDLScope) {
3598 SmallString<16> CharBuffer;
3599 bool Invalid = false;
3600 StringRef ThisTok = PP.getSpelling(Tok, CharBuffer, &Invalid);
3601 if (Invalid)
3602 return ExprError();
3603
3604 CharLiteralParser Literal(ThisTok.begin(), ThisTok.end(), Tok.getLocation(),
3605 PP, Tok.getKind());
3606 if (Literal.hadError())
3607 return ExprError();
3608
3609 QualType Ty;
3610 if (Literal.isWide())
3611 Ty = Context.WideCharTy; // L'x' -> wchar_t in C and C++.
3612 else if (Literal.isUTF8() && getLangOpts().C2x)
3613 Ty = Context.UnsignedCharTy; // u8'x' -> unsigned char in C2x
3614 else if (Literal.isUTF8() && getLangOpts().Char8)
3615 Ty = Context.Char8Ty; // u8'x' -> char8_t when it exists.
3616 else if (Literal.isUTF16())
3617 Ty = Context.Char16Ty; // u'x' -> char16_t in C11 and C++11.
3618 else if (Literal.isUTF32())
3619 Ty = Context.Char32Ty; // U'x' -> char32_t in C11 and C++11.
3620 else if (!getLangOpts().CPlusPlus || Literal.isMultiChar())
3621 Ty = Context.IntTy; // 'x' -> int in C, 'wxyz' -> int in C++.
3622 else
3623 Ty = Context.CharTy; // 'x' -> char in C++;
3624 // u8'x' -> char in C11-C17 and in C++ without char8_t.
3625
3626 CharacterLiteral::CharacterKind Kind = CharacterLiteral::Ascii;
3627 if (Literal.isWide())
3628 Kind = CharacterLiteral::Wide;
3629 else if (Literal.isUTF16())
3630 Kind = CharacterLiteral::UTF16;
3631 else if (Literal.isUTF32())
3632 Kind = CharacterLiteral::UTF32;
3633 else if (Literal.isUTF8())
3634 Kind = CharacterLiteral::UTF8;
3635
3636 Expr *Lit = new (Context) CharacterLiteral(Literal.getValue(), Kind, Ty,
3637 Tok.getLocation());
3638
3639 if (Literal.getUDSuffix().empty())
3640 return Lit;
3641
3642 // We're building a user-defined literal.
3643 IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix());
3644 SourceLocation UDSuffixLoc =
3645 getUDSuffixLoc(*this, Tok.getLocation(), Literal.getUDSuffixOffset());
3646
3647 // Make sure we're allowed user-defined literals here.
3648 if (!UDLScope)
3649 return ExprError(Diag(UDSuffixLoc, diag::err_invalid_character_udl));
3650
3651 // C++11 [lex.ext]p6: The literal L is treated as a call of the form
3652 // operator "" X (ch)
3653 return BuildCookedLiteralOperatorCall(*this, UDLScope, UDSuffix, UDSuffixLoc,
3654 Lit, Tok.getLocation());
3655}
3656
3657ExprResult Sema::ActOnIntegerConstant(SourceLocation Loc, uint64_t Val) {
3658 unsigned IntSize = Context.getTargetInfo().getIntWidth();
3659 return IntegerLiteral::Create(Context, llvm::APInt(IntSize, Val),
3660 Context.IntTy, Loc);
3661}
3662
3663static Expr *BuildFloatingLiteral(Sema &S, NumericLiteralParser &Literal,
3664 QualType Ty, SourceLocation Loc) {
3665 const llvm::fltSemantics &Format = S.Context.getFloatTypeSemantics(Ty);
3666
3667 using llvm::APFloat;
3668 APFloat Val(Format);
3669
3670 APFloat::opStatus result = Literal.GetFloatValue(Val);
3671
3672 // Overflow is always an error, but underflow is only an error if
3673 // we underflowed to zero (APFloat reports denormals as underflow).
3674 if ((result & APFloat::opOverflow) ||
3675 ((result & APFloat::opUnderflow) && Val.isZero())) {
3676 unsigned diagnostic;
3677 SmallString<20> buffer;
3678 if (result & APFloat::opOverflow) {
3679 diagnostic = diag::warn_float_overflow;
3680 APFloat::getLargest(Format).toString(buffer);
3681 } else {
3682 diagnostic = diag::warn_float_underflow;
3683 APFloat::getSmallest(Format).toString(buffer);
3684 }
3685
3686 S.Diag(Loc, diagnostic)
3687 << Ty
3688 << StringRef(buffer.data(), buffer.size());
3689 }
3690
3691 bool isExact = (result == APFloat::opOK);
3692 return FloatingLiteral::Create(S.Context, Val, isExact, Ty, Loc);
3693}
3694
3695bool Sema::CheckLoopHintExpr(Expr *E, SourceLocation Loc) {
3696 assert(E && "Invalid expression")(static_cast <bool> (E && "Invalid expression")
? void (0) : __assert_fail ("E && \"Invalid expression\""
, "clang/lib/Sema/SemaExpr.cpp", 3696, __extension__ __PRETTY_FUNCTION__
))
;
3697
3698 if (E->isValueDependent())
3699 return false;
3700
3701 QualType QT = E->getType();
3702 if (!QT->isIntegerType() || QT->isBooleanType() || QT->isCharType()) {
3703 Diag(E->getExprLoc(), diag::err_pragma_loop_invalid_argument_type) << QT;
3704 return true;
3705 }
3706
3707 llvm::APSInt ValueAPS;
3708 ExprResult R = VerifyIntegerConstantExpression(E, &ValueAPS);
3709
3710 if (R.isInvalid())
3711 return true;
3712
3713 bool ValueIsPositive = ValueAPS.isStrictlyPositive();
3714 if (!ValueIsPositive || ValueAPS.getActiveBits() > 31) {
3715 Diag(E->getExprLoc(), diag::err_pragma_loop_invalid_argument_value)
3716 << toString(ValueAPS, 10) << ValueIsPositive;
3717 return true;
3718 }
3719
3720 return false;
3721}
3722
3723ExprResult Sema::ActOnNumericConstant(const Token &Tok, Scope *UDLScope) {
3724 // Fast path for a single digit (which is quite common). A single digit
3725 // cannot have a trigraph, escaped newline, radix prefix, or suffix.
3726 if (Tok.getLength() == 1) {
3727 const char Val = PP.getSpellingOfSingleCharacterNumericConstant(Tok);
3728 return ActOnIntegerConstant(Tok.getLocation(), Val-'0');
3729 }
3730
3731 SmallString<128> SpellingBuffer;
3732 // NumericLiteralParser wants to overread by one character. Add padding to
3733 // the buffer in case the token is copied to the buffer. If getSpelling()
3734 // returns a StringRef to the memory buffer, it should have a null char at
3735 // the EOF, so it is also safe.
3736 SpellingBuffer.resize(Tok.getLength() + 1);
3737
3738 // Get the spelling of the token, which eliminates trigraphs, etc.
3739 bool Invalid = false;
3740 StringRef TokSpelling = PP.getSpelling(Tok, SpellingBuffer, &Invalid);
3741 if (Invalid)
3742 return ExprError();
3743
3744 NumericLiteralParser Literal(TokSpelling, Tok.getLocation(),
3745 PP.getSourceManager(), PP.getLangOpts(),
3746 PP.getTargetInfo(), PP.getDiagnostics());
3747 if (Literal.hadError)
3748 return ExprError();
3749
3750 if (Literal.hasUDSuffix()) {
3751 // We're building a user-defined literal.
3752 IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix());
3753 SourceLocation UDSuffixLoc =
3754 getUDSuffixLoc(*this, Tok.getLocation(), Literal.getUDSuffixOffset());
3755
3756 // Make sure we're allowed user-defined literals here.
3757 if (!UDLScope)
3758 return ExprError(Diag(UDSuffixLoc, diag::err_invalid_numeric_udl));
3759
3760 QualType CookedTy;
3761 if (Literal.isFloatingLiteral()) {
3762 // C++11 [lex.ext]p4: If S contains a literal operator with parameter type
3763 // long double, the literal is treated as a call of the form
3764 // operator "" X (f L)
3765 CookedTy = Context.LongDoubleTy;
3766 } else {
3767 // C++11 [lex.ext]p3: If S contains a literal operator with parameter type
3768 // unsigned long long, the literal is treated as a call of the form
3769 // operator "" X (n ULL)
3770 CookedTy = Context.UnsignedLongLongTy;
3771 }
3772
3773 DeclarationName OpName =
3774 Context.DeclarationNames.getCXXLiteralOperatorName(UDSuffix);
3775 DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc);
3776 OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc);
3777
3778 SourceLocation TokLoc = Tok.getLocation();
3779
3780 // Perform literal operator lookup to determine if we're building a raw
3781 // literal or a cooked one.
3782 LookupResult R(*this, OpName, UDSuffixLoc, LookupOrdinaryName);
3783 switch (LookupLiteralOperator(UDLScope, R, CookedTy,
3784 /*AllowRaw*/ true, /*AllowTemplate*/ true,
3785 /*AllowStringTemplatePack*/ false,
3786 /*DiagnoseMissing*/ !Literal.isImaginary)) {
3787 case LOLR_ErrorNoDiagnostic:
3788 // Lookup failure for imaginary constants isn't fatal, there's still the
3789 // GNU extension producing _Complex types.
3790 break;
3791 case LOLR_Error:
3792 return ExprError();
3793 case LOLR_Cooked: {
3794 Expr *Lit;
3795 if (Literal.isFloatingLiteral()) {
3796 Lit = BuildFloatingLiteral(*this, Literal, CookedTy, Tok.getLocation());
3797 } else {
3798 llvm::APInt ResultVal(Context.getTargetInfo().getLongLongWidth(), 0);
3799 if (Literal.GetIntegerValue(ResultVal))
3800 Diag(Tok.getLocation(), diag::err_integer_literal_too_large)
3801 << /* Unsigned */ 1;
3802 Lit = IntegerLiteral::Create(Context, ResultVal, CookedTy,
3803 Tok.getLocation());
3804 }
3805 return BuildLiteralOperatorCall(R, OpNameInfo, Lit, TokLoc);
3806 }
3807
3808 case LOLR_Raw: {
3809 // C++11 [lit.ext]p3, p4: If S contains a raw literal operator, the
3810 // literal is treated as a call of the form
3811 // operator "" X ("n")
3812 unsigned Length = Literal.getUDSuffixOffset();
3813 QualType StrTy = Context.getConstantArrayType(
3814 Context.adjustStringLiteralBaseType(Context.CharTy.withConst()),
3815 llvm::APInt(32, Length + 1), nullptr, ArrayType::Normal, 0);
3816 Expr *Lit = StringLiteral::Create(
3817 Context, StringRef(TokSpelling.data(), Length), StringLiteral::Ascii,
3818 /*Pascal*/false, StrTy, &TokLoc, 1);
3819 return BuildLiteralOperatorCall(R, OpNameInfo, Lit, TokLoc);
3820 }
3821
3822 case LOLR_Template: {
3823 // C++11 [lit.ext]p3, p4: Otherwise (S contains a literal operator
3824 // template), L is treated as a call fo the form
3825 // operator "" X <'c1', 'c2', ... 'ck'>()
3826 // where n is the source character sequence c1 c2 ... ck.
3827 TemplateArgumentListInfo ExplicitArgs;
3828 unsigned CharBits = Context.getIntWidth(Context.CharTy);
3829 bool CharIsUnsigned = Context.CharTy->isUnsignedIntegerType();
3830 llvm::APSInt Value(CharBits, CharIsUnsigned);
3831 for (unsigned I = 0, N = Literal.getUDSuffixOffset(); I != N; ++I) {
3832 Value = TokSpelling[I];
3833 TemplateArgument Arg(Context, Value, Context.CharTy);
3834 TemplateArgumentLocInfo ArgInfo;
3835 ExplicitArgs.addArgument(TemplateArgumentLoc(Arg, ArgInfo));
3836 }
3837 return BuildLiteralOperatorCall(R, OpNameInfo, None, TokLoc,
3838 &ExplicitArgs);
3839 }
3840 case LOLR_StringTemplatePack:
3841 llvm_unreachable("unexpected literal operator lookup result")::llvm::llvm_unreachable_internal("unexpected literal operator lookup result"
, "clang/lib/Sema/SemaExpr.cpp", 3841)
;
3842 }
3843 }
3844
3845 Expr *Res;
3846
3847 if (Literal.isFixedPointLiteral()) {
3848 QualType Ty;
3849
3850 if (Literal.isAccum) {
3851 if (Literal.isHalf) {
3852 Ty = Context.ShortAccumTy;
3853 } else if (Literal.isLong) {
3854 Ty = Context.LongAccumTy;
3855 } else {
3856 Ty = Context.AccumTy;
3857 }
3858 } else if (Literal.isFract) {
3859 if (Literal.isHalf) {
3860 Ty = Context.ShortFractTy;
3861 } else if (Literal.isLong) {
3862 Ty = Context.LongFractTy;
3863 } else {
3864 Ty = Context.FractTy;
3865 }
3866 }
3867
3868 if (Literal.isUnsigned) Ty = Context.getCorrespondingUnsignedType(Ty);
3869
3870 bool isSigned = !Literal.isUnsigned;
3871 unsigned scale = Context.getFixedPointScale(Ty);
3872 unsigned bit_width = Context.getTypeInfo(Ty).Width;
3873
3874 llvm::APInt Val(bit_width, 0, isSigned);
3875 bool Overflowed = Literal.GetFixedPointValue(Val, scale);
3876 bool ValIsZero = Val.isZero() && !Overflowed;
3877
3878 auto MaxVal = Context.getFixedPointMax(Ty).getValue();
3879 if (Literal.isFract && Val == MaxVal + 1 && !ValIsZero)
3880 // Clause 6.4.4 - The value of a constant shall be in the range of
3881 // representable values for its type, with exception for constants of a
3882 // fract type with a value of exactly 1; such a constant shall denote
3883 // the maximal value for the type.
3884 --Val;
3885 else if (Val.ugt(MaxVal) || Overflowed)
3886 Diag(Tok.getLocation(), diag::err_too_large_for_fixed_point);
3887
3888 Res = FixedPointLiteral::CreateFromRawInt(Context, Val, Ty,
3889 Tok.getLocation(), scale);
3890 } else if (Literal.isFloatingLiteral()) {
3891 QualType Ty;
3892 if (Literal.isHalf){
3893 if (getOpenCLOptions().isAvailableOption("cl_khr_fp16", getLangOpts()))
3894 Ty = Context.HalfTy;
3895 else {
3896 Diag(Tok.getLocation(), diag::err_half_const_requires_fp16);
3897 return ExprError();
3898 }
3899 } else if (Literal.isFloat)
3900 Ty = Context.FloatTy;
3901 else if (Literal.isLong)
3902 Ty = Context.LongDoubleTy;
3903 else if (Literal.isFloat16)
3904 Ty = Context.Float16Ty;
3905 else if (Literal.isFloat128)
3906 Ty = Context.Float128Ty;
3907 else
3908 Ty = Context.DoubleTy;
3909
3910 Res = BuildFloatingLiteral(*this, Literal, Ty, Tok.getLocation());
3911
3912 if (Ty == Context.DoubleTy) {
3913 if (getLangOpts().SinglePrecisionConstants) {
3914 if (Ty->castAs<BuiltinType>()->getKind() != BuiltinType::Float) {
3915 Res = ImpCastExprToType(Res, Context.FloatTy, CK_FloatingCast).get();
3916 }
3917 } else if (getLangOpts().OpenCL && !getOpenCLOptions().isAvailableOption(
3918 "cl_khr_fp64", getLangOpts())) {
3919 // Impose single-precision float type when cl_khr_fp64 is not enabled.
3920 Diag(Tok.getLocation(), diag::warn_double_const_requires_fp64)
3921 << (getLangOpts().getOpenCLCompatibleVersion() >= 300);
3922 Res = ImpCastExprToType(Res, Context.FloatTy, CK_FloatingCast).get();
3923 }
3924 }
3925 } else if (!Literal.isIntegerLiteral()) {
3926 return ExprError();
3927 } else {
3928 QualType Ty;
3929
3930 // 'long long' is a C99 or C++11 feature.
3931 if (!getLangOpts().C99 && Literal.isLongLong) {
3932 if (getLangOpts().CPlusPlus)
3933 Diag(Tok.getLocation(),
3934 getLangOpts().CPlusPlus11 ?
3935 diag::warn_cxx98_compat_longlong : diag::ext_cxx11_longlong);
3936 else
3937 Diag(Tok.getLocation(), diag::ext_c99_longlong);
3938 }
3939
3940 // 'z/uz' literals are a C++2b feature.
3941 if (Literal.isSizeT)
3942 Diag(Tok.getLocation(), getLangOpts().CPlusPlus
3943 ? getLangOpts().CPlusPlus2b
3944 ? diag::warn_cxx20_compat_size_t_suffix
3945 : diag::ext_cxx2b_size_t_suffix
3946 : diag::err_cxx2b_size_t_suffix);
3947
3948 // 'wb/uwb' literals are a C2x feature. We support _BitInt as a type in C++,
3949 // but we do not currently support the suffix in C++ mode because it's not
3950 // entirely clear whether WG21 will prefer this suffix to return a library
3951 // type such as std::bit_int instead of returning a _BitInt.
3952 if (Literal.isBitInt && !getLangOpts().CPlusPlus)
3953 PP.Diag(Tok.getLocation(), getLangOpts().C2x
3954 ? diag::warn_c2x_compat_bitint_suffix
3955 : diag::ext_c2x_bitint_suffix);
3956
3957 // Get the value in the widest-possible width. What is "widest" depends on
3958 // whether the literal is a bit-precise integer or not. For a bit-precise
3959 // integer type, try to scan the source to determine how many bits are
3960 // needed to represent the value. This may seem a bit expensive, but trying
3961 // to get the integer value from an overly-wide APInt is *extremely*
3962 // expensive, so the naive approach of assuming
3963 // llvm::IntegerType::MAX_INT_BITS is a big performance hit.
3964 unsigned BitsNeeded =
3965 Literal.isBitInt ? llvm::APInt::getSufficientBitsNeeded(
3966 Literal.getLiteralDigits(), Literal.getRadix())
3967 : Context.getTargetInfo().getIntMaxTWidth();
3968 llvm::APInt ResultVal(BitsNeeded, 0);
3969
3970 if (Literal.GetIntegerValue(ResultVal)) {
3971 // If this value didn't fit into uintmax_t, error and force to ull.
3972 Diag(Tok.getLocation(), diag::err_integer_literal_too_large)
3973 << /* Unsigned */ 1;
3974 Ty = Context.UnsignedLongLongTy;
3975 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", 3976, __extension__ __PRETTY_FUNCTION__
))
3976 "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", 3976, __extension__ __PRETTY_FUNCTION__
))
;
3977 } else {
3978 // If this value fits into a ULL, try to figure out what else it fits into
3979 // according to the rules of C99 6.4.4.1p5.
3980
3981 // Octal, Hexadecimal, and integers with a U suffix are allowed to
3982 // be an unsigned int.
3983 bool AllowUnsigned = Literal.isUnsigned || Literal.getRadix() != 10;
3984
3985 // Check from smallest to largest, picking the smallest type we can.
3986 unsigned Width = 0;
3987
3988 // Microsoft specific integer suffixes are explicitly sized.
3989 if (Literal.MicrosoftInteger) {
3990 if (Literal.MicrosoftInteger == 8 && !Literal.isUnsigned) {
3991 Width = 8;
3992 Ty = Context.CharTy;
3993 } else {
3994 Width = Literal.MicrosoftInteger;
3995 Ty = Context.getIntTypeForBitwidth(Width,
3996 /*Signed=*/!Literal.isUnsigned);
3997 }
3998 }
3999
4000 // Bit-precise integer literals are automagically-sized based on the
4001 // width required by the literal.
4002 if (Literal.isBitInt) {
4003 // The signed version has one more bit for the sign value. There are no
4004 // zero-width bit-precise integers, even if the literal value is 0.
4005 Width = std::max(ResultVal.getActiveBits(), 1u) +
4006 (Literal.isUnsigned ? 0u : 1u);
4007
4008 // Diagnose if the width of the constant is larger than BITINT_MAXWIDTH,
4009 // and reset the type to the largest supported width.
4010 unsigned int MaxBitIntWidth =
4011 Context.getTargetInfo().getMaxBitIntWidth();
4012 if (Width > MaxBitIntWidth) {
4013 Diag(Tok.getLocation(), diag::err_integer_literal_too_large)
4014 << Literal.isUnsigned;
4015 Width = MaxBitIntWidth;
4016 }
4017
4018 // Reset the result value to the smaller APInt and select the correct
4019 // type to be used. Note, we zext even for signed values because the
4020 // literal itself is always an unsigned value (a preceeding - is a
4021 // unary operator, not part of the literal).
4022 ResultVal = ResultVal.zextOrTrunc(Width);
4023 Ty = Context.getBitIntType(Literal.isUnsigned, Width);
4024 }
4025
4026 // Check C++2b size_t literals.
4027 if (Literal.isSizeT) {
4028 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", 4029, __extension__ __PRETTY_FUNCTION__
))
4029 "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", 4029, __extension__ __PRETTY_FUNCTION__
))
;
4030 unsigned SizeTSize = Context.getTargetInfo().getTypeWidth(
4031 Context.getTargetInfo().getSizeType());
4032
4033 // Does it fit in size_t?
4034 if (ResultVal.isIntN(SizeTSize)) {
4035 // Does it fit in ssize_t?
4036 if (!Literal.isUnsigned && ResultVal[SizeTSize - 1] == 0)
4037 Ty = Context.getSignedSizeType();
4038 else if (AllowUnsigned)
4039 Ty = Context.getSizeType();
4040 Width = SizeTSize;
4041 }
4042 }
4043
4044 if (Ty.isNull() && !Literal.isLong && !Literal.isLongLong &&
4045 !Literal.isSizeT) {
4046 // Are int/unsigned possibilities?
4047 unsigned IntSize = Context.getTargetInfo().getIntWidth();
4048
4049 // Does it fit in a unsigned int?
4050 if (ResultVal.isIntN(IntSize)) {
4051 // Does it fit in a signed int?
4052 if (!Literal.isUnsigned && ResultVal[IntSize-1] == 0)
4053 Ty = Context.IntTy;
4054 else if (AllowUnsigned)
4055 Ty = Context.UnsignedIntTy;
4056 Width = IntSize;
4057 }
4058 }
4059
4060 // Are long/unsigned long possibilities?
4061 if (Ty.isNull() && !Literal.isLongLong && !Literal.isSizeT) {
4062 unsigned LongSize = Context.getTargetInfo().getLongWidth();
4063
4064 // Does it fit in a unsigned long?
4065 if (ResultVal.isIntN(LongSize)) {
4066 // Does it fit in a signed long?
4067 if (!Literal.isUnsigned && ResultVal[LongSize-1] == 0)
4068 Ty = Context.LongTy;
4069 else if (AllowUnsigned)
4070 Ty = Context.UnsignedLongTy;
4071 // Check according to the rules of C90 6.1.3.2p5. C++03 [lex.icon]p2
4072 // is compatible.
4073 else if (!getLangOpts().C99 && !getLangOpts().CPlusPlus11) {
4074 const unsigned LongLongSize =
4075 Context.getTargetInfo().getLongLongWidth();
4076 Diag(Tok.getLocation(),
4077 getLangOpts().CPlusPlus
4078 ? Literal.isLong
4079 ? diag::warn_old_implicitly_unsigned_long_cxx
4080 : /*C++98 UB*/ diag::
4081 ext_old_implicitly_unsigned_long_cxx
4082 : diag::warn_old_implicitly_unsigned_long)
4083 << (LongLongSize > LongSize ? /*will have type 'long long'*/ 0
4084 : /*will be ill-formed*/ 1);
4085 Ty = Context.UnsignedLongTy;
4086 }
4087 Width = LongSize;
4088 }
4089 }
4090
4091 // Check long long if needed.
4092 if (Ty.isNull() && !Literal.isSizeT) {
4093 unsigned LongLongSize = Context.getTargetInfo().getLongLongWidth();
4094
4095 // Does it fit in a unsigned long long?
4096 if (ResultVal.isIntN(LongLongSize)) {
4097 // Does it fit in a signed long long?
4098 // To be compatible with MSVC, hex integer literals ending with the
4099 // LL or i64 suffix are always signed in Microsoft mode.
4100 if (!Literal.isUnsigned && (ResultVal[LongLongSize-1] == 0 ||
4101 (getLangOpts().MSVCCompat && Literal.isLongLong)))
4102 Ty = Context.LongLongTy;
4103 else if (AllowUnsigned)
4104 Ty = Context.UnsignedLongLongTy;
4105 Width = LongLongSize;
4106 }
4107 }
4108
4109 // If we still couldn't decide a type, we either have 'size_t' literal
4110 // that is out of range, or a decimal literal that does not fit in a
4111 // signed long long and has no U suffix.
4112 if (Ty.isNull()) {
4113 if (Literal.isSizeT)
4114 Diag(Tok.getLocation(), diag::err_size_t_literal_too_large)
4115 << Literal.isUnsigned;
4116 else
4117 Diag(Tok.getLocation(),
4118 diag::ext_integer_literal_too_large_for_signed);
4119 Ty = Context.UnsignedLongLongTy;
4120 Width = Context.getTargetInfo().getLongLongWidth();
4121 }
4122
4123 if (ResultVal.getBitWidth() != Width)
4124 ResultVal = ResultVal.trunc(Width);
4125 }
4126 Res = IntegerLiteral::Create(Context, ResultVal, Ty, Tok.getLocation());
4127 }
4128
4129 // If this is an imaginary literal, create the ImaginaryLiteral wrapper.
4130 if (Literal.isImaginary) {
4131 Res = new (Context) ImaginaryLiteral(Res,
4132 Context.getComplexType(Res->getType()));
4133
4134 Diag(Tok.getLocation(), diag::ext_imaginary_constant);
4135 }
4136 return Res;
4137}
4138
4139ExprResult Sema::ActOnParenExpr(SourceLocation L, SourceLocation R, Expr *E) {
4140 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", 4140, __extension__ __PRETTY_FUNCTION__
))
;
4141 QualType ExprTy = E->getType();
4142 if (getLangOpts().ProtectParens && CurFPFeatures.getAllowFPReassociate() &&
4143 !E->isLValue() && ExprTy->hasFloatingRepresentation())
4144 return BuildBuiltinCallExpr(R, Builtin::BI__arithmetic_fence, E);
4145 return new (Context) ParenExpr(L, R, E);
4146}
4147
4148static bool CheckVecStepTraitOperandType(Sema &S, QualType T,
4149 SourceLocation Loc,
4150 SourceRange ArgRange) {
4151 // [OpenCL 1.1 6.11.12] "The vec_step built-in function takes a built-in
4152 // scalar or vector data type argument..."
4153 // Every built-in scalar type (OpenCL 1.1 6.1.1) is either an arithmetic
4154 // type (C99 6.2.5p18) or void.
4155 if (!(T->isArithmeticType() || T->isVoidType() || T->isVectorType())) {
4156 S.Diag(Loc, diag::err_vecstep_non_scalar_vector_type)
4157 << T << ArgRange;
4158 return true;
4159 }
4160
4161 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", 4162, __extension__ __PRETTY_FUNCTION__
))
4162 "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", 4162, __extension__ __PRETTY_FUNCTION__
))
;
4163 return false;
4164}
4165
4166static bool CheckExtensionTraitOperandType(Sema &S, QualType T,
4167 SourceLocation Loc,
4168 SourceRange ArgRange,
4169 UnaryExprOrTypeTrait TraitKind) {
4170 // Invalid types must be hard errors for SFINAE in C++.
4171 if (S.LangOpts.CPlusPlus)
4172 return true;
4173
4174 // C99 6.5.3.4p1:
4175 if (T->isFunctionType() &&
4176 (TraitKind == UETT_SizeOf || TraitKind == UETT_AlignOf ||
4177 TraitKind == UETT_PreferredAlignOf)) {
4178 // sizeof(function)/alignof(function) is allowed as an extension.
4179 S.Diag(Loc, diag::ext_sizeof_alignof_function_type)
4180 << getTraitSpelling(TraitKind) << ArgRange;
4181 return false;
4182 }
4183
4184 // Allow sizeof(void)/alignof(void) as an extension, unless in OpenCL where
4185 // this is an error (OpenCL v1.1 s6.3.k)
4186 if (T->isVoidType()) {
4187 unsigned DiagID = S.LangOpts.OpenCL ? diag::err_opencl_sizeof_alignof_type
4188 : diag::ext_sizeof_alignof_void_type;
4189 S.Diag(Loc, DiagID) << getTraitSpelling(TraitKind) << ArgRange;
4190 return false;
4191 }
4192
4193 return true;
4194}
4195
4196static bool CheckObjCTraitOperandConstraints(Sema &S, QualType T,
4197 SourceLocation Loc,
4198 SourceRange ArgRange,
4199 UnaryExprOrTypeTrait TraitKind) {
4200 // Reject sizeof(interface) and sizeof(interface<proto>) if the
4201 // runtime doesn't allow it.
4202 if (!S.LangOpts.ObjCRuntime.allowsSizeofAlignof() && T->isObjCObjectType()) {
4203 S.Diag(Loc, diag::err_sizeof_nonfragile_interface)
4204 << T << (TraitKind == UETT_SizeOf)
4205 << ArgRange;
4206 return true;
4207 }
4208
4209 return false;
4210}
4211
4212/// Check whether E is a pointer from a decayed array type (the decayed
4213/// pointer type is equal to T) and emit a warning if it is.
4214static void warnOnSizeofOnArrayDecay(Sema &S, SourceLocation Loc, QualType T,
4215 Expr *E) {
4216 // Don't warn if the operation changed the type.
4217 if (T != E->getType())
4218 return;
4219
4220 // Now look for array decays.
4221 ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E);
4222 if (!ICE || ICE->getCastKind() != CK_ArrayToPointerDecay)
4223 return;
4224
4225 S.Diag(Loc, diag::warn_sizeof_array_decay) << ICE->getSourceRange()
4226 << ICE->getType()
4227 << ICE->getSubExpr()->getType();
4228}
4229
4230/// Check the constraints on expression operands to unary type expression
4231/// and type traits.
4232///
4233/// Completes any types necessary and validates the constraints on the operand
4234/// expression. The logic mostly mirrors the type-based overload, but may modify
4235/// the expression as it completes the type for that expression through template
4236/// instantiation, etc.
4237bool Sema::CheckUnaryExprOrTypeTraitOperand(Expr *E,
4238 UnaryExprOrTypeTrait ExprKind) {
4239 QualType ExprTy = E->getType();
4240 assert(!ExprTy->isReferenceType())(static_cast <bool> (!ExprTy->isReferenceType()) ? void
(0) : __assert_fail ("!ExprTy->isReferenceType()", "clang/lib/Sema/SemaExpr.cpp"
, 4240, __extension__ __PRETTY_FUNCTION__))
;
4241
4242 bool IsUnevaluatedOperand =
4243 (ExprKind == UETT_SizeOf || ExprKind == UETT_AlignOf ||
4244 ExprKind == UETT_PreferredAlignOf || ExprKind == UETT_VecStep);
4245 if (IsUnevaluatedOperand) {
4246 ExprResult Result = CheckUnevaluatedOperand(E);
4247 if (Result.isInvalid())
4248 return true;
4249 E = Result.get();
4250 }
4251
4252 // The operand for sizeof and alignof is in an unevaluated expression context,
4253 // so side effects could result in unintended consequences.
4254 // Exclude instantiation-dependent expressions, because 'sizeof' is sometimes
4255 // used to build SFINAE gadgets.
4256 // FIXME: Should we consider instantiation-dependent operands to 'alignof'?
4257 if (IsUnevaluatedOperand && !inTemplateInstantiation() &&
4258 !E->isInstantiationDependent() &&
4259 E->HasSideEffects(Context, false))
4260 Diag(E->getExprLoc(), diag::warn_side_effects_unevaluated_context);
4261
4262 if (ExprKind == UETT_VecStep)
4263 return CheckVecStepTraitOperandType(*this, ExprTy, E->getExprLoc(),
4264 E->getSourceRange());
4265
4266 // Explicitly list some types as extensions.
4267 if (!CheckExtensionTraitOperandType(*this, ExprTy, E->getExprLoc(),
4268 E->getSourceRange(), ExprKind))
4269 return false;
4270
4271 // 'alignof' applied to an expression only requires the base element type of
4272 // the expression to be complete. 'sizeof' requires the expression's type to
4273 // be complete (and will attempt to complete it if it's an array of unknown
4274 // bound).
4275 if (ExprKind == UETT_AlignOf || ExprKind == UETT_PreferredAlignOf) {
4276 if (RequireCompleteSizedType(
4277 E->getExprLoc(), Context.getBaseElementType(E->getType()),
4278 diag::err_sizeof_alignof_incomplete_or_sizeless_type,
4279 getTraitSpelling(ExprKind), E->getSourceRange()))
4280 return true;
4281 } else {
4282 if (RequireCompleteSizedExprType(
4283 E, diag::err_sizeof_alignof_incomplete_or_sizeless_type,
4284 getTraitSpelling(ExprKind), E->getSourceRange()))
4285 return true;
4286 }
4287
4288 // Completing the expression's type may have changed it.
4289 ExprTy = E->getType();
4290 assert(!ExprTy->isReferenceType())(static_cast <bool> (!ExprTy->isReferenceType()) ? void
(0) : __assert_fail ("!ExprTy->isReferenceType()", "clang/lib/Sema/SemaExpr.cpp"
, 4290, __extension__ __PRETTY_FUNCTION__))
;
4291
4292 if (ExprTy->isFunctionType()) {
4293 Diag(E->getExprLoc(), diag::err_sizeof_alignof_function_type)
4294 << getTraitSpelling(ExprKind) << E->getSourceRange();
4295 return true;
4296 }
4297
4298 if (CheckObjCTraitOperandConstraints(*this, ExprTy, E->getExprLoc(),
4299 E->getSourceRange(), ExprKind))
4300 return true;
4301
4302 if (ExprKind == UETT_SizeOf) {
4303 if (DeclRefExpr *DeclRef = dyn_cast<DeclRefExpr>(E->IgnoreParens())) {
4304 if (ParmVarDecl *PVD = dyn_cast<ParmVarDecl>(DeclRef->getFoundDecl())) {
4305 QualType OType = PVD->getOriginalType();
4306 QualType Type = PVD->getType();
4307 if (Type->isPointerType() && OType->isArrayType()) {
4308 Diag(E->getExprLoc(), diag::warn_sizeof_array_param)
4309 << Type << OType;
4310 Diag(PVD->getLocation(), diag::note_declared_at);
4311 }
4312 }
4313 }
4314
4315 // Warn on "sizeof(array op x)" and "sizeof(x op array)", where the array
4316 // decays into a pointer and returns an unintended result. This is most
4317 // likely a typo for "sizeof(array) op x".
4318 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E->IgnoreParens())) {
4319 warnOnSizeofOnArrayDecay(*this, BO->getOperatorLoc(), BO->getType(),
4320 BO->getLHS());
4321 warnOnSizeofOnArrayDecay(*this, BO->getOperatorLoc(), BO->getType(),
4322 BO->getRHS());
4323 }
4324 }
4325
4326 return false;
4327}
4328
4329/// Check the constraints on operands to unary expression and type
4330/// traits.
4331///
4332/// This will complete any types necessary, and validate the various constraints
4333/// on those operands.
4334///
4335/// The UsualUnaryConversions() function is *not* called by this routine.
4336/// C99 6.3.2.1p[2-4] all state:
4337/// Except when it is the operand of the sizeof operator ...
4338///
4339/// C++ [expr.sizeof]p4
4340/// The lvalue-to-rvalue, array-to-pointer, and function-to-pointer
4341/// standard conversions are not applied to the operand of sizeof.
4342///
4343/// This policy is followed for all of the unary trait expressions.
4344bool Sema::CheckUnaryExprOrTypeTraitOperand(QualType ExprType,
4345 SourceLocation OpLoc,
4346 SourceRange ExprRange,
4347 UnaryExprOrTypeTrait ExprKind) {
4348 if (ExprType->isDependentType())
4349 return false;
4350
4351 // C++ [expr.sizeof]p2:
4352 // When applied to a reference or a reference type, the result
4353 // is the size of the referenced type.
4354 // C++11 [expr.alignof]p3:
4355 // When alignof is applied to a reference type, the result
4356 // shall be the alignment of the referenced type.
4357 if (const ReferenceType *Ref = ExprType->getAs<ReferenceType>())
4358 ExprType = Ref->getPointeeType();
4359
4360 // C11 6.5.3.4/3, C++11 [expr.alignof]p3:
4361 // When alignof or _Alignof is applied to an array type, the result
4362 // is the alignment of the element type.
4363 if (ExprKind == UETT_AlignOf || ExprKind == UETT_PreferredAlignOf ||
4364 ExprKind == UETT_OpenMPRequiredSimdAlign)
4365 ExprType = Context.getBaseElementType(ExprType);
4366
4367 if (ExprKind == UETT_VecStep)
4368 return CheckVecStepTraitOperandType(*this, ExprType, OpLoc, ExprRange);
4369
4370 // Explicitly list some types as extensions.
4371 if (!CheckExtensionTraitOperandType(*this, ExprType, OpLoc, ExprRange,
4372 ExprKind))
4373 return false;
4374
4375 if (RequireCompleteSizedType(
4376 OpLoc, ExprType, diag::err_sizeof_alignof_incomplete_or_sizeless_type,
4377 getTraitSpelling(ExprKind), ExprRange))
4378 return true;
4379
4380 if (ExprType->isFunctionType()) {
4381 Diag(OpLoc, diag::err_sizeof_alignof_function_type)
4382 << getTraitSpelling(ExprKind) << ExprRange;
4383 return true;
4384 }
4385
4386 if (CheckObjCTraitOperandConstraints(*this, ExprType, OpLoc, ExprRange,
4387 ExprKind))
4388 return true;
4389
4390 return false;
4391}
4392
4393static bool CheckAlignOfExpr(Sema &S, Expr *E, UnaryExprOrTypeTrait ExprKind) {
4394 // Cannot know anything else if the expression is dependent.
4395 if (E->isTypeDependent())
4396 return false;
4397
4398 if (E->getObjectKind() == OK_BitField) {
4399 S.Diag(E->getExprLoc(), diag::err_sizeof_alignof_typeof_bitfield)
4400 << 1 << E->getSourceRange();
4401 return true;
4402 }
4403
4404 ValueDecl *D = nullptr;
4405 Expr *Inner = E->IgnoreParens();
4406 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Inner)) {
4407 D = DRE->getDecl();
4408 } else if (MemberExpr *ME = dyn_cast<MemberExpr>(Inner)) {
4409 D = ME->getMemberDecl();
4410 }
4411
4412 // If it's a field, require the containing struct to have a
4413 // complete definition so that we can compute the layout.
4414 //
4415 // This can happen in C++11 onwards, either by naming the member
4416 // in a way that is not transformed into a member access expression
4417 // (in an unevaluated operand, for instance), or by naming the member
4418 // in a trailing-return-type.
4419 //
4420 // For the record, since __alignof__ on expressions is a GCC
4421 // extension, GCC seems to permit this but always gives the
4422 // nonsensical answer 0.
4423 //
4424 // We don't really need the layout here --- we could instead just
4425 // directly check for all the appropriate alignment-lowing
4426 // attributes --- but that would require duplicating a lot of
4427 // logic that just isn't worth duplicating for such a marginal
4428 // use-case.
4429 if (FieldDecl *FD = dyn_cast_or_null<FieldDecl>(D)) {
4430 // Fast path this check, since we at least know the record has a
4431 // definition if we can find a member of it.
4432 if (!FD->getParent()->isCompleteDefinition()) {
4433 S.Diag(E->getExprLoc(), diag::err_alignof_member_of_incomplete_type)
4434 << E->getSourceRange();
4435 return true;
4436 }
4437
4438 // Otherwise, if it's a field, and the field doesn't have
4439 // reference type, then it must have a complete type (or be a
4440 // flexible array member, which we explicitly want to
4441 // white-list anyway), which makes the following checks trivial.
4442 if (!FD->getType()->isReferenceType())
4443 return false;
4444 }
4445
4446 return S.CheckUnaryExprOrTypeTraitOperand(E, ExprKind);
4447}
4448
4449bool Sema::CheckVecStepExpr(Expr *E) {
4450 E = E->IgnoreParens();
4451
4452 // Cannot know anything else if the expression is dependent.
4453 if (E->isTypeDependent())
4454 return false;
4455
4456 return CheckUnaryExprOrTypeTraitOperand(E, UETT_VecStep);
4457}
4458
4459static void captureVariablyModifiedType(ASTContext &Context, QualType T,
4460 CapturingScopeInfo *CSI) {
4461 assert(T->isVariablyModifiedType())(static_cast <bool> (T->isVariablyModifiedType()) ? void
(0) : __assert_fail ("T->isVariablyModifiedType()", "clang/lib/Sema/SemaExpr.cpp"
, 4461, __extension__ __PRETTY_FUNCTION__))
;
4462 assert(CSI != nullptr)(static_cast <bool> (CSI != nullptr) ? void (0) : __assert_fail
("CSI != nullptr", "clang/lib/Sema/SemaExpr.cpp", 4462, __extension__
__PRETTY_FUNCTION__))
;
4463
4464 // We're going to walk down into the type and look for VLA expressions.
4465 do {
4466 const Type *Ty = T.getTypePtr();
4467 switch (Ty->getTypeClass()) {
4468#define TYPE(Class, Base)
4469#define ABSTRACT_TYPE(Class, Base)
4470#define NON_CANONICAL_TYPE(Class, Base)
4471#define DEPENDENT_TYPE(Class, Base) case Type::Class:
4472#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base)
4473#include "clang/AST/TypeNodes.inc"
4474 T = QualType();
4475 break;
4476 // These types are never variably-modified.
4477 case Type::Builtin:
4478 case Type::Complex:
4479 case Type::Vector:
4480 case Type::ExtVector:
4481 case Type::ConstantMatrix:
4482 case Type::Record:
4483 case Type::Enum:
4484 case Type::Elaborated:
4485 case Type::TemplateSpecialization:
4486 case Type::ObjCObject:
4487 case Type::ObjCInterface:
4488 case Type::ObjCObjectPointer:
4489 case Type::ObjCTypeParam:
4490 case Type::Pipe:
4491 case Type::BitInt:
4492 llvm_unreachable("type class is never variably-modified!")::llvm::llvm_unreachable_internal("type class is never variably-modified!"
, "clang/lib/Sema/SemaExpr.cpp", 4492)
;
4493 case Type::Adjusted:
4494 T = cast<AdjustedType>(Ty)->getOriginalType();
4495 break;
4496 case Type::Decayed:
4497 T = cast<DecayedType>(Ty)->getPointeeType();
4498 break;
4499 case Type::Pointer:
4500 T = cast<PointerType>(Ty)->getPointeeType();
4501 break;
4502 case Type::BlockPointer:
4503 T = cast<BlockPointerType>(Ty)->getPointeeType();
4504 break;
4505 case Type::LValueReference:
4506 case Type::RValueReference:
4507 T = cast<ReferenceType>(Ty)->getPointeeType();
4508 break;
4509 case Type::MemberPointer:
4510 T = cast<MemberPointerType>(Ty)->getPointeeType();
4511 break;
4512 case Type::ConstantArray:
4513 case Type::IncompleteArray:
4514 // Losing element qualification here is fine.
4515 T = cast<ArrayType>(Ty)->getElementType();
4516 break;
4517 case Type::VariableArray: {
4518 // Losing element qualification here is fine.
4519 const VariableArrayType *VAT = cast<VariableArrayType>(Ty);
4520
4521 // Unknown size indication requires no size computation.
4522 // Otherwise, evaluate and record it.
4523 auto Size = VAT->getSizeExpr();
4524 if (Size && !CSI->isVLATypeCaptured(VAT) &&
4525 (isa<CapturedRegionScopeInfo>(CSI) || isa<LambdaScopeInfo>(CSI)))
4526 CSI->addVLATypeCapture(Size->getExprLoc(), VAT, Context.getSizeType());
4527
4528 T = VAT->getElementType();
4529 break;
4530 }
4531 case Type::FunctionProto:
4532 case Type::FunctionNoProto:
4533 T = cast<FunctionType>(Ty)->getReturnType();
4534 break;
4535 case Type::Paren:
4536 case Type::TypeOf:
4537 case Type::UnaryTransform:
4538 case Type::Attributed:
4539 case Type::BTFTagAttributed:
4540 case Type::SubstTemplateTypeParm:
4541 case Type::MacroQualified:
4542 // Keep walking after single level desugaring.
4543 T = T.getSingleStepDesugaredType(Context);
4544 break;
4545 case Type::Typedef:
4546 T = cast<TypedefType>(Ty)->desugar();
4547 break;
4548 case Type::Decltype:
4549 T = cast<DecltypeType>(Ty)->desugar();
4550 break;
4551 case Type::Using:
4552 T = cast<UsingType>(Ty)->desugar();
4553 break;
4554 case Type::Auto:
4555 case Type::DeducedTemplateSpecialization:
4556 T = cast<DeducedType>(Ty)->getDeducedType();
4557 break;
4558 case Type::TypeOfExpr:
4559 T = cast<TypeOfExprType>(Ty)->getUnderlyingExpr()->getType();
4560 break;
4561 case Type::Atomic:
4562 T = cast<AtomicType>(Ty)->getValueType();
4563 break;
4564 }
4565 } while (!T.isNull() && T->isVariablyModifiedType());
4566}
4567
4568/// Build a sizeof or alignof expression given a type operand.
4569ExprResult
4570Sema::CreateUnaryExprOrTypeTraitExpr(TypeSourceInfo *TInfo,
4571 SourceLocation OpLoc,
4572 UnaryExprOrTypeTrait ExprKind,
4573 SourceRange R) {
4574 if (!TInfo)
4575 return ExprError();
4576
4577 QualType T = TInfo->getType();
4578
4579 if (!T->isDependentType() &&
4580 CheckUnaryExprOrTypeTraitOperand(T, OpLoc, R, ExprKind))
4581 return ExprError();
4582
4583 if (T->isVariablyModifiedType() && FunctionScopes.size() > 1) {
4584 if (auto *TT = T->getAs<TypedefType>()) {
4585 for (auto I = FunctionScopes.rbegin(),
4586 E = std::prev(FunctionScopes.rend());
4587 I != E; ++I) {
4588 auto *CSI = dyn_cast<CapturingScopeInfo>(*I);
4589 if (CSI == nullptr)
4590 break;
4591 DeclContext *DC = nullptr;
4592 if (auto *LSI = dyn_cast<LambdaScopeInfo>(CSI))
4593 DC = LSI->CallOperator;
4594 else if (auto *CRSI = dyn_cast<CapturedRegionScopeInfo>(CSI))
4595 DC = CRSI->TheCapturedDecl;
4596 else if (auto *BSI = dyn_cast<BlockScopeInfo>(CSI))
4597 DC = BSI->TheDecl;
4598 if (DC) {
4599 if (DC->containsDecl(TT->getDecl()))
4600 break;
4601 captureVariablyModifiedType(Context, T, CSI);
4602 }
4603 }
4604 }
4605 }
4606
4607 // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t.
4608 if (isUnevaluatedContext() && ExprKind == UETT_SizeOf &&
4609 TInfo->getType()->isVariablyModifiedType())
4610 TInfo = TransformToPotentiallyEvaluated(TInfo);
4611
4612 return new (Context) UnaryExprOrTypeTraitExpr(
4613 ExprKind, TInfo, Context.getSizeType(), OpLoc, R.getEnd());
4614}
4615
4616/// Build a sizeof or alignof expression given an expression
4617/// operand.
4618ExprResult
4619Sema::CreateUnaryExprOrTypeTraitExpr(Expr *E, SourceLocation OpLoc,
4620 UnaryExprOrTypeTrait ExprKind) {
4621 ExprResult PE = CheckPlaceholderExpr(E);
4622 if (PE.isInvalid())
4623 return ExprError();
4624
4625 E = PE.get();
4626
4627 // Verify that the operand is valid.
4628 bool isInvalid = false;
4629 if (E->isTypeDependent()) {
4630 // Delay type-checking for type-dependent expressions.
4631 } else if (ExprKind == UETT_AlignOf || ExprKind == UETT_PreferredAlignOf) {
4632 isInvalid = CheckAlignOfExpr(*this, E, ExprKind);
4633 } else if (ExprKind == UETT_VecStep) {
4634 isInvalid = CheckVecStepExpr(E);
4635 } else if (ExprKind == UETT_OpenMPRequiredSimdAlign) {
4636 Diag(E->getExprLoc(), diag::err_openmp_default_simd_align_expr);
4637 isInvalid = true;
4638 } else if (E->refersToBitField()) { // C99 6.5.3.4p1.
4639 Diag(E->getExprLoc(), diag::err_sizeof_alignof_typeof_bitfield) << 0;
4640 isInvalid = true;
4641 } else {
4642 isInvalid = CheckUnaryExprOrTypeTraitOperand(E, UETT_SizeOf);
4643 }
4644
4645 if (isInvalid)
4646 return ExprError();
4647
4648 if (ExprKind == UETT_SizeOf && E->getType()->isVariableArrayType()) {
4649 PE = TransformToPotentiallyEvaluated(E);
4650 if (PE.isInvalid()) return ExprError();
4651 E = PE.get();
4652 }
4653
4654 // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t.
4655 return new (Context) UnaryExprOrTypeTraitExpr(
4656 ExprKind, E, Context.getSizeType(), OpLoc, E->getSourceRange().getEnd());
4657}
4658
4659/// ActOnUnaryExprOrTypeTraitExpr - Handle @c sizeof(type) and @c sizeof @c
4660/// expr and the same for @c alignof and @c __alignof
4661/// Note that the ArgRange is invalid if isType is false.
4662ExprResult
4663Sema::ActOnUnaryExprOrTypeTraitExpr(SourceLocation OpLoc,
4664 UnaryExprOrTypeTrait ExprKind, bool IsType,
4665 void *TyOrEx, SourceRange ArgRange) {
4666 // If error parsing type, ignore.
4667 if (!TyOrEx) return ExprError();
4668
4669 if (IsType) {
4670 TypeSourceInfo *TInfo;
4671 (void) GetTypeFromParser(ParsedType::getFromOpaquePtr(TyOrEx), &TInfo);
4672 return CreateUnaryExprOrTypeTraitExpr(TInfo, OpLoc, ExprKind, ArgRange);
4673 }
4674
4675 Expr *ArgEx = (Expr *)TyOrEx;
4676 ExprResult Result = CreateUnaryExprOrTypeTraitExpr(ArgEx, OpLoc, ExprKind);
4677 return Result;
4678}
4679
4680static QualType CheckRealImagOperand(Sema &S, ExprResult &V, SourceLocation Loc,
4681 bool IsReal) {
4682 if (V.get()->isTypeDependent())
4683 return S.Context.DependentTy;
4684
4685 // _Real and _Imag are only l-values for normal l-values.
4686 if (V.get()->getObjectKind() != OK_Ordinary) {
4687 V = S.DefaultLvalueConversion(V.get());
4688 if (V.isInvalid())
4689 return QualType();
4690 }
4691
4692 // These operators return the element type of a complex type.
4693 if (const ComplexType *CT = V.get()->getType()->getAs<ComplexType>())
4694 return CT->getElementType();
4695
4696 // Otherwise they pass through real integer and floating point types here.
4697 if (V.get()->getType()->isArithmeticType())
4698 return V.get()->getType();
4699
4700 // Test for placeholders.
4701 ExprResult PR = S.CheckPlaceholderExpr(V.get());
4702 if (PR.isInvalid()) return QualType();
4703 if (PR.get() != V.get()) {
4704 V = PR;
4705 return CheckRealImagOperand(S, V, Loc, IsReal);
4706 }
4707
4708 // Reject anything else.
4709 S.Diag(Loc, diag::err_realimag_invalid_type) << V.get()->getType()
4710 << (IsReal ? "__real" : "__imag");
4711 return QualType();
4712}
4713
4714
4715
4716ExprResult
4717Sema::ActOnPostfixUnaryOp(Scope *S, SourceLocation OpLoc,
4718 tok::TokenKind Kind, Expr *Input) {
4719 UnaryOperatorKind Opc;
4720 switch (Kind) {
4721 default: llvm_unreachable("Unknown unary op!")::llvm::llvm_unreachable_internal("Unknown unary op!", "clang/lib/Sema/SemaExpr.cpp"
, 4721)
;
4722 case tok::plusplus: Opc = UO_PostInc; break;
4723 case tok::minusminus: Opc = UO_PostDec; break;
4724 }
4725
4726 // Since this might is a postfix expression, get rid of ParenListExprs.
4727 ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Input);
4728 if (Result.isInvalid()) return ExprError();
4729 Input = Result.get();
4730
4731 return BuildUnaryOp(S, OpLoc, Opc, Input);
4732}
4733
4734/// Diagnose if arithmetic on the given ObjC pointer is illegal.
4735///
4736/// \return true on error
4737static bool checkArithmeticOnObjCPointer(Sema &S,
4738 SourceLocation opLoc,
4739 Expr *op) {
4740 assert(op->getType()->isObjCObjectPointerType())(static_cast <bool> (op->getType()->isObjCObjectPointerType
()) ? void (0) : __assert_fail ("op->getType()->isObjCObjectPointerType()"
, "clang/lib/Sema/SemaExpr.cpp", 4740, __extension__ __PRETTY_FUNCTION__
))
;
4741 if (S.LangOpts.ObjCRuntime.allowsPointerArithmetic() &&
4742 !S.LangOpts.ObjCSubscriptingLegacyRuntime)
4743 return false;
4744
4745 S.Diag(opLoc, diag::err_arithmetic_nonfragile_interface)
4746 << op->getType()->castAs<ObjCObjectPointerType>()->getPointeeType()
4747 << op->getSourceRange();
4748 return true;
4749}
4750
4751static bool isMSPropertySubscriptExpr(Sema &S, Expr *Base) {
4752 auto *BaseNoParens = Base->IgnoreParens();
4753 if (auto *MSProp = dyn_cast<MSPropertyRefExpr>(BaseNoParens))
4754 return MSProp->getPropertyDecl()->getType()->isArrayType();
4755 return isa<MSPropertySubscriptExpr>(BaseNoParens);
4756}
4757
4758// Returns the type used for LHS[RHS], given one of LHS, RHS is type-dependent.
4759// Typically this is DependentTy, but can sometimes be more precise.
4760//
4761// There are cases when we could determine a non-dependent type:
4762// - LHS and RHS may have non-dependent types despite being type-dependent
4763// (e.g. unbounded array static members of the current instantiation)
4764// - one may be a dependent-sized array with known element type
4765// - one may be a dependent-typed valid index (enum in current instantiation)
4766//
4767// We *always* return a dependent type, in such cases it is DependentTy.
4768// This avoids creating type-dependent expressions with non-dependent types.
4769// FIXME: is this important to avoid? See https://reviews.llvm.org/D107275
4770static QualType getDependentArraySubscriptType(Expr *LHS, Expr *RHS,
4771 const ASTContext &Ctx) {
4772 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", 4772, __extension__ __PRETTY_FUNCTION__
))
;
4773 QualType LTy = LHS->getType(), RTy = RHS->getType();
4774 QualType Result = Ctx.DependentTy;
4775 if (RTy->isIntegralOrUnscopedEnumerationType()) {
4776 if (const PointerType *PT = LTy->getAs<PointerType>())
4777 Result = PT->getPointeeType();
4778 else if (const ArrayType *AT = LTy->getAsArrayTypeUnsafe())
4779 Result = AT->getElementType();
4780 } else if (LTy->isIntegralOrUnscopedEnumerationType()) {
4781 if (const PointerType *PT = RTy->getAs<PointerType>())
4782 Result = PT->getPointeeType();
4783 else if (const ArrayType *AT = RTy->getAsArrayTypeUnsafe())
4784 Result = AT->getElementType();
4785 }
4786 // Ensure we return a dependent type.
4787 return Result->isDependentType() ? Result : Ctx.DependentTy;
4788}
4789
4790static bool checkArgsForPlaceholders(Sema &S, MultiExprArg args);
4791
4792ExprResult Sema::ActOnArraySubscriptExpr(Scope *S, Expr *base,
4793 SourceLocation lbLoc,
4794 MultiExprArg ArgExprs,
4795 SourceLocation rbLoc) {
4796
4797 if (base && !base->getType().isNull() &&
4798 base->hasPlaceholderType(BuiltinType::OMPArraySection))
4799 return ActOnOMPArraySectionExpr(base, lbLoc, ArgExprs.front(), SourceLocation(),
4800 SourceLocation(), /*Length*/ nullptr,
4801 /*Stride=*/nullptr, rbLoc);
4802
4803 // Since this might be a postfix expression, get rid of ParenListExprs.
4804 if (isa<ParenListExpr>(base)) {
4805 ExprResult result = MaybeConvertParenListExprToParenExpr(S, base);
4806 if (result.isInvalid())
4807 return ExprError();
4808 base = result.get();
4809 }
4810
4811 // Check if base and idx form a MatrixSubscriptExpr.
4812 //
4813 // Helper to check for comma expressions, which are not allowed as indices for
4814 // matrix subscript expressions.
4815 auto CheckAndReportCommaError = [this, base, rbLoc](Expr *E) {
4816 if (isa<BinaryOperator>(E) && cast<BinaryOperator>(E)->isCommaOp()) {
4817 Diag(E->getExprLoc(), diag::err_matrix_subscript_comma)
4818 << SourceRange(base->getBeginLoc(), rbLoc);
4819 return true;
4820 }
4821 return false;
4822 };
4823 // The matrix subscript operator ([][])is considered a single operator.
4824 // Separating the index expressions by parenthesis is not allowed.
4825 if (base->hasPlaceholderType(BuiltinType::IncompleteMatrixIdx) &&
4826 !isa<MatrixSubscriptExpr>(base)) {
4827 Diag(base->getExprLoc(), diag::err_matrix_separate_incomplete_index)
4828 << SourceRange(base->getBeginLoc(), rbLoc);
4829 return ExprError();
4830 }
4831 // If the base is a MatrixSubscriptExpr, try to create a new
4832 // MatrixSubscriptExpr.
4833 auto *matSubscriptE = dyn_cast<MatrixSubscriptExpr>(base);
4834 if (matSubscriptE) {
4835 assert(ArgExprs.size() == 1)(static_cast <bool> (ArgExprs.size() == 1) ? void (0) :
__assert_fail ("ArgExprs.size() == 1", "clang/lib/Sema/SemaExpr.cpp"
, 4835, __extension__ __PRETTY_FUNCTION__))
;
4836 if (CheckAndReportCommaError(ArgExprs.front()))
4837 return ExprError();
4838
4839 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", 4840, __extension__ __PRETTY_FUNCTION__
))
4840 "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", 4840, __extension__ __PRETTY_FUNCTION__
))
;
4841 return CreateBuiltinMatrixSubscriptExpr(matSubscriptE->getBase(),
4842 matSubscriptE->getRowIdx(),
4843 ArgExprs.front(), rbLoc);
4844 }
4845
4846 // Handle any non-overload placeholder types in the base and index
4847 // expressions. We can't handle overloads here because the other
4848 // operand might be an overloadable type, in which case the overload
4849 // resolution for the operator overload should get the first crack
4850 // at the overload.
4851 bool IsMSPropertySubscript = false;
4852 if (base->getType()->isNonOverloadPlaceholderType()) {
4853 IsMSPropertySubscript = isMSPropertySubscriptExpr(*this, base);
4854 if (!IsMSPropertySubscript) {
4855 ExprResult result = CheckPlaceholderExpr(base);
4856 if (result.isInvalid())
4857 return ExprError();
4858 base = result.get();
4859 }
4860 }
4861
4862 // If the base is a matrix type, try to create a new MatrixSubscriptExpr.
4863 if (base->getType()->isMatrixType()) {
4864 assert(ArgExprs.size() == 1)(static_cast <bool> (ArgExprs.size() == 1) ? void (0) :
__assert_fail ("ArgExprs.size() == 1", "clang/lib/Sema/SemaExpr.cpp"
, 4864, __extension__ __PRETTY_FUNCTION__))
;
4865 if (CheckAndReportCommaError(ArgExprs.front()))
4866 return ExprError();
4867
4868 return CreateBuiltinMatrixSubscriptExpr(base, ArgExprs.front(), nullptr,
4869 rbLoc);
4870 }
4871
4872 if (ArgExprs.size() == 1 && getLangOpts().CPlusPlus20) {
4873 Expr *idx = ArgExprs[0];
4874 if ((isa<BinaryOperator>(idx) && cast<BinaryOperator>(idx)->isCommaOp()) ||
4875 (isa<CXXOperatorCallExpr>(idx) &&
4876 cast<CXXOperatorCallExpr>(idx)->getOperator() == OO_Comma)) {
4877 Diag(idx->getExprLoc(), diag::warn_deprecated_comma_subscript)
4878 << SourceRange(base->getBeginLoc(), rbLoc);
4879 }
4880 }
4881
4882 if (ArgExprs.size() == 1 &&
4883 ArgExprs[0]->getType()->isNonOverloadPlaceholderType()) {
4884 ExprResult result = CheckPlaceholderExpr(ArgExprs[0]);
4885 if (result.isInvalid())
4886 return ExprError();
4887 ArgExprs[0] = result.get();
4888 } else {
4889 if (checkArgsForPlaceholders(*this, ArgExprs))
4890 return ExprError();
4891 }
4892
4893 // Build an unanalyzed expression if either operand is type-dependent.
4894 if (getLangOpts().CPlusPlus && ArgExprs.size() == 1 &&
4895 (base->isTypeDependent() ||
4896 Expr::hasAnyTypeDependentArguments(ArgExprs))) {
4897 return new (Context) ArraySubscriptExpr(
4898 base, ArgExprs.front(),
4899 getDependentArraySubscriptType(base, ArgExprs.front(), getASTContext()),
4900 VK_LValue, OK_Ordinary, rbLoc);
4901 }
4902
4903 // MSDN, property (C++)
4904 // https://msdn.microsoft.com/en-us/library/yhfk0thd(v=vs.120).aspx
4905 // This attribute can also be used in the declaration of an empty array in a
4906 // class or structure definition. For example:
4907 // __declspec(property(get=GetX, put=PutX)) int x[];
4908 // The above statement indicates that x[] can be used with one or more array
4909 // indices. In this case, i=p->x[a][b] will be turned into i=p->GetX(a, b),
4910 // and p->x[a][b] = i will be turned into p->PutX(a, b, i);
4911 if (IsMSPropertySubscript) {
4912 assert(ArgExprs.size() == 1)(static_cast <bool> (ArgExprs.size() == 1) ? void (0) :
__assert_fail ("ArgExprs.size() == 1", "clang/lib/Sema/SemaExpr.cpp"
, 4912, __extension__ __PRETTY_FUNCTION__))
;
4913 // Build MS property subscript expression if base is MS property reference
4914 // or MS property subscript.
4915 return new (Context)
4916 MSPropertySubscriptExpr(base, ArgExprs.front(), Context.PseudoObjectTy,
4917 VK_LValue, OK_Ordinary, rbLoc);
4918 }
4919
4920 // Use C++ overloaded-operator rules if either operand has record
4921 // type. The spec says to do this if either type is *overloadable*,
4922 // but enum types can't declare subscript operators or conversion
4923 // operators, so there's nothing interesting for overload resolution
4924 // to do if there aren't any record types involved.
4925 //
4926 // ObjC pointers have their own subscripting logic that is not tied
4927 // to overload resolution and so should not take this path.
4928 if (getLangOpts().CPlusPlus && !base->getType()->isObjCObjectPointerType() &&
4929 ((base->getType()->isRecordType() ||
4930 (ArgExprs.size() != 1 || ArgExprs[0]->getType()->isRecordType())))) {
4931 return CreateOverloadedArraySubscriptExpr(lbLoc, rbLoc, base, ArgExprs);
4932 }
4933
4934 ExprResult Res =
4935 CreateBuiltinArraySubscriptExpr(base, lbLoc, ArgExprs.front(), rbLoc);
4936
4937 if (!Res.isInvalid() && isa<ArraySubscriptExpr>(Res.get()))
4938 CheckSubscriptAccessOfNoDeref(cast<ArraySubscriptExpr>(Res.get()));
4939
4940 return Res;
4941}
4942
4943ExprResult Sema::tryConvertExprToType(Expr *E, QualType Ty) {
4944 InitializedEntity Entity = InitializedEntity::InitializeTemporary(Ty);
4945 InitializationKind Kind =
4946 InitializationKind::CreateCopy(E->getBeginLoc(), SourceLocation());
4947 InitializationSequence InitSeq(*this, Entity, Kind, E);
4948 return InitSeq.Perform(*this, Entity, Kind, E);
4949}
4950
4951ExprResult Sema::CreateBuiltinMatrixSubscriptExpr(Expr *Base, Expr *RowIdx,
4952 Expr *ColumnIdx,
4953 SourceLocation RBLoc) {
4954 ExprResult BaseR = CheckPlaceholderExpr(Base);
4955 if (BaseR.isInvalid())
4956 return BaseR;
4957 Base = BaseR.get();
4958
4959 ExprResult RowR = CheckPlaceholderExpr(RowIdx);
4960 if (RowR.isInvalid())
4961 return RowR;
4962 RowIdx = RowR.get();
4963
4964 if (!ColumnIdx)
4965 return new (Context) MatrixSubscriptExpr(
4966 Base, RowIdx, ColumnIdx, Context.IncompleteMatrixIdxTy, RBLoc);
4967
4968 // Build an unanalyzed expression if any of the operands is type-dependent.
4969 if (Base->isTypeDependent() || RowIdx->isTypeDependent() ||
4970 ColumnIdx->isTypeDependent())
4971 return new (Context) MatrixSubscriptExpr(Base, RowIdx, ColumnIdx,
4972 Context.DependentTy, RBLoc);
4973
4974 ExprResult ColumnR = CheckPlaceholderExpr(ColumnIdx);
4975 if (ColumnR.isInvalid())
4976 return ColumnR;
4977 ColumnIdx = ColumnR.get();
4978
4979 // Check that IndexExpr is an integer expression. If it is a constant
4980 // expression, check that it is less than Dim (= the number of elements in the
4981 // corresponding dimension).
4982 auto IsIndexValid = [&](Expr *IndexExpr, unsigned Dim,
4983 bool IsColumnIdx) -> Expr * {
4984 if (!IndexExpr->getType()->isIntegerType() &&
4985 !IndexExpr->isTypeDependent()) {
4986 Diag(IndexExpr->getBeginLoc(), diag::err_matrix_index_not_integer)
4987 << IsColumnIdx;
4988 return nullptr;
4989 }
4990
4991 if (Optional<llvm::APSInt> Idx =
4992 IndexExpr->getIntegerConstantExpr(Context)) {
4993 if ((*Idx < 0 || *Idx >= Dim)) {
4994 Diag(IndexExpr->getBeginLoc(), diag::err_matrix_index_outside_range)
4995 << IsColumnIdx << Dim;
4996 return nullptr;
4997 }
4998 }
4999
5000 ExprResult ConvExpr =
5001 tryConvertExprToType(IndexExpr, Context.getSizeType());
5002 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", 5003, __extension__ __PRETTY_FUNCTION__
))
5003 "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", 5003, __extension__ __PRETTY_FUNCTION__
))
;
5004 return ConvExpr.get();
5005 };
5006
5007 auto *MTy = Base->getType()->getAs<ConstantMatrixType>();
5008 RowIdx = IsIndexValid(RowIdx, MTy->getNumRows(), false);
5009 ColumnIdx = IsIndexValid(ColumnIdx, MTy->getNumColumns(), true);
5010 if (!RowIdx || !ColumnIdx)
5011 return ExprError();
5012
5013 return new (Context) MatrixSubscriptExpr(Base, RowIdx, ColumnIdx,
5014 MTy->getElementType(), RBLoc);
5015}
5016
5017void Sema::CheckAddressOfNoDeref(const Expr *E) {
5018 ExpressionEvaluationContextRecord &LastRecord = ExprEvalContexts.back();
5019 const Expr *StrippedExpr = E->IgnoreParenImpCasts();
5020
5021 // For expressions like `&(*s).b`, the base is recorded and what should be
5022 // checked.
5023 const MemberExpr *Member = nullptr;
5024 while ((Member = dyn_cast<MemberExpr>(StrippedExpr)) && !Member->isArrow())
5025 StrippedExpr = Member->getBase()->IgnoreParenImpCasts();
5026
5027 LastRecord.PossibleDerefs.erase(StrippedExpr);
5028}
5029
5030void Sema::CheckSubscriptAccessOfNoDeref(const ArraySubscriptExpr *E) {
5031 if (isUnevaluatedContext())
5032 return;
5033
5034 QualType ResultTy = E->getType();
5035 ExpressionEvaluationContextRecord &LastRecord = ExprEvalContexts.back();
5036
5037 // Bail if the element is an array since it is not memory access.
5038 if (isa<ArrayType>(ResultTy))
5039 return;
5040
5041 if (ResultTy->hasAttr(attr::NoDeref)) {
5042 LastRecord.PossibleDerefs.insert(E);
5043 return;
5044 }
5045
5046 // Check if the base type is a pointer to a member access of a struct
5047 // marked with noderef.
5048 const Expr *Base = E->getBase();
5049 QualType BaseTy = Base->getType();
5050 if (!(isa<ArrayType>(BaseTy) || isa<PointerType>(BaseTy)))
5051 // Not a pointer access
5052 return;
5053
5054 const MemberExpr *Member = nullptr;
5055 while ((Member = dyn_cast<MemberExpr>(Base->IgnoreParenCasts())) &&
5056 Member->isArrow())
5057 Base = Member->getBase();
5058
5059 if (const auto *Ptr = dyn_cast<PointerType>(Base->getType())) {
5060 if (Ptr->getPointeeType()->hasAttr(attr::NoDeref))
5061 LastRecord.PossibleDerefs.insert(E);
5062 }
5063}
5064
5065ExprResult Sema::ActOnOMPArraySectionExpr(Expr *Base, SourceLocation LBLoc,
5066 Expr *LowerBound,
5067 SourceLocation ColonLocFirst,
5068 SourceLocation ColonLocSecond,
5069 Expr *Length, Expr *Stride,
5070 SourceLocation RBLoc) {
5071 if (Base->hasPlaceholderType() &&
5072 !Base->hasPlaceholderType(BuiltinType::OMPArraySection)) {
5073 ExprResult Result = CheckPlaceholderExpr(Base);
5074 if (Result.isInvalid())
5075 return ExprError();
5076 Base = Result.get();
5077 }
5078 if (LowerBound && LowerBound->getType()->isNonOverloadPlaceholderType()) {
5079 ExprResult Result = CheckPlaceholderExpr(LowerBound);
5080 if (Result.isInvalid())
5081 return ExprError();
5082 Result = DefaultLvalueConversion(Result.get());
5083 if (Result.isInvalid())
5084 return ExprError();
5085 LowerBound = Result.get();
5086 }
5087 if (Length && Length->getType()->isNonOverloadPlaceholderType()) {
5088 ExprResult Result = CheckPlaceholderExpr(Length);
5089 if (Result.isInvalid())
5090 return ExprError();
5091 Result = DefaultLvalueConversion(Result.get());
5092 if (Result.isInvalid())
5093 return ExprError();
5094 Length = Result.get();
5095 }
5096 if (Stride && Stride->getType()->isNonOverloadPlaceholderType()) {
5097 ExprResult Result = CheckPlaceholderExpr(Stride);
5098 if (Result.isInvalid())
5099 return ExprError();
5100 Result = DefaultLvalueConversion(Result.get());
5101 if (Result.isInvalid())
5102 return ExprError();
5103 Stride = Result.get();
5104 }
5105
5106 // Build an unanalyzed expression if either operand is type-dependent.
5107 if (Base->isTypeDependent() ||
5108 (LowerBound &&
5109 (LowerBound->isTypeDependent() || LowerBound->isValueDependent())) ||
5110 (Length && (Length->isTypeDependent() || Length->isValueDependent())) ||
5111 (Stride && (Stride->isTypeDependent() || Stride->isValueDependent()))) {
5112 return new (Context) OMPArraySectionExpr(
5113 Base, LowerBound, Length, Stride, Context.DependentTy, VK_LValue,
5114 OK_Ordinary, ColonLocFirst, ColonLocSecond, RBLoc);
5115 }
5116
5117 // Perform default conversions.
5118 QualType OriginalTy = OMPArraySectionExpr::getBaseOriginalType(Base);
5119 QualType ResultTy;
5120 if (OriginalTy->isAnyPointerType()) {
5121 ResultTy = OriginalTy->getPointeeType();
5122 } else if (OriginalTy->isArrayType()) {
5123 ResultTy = OriginalTy->getAsArrayTypeUnsafe()->getElementType();
5124 } else {
5125 return ExprError(
5126 Diag(Base->getExprLoc(), diag::err_omp_typecheck_section_value)
5127 << Base->getSourceRange());
5128 }
5129 // C99 6.5.2.1p1
5130 if (LowerBound) {
5131 auto Res = PerformOpenMPImplicitIntegerConversion(LowerBound->getExprLoc(),
5132 LowerBound);
5133 if (Res.isInvalid())
5134 return ExprError(Diag(LowerBound->getExprLoc(),
5135 diag::err_omp_typecheck_section_not_integer)
5136 << 0 << LowerBound->getSourceRange());
5137 LowerBound = Res.get();
5138
5139 if (LowerBound->getType()->isSpecificBuiltinType(BuiltinType::Char_S) ||
5140 LowerBound->getType()->isSpecificBuiltinType(BuiltinType::Char_U))
5141 Diag(LowerBound->getExprLoc(), diag::warn_omp_section_is_char)
5142 << 0 << LowerBound->getSourceRange();
5143 }
5144 if (Length) {
5145 auto Res =
5146 PerformOpenMPImplicitIntegerConversion(Length->getExprLoc(), Length);
5147 if (Res.isInvalid())
5148 return ExprError(Diag(Length->getExprLoc(),
5149 diag::err_omp_typecheck_section_not_integer)
5150 << 1 << Length->getSourceRange());
5151 Length = Res.get();
5152
5153 if (Length->getType()->isSpecificBuiltinType(BuiltinType::Char_S) ||
5154 Length->getType()->isSpecificBuiltinType(BuiltinType::Char_U))
5155 Diag(Length->getExprLoc(), diag::warn_omp_section_is_char)
5156 << 1 << Length->getSourceRange();
5157 }
5158 if (Stride) {
5159 ExprResult Res =
5160 PerformOpenMPImplicitIntegerConversion(Stride->getExprLoc(), Stride);
5161 if (Res.isInvalid())
5162 return ExprError(Diag(Stride->getExprLoc(),
5163 diag::err_omp_typecheck_section_not_integer)
5164 << 1 << Stride->getSourceRange());
5165 Stride = Res.get();
5166
5167 if (Stride->getType()->isSpecificBuiltinType(BuiltinType::Char_S) ||
5168 Stride->getType()->isSpecificBuiltinType(BuiltinType::Char_U))
5169 Diag(Stride->getExprLoc(), diag::warn_omp_section_is_char)
5170 << 1 << Stride->getSourceRange();
5171 }
5172
5173 // C99 6.5.2.1p1: "shall have type "pointer to *object* type". Similarly,
5174 // C++ [expr.sub]p1: The type "T" shall be a completely-defined object
5175 // type. Note that functions are not objects, and that (in C99 parlance)
5176 // incomplete types are not object types.
5177 if (ResultTy->isFunctionType()) {
5178 Diag(Base->getExprLoc(), diag::err_omp_section_function_type)
5179 << ResultTy << Base->getSourceRange();
5180 return ExprError();
5181 }
5182
5183 if (RequireCompleteType(Base->getExprLoc(), ResultTy,
5184 diag::err_omp_section_incomplete_type, Base))
5185 return ExprError();
5186
5187 if (LowerBound && !OriginalTy->isAnyPointerType()) {
5188 Expr::EvalResult Result;
5189 if (LowerBound->EvaluateAsInt(Result, Context)) {
5190 // OpenMP 5.0, [2.1.5 Array Sections]
5191 // The array section must be a subset of the original array.
5192 llvm::APSInt LowerBoundValue = Result.Val.getInt();
5193 if (LowerBoundValue.isNegative()) {
5194 Diag(LowerBound->getExprLoc(), diag::err_omp_section_not_subset_of_array)
5195 << LowerBound->getSourceRange();
5196 return ExprError();
5197 }
5198 }
5199 }
5200
5201 if (Length) {
5202 Expr::EvalResult Result;
5203 if (Length->EvaluateAsInt(Result, Context)) {
5204 // OpenMP 5.0, [2.1.5 Array Sections]
5205 // The length must evaluate to non-negative integers.
5206 llvm::APSInt LengthValue = Result.Val.getInt();
5207 if (LengthValue.isNegative()) {
5208 Diag(Length->getExprLoc(), diag::err_omp_section_length_negative)
5209 << toString(LengthValue, /*Radix=*/10, /*Signed=*/true)
5210 << Length->getSourceRange();
5211 return ExprError();
5212 }
5213 }
5214 } else if (ColonLocFirst.isValid() &&
5215 (OriginalTy.isNull() || (!OriginalTy->isConstantArrayType() &&
5216 !OriginalTy->isVariableArrayType()))) {
5217 // OpenMP 5.0, [2.1.5 Array Sections]
5218 // When the size of the array dimension is not known, the length must be
5219 // specified explicitly.
5220 Diag(ColonLocFirst, diag::err_omp_section_length_undefined)
5221 << (!OriginalTy.isNull() && OriginalTy->isArrayType());
5222 return ExprError();
5223 }
5224
5225 if (Stride) {
5226 Expr::EvalResult Result;
5227 if (Stride->EvaluateAsInt(Result, Context)) {
5228 // OpenMP 5.0, [2.1.5 Array Sections]
5229 // The stride must evaluate to a positive integer.
5230 llvm::APSInt StrideValue = Result.Val.getInt();
5231 if (!StrideValue.isStrictlyPositive()) {
5232 Diag(Stride->getExprLoc(), diag::err_omp_section_stride_non_positive)
5233 << toString(StrideValue, /*Radix=*/10, /*Signed=*/true)
5234 << Stride->getSourceRange();
5235 return ExprError();
5236 }
5237 }
5238 }
5239
5240 if (!Base->hasPlaceholderType(BuiltinType::OMPArraySection)) {
5241 ExprResult Result = DefaultFunctionArrayLvalueConversion(Base);
5242 if (Result.isInvalid())
5243 return ExprError();
5244 Base = Result.get();
5245 }
5246 return new (Context) OMPArraySectionExpr(
5247 Base, LowerBound, Length, Stride, Context.OMPArraySectionTy, VK_LValue,
5248 OK_Ordinary, ColonLocFirst, ColonLocSecond, RBLoc);
5249}
5250
5251ExprResult Sema::ActOnOMPArrayShapingExpr(Expr *Base, SourceLocation LParenLoc,
5252 SourceLocation RParenLoc,
5253 ArrayRef<Expr *> Dims,
5254 ArrayRef<SourceRange> Brackets) {
5255 if (Base->hasPlaceholderType()) {
5256 ExprResult Result = CheckPlaceholderExpr(Base);
5257 if (Result.isInvalid())
5258 return ExprError();
5259 Result = DefaultLvalueConversion(Result.get());
5260 if (Result.isInvalid())
5261 return ExprError();
5262 Base = Result.get();
5263 }
5264 QualType BaseTy = Base->getType();
5265 // Delay analysis of the types/expressions if instantiation/specialization is
5266 // required.
5267 if (!BaseTy->isPointerType() && Base->isTypeDependent())
5268 return OMPArrayShapingExpr::Create(Context, Context.DependentTy, Base,
5269 LParenLoc, RParenLoc, Dims, Brackets);
5270 if (!BaseTy->isPointerType() ||
5271 (!Base->isTypeDependent() &&
5272 BaseTy->getPointeeType()->isIncompleteType()))
5273 return ExprError(Diag(Base->getExprLoc(),
5274 diag::err_omp_non_pointer_type_array_shaping_base)
5275 << Base->getSourceRange());
5276
5277 SmallVector<Expr *, 4> NewDims;
5278 bool ErrorFound = false;
5279 for (Expr *Dim : Dims) {
5280 if (Dim->hasPlaceholderType()) {
5281 ExprResult Result = CheckPlaceholderExpr(Dim);
5282 if (Result.isInvalid()) {
5283 ErrorFound = true;
5284 continue;
5285 }
5286 Result = DefaultLvalueConversion(Result.get());
5287 if (Result.isInvalid()) {
5288 ErrorFound = true;
5289 continue;
5290 }
5291 Dim = Result.get();
5292 }
5293 if (!Dim->isTypeDependent()) {
5294 ExprResult Result =
5295 PerformOpenMPImplicitIntegerConversion(Dim->getExprLoc(), Dim);
5296 if (Result.isInvalid()) {
5297 ErrorFound = true;
5298 Diag(Dim->getExprLoc(), diag::err_omp_typecheck_shaping_not_integer)
5299 << Dim->getSourceRange();
5300 continue;
5301 }
5302 Dim = Result.get();
5303 Expr::EvalResult EvResult;
5304 if (!Dim->isValueDependent() && Dim->EvaluateAsInt(EvResult, Context)) {
5305 // OpenMP 5.0, [2.1.4 Array Shaping]
5306 // Each si is an integral type expression that must evaluate to a
5307 // positive integer.
5308 llvm::APSInt Value = EvResult.Val.getInt();
5309 if (!Value.isStrictlyPositive()) {
5310 Diag(Dim->getExprLoc(), diag::err_omp_shaping_dimension_not_positive)
5311 << toString(Value, /*Radix=*/10, /*Signed=*/true)
5312 << Dim->getSourceRange();
5313 ErrorFound = true;
5314 continue;
5315 }
5316 }
5317 }
5318 NewDims.push_back(Dim);
5319 }
5320 if (ErrorFound)
5321 return ExprError();
5322 return OMPArrayShapingExpr::Create(Context, Context.OMPArrayShapingTy, Base,
5323 LParenLoc, RParenLoc, NewDims, Brackets);
5324}
5325
5326ExprResult Sema::ActOnOMPIteratorExpr(Scope *S, SourceLocation IteratorKwLoc,
5327 SourceLocation LLoc, SourceLocation RLoc,
5328 ArrayRef<OMPIteratorData> Data) {
5329 SmallVector<OMPIteratorExpr::IteratorDefinition, 4> ID;
5330 bool IsCorrect = true;
5331 for (const OMPIteratorData &D : Data) {
5332 TypeSourceInfo *TInfo = nullptr;
5333 SourceLocation StartLoc;
5334 QualType DeclTy;
5335 if (!D.Type.getAsOpaquePtr()) {
5336 // OpenMP 5.0, 2.1.6 Iterators
5337 // In an iterator-specifier, if the iterator-type is not specified then
5338 // the type of that iterator is of int type.
5339 DeclTy = Context.IntTy;
5340 StartLoc = D.DeclIdentLoc;
5341 } else {
5342 DeclTy = GetTypeFromParser(D.Type, &TInfo);
5343 StartLoc = TInfo->getTypeLoc().getBeginLoc();
5344 }
5345
5346 bool IsDeclTyDependent = DeclTy->isDependentType() ||
5347 DeclTy->containsUnexpandedParameterPack() ||
5348 DeclTy->isInstantiationDependentType();
5349 if (!IsDeclTyDependent) {
5350 if (!DeclTy->isIntegralType(Context) && !DeclTy->isAnyPointerType()) {
5351 // OpenMP 5.0, 2.1.6 Iterators, Restrictions, C/C++
5352 // The iterator-type must be an integral or pointer type.
5353 Diag(StartLoc, diag::err_omp_iterator_not_integral_or_pointer)
5354 << DeclTy;
5355 IsCorrect = false;
5356 continue;
5357 }
5358 if (DeclTy.isConstant(Context)) {
5359 // OpenMP 5.0, 2.1.6 Iterators, Restrictions, C/C++
5360 // The iterator-type must not be const qualified.
5361 Diag(StartLoc, diag::err_omp_iterator_not_integral_or_pointer)
5362 << DeclTy;
5363 IsCorrect = false;
5364 continue;
5365 }
5366 }
5367
5368 // Iterator declaration.
5369 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", 5369, __extension__ __PRETTY_FUNCTION__
))
;
5370 // Always try to create iterator declarator to avoid extra error messages
5371 // about unknown declarations use.
5372 auto *VD = VarDecl::Create(Context, CurContext, StartLoc, D.DeclIdentLoc,
5373 D.DeclIdent, DeclTy, TInfo, SC_None);
5374 VD->setImplicit();
5375 if (S) {
5376 // Check for conflicting previous declaration.
5377 DeclarationNameInfo NameInfo(VD->getDeclName(), D.DeclIdentLoc);
5378 LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
5379 ForVisibleRedeclaration);
5380 Previous.suppressDiagnostics();
5381 LookupName(Previous, S);
5382
5383 FilterLookupForScope(Previous, CurContext, S, /*ConsiderLinkage=*/false,
5384 /*AllowInlineNamespace=*/false);
5385 if (!Previous.empty()) {
5386 NamedDecl *Old = Previous.getRepresentativeDecl();
5387 Diag(D.DeclIdentLoc, diag::err_redefinition) << VD->getDeclName();
5388 Diag(Old->getLocation(), diag::note_previous_definition);
5389 } else {
5390 PushOnScopeChains(VD, S);
5391 }
5392 } else {
5393 CurContext->addDecl(VD);
5394 }
5395 Expr *Begin = D.Range.Begin;
5396 if (!IsDeclTyDependent && Begin && !Begin->isTypeDependent()) {
5397 ExprResult BeginRes =
5398 PerformImplicitConversion(Begin, DeclTy, AA_Converting);
5399 Begin = BeginRes.get();
5400 }
5401 Expr *End = D.Range.End;
5402 if (!IsDeclTyDependent && End && !End->isTypeDependent()) {
5403 ExprResult EndRes = PerformImplicitConversion(End, DeclTy, AA_Converting);
5404 End = EndRes.get();
5405 }
5406 Expr *Step = D.Range.Step;
5407 if (!IsDeclTyDependent && Step && !Step->isTypeDependent()) {
5408 if (!Step->getType()->isIntegralType(Context)) {
5409 Diag(Step->getExprLoc(), diag::err_omp_iterator_step_not_integral)
5410 << Step << Step->getSourceRange();
5411 IsCorrect = false;
5412 continue;
5413 }
5414 Optional<llvm::APSInt> Result = Step->getIntegerConstantExpr(Context);
5415 // OpenMP 5.0, 2.1.6 Iterators, Restrictions
5416 // If the step expression of a range-specification equals zero, the
5417 // behavior is unspecified.
5418 if (Result && Result->isZero()) {
5419 Diag(Step->getExprLoc(), diag::err_omp_iterator_step_constant_zero)
5420 << Step << Step->getSourceRange();
5421 IsCorrect = false;
5422 continue;
5423 }
5424 }
5425 if (!Begin || !End || !IsCorrect) {
5426 IsCorrect = false;
5427 continue;
5428 }
5429 OMPIteratorExpr::IteratorDefinition &IDElem = ID.emplace_back();
5430 IDElem.IteratorDecl = VD;
5431 IDElem.AssignmentLoc = D.AssignLoc;
5432 IDElem.Range.Begin = Begin;
5433 IDElem.Range.End = End;
5434 IDElem.Range.Step = Step;
5435 IDElem.ColonLoc = D.ColonLoc;
5436 IDElem.SecondColonLoc = D.SecColonLoc;
5437 }
5438 if (!IsCorrect) {
5439 // Invalidate all created iterator declarations if error is found.
5440 for (const OMPIteratorExpr::IteratorDefinition &D : ID) {
5441 if (Decl *ID = D.IteratorDecl)
5442 ID->setInvalidDecl();
5443 }
5444 return ExprError();
5445 }
5446 SmallVector<OMPIteratorHelperData, 4> Helpers;
5447 if (!CurContext->isDependentContext()) {
5448 // Build number of ityeration for each iteration range.
5449 // Ni = ((Stepi > 0) ? ((Endi + Stepi -1 - Begini)/Stepi) :
5450 // ((Begini-Stepi-1-Endi) / -Stepi);
5451 for (OMPIteratorExpr::IteratorDefinition &D : ID) {
5452 // (Endi - Begini)
5453 ExprResult Res = CreateBuiltinBinOp(D.AssignmentLoc, BO_Sub, D.Range.End,
5454 D.Range.Begin);
5455 if(!Res.isUsable()) {
5456 IsCorrect = false;
5457 continue;
5458 }
5459 ExprResult St, St1;
5460 if (D.Range.Step) {
5461 St = D.Range.Step;
5462 // (Endi - Begini) + Stepi
5463 Res = CreateBuiltinBinOp(D.AssignmentLoc, BO_Add, Res.get(), St.get());
5464 if (!Res.isUsable()) {
5465 IsCorrect = false;
5466 continue;
5467 }
5468 // (Endi - Begini) + Stepi - 1
5469 Res =
5470 CreateBuiltinBinOp(D.AssignmentLoc, BO_Sub, Res.get(),
5471 ActOnIntegerConstant(D.AssignmentLoc, 1).get());
5472 if (!Res.isUsable()) {
5473 IsCorrect = false;
5474 continue;
5475 }
5476 // ((Endi - Begini) + Stepi - 1) / Stepi
5477 Res = CreateBuiltinBinOp(D.AssignmentLoc, BO_Div, Res.get(), St.get());
5478 if (!Res.isUsable()) {
5479 IsCorrect = false;
5480 continue;
5481 }
5482 St1 = CreateBuiltinUnaryOp(D.AssignmentLoc, UO_Minus, D.Range.Step);
5483 // (Begini - Endi)
5484 ExprResult Res1 = CreateBuiltinBinOp(D.AssignmentLoc, BO_Sub,
5485 D.Range.Begin, D.Range.End);
5486 if (!Res1.isUsable()) {
5487 IsCorrect = false;
5488 continue;
5489 }
5490 // (Begini - Endi) - Stepi
5491 Res1 =
5492 CreateBuiltinBinOp(D.AssignmentLoc, BO_Add, Res1.get(), St1.get());
5493 if (!Res1.isUsable()) {
5494 IsCorrect = false;
5495 continue;
5496 }
5497 // (Begini - Endi) - Stepi - 1
5498 Res1 =
5499 CreateBuiltinBinOp(D.AssignmentLoc, BO_Sub, Res1.get(),
5500 ActOnIntegerConstant(D.AssignmentLoc, 1).get());
5501 if (!Res1.isUsable()) {
5502 IsCorrect = false;
5503 continue;
5504 }
5505 // ((Begini - Endi) - Stepi - 1) / (-Stepi)
5506 Res1 =
5507 CreateBuiltinBinOp(D.AssignmentLoc, BO_Div, Res1.get(), St1.get());
5508 if (!Res1.isUsable()) {
5509 IsCorrect = false;
5510 continue;
5511 }
5512 // Stepi > 0.
5513 ExprResult CmpRes =
5514 CreateBuiltinBinOp(D.AssignmentLoc, BO_GT, D.Range.Step,
5515 ActOnIntegerConstant(D.AssignmentLoc, 0).get());
5516 if (!CmpRes.isUsable()) {
5517 IsCorrect = false;
5518 continue;
5519 }
5520 Res = ActOnConditionalOp(D.AssignmentLoc, D.AssignmentLoc, CmpRes.get(),
5521 Res.get(), Res1.get());
5522 if (!Res.isUsable()) {
5523 IsCorrect = false;
5524 continue;
5525 }
5526 }
5527 Res = ActOnFinishFullExpr(Res.get(), /*DiscardedValue=*/false);
5528 if (!Res.isUsable()) {
5529 IsCorrect = false;
5530 continue;
5531 }
5532
5533 // Build counter update.
5534 // Build counter.
5535 auto *CounterVD =
5536 VarDecl::Create(Context, CurContext, D.IteratorDecl->getBeginLoc(),
5537 D.IteratorDecl->getBeginLoc(), nullptr,
5538 Res.get()->getType(), nullptr, SC_None);
5539 CounterVD->setImplicit();
5540 ExprResult RefRes =
5541 BuildDeclRefExpr(CounterVD, CounterVD->getType(), VK_LValue,
5542 D.IteratorDecl->getBeginLoc());
5543 // Build counter update.
5544 // I = Begini + counter * Stepi;
5545 ExprResult UpdateRes;
5546 if (D.Range.Step) {
5547 UpdateRes = CreateBuiltinBinOp(
5548 D.AssignmentLoc, BO_Mul,
5549 DefaultLvalueConversion(RefRes.get()).get(), St.get());
5550 } else {
5551 UpdateRes = DefaultLvalueConversion(RefRes.get());
5552 }
5553 if (!UpdateRes.isUsable()) {
5554 IsCorrect = false;
5555 continue;
5556 }
5557 UpdateRes = CreateBuiltinBinOp(D.AssignmentLoc, BO_Add, D.Range.Begin,
5558 UpdateRes.get());
5559 if (!UpdateRes.isUsable()) {
5560 IsCorrect = false;
5561 continue;
5562 }
5563 ExprResult VDRes =
5564 BuildDeclRefExpr(cast<VarDecl>(D.IteratorDecl),
5565 cast<VarDecl>(D.IteratorDecl)->getType(), VK_LValue,
5566 D.IteratorDecl->getBeginLoc());
5567 UpdateRes = CreateBuiltinBinOp(D.AssignmentLoc, BO_Assign, VDRes.get(),
5568 UpdateRes.get());
5569 if (!UpdateRes.isUsable()) {
5570 IsCorrect = false;
5571 continue;
5572 }
5573 UpdateRes =
5574 ActOnFinishFullExpr(UpdateRes.get(), /*DiscardedValue=*/true);
5575 if (!UpdateRes.isUsable()) {
5576 IsCorrect = false;
5577 continue;
5578 }
5579 ExprResult CounterUpdateRes =
5580 CreateBuiltinUnaryOp(D.AssignmentLoc, UO_PreInc, RefRes.get());
5581 if (!CounterUpdateRes.isUsable()) {
5582 IsCorrect = false;
5583 continue;
5584 }
5585 CounterUpdateRes =
5586 ActOnFinishFullExpr(CounterUpdateRes.get(), /*DiscardedValue=*/true);
5587 if (!CounterUpdateRes.isUsable()) {
5588 IsCorrect = false;
5589 continue;
5590 }
5591 OMPIteratorHelperData &HD = Helpers.emplace_back();
5592 HD.CounterVD = CounterVD;
5593 HD.Upper = Res.get();
5594 HD.Update = UpdateRes.get();
5595 HD.CounterUpdate = CounterUpdateRes.get();
5596 }
5597 } else {
5598 Helpers.assign(ID.size(), {});
5599 }
5600 if (!IsCorrect) {
5601 // Invalidate all created iterator declarations if error is found.
5602 for (const OMPIteratorExpr::IteratorDefinition &D : ID) {
5603 if (Decl *ID = D.IteratorDecl)
5604 ID->setInvalidDecl();
5605 }
5606 return ExprError();
5607 }
5608 return OMPIteratorExpr::Create(Context, Context.OMPIteratorTy, IteratorKwLoc,
5609 LLoc, RLoc, ID, Helpers);
5610}
5611
5612ExprResult
5613Sema::CreateBuiltinArraySubscriptExpr(Expr *Base, SourceLocation LLoc,
5614 Expr *Idx, SourceLocation RLoc) {
5615 Expr *LHSExp = Base;
5616 Expr *RHSExp = Idx;
5617
5618 ExprValueKind VK = VK_LValue;
5619 ExprObjectKind OK = OK_Ordinary;
5620
5621 // Per C++ core issue 1213, the result is an xvalue if either operand is
5622 // a non-lvalue array, and an lvalue otherwise.
5623 if (getLangOpts().CPlusPlus11) {
5624 for (auto *Op : {LHSExp, RHSExp}) {
5625 Op = Op->IgnoreImplicit();
5626 if (Op->getType()->isArrayType() && !Op->isLValue())
5627 VK = VK_XValue;
5628 }
5629 }
5630
5631 // Perform default conversions.
5632 if (!LHSExp->getType()->getAs<VectorType>()) {
5633 ExprResult Result = DefaultFunctionArrayLvalueConversion(LHSExp);
5634 if (Result.isInvalid())
5635 return ExprError();
5636 LHSExp = Result.get();
5637 }
5638 ExprResult Result = DefaultFunctionArrayLvalueConversion(RHSExp);
5639 if (Result.isInvalid())
5640 return ExprError();
5641 RHSExp = Result.get();
5642
5643 QualType LHSTy = LHSExp->getType(), RHSTy = RHSExp->getType();
5644
5645 // C99 6.5.2.1p2: the expression e1[e2] is by definition precisely equivalent
5646 // to the expression *((e1)+(e2)). This means the array "Base" may actually be
5647 // in the subscript position. As a result, we need to derive the array base
5648 // and index from the expression types.
5649 Expr *BaseExpr, *IndexExpr;
5650 QualType ResultType;
5651 if (LHSTy->isDependentType() || RHSTy->isDependentType()) {
5652 BaseExpr = LHSExp;
5653 IndexExpr = RHSExp;
5654 ResultType =
5655 getDependentArraySubscriptType(LHSExp, RHSExp, getASTContext());
5656 } else if (const PointerType *PTy = LHSTy->getAs<PointerType>()) {
5657 BaseExpr = LHSExp;
5658 IndexExpr = RHSExp;
5659 ResultType = PTy->getPointeeType();
5660 } else if (const ObjCObjectPointerType *PTy =
5661 LHSTy->getAs<ObjCObjectPointerType>()) {
5662 BaseExpr = LHSExp;
5663 IndexExpr = RHSExp;
5664
5665 // Use custom logic if this should be the pseudo-object subscript
5666 // expression.
5667 if (!LangOpts.isSubscriptPointerArithmetic())
5668 return BuildObjCSubscriptExpression(RLoc, BaseExpr, IndexExpr, nullptr,
5669 nullptr);
5670
5671 ResultType = PTy->getPointeeType();
5672 } else if (const PointerType *PTy = RHSTy->getAs<PointerType>()) {
5673 // Handle the uncommon case of "123[Ptr]".
5674 BaseExpr = RHSExp;
5675 IndexExpr = LHSExp;
5676 ResultType = PTy->getPointeeType();
5677 } else if (const ObjCObjectPointerType *PTy =
5678 RHSTy->getAs<ObjCObjectPointerType>()) {
5679 // Handle the uncommon case of "123[Ptr]".
5680 BaseExpr = RHSExp;
5681 IndexExpr = LHSExp;
5682 ResultType = PTy->getPointeeType();
5683 if (!LangOpts.isSubscriptPointerArithmetic()) {
5684 Diag(LLoc, diag::err_subscript_nonfragile_interface)
5685 << ResultType << BaseExpr->getSourceRange();
5686 return ExprError();
5687 }
5688 } else if (const VectorType *VTy = LHSTy->getAs<VectorType>()) {
5689 BaseExpr = LHSExp; // vectors: V[123]
5690 IndexExpr = RHSExp;
5691 // We apply C++ DR1213 to vector subscripting too.
5692 if (getLangOpts().CPlusPlus11 && LHSExp->isPRValue()) {
5693 ExprResult Materialized = TemporaryMaterializationConversion(LHSExp);
5694 if (Materialized.isInvalid())
5695 return ExprError();
5696 LHSExp = Materialized.get();
5697 }
5698 VK = LHSExp->getValueKind();
5699 if (VK != VK_PRValue)
5700 OK = OK_VectorComponent;
5701
5702 ResultType = VTy->getElementType();
5703 QualType BaseType = BaseExpr->getType();
5704 Qualifiers BaseQuals = BaseType.getQualifiers();
5705 Qualifiers MemberQuals = ResultType.getQualifiers();
5706 Qualifiers Combined = BaseQuals + MemberQuals;
5707 if (Combined != MemberQuals)
5708 ResultType = Context.getQualifiedType(ResultType, Combined);
5709 } else if (LHSTy->isBuiltinType() &&
5710 LHSTy->getAs<BuiltinType>()->isVLSTBuiltinType()) {
5711 const BuiltinType *BTy = LHSTy->getAs<BuiltinType>();
5712 if (BTy->isSVEBool())
5713 return ExprError(Diag(LLoc, diag::err_subscript_svbool_t)
5714 << LHSExp->getSourceRange() << RHSExp->getSourceRange());
5715
5716 BaseExpr = LHSExp;
5717 IndexExpr = RHSExp;
5718 if (getLangOpts().CPlusPlus11 && LHSExp->isPRValue()) {
5719 ExprResult Materialized = TemporaryMaterializationConversion(LHSExp);
5720 if (Materialized.isInvalid())
5721 return ExprError();
5722 LHSExp = Materialized.get();
5723 }
5724 VK = LHSExp->getValueKind();
5725 if (VK != VK_PRValue)
5726 OK = OK_VectorComponent;
5727
5728 ResultType = BTy->getSveEltType(Context);
5729
5730 QualType BaseType = BaseExpr->getType();
5731 Qualifiers BaseQuals = BaseType.getQualifiers();
5732 Qualifiers MemberQuals = ResultType.getQualifiers();
5733 Qualifiers Combined = BaseQuals + MemberQuals;
5734 if (Combined != MemberQuals)
5735 ResultType = Context.getQualifiedType(ResultType, Combined);
5736 } else if (LHSTy->isArrayType()) {
5737 // If we see an array that wasn't promoted by
5738 // DefaultFunctionArrayLvalueConversion, it must be an array that
5739 // wasn't promoted because of the C90 rule that doesn't
5740 // allow promoting non-lvalue arrays. Warn, then
5741 // force the promotion here.
5742 Diag(LHSExp->getBeginLoc(), diag::ext_subscript_non_lvalue)
5743 << LHSExp->getSourceRange();
5744 LHSExp = ImpCastExprToType(LHSExp, Context.getArrayDecayedType(LHSTy),
5745 CK_ArrayToPointerDecay).get();
5746 LHSTy = LHSExp->getType();
5747
5748 BaseExpr = LHSExp;
5749 IndexExpr = RHSExp;
5750 ResultType = LHSTy->castAs<PointerType>()->getPointeeType();
5751 } else if (RHSTy->isArrayType()) {
5752 // Same as previous, except for 123[f().a] case
5753 Diag(RHSExp->getBeginLoc(), diag::ext_subscript_non_lvalue)
5754 << RHSExp->getSourceRange();
5755 RHSExp = ImpCastExprToType(RHSExp, Context.getArrayDecayedType(RHSTy),
5756 CK_ArrayToPointerDecay).get();
5757 RHSTy = RHSExp->getType();
5758
5759 BaseExpr = RHSExp;
5760 IndexExpr = LHSExp;
5761 ResultType = RHSTy->castAs<PointerType>()->getPointeeType();
5762 } else {
5763 return ExprError(Diag(LLoc, diag::err_typecheck_subscript_value)
5764 << LHSExp->getSourceRange() << RHSExp->getSourceRange());
5765 }
5766 // C99 6.5.2.1p1
5767 if (!IndexExpr->getType()->isIntegerType() && !IndexExpr->isTypeDependent())
5768 return ExprError(Diag(LLoc, diag::err_typecheck_subscript_not_integer)
5769 << IndexExpr->getSourceRange());
5770
5771 if ((IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_S) ||
5772 IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_U))
5773 && !IndexExpr->isTypeDependent())
5774 Diag(LLoc, diag::warn_subscript_is_char) << IndexExpr->getSourceRange();
5775
5776 // C99 6.5.2.1p1: "shall have type "pointer to *object* type". Similarly,
5777 // C++ [expr.sub]p1: The type "T" shall be a completely-defined object
5778 // type. Note that Functions are not objects, and that (in C99 parlance)
5779 // incomplete types are not object types.
5780 if (ResultType->isFunctionType()) {
5781 Diag(BaseExpr->getBeginLoc(), diag::err_subscript_function_type)
5782 << ResultType << BaseExpr->getSourceRange();
5783 return ExprError();
5784 }
5785
5786 if (ResultType->isVoidType() && !getLangOpts().CPlusPlus) {
5787 // GNU extension: subscripting on pointer to void
5788 Diag(LLoc, diag::ext_gnu_subscript_void_type)
5789 << BaseExpr->getSourceRange();
5790
5791 // C forbids expressions of unqualified void type from being l-values.
5792 // See IsCForbiddenLValueType.
5793 if (!ResultType.hasQualifiers())
5794 VK = VK_PRValue;
5795 } else if (!ResultType->isDependentType() &&
5796 RequireCompleteSizedType(
5797 LLoc, ResultType,
5798 diag::err_subscript_incomplete_or_sizeless_type, BaseExpr))
5799 return ExprError();
5800
5801 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", 5802, __extension__ __PRETTY_FUNCTION__
))
5802 !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", 5802, __extension__ __PRETTY_FUNCTION__
))
;
5803
5804 if (LHSExp->IgnoreParenImpCasts()->getType()->isVariablyModifiedType() &&
5805 FunctionScopes.size() > 1) {
5806 if (auto *TT =
5807 LHSExp->IgnoreParenImpCasts()->getType()->getAs<TypedefType>()) {
5808 for (auto I = FunctionScopes.rbegin(),
5809 E = std::prev(FunctionScopes.rend());
5810 I != E; ++I) {
5811 auto *CSI = dyn_cast<CapturingScopeInfo>(*I);
5812 if (CSI == nullptr)
5813 break;
5814 DeclContext *DC = nullptr;
5815 if (auto *LSI = dyn_cast<LambdaScopeInfo>(CSI))
5816 DC = LSI->CallOperator;
5817 else if (auto *CRSI = dyn_cast<CapturedRegionScopeInfo>(CSI))
5818 DC = CRSI->TheCapturedDecl;
5819 else if (auto *BSI = dyn_cast<BlockScopeInfo>(CSI))
5820 DC = BSI->TheDecl;
5821 if (DC) {
5822 if (DC->containsDecl(TT->getDecl()))
5823 break;
5824 captureVariablyModifiedType(
5825 Context, LHSExp->IgnoreParenImpCasts()->getType(), CSI);
5826 }
5827 }
5828 }
5829 }
5830
5831 return new (Context)
5832 ArraySubscriptExpr(LHSExp, RHSExp, ResultType, VK, OK, RLoc);
5833}
5834
5835bool Sema::CheckCXXDefaultArgExpr(SourceLocation CallLoc, FunctionDecl *FD,
5836 ParmVarDecl *Param) {
5837 if (Param->hasUnparsedDefaultArg()) {
5838 // If we've already cleared out the location for the default argument,
5839 // that means we're parsing it right now.
5840 if (!UnparsedDefaultArgLocs.count(Param)) {
5841 Diag(Param->getBeginLoc(), diag::err_recursive_default_argument) << FD;
5842 Diag(CallLoc, diag::note_recursive_default_argument_used_here);
5843 Param->setInvalidDecl();
5844 return true;
5845 }
5846
5847 Diag(CallLoc, diag::err_use_of_default_argument_to_function_declared_later)
5848 << FD << cast<CXXRecordDecl>(FD->getDeclContext());
5849 Diag(UnparsedDefaultArgLocs[Param],
5850 diag::note_default_argument_declared_here);
5851 return true;
5852 }
5853
5854 if (Param->hasUninstantiatedDefaultArg() &&
5855 InstantiateDefaultArgument(CallLoc, FD, Param))
5856 return true;
5857
5858 assert(Param->hasInit() && "default argument but no initializer?")(static_cast <bool> (Param->hasInit() && "default argument but no initializer?"
) ? void (0) : __assert_fail ("Param->hasInit() && \"default argument but no initializer?\""
, "clang/lib/Sema/SemaExpr.cpp", 5858, __extension__ __PRETTY_FUNCTION__
))
;
5859
5860 // If the default expression creates temporaries, we need to
5861 // push them to the current stack of expression temporaries so they'll
5862 // be properly destroyed.
5863 // FIXME: We should really be rebuilding the default argument with new
5864 // bound temporaries; see the comment in PR5810.
5865 // We don't need to do that with block decls, though, because
5866 // blocks in default argument expression can never capture anything.
5867 if (auto Init = dyn_cast<ExprWithCleanups>(Param->getInit())) {
5868 // Set the "needs cleanups" bit regardless of whether there are
5869 // any explicit objects.
5870 Cleanup.setExprNeedsCleanups(Init->cleanupsHaveSideEffects());
5871
5872 // Append all the objects to the cleanup list. Right now, this
5873 // should always be a no-op, because blocks in default argument
5874 // expressions should never be able to capture anything.
5875 assert(!Init->getNumObjects() &&(static_cast <bool> (!Init->getNumObjects() &&
"default argument expression has capturing blocks?") ? void (
0) : __assert_fail ("!Init->getNumObjects() && \"default argument expression has capturing blocks?\""
, "clang/lib/Sema/SemaExpr.cpp", 5876, __extension__ __PRETTY_FUNCTION__
))
5876 "default argument expression has capturing blocks?")(static_cast <bool> (!Init->getNumObjects() &&
"default argument expression has capturing blocks?") ? void (
0) : __assert_fail ("!Init->getNumObjects() && \"default argument expression has capturing blocks?\""
, "clang/lib/Sema/SemaExpr.cpp", 5876, __extension__ __PRETTY_FUNCTION__
))
;
5877 }
5878
5879 // We already type-checked the argument, so we know it works.
5880 // Just mark all of the declarations in this potentially-evaluated expression
5881 // as being "referenced".
5882 EnterExpressionEvaluationContext EvalContext(
5883 *this, ExpressionEvaluationContext::PotentiallyEvaluated, Param);
5884 MarkDeclarationsReferencedInExpr(Param->getDefaultArg(),
5885 /*SkipLocalVariables=*/true);
5886 return false;
5887}
5888
5889ExprResult Sema::BuildCXXDefaultArgExpr(SourceLocation CallLoc,
5890 FunctionDecl *FD, ParmVarDecl *Param) {
5891 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", 5891, __extension__ __PRETTY_FUNCTION__
))
;
5892 if (CheckCXXDefaultArgExpr(CallLoc, FD, Param))
5893 return ExprError();
5894 return CXXDefaultArgExpr::Create(Context, CallLoc, Param, CurContext);
5895}
5896
5897Sema::VariadicCallType
5898Sema::getVariadicCallType(FunctionDecl *FDecl, const FunctionProtoType *Proto,
5899 Expr *Fn) {
5900 if (Proto && Proto->isVariadic()) {
5901 if (isa_and_nonnull<CXXConstructorDecl>(FDecl))
5902 return VariadicConstructor;
5903 else if (Fn && Fn->getType()->isBlockPointerType())
5904 return VariadicBlock;
5905 else if (FDecl) {
5906 if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(FDecl))
5907 if (Method->isInstance())
5908 return VariadicMethod;
5909 } else if (Fn && Fn->getType() == Context.BoundMemberTy)
5910 return VariadicMethod;
5911 return VariadicFunction;
5912 }
5913 return VariadicDoesNotApply;
5914}
5915
5916namespace {
5917class FunctionCallCCC final : public FunctionCallFilterCCC {
5918public:
5919 FunctionCallCCC(Sema &SemaRef, const IdentifierInfo *FuncName,
5920 unsigned NumArgs, MemberExpr *ME)
5921 : FunctionCallFilterCCC(SemaRef, NumArgs, false, ME),
5922 FunctionName(FuncName) {}
5923
5924 bool ValidateCandidate(const TypoCorrection &candidate) override {
5925 if (!candidate.getCorrectionSpecifier() ||
5926 candidate.getCorrectionAsIdentifierInfo() != FunctionName) {
5927 return false;
5928 }
5929
5930 return FunctionCallFilterCCC::ValidateCandidate(candidate);
5931 }
5932
5933 std::unique_ptr<CorrectionCandidateCallback> clone() override {
5934 return std::make_unique<FunctionCallCCC>(*this);
5935 }
5936
5937private:
5938 const IdentifierInfo *const FunctionName;
5939};
5940}
5941
5942static TypoCorrection TryTypoCorrectionForCall(Sema &S, Expr *Fn,
5943 FunctionDecl *FDecl,
5944 ArrayRef<Expr *> Args) {
5945 MemberExpr *ME = dyn_cast<MemberExpr>(Fn);
5946 DeclarationName FuncName = FDecl->getDeclName();
5947 SourceLocation NameLoc = ME ? ME->getMemberLoc() : Fn->getBeginLoc();
5948
5949 FunctionCallCCC CCC(S, FuncName.getAsIdentifierInfo(), Args.size(), ME);
5950 if (TypoCorrection Corrected = S.CorrectTypo(
5951 DeclarationNameInfo(FuncName, NameLoc), Sema::LookupOrdinaryName,
5952 S.getScopeForContext(S.CurContext), nullptr, CCC,
5953 Sema::CTK_ErrorRecovery)) {
5954 if (NamedDecl *ND = Corrected.getFoundDecl()) {
5955 if (Corrected.isOverloaded()) {
5956 OverloadCandidateSet OCS(NameLoc, OverloadCandidateSet::CSK_Normal);
5957 OverloadCandidateSet::iterator Best;
5958 for (NamedDecl *CD : Corrected) {
5959 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(CD))
5960 S.AddOverloadCandidate(FD, DeclAccessPair::make(FD, AS_none), Args,
5961 OCS);
5962 }
5963 switch (OCS.BestViableFunction(S, NameLoc, Best)) {
5964 case OR_Success:
5965 ND = Best->FoundDecl;
5966 Corrected.setCorrectionDecl(ND);
5967 break;
5968 default:
5969 break;
5970 }
5971 }
5972 ND = ND->getUnderlyingDecl();
5973 if (isa<ValueDecl>(ND) || isa<FunctionTemplateDecl>(ND))
5974 return Corrected;
5975 }
5976 }
5977 return TypoCorrection();
5978}
5979
5980/// ConvertArgumentsForCall - Converts the arguments specified in
5981/// Args/NumArgs to the parameter types of the function FDecl with
5982/// function prototype Proto. Call is the call expression itself, and
5983/// Fn is the function expression. For a C++ member function, this
5984/// routine does not attempt to convert the object argument. Returns
5985/// true if the call is ill-formed.
5986bool
5987Sema::ConvertArgumentsForCall(CallExpr *Call, Expr *Fn,
5988 FunctionDecl *FDecl,
5989 const FunctionProtoType *Proto,
5990 ArrayRef<Expr *> Args,
5991 SourceLocation RParenLoc,
5992 bool IsExecConfig) {
5993 // Bail out early if calling a builtin with custom typechecking.
5994 if (FDecl)
5995 if (unsigned ID = FDecl->getBuiltinID())
5996 if (Context.BuiltinInfo.hasCustomTypechecking(ID))
5997 return false;
5998
5999 // C99 6.5.2.2p7 - the arguments are implicitly converted, as if by
6000 // assignment, to the types of the corresponding parameter, ...
6001 unsigned NumParams = Proto->getNumParams();
6002 bool Invalid = false;
6003 unsigned MinArgs = FDecl ? FDecl->getMinRequiredArguments() : NumParams;
6004 unsigned FnKind = Fn->getType()->isBlockPointerType()
6005 ? 1 /* block */
6006 : (IsExecConfig ? 3 /* kernel function (exec config) */
6007 : 0 /* function */);
6008
6009 // If too few arguments are available (and we don't have default
6010 // arguments for the remaining parameters), don't make the call.
6011 if (Args.size() < NumParams) {
6012 if (Args.size() < MinArgs) {
6013 TypoCorrection TC;
6014 if (FDecl && (TC = TryTypoCorrectionForCall(*this, Fn, FDecl, Args))) {
6015 unsigned diag_id =
6016 MinArgs == NumParams && !Proto->isVariadic()
6017 ? diag::err_typecheck_call_too_few_args_suggest
6018 : diag::err_typecheck_call_too_few_args_at_least_suggest;
6019 diagnoseTypo(TC, PDiag(diag_id) << FnKind << MinArgs
6020 << static_cast<unsigned>(Args.size())
6021 << TC.getCorrectionRange());
6022 } else if (MinArgs == 1 && FDecl && FDecl->getParamDecl(0)->getDeclName())
6023 Diag(RParenLoc,
6024 MinArgs == NumParams && !Proto->isVariadic()
6025 ? diag::err_typecheck_call_too_few_args_one
6026 : diag::err_typecheck_call_too_few_args_at_least_one)
6027 << FnKind << FDecl->getParamDecl(0) << Fn->getSourceRange();
6028 else
6029 Diag(RParenLoc, MinArgs == NumParams && !Proto->isVariadic()
6030 ? diag::err_typecheck_call_too_few_args
6031 : diag::err_typecheck_call_too_few_args_at_least)
6032 << FnKind << MinArgs << static_cast<unsigned>(Args.size())
6033 << Fn->getSourceRange();
6034
6035 // Emit the location of the prototype.
6036 if (!TC && FDecl && !FDecl->getBuiltinID() && !IsExecConfig)
6037 Diag(FDecl->getLocation(), diag::note_callee_decl) << FDecl;
6038
6039 return true;
6040 }
6041 // We reserve space for the default arguments when we create
6042 // the call expression, before calling ConvertArgumentsForCall.
6043 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", 6044, __extension__ __PRETTY_FUNCTION__
))
6044 "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", 6044, __extension__ __PRETTY_FUNCTION__
))
;
6045 }
6046
6047 // If too many are passed and not variadic, error on the extras and drop
6048 // them.
6049 if (Args.size() > NumParams) {
6050 if (!Proto->isVariadic()) {
6051 TypoCorrection TC;
6052 if (FDecl && (TC = TryTypoCorrectionForCall(*this, Fn, FDecl, Args))) {
6053 unsigned diag_id =
6054 MinArgs == NumParams && !Proto->isVariadic()
6055 ? diag::err_typecheck_call_too_many_args_suggest
6056 : diag::err_typecheck_call_too_many_args_at_most_suggest;
6057 diagnoseTypo(TC, PDiag(diag_id) << FnKind << NumParams
6058 << static_cast<unsigned>(Args.size())
6059 << TC.getCorrectionRange());
6060 } else if (NumParams == 1 && FDecl &&
6061 FDecl->getParamDecl(0)->getDeclName())
6062 Diag(Args[NumParams]->getBeginLoc(),
6063 MinArgs == NumParams
6064 ? diag::err_typecheck_call_too_many_args_one
6065 : diag::err_typecheck_call_too_many_args_at_most_one)
6066 << FnKind << FDecl->getParamDecl(0)
6067 << static_cast<unsigned>(Args.size()) << Fn->getSourceRange()
6068 << SourceRange(Args[NumParams]->getBeginLoc(),
6069 Args.back()->getEndLoc());
6070 else
6071 Diag(Args[NumParams]->getBeginLoc(),
6072 MinArgs == NumParams
6073 ? diag::err_typecheck_call_too_many_args
6074 : diag::err_typecheck_call_too_many_args_at_most)
6075 << FnKind << NumParams << static_cast<unsigned>(Args.size())
6076 << Fn->getSourceRange()
6077 << SourceRange(Args[NumParams]->getBeginLoc(),
6078 Args.back()->getEndLoc());
6079
6080 // Emit the location of the prototype.
6081 if (!TC && FDecl && !FDecl->getBuiltinID() && !IsExecConfig)
6082 Diag(FDecl->getLocation(), diag::note_callee_decl) << FDecl;
6083
6084 // This deletes the extra arguments.
6085 Call->shrinkNumArgs(NumParams);
6086 return true;
6087 }
6088 }
6089 SmallVector<Expr *, 8> AllArgs;
6090 VariadicCallType CallType = getVariadicCallType(FDecl, Proto, Fn);
6091
6092 Invalid = GatherArgumentsForCall(Call->getBeginLoc(), FDecl, Proto, 0, Args,
6093 AllArgs, CallType);
6094 if (Invalid)
6095 return true;
6096 unsigned TotalNumArgs = AllArgs.size();
6097 for (unsigned i = 0; i < TotalNumArgs; ++i)
6098 Call->setArg(i, AllArgs[i]);
6099
6100 Call->computeDependence();
6101 return false;
6102}
6103
6104bool Sema::GatherArgumentsForCall(SourceLocation CallLoc, FunctionDecl *FDecl,
6105 const FunctionProtoType *Proto,
6106 unsigned FirstParam, ArrayRef<Expr *> Args,
6107 SmallVectorImpl<Expr *> &AllArgs,
6108 VariadicCallType CallType, bool AllowExplicit,
6109 bool IsListInitialization) {
6110 unsigned NumParams = Proto->getNumParams();
6111 bool Invalid = false;
6112 size_t ArgIx = 0;
6113 // Continue to check argument types (even if we have too few/many args).
6114 for (unsigned i = FirstParam; i < NumParams; i++) {
6115 QualType ProtoArgType = Proto->getParamType(i);
6116
6117 Expr *Arg;
6118 ParmVarDecl *Param = FDecl ? FDecl->getParamDecl(i) : nullptr;
6119 if (ArgIx < Args.size()) {
6120 Arg = Args[ArgIx++];
6121
6122 if (RequireCompleteType(Arg->getBeginLoc(), ProtoArgType,
6123 diag::err_call_incomplete_argument, Arg))
6124 return true;
6125
6126 // Strip the unbridged-cast placeholder expression off, if applicable.
6127 bool CFAudited = false;
6128 if (Arg->getType() == Context.ARCUnbridgedCastTy &&
6129 FDecl && FDecl->hasAttr<CFAuditedTransferAttr>() &&
6130 (!Param || !Param->hasAttr<CFConsumedAttr>()))
6131 Arg = stripARCUnbridgedCast(Arg);
6132 else if (getLangOpts().ObjCAutoRefCount &&
6133 FDecl && FDecl->hasAttr<CFAuditedTransferAttr>() &&
6134 (!Param || !Param->hasAttr<CFConsumedAttr>()))
6135 CFAudited = true;
6136
6137 if (Proto->getExtParameterInfo(i).isNoEscape() &&
6138 ProtoArgType->isBlockPointerType())
6139 if (auto *BE = dyn_cast<BlockExpr>(Arg->IgnoreParenNoopCasts(Context)))
6140 BE->getBlockDecl()->setDoesNotEscape();
6141
6142 InitializedEntity Entity =
6143 Param ? InitializedEntity::InitializeParameter(Context, Param,
6144 ProtoArgType)
6145 : InitializedEntity::InitializeParameter(
6146 Context, ProtoArgType, Proto->isParamConsumed(i));
6147
6148 // Remember that parameter belongs to a CF audited API.
6149 if (CFAudited)
6150 Entity.setParameterCFAudited();
6151
6152 ExprResult ArgE = PerformCopyInitialization(
6153 Entity, SourceLocation(), Arg, IsListInitialization, AllowExplicit);
6154 if (ArgE.isInvalid())
6155 return true;
6156
6157 Arg = ArgE.getAs<Expr>();
6158 } else {
6159 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", 6159, __extension__ __PRETTY_FUNCTION__
))
;
6160
6161 ExprResult ArgExpr = BuildCXXDefaultArgExpr(CallLoc, FDecl, Param);
6162 if (ArgExpr.isInvalid())
6163 return true;
6164
6165 Arg = ArgExpr.getAs<Expr>();
6166 }
6167
6168 // Check for array bounds violations for each argument to the call. This
6169 // check only triggers warnings when the argument isn't a more complex Expr
6170 // with its own checking, such as a BinaryOperator.
6171 CheckArrayAccess(Arg);
6172
6173 // Check for violations of C99 static array rules (C99 6.7.5.3p7).
6174 CheckStaticArrayArgument(CallLoc, Param, Arg);
6175
6176 AllArgs.push_back(Arg);
6177 }
6178
6179 // If this is a variadic call, handle args passed through "...".
6180 if (CallType != VariadicDoesNotApply) {
6181 // Assume that extern "C" functions with variadic arguments that
6182 // return __unknown_anytype aren't *really* variadic.
6183 if (Proto->getReturnType() == Context.UnknownAnyTy && FDecl &&
6184 FDecl->isExternC()) {
6185 for (Expr *A : Args.slice(ArgIx)) {
6186 QualType paramType; // ignored
6187 ExprResult arg = checkUnknownAnyArg(CallLoc, A, paramType);
6188 Invalid |= arg.isInvalid();
6189 AllArgs.push_back(arg.get());
6190 }
6191
6192 // Otherwise do argument promotion, (C99 6.5.2.2p7).
6193 } else {
6194 for (Expr *A : Args.slice(ArgIx)) {
6195 ExprResult Arg = DefaultVariadicArgumentPromotion(A, CallType, FDecl);
6196 Invalid |= Arg.isInvalid();
6197 AllArgs.push_back(Arg.get());
6198 }
6199 }
6200
6201 // Check for array bounds violations.
6202 for (Expr *A : Args.slice(ArgIx))
6203 CheckArrayAccess(A);
6204 }
6205 return Invalid;
6206}
6207
6208static void DiagnoseCalleeStaticArrayParam(Sema &S, ParmVarDecl *PVD) {
6209 TypeLoc TL = PVD->getTypeSourceInfo()->getTypeLoc();
6210 if (DecayedTypeLoc DTL = TL.getAs<DecayedTypeLoc>())
6211 TL = DTL.getOriginalLoc();
6212 if (ArrayTypeLoc ATL = TL.getAs<ArrayTypeLoc>())
6213 S.Diag(PVD->getLocation(), diag::note_callee_static_array)
6214 << ATL.getLocalSourceRange();
6215}
6216
6217/// CheckStaticArrayArgument - If the given argument corresponds to a static
6218/// array parameter, check that it is non-null, and that if it is formed by
6219/// array-to-pointer decay, the underlying array is sufficiently large.
6220///
6221/// C99 6.7.5.3p7: If the keyword static also appears within the [ and ] of the
6222/// array type derivation, then for each call to the function, the value of the
6223/// corresponding actual argument shall provide access to the first element of
6224/// an array with at least as many elements as specified by the size expression.
6225void
6226Sema::CheckStaticArrayArgument(SourceLocation CallLoc,
6227 ParmVarDecl *Param,
6228 const Expr *ArgExpr) {
6229 // Static array parameters are not supported in C++.
6230 if (!Param || getLangOpts().CPlusPlus)
6231 return;
6232
6233 QualType OrigTy = Param->getOriginalType();
6234
6235 const ArrayType *AT = Context.getAsArrayType(OrigTy);
6236 if (!AT || AT->getSizeModifier() != ArrayType::Static)
6237 return;
6238
6239 if (ArgExpr->isNullPointerConstant(Context,
6240 Expr::NPC_NeverValueDependent)) {
6241 Diag(CallLoc, diag::warn_null_arg) << ArgExpr->getSourceRange();
6242 DiagnoseCalleeStaticArrayParam(*this, Param);
6243 return;
6244 }
6245
6246 const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT);
6247 if (!CAT)
6248 return;
6249
6250 const ConstantArrayType *ArgCAT =
6251 Context.getAsConstantArrayType(ArgExpr->IgnoreParenCasts()->getType());
6252 if (!ArgCAT)
6253 return;
6254
6255 if (getASTContext().hasSameUnqualifiedType(CAT->getElementType(),
6256 ArgCAT->getElementType())) {
6257 if (ArgCAT->getSize().ult(CAT->getSize())) {
6258 Diag(CallLoc, diag::warn_static_array_too_small)
6259 << ArgExpr->getSourceRange()
6260 << (unsigned)ArgCAT->getSize().getZExtValue()
6261 << (unsigned)CAT->getSize().getZExtValue() << 0;
6262 DiagnoseCalleeStaticArrayParam(*this, Param);
6263 }
6264 return;
6265 }
6266
6267 Optional<CharUnits> ArgSize =
6268 getASTContext().getTypeSizeInCharsIfKnown(ArgCAT);
6269 Optional<CharUnits> ParmSize = getASTContext().getTypeSizeInCharsIfKnown(CAT);
6270 if (ArgSize && ParmSize && *ArgSize < *ParmSize) {
6271 Diag(CallLoc, diag::warn_static_array_too_small)
6272 << ArgExpr->getSourceRange() << (unsigned)ArgSize->getQuantity()
6273 << (unsigned)ParmSize->getQuantity() << 1;
6274 DiagnoseCalleeStaticArrayParam(*this, Param);
6275 }
6276}
6277
6278/// Given a function expression of unknown-any type, try to rebuild it
6279/// to have a function type.
6280static ExprResult rebuildUnknownAnyFunction(Sema &S, Expr *fn);
6281
6282/// Is the given type a placeholder that we need to lower out
6283/// immediately during argument processing?
6284static bool isPlaceholderToRemoveAsArg(QualType type) {
6285 // Placeholders are never sugared.
6286 const BuiltinType *placeholder = dyn_cast<BuiltinType>(type);
6287 if (!placeholder) return false;
6288
6289 switch (placeholder->getKind()) {
6290 // Ignore all the non-placeholder types.
6291#define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
6292 case BuiltinType::Id:
6293#include "clang/Basic/OpenCLImageTypes.def"
6294#define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \
6295 case BuiltinType::Id:
6296#include "clang/Basic/OpenCLExtensionTypes.def"
6297 // In practice we'll never use this, since all SVE types are sugared
6298 // via TypedefTypes rather than exposed directly as BuiltinTypes.
6299#define SVE_TYPE(Name, Id, SingletonId) \
6300 case BuiltinType::Id:
6301#include "clang/Basic/AArch64SVEACLETypes.def"
6302#define PPC_VECTOR_TYPE(Name, Id, Size) \
6303 case BuiltinType::Id:
6304#include "clang/Basic/PPCTypes.def"
6305#define RVV_TYPE(Name, Id, SingletonId) case BuiltinType::Id:
6306#include "clang/Basic/RISCVVTypes.def"
6307#define PLACEHOLDER_TYPE(ID, SINGLETON_ID)
6308#define BUILTIN_TYPE(ID, SINGLETON_ID) case BuiltinType::ID:
6309#include "clang/AST/BuiltinTypes.def"
6310 return false;
6311
6312 // We cannot lower out overload sets; they might validly be resolved
6313 // by the call machinery.
6314 case BuiltinType::Overload:
6315 return false;
6316
6317 // Unbridged casts in ARC can be handled in some call positions and
6318 // should be left in place.
6319 case BuiltinType::ARCUnbridgedCast:
6320 return false;
6321
6322 // Pseudo-objects should be converted as soon as possible.
6323 case BuiltinType::PseudoObject:
6324 return true;
6325
6326 // The debugger mode could theoretically but currently does not try
6327 // to resolve unknown-typed arguments based on known parameter types.
6328 case BuiltinType::UnknownAny:
6329 return true;
6330
6331 // These are always invalid as call arguments and should be reported.
6332 case BuiltinType::BoundMember:
6333 case BuiltinType::BuiltinFn:
6334 case BuiltinType::IncompleteMatrixIdx:
6335 case BuiltinType::OMPArraySection:
6336 case BuiltinType::OMPArrayShaping:
6337 case BuiltinType::OMPIterator:
6338 return true;
6339
6340 }
6341 llvm_unreachable("bad builtin type kind")::llvm::llvm_unreachable_internal("bad builtin type kind", "clang/lib/Sema/SemaExpr.cpp"
, 6341)
;
6342}
6343
6344/// Check an argument list for placeholders that we won't try to
6345/// handle later.
6346static bool checkArgsForPlaceholders(Sema &S, MultiExprArg args) {
6347 // Apply this processing to all the arguments at once instead of
6348 // dying at the first failure.
6349 bool hasInvalid = false;
6350 for (size_t i = 0, e = args.size(); i != e; i++) {
6351 if (isPlaceholderToRemoveAsArg(args[i]->getType())) {
6352 ExprResult result = S.CheckPlaceholderExpr(args[i]);
6353 if (result.isInvalid()) hasInvalid = true;
6354 else args[i] = result.get();
6355 }
6356 }
6357 return hasInvalid;
6358}
6359
6360/// If a builtin function has a pointer argument with no explicit address
6361/// space, then it should be able to accept a pointer to any address
6362/// space as input. In order to do this, we need to replace the
6363/// standard builtin declaration with one that uses the same address space
6364/// as the call.
6365///
6366/// \returns nullptr If this builtin is not a candidate for a rewrite i.e.
6367/// it does not contain any pointer arguments without
6368/// an address space qualifer. Otherwise the rewritten
6369/// FunctionDecl is returned.
6370/// TODO: Handle pointer return types.
6371static FunctionDecl *rewriteBuiltinFunctionDecl(Sema *Sema, ASTContext &Context,
6372 FunctionDecl *FDecl,
6373 MultiExprArg ArgExprs) {
6374
6375 QualType DeclType = FDecl->getType();
6376 const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(DeclType);
6377
6378 if (!Context.BuiltinInfo.hasPtrArgsOrResult(FDecl->getBuiltinID()) || !FT ||
6379 ArgExprs.size() < FT->getNumParams())
6380 return nullptr;
6381
6382 bool NeedsNewDecl = false;
6383 unsigned i = 0;
6384 SmallVector<QualType, 8> OverloadParams;
6385
6386 for (QualType ParamType : FT->param_types()) {
6387
6388 // Convert array arguments to pointer to simplify type lookup.
6389 ExprResult ArgRes =
6390 Sema->DefaultFunctionArrayLvalueConversion(ArgExprs[i++]);
6391 if (ArgRes.isInvalid())
6392 return nullptr;
6393 Expr *Arg = ArgRes.get();
6394 QualType ArgType = Arg->getType();
6395 if (!ParamType->isPointerType() ||
6396 ParamType.hasAddressSpace() ||
6397 !ArgType->isPointerType() ||
6398 !ArgType->getPointeeType().hasAddressSpace()) {
6399 OverloadParams.push_back(ParamType);
6400 continue;
6401 }
6402
6403 QualType PointeeType = ParamType->getPointeeType();
6404 if (PointeeType.hasAddressSpace())
6405 continue;
6406
6407 NeedsNewDecl = true;
6408 LangAS AS = ArgType->getPointeeType().getAddressSpace();
6409
6410 PointeeType = Context.getAddrSpaceQualType(PointeeType, AS);
6411 OverloadParams.push_back(Context.getPointerType(PointeeType));
6412 }
6413
6414 if (!NeedsNewDecl)
6415 return nullptr;
6416
6417 FunctionProtoType::ExtProtoInfo EPI;
6418 EPI.Variadic = FT->isVariadic();
6419 QualType OverloadTy = Context.getFunctionType(FT->getReturnType(),
6420 OverloadParams, EPI);
6421 DeclContext *Parent = FDecl->getParent();
6422 FunctionDecl *OverloadDecl = FunctionDecl::Create(
6423 Context, Parent, FDecl->getLocation(), FDecl->getLocation(),
6424 FDecl->getIdentifier(), OverloadTy,
6425 /*TInfo=*/nullptr, SC_Extern, Sema->getCurFPFeatures().isFPConstrained(),
6426 false,
6427 /*hasPrototype=*/true);
6428 SmallVector<ParmVarDecl*, 16> Params;
6429 FT = cast<FunctionProtoType>(OverloadTy);
6430 for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i) {
6431 QualType ParamType = FT->getParamType(i);
6432 ParmVarDecl *Parm =
6433 ParmVarDecl::Create(Context, OverloadDecl, SourceLocation(),
6434 SourceLocation(), nullptr, ParamType,
6435 /*TInfo=*/nullptr, SC_None, nullptr);
6436 Parm->setScopeInfo(0, i);
6437 Params.push_back(Parm);
6438 }
6439 OverloadDecl->setParams(Params);
6440 Sema->mergeDeclAttributes(OverloadDecl, FDecl);
6441 return OverloadDecl;
6442}
6443
6444static void checkDirectCallValidity(Sema &S, const Expr *Fn,
6445 FunctionDecl *Callee,
6446 MultiExprArg ArgExprs) {
6447 // `Callee` (when called with ArgExprs) may be ill-formed. enable_if (and
6448 // similar attributes) really don't like it when functions are called with an
6449 // invalid number of args.
6450 if (S.TooManyArguments(Callee->getNumParams(), ArgExprs.size(),
6451 /*PartialOverloading=*/false) &&
6452 !Callee->isVariadic())
6453 return;
6454 if (Callee->getMinRequiredArguments() > ArgExprs.size())
6455 return;
6456
6457 if (const EnableIfAttr *Attr =
6458 S.CheckEnableIf(Callee, Fn->getBeginLoc(), ArgExprs, true)) {
6459 S.Diag(Fn->getBeginLoc(),
6460 isa<CXXMethodDecl>(Callee)
6461 ? diag::err_ovl_no_viable_member_function_in_call
6462 : diag::err_ovl_no_viable_function_in_call)
6463 << Callee << Callee->getSourceRange();
6464 S.Diag(Callee->getLocation(),
6465 diag::note_ovl_candidate_disabled_by_function_cond_attr)
6466 << Attr->getCond()->getSourceRange() << Attr->getMessage();
6467 return;
6468 }
6469}
6470
6471static bool enclosingClassIsRelatedToClassInWhichMembersWereFound(
6472 const UnresolvedMemberExpr *const UME, Sema &S) {
6473
6474 const auto GetFunctionLevelDCIfCXXClass =
6475 [](Sema &S) -> const CXXRecordDecl * {
6476 const DeclContext *const DC = S.getFunctionLevelDeclContext();
6477 if (!DC || !DC->getParent())
6478 return nullptr;
6479
6480 // If the call to some member function was made from within a member
6481 // function body 'M' return return 'M's parent.
6482 if (const auto *MD = dyn_cast<CXXMethodDecl>(DC))
6483 return MD->getParent()->getCanonicalDecl();
6484 // else the call was made from within a default member initializer of a
6485 // class, so return the class.
6486 if (const auto *RD = dyn_cast<CXXRecordDecl>(DC))
6487 return RD->getCanonicalDecl();
6488 return nullptr;
6489 };
6490 // If our DeclContext is neither a member function nor a class (in the
6491 // case of a lambda in a default member initializer), we can't have an
6492 // enclosing 'this'.
6493
6494 const CXXRecordDecl *const CurParentClass = GetFunctionLevelDCIfCXXClass(S);
6495 if (!CurParentClass)
6496 return false;
6497
6498 // The naming class for implicit member functions call is the class in which
6499 // name lookup starts.
6500 const CXXRecordDecl *const NamingClass =
6501 UME->getNamingClass()->getCanonicalDecl();
6502 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", 6502, __extension__ __PRETTY_FUNCTION__
))
;
6503
6504 // If the unresolved member functions were found in a 'naming class' that is
6505 // related (either the same or derived from) to the class that contains the
6506 // member function that itself contained the implicit member access.
6507
6508 return CurParentClass == NamingClass ||
6509 CurParentClass->isDerivedFrom(NamingClass);
6510}
6511
6512static void
6513tryImplicitlyCaptureThisIfImplicitMemberFunctionAccessWithDependentArgs(
6514 Sema &S, const UnresolvedMemberExpr *const UME, SourceLocation CallLoc) {
6515
6516 if (!UME)
6517 return;
6518
6519 LambdaScopeInfo *const CurLSI = S.getCurLambda();
6520 // Only try and implicitly capture 'this' within a C++ Lambda if it hasn't
6521 // already been captured, or if this is an implicit member function call (if
6522 // it isn't, an attempt to capture 'this' should already have been made).
6523 if (!CurLSI || CurLSI->ImpCaptureStyle == CurLSI->ImpCap_None ||
6524 !UME->isImplicitAccess() || CurLSI->isCXXThisCaptured())
6525 return;
6526
6527 // Check if the naming class in which the unresolved members were found is
6528 // related (same as or is a base of) to the enclosing class.
6529
6530 if (!enclosingClassIsRelatedToClassInWhichMembersWereFound(UME, S))
6531 return;
6532
6533
6534 DeclContext *EnclosingFunctionCtx = S.CurContext->getParent()->getParent();
6535 // If the enclosing function is not dependent, then this lambda is
6536 // capture ready, so if we can capture this, do so.
6537 if (!EnclosingFunctionCtx->isDependentContext()) {
6538 // If the current lambda and all enclosing lambdas can capture 'this' -
6539 // then go ahead and capture 'this' (since our unresolved overload set
6540 // contains at least one non-static member function).
6541 if (!S.CheckCXXThisCapture(CallLoc, /*Explcit*/ false, /*Diagnose*/ false))
6542 S.CheckCXXThisCapture(CallLoc);
6543 } else if (S.CurContext->isDependentContext()) {
6544 // ... since this is an implicit member reference, that might potentially
6545 // involve a 'this' capture, mark 'this' for potential capture in
6546 // enclosing lambdas.
6547 if (CurLSI->ImpCaptureStyle != CurLSI->ImpCap_None)
6548 CurLSI->addPotentialThisCapture(CallLoc);
6549 }
6550}
6551
6552// Once a call is fully resolved, warn for unqualified calls to specific
6553// C++ standard functions, like move and forward.
6554static void DiagnosedUnqualifiedCallsToStdFunctions(Sema &S, CallExpr *Call) {
6555 // We are only checking unary move and forward so exit early here.
6556 if (Call->getNumArgs() != 1)
6557 return;
6558
6559 Expr *E = Call->getCallee()->IgnoreParenImpCasts();
6560 if (!E || isa<UnresolvedLookupExpr>(E))
6561 return;
6562 DeclRefExpr *DRE = dyn_cast_or_null<DeclRefExpr>(E);
6563 if (!DRE || !DRE->getLocation().isValid())
6564 return;
6565
6566 if (DRE->getQualifier())
6567 return;
6568
6569 NamedDecl *D = dyn_cast_or_null<NamedDecl>(Call->getCalleeDecl());
6570 if (!D || !D->isInStdNamespace())
6571 return;
6572
6573 // Only warn for some functions deemed more frequent or problematic.
6574 static constexpr llvm::StringRef SpecialFunctions[] = {"move", "forward"};
6575 auto it = llvm::find(SpecialFunctions, D->getName());
6576 if (it == std::end(SpecialFunctions))
6577 return;
6578
6579 S.Diag(DRE->getLocation(), diag::warn_unqualified_call_to_std_cast_function)
6580 << D->getQualifiedNameAsString()
6581 << FixItHint::CreateInsertion(DRE->getLocation(), "std::");
6582}
6583
6584ExprResult Sema::ActOnCallExpr(Scope *Scope, Expr *Fn, SourceLocation LParenLoc,
6585 MultiExprArg ArgExprs, SourceLocation RParenLoc,
6586 Expr *ExecConfig) {
6587 ExprResult Call =
6588 BuildCallExpr(Scope, Fn, LParenLoc, ArgExprs, RParenLoc, ExecConfig,
6589 /*IsExecConfig=*/false, /*AllowRecovery=*/true);
6590 if (Call.isInvalid())
6591 return Call;
6592
6593 // Diagnose uses of the C++20 "ADL-only template-id call" feature in earlier
6594 // language modes.
6595 if (auto *ULE = dyn_cast<UnresolvedLookupExpr>(Fn)) {
6596 if (ULE->hasExplicitTemplateArgs() &&
6597 ULE->decls_begin() == ULE->decls_end()) {
6598 Diag(Fn->getExprLoc(), getLangOpts().CPlusPlus20
6599 ? diag::warn_cxx17_compat_adl_only_template_id
6600 : diag::ext_adl_only_template_id)
6601 << ULE->getName();
6602 }
6603 }
6604
6605 if (LangOpts.OpenMP)
6606 Call = ActOnOpenMPCall(Call, Scope, LParenLoc, ArgExprs, RParenLoc,
6607 ExecConfig);
6608 if (LangOpts.CPlusPlus) {
6609 CallExpr *CE = dyn_cast<CallExpr>(Call.get());
6610 if (CE)
6611 DiagnosedUnqualifiedCallsToStdFunctions(*this, CE);
6612 }
6613 return Call;
6614}
6615
6616/// BuildCallExpr - Handle a call to Fn with the specified array of arguments.
6617/// This provides the location of the left/right parens and a list of comma
6618/// locations.
6619ExprResult Sema::BuildCallExpr(Scope *Scope, Expr *Fn, SourceLocation LParenLoc,
6620 MultiExprArg ArgExprs, SourceLocation RParenLoc,
6621 Expr *ExecConfig, bool IsExecConfig,
6622 bool AllowRecovery) {
6623 // Since this might be a postfix expression, get rid of ParenListExprs.
6624 ExprResult Result = MaybeConvertParenListExprToParenExpr(Scope, Fn);
6625 if (Result.isInvalid()) return ExprError();
6626 Fn = Result.get();
6627
6628 if (checkArgsForPlaceholders(*this, ArgExprs))
6629 return ExprError();
6630
6631 if (getLangOpts().CPlusPlus) {
6632 // If this is a pseudo-destructor expression, build the call immediately.
6633 if (isa<CXXPseudoDestructorExpr>(Fn)) {
6634 if (!ArgExprs.empty()) {
6635 // Pseudo-destructor calls should not have any arguments.
6636 Diag(Fn->getBeginLoc(), diag::err_pseudo_dtor_call_with_args)
6637 << FixItHint::CreateRemoval(
6638 SourceRange(ArgExprs.front()->getBeginLoc(),
6639 ArgExprs.back()->getEndLoc()));
6640 }
6641
6642 return CallExpr::Create(Context, Fn, /*Args=*/{}, Context.VoidTy,
6643 VK_PRValue, RParenLoc, CurFPFeatureOverrides());
6644 }
6645 if (Fn->getType() == Context.PseudoObjectTy) {
6646 ExprResult result = CheckPlaceholderExpr(Fn);
6647 if (result.isInvalid()) return ExprError();
6648 Fn = result.get();
6649 }
6650
6651 // Determine whether this is a dependent call inside a C++ template,
6652 // in which case we won't do any semantic analysis now.
6653 if (Fn->isTypeDependent() || Expr::hasAnyTypeDependentArguments(ArgExprs)) {
6654 if (ExecConfig) {
6655 return CUDAKernelCallExpr::Create(Context, Fn,
6656 cast<CallExpr>(ExecConfig), ArgExprs,
6657 Context.DependentTy, VK_PRValue,
6658 RParenLoc, CurFPFeatureOverrides());
6659 } else {
6660
6661 tryImplicitlyCaptureThisIfImplicitMemberFunctionAccessWithDependentArgs(
6662 *this, dyn_cast<UnresolvedMemberExpr>(Fn->IgnoreParens()),
6663 Fn->getBeginLoc());
6664
6665 return CallExpr::Create(Context, Fn, ArgExprs, Context.DependentTy,
6666 VK_PRValue, RParenLoc, CurFPFeatureOverrides());
6667 }
6668 }
6669
6670 // Determine whether this is a call to an object (C++ [over.call.object]).
6671 if (Fn->getType()->isRecordType())
6672 return BuildCallToObjectOfClassType(Scope, Fn, LParenLoc, ArgExprs,
6673 RParenLoc);
6674
6675 if (Fn->getType() == Context.UnknownAnyTy) {
6676 ExprResult result = rebuildUnknownAnyFunction(*this, Fn);
6677 if (result.isInvalid()) return ExprError();
6678 Fn = result.get();
6679 }
6680
6681 if (Fn->getType() == Context.BoundMemberTy) {
6682 return BuildCallToMemberFunction(Scope, Fn, LParenLoc, ArgExprs,
6683 RParenLoc, ExecConfig, IsExecConfig,
6684 AllowRecovery);
6685 }
6686 }
6687
6688 // Check for overloaded calls. This can happen even in C due to extensions.
6689 if (Fn->getType() == Context.OverloadTy) {
6690 OverloadExpr::FindResult find = OverloadExpr::find(Fn);
6691
6692 // We aren't supposed to apply this logic if there's an '&' involved.
6693 if (!find.HasFormOfMemberPointer) {
6694 if (Expr::hasAnyTypeDependentArguments(ArgExprs))
6695 return CallExpr::Create(Context, Fn, ArgExprs, Context.DependentTy,
6696 VK_PRValue, RParenLoc, CurFPFeatureOverrides());
6697 OverloadExpr *ovl = find.Expression;
6698 if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(ovl))
6699 return BuildOverloadedCallExpr(
6700 Scope, Fn, ULE, LParenLoc, ArgExprs, RParenLoc, ExecConfig,
6701 /*AllowTypoCorrection=*/true, find.IsAddressOfOperand);
6702 return BuildCallToMemberFunction(Scope, Fn, LParenLoc, ArgExprs,
6703 RParenLoc, ExecConfig, IsExecConfig,
6704 AllowRecovery);
6705 }
6706 }
6707
6708 // If we're directly calling a function, get the appropriate declaration.
6709 if (Fn->getType() == Context.UnknownAnyTy) {
6710 ExprResult result = rebuildUnknownAnyFunction(*this, Fn);
6711 if (result.isInvalid()) return ExprError();
6712 Fn = result.get();
6713 }
6714
6715 Expr *NakedFn = Fn->IgnoreParens();
6716
6717 bool CallingNDeclIndirectly = false;
6718 NamedDecl *NDecl = nullptr;
6719 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(NakedFn)) {
6720 if (UnOp->getOpcode() == UO_AddrOf) {
6721 CallingNDeclIndirectly = true;
6722 NakedFn = UnOp->getSubExpr()->IgnoreParens();
6723 }
6724 }
6725
6726 if (auto *DRE = dyn_cast<DeclRefExpr>(NakedFn)) {
6727 NDecl = DRE->getDecl();
6728
6729 FunctionDecl *FDecl = dyn_cast<FunctionDecl>(NDecl);
6730 if (FDecl && FDecl->getBuiltinID()) {
6731 // Rewrite the function decl for this builtin by replacing parameters
6732 // with no explicit address space with the address space of the arguments
6733 // in ArgExprs.
6734 if ((FDecl =
6735 rewriteBuiltinFunctionDecl(this, Context, FDecl, ArgExprs))) {
6736 NDecl = FDecl;
6737 Fn = DeclRefExpr::Create(
6738 Context, FDecl->getQualifierLoc(), SourceLocation(), FDecl, false,
6739 SourceLocation(), FDecl->getType(), Fn->getValueKind(), FDecl,
6740 nullptr, DRE->isNonOdrUse());
6741 }
6742 }
6743 } else if (isa<MemberExpr>(NakedFn))
6744 NDecl = cast<MemberExpr>(NakedFn)->getMemberDecl();
6745
6746 if (FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(NDecl)) {
6747 if (CallingNDeclIndirectly && !checkAddressOfFunctionIsAvailable(
6748 FD, /*Complain=*/true, Fn->getBeginLoc()))
6749 return ExprError();
6750
6751 checkDirectCallValidity(*this, Fn, FD, ArgExprs);
6752
6753 // If this expression is a call to a builtin function in HIP device
6754 // compilation, allow a pointer-type argument to default address space to be
6755 // passed as a pointer-type parameter to a non-default address space.
6756 // If Arg is declared in the default address space and Param is declared
6757 // in a non-default address space, perform an implicit address space cast to
6758 // the parameter type.
6759 if (getLangOpts().HIP && getLangOpts().CUDAIsDevice && FD &&
6760 FD->getBuiltinID()) {
6761 for (unsigned Idx = 0; Idx < FD->param_size(); ++Idx) {
6762 ParmVarDecl *Param = FD->getParamDecl(Idx);
6763 if (!ArgExprs[Idx] || !Param || !Param->getType()->isPointerType() ||
6764 !ArgExprs[Idx]->getType()->isPointerType())
6765 continue;
6766
6767 auto ParamAS = Param->getType()->getPointeeType().getAddressSpace();
6768 auto ArgTy = ArgExprs[Idx]->getType();
6769 auto ArgPtTy = ArgTy->getPointeeType();
6770 auto ArgAS = ArgPtTy.getAddressSpace();
6771
6772 // Add address space cast if target address spaces are different
6773 bool NeedImplicitASC =
6774 ParamAS != LangAS::Default && // Pointer params in generic AS don't need special handling.
6775 ( ArgAS == LangAS::Default || // We do allow implicit conversion from generic AS
6776 // or from specific AS which has target AS matching that of Param.
6777 getASTContext().getTargetAddressSpace(ArgAS) == getASTContext().getTargetAddressSpace(ParamAS));
6778 if (!NeedImplicitASC)
6779 continue;
6780
6781 // First, ensure that the Arg is an RValue.
6782 if (ArgExprs[Idx]->isGLValue()) {
6783 ArgExprs[Idx] = ImplicitCastExpr::Create(
6784 Context, ArgExprs[Idx]->getType(), CK_NoOp, ArgExprs[Idx],
6785 nullptr, VK_PRValue, FPOptionsOverride());
6786 }
6787
6788 // Construct a new arg type with address space of Param
6789 Qualifiers ArgPtQuals = ArgPtTy.getQualifiers();
6790 ArgPtQuals.setAddressSpace(ParamAS);
6791 auto NewArgPtTy =
6792 Context.getQualifiedType(ArgPtTy.getUnqualifiedType(), ArgPtQuals);
6793 auto NewArgTy =
6794 Context.getQualifiedType(Context.getPointerType(NewArgPtTy),
6795 ArgTy.getQualifiers());
6796
6797 // Finally perform an implicit address space cast
6798 ArgExprs[Idx] = ImpCastExprToType(ArgExprs[Idx], NewArgTy,
6799 CK_AddressSpaceConversion)
6800 .get();
6801 }
6802 }
6803 }
6804
6805 if (Context.isDependenceAllowed() &&
6806 (Fn->isTypeDependent() || Expr::hasAnyTypeDependentArguments(ArgExprs))) {
6807 assert(!getLangOpts().CPlusPlus)(static_cast <bool> (!getLangOpts().CPlusPlus) ? void (
0) : __assert_fail ("!getLangOpts().CPlusPlus", "clang/lib/Sema/SemaExpr.cpp"
, 6807, __extension__ __PRETTY_FUNCTION__))
;
6808 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", 6811, __extension__ __PRETTY_FUNCTION__
))
6809 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", 6811, __extension__ __PRETTY_FUNCTION__
))
6810 [](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", 6811, __extension__ __PRETTY_FUNCTION__
))
6811 "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", 6811, __extension__ __PRETTY_FUNCTION__
))
;
6812 QualType ReturnType =
6813 llvm::isa_and_nonnull<FunctionDecl>(NDecl)
6814 ? cast<FunctionDecl>(NDecl)->getCallResultType()
6815 : Context.DependentTy;
6816 return CallExpr::Create(Context, Fn, ArgExprs, ReturnType,
6817 Expr::getValueKindForType(ReturnType), RParenLoc,
6818 CurFPFeatureOverrides());
6819 }
6820 return BuildResolvedCallExpr(Fn, NDecl, LParenLoc, ArgExprs, RParenLoc,
6821 ExecConfig, IsExecConfig);
6822}
6823
6824/// BuildBuiltinCallExpr - Create a call to a builtin function specified by Id
6825// with the specified CallArgs
6826Expr *Sema::BuildBuiltinCallExpr(SourceLocation Loc, Builtin::ID Id,
6827 MultiExprArg CallArgs) {
6828 StringRef Name = Context.BuiltinInfo.getName(Id);
6829 LookupResult R(*this, &Context.Idents.get(Name), Loc,
6830 Sema::LookupOrdinaryName);
6831 LookupName(R, TUScope, /*AllowBuiltinCreation=*/true);
6832
6833 auto *BuiltInDecl = R.getAsSingle<FunctionDecl>();
6834 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", 6834, __extension__ __PRETTY_FUNCTION__
))
;
6835
6836 ExprResult DeclRef =
6837 BuildDeclRefExpr(BuiltInDecl, BuiltInDecl->getType(), VK_LValue, Loc);
6838 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", 6838, __extension__ __PRETTY_FUNCTION__
))
;
6839
6840 ExprResult Call =
6841 BuildCallExpr(/*Scope=*/nullptr, DeclRef.get(), Loc, CallArgs, Loc);
6842
6843 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", 6843, __extension__ __PRETTY_FUNCTION__
))
;
6844 return Call.get();
6845}
6846
6847/// Parse a __builtin_astype expression.
6848///
6849/// __builtin_astype( value, dst type )
6850///
6851ExprResult Sema::ActOnAsTypeExpr(Expr *E, ParsedType ParsedDestTy,
6852 SourceLocation BuiltinLoc,
6853 SourceLocation RParenLoc) {
6854 QualType DstTy = GetTypeFromParser(ParsedDestTy);
6855 return BuildAsTypeExpr(E, DstTy, BuiltinLoc, RParenLoc);
6856}
6857
6858/// Create a new AsTypeExpr node (bitcast) from the arguments.
6859ExprResult Sema::BuildAsTypeExpr(Expr *E, QualType DestTy,
6860 SourceLocation BuiltinLoc,
6861 SourceLocation RParenLoc) {
6862 ExprValueKind VK = VK_PRValue;
6863 ExprObjectKind OK = OK_Ordinary;
6864 QualType SrcTy = E->getType();
6865 if (!SrcTy->isDependentType() &&
6866 Context.getTypeSize(DestTy) != Context.getTypeSize(SrcTy))
6867 return ExprError(
6868 Diag(BuiltinLoc, diag::err_invalid_astype_of_different_size)
6869 << DestTy << SrcTy << E->getSourceRange());
6870 return new (Context) AsTypeExpr(E, DestTy, VK, OK, BuiltinLoc, RParenLoc);
6871}
6872
6873/// ActOnConvertVectorExpr - create a new convert-vector expression from the
6874/// provided arguments.
6875///
6876/// __builtin_convertvector( value, dst type )
6877///
6878ExprResult Sema::ActOnConvertVectorExpr(Expr *E, ParsedType ParsedDestTy,
6879 SourceLocation BuiltinLoc,
6880 SourceLocation RParenLoc) {
6881 TypeSourceInfo *TInfo;
6882 GetTypeFromParser(ParsedDestTy, &TInfo);
6883 return SemaConvertVectorExpr(E, TInfo, BuiltinLoc, RParenLoc);
6884}
6885
6886/// BuildResolvedCallExpr - Build a call to a resolved expression,
6887/// i.e. an expression not of \p OverloadTy. The expression should
6888/// unary-convert to an expression of function-pointer or
6889/// block-pointer type.
6890///
6891/// \param NDecl the declaration being called, if available
6892ExprResult Sema::BuildResolvedCallExpr(Expr *Fn, NamedDecl *NDecl,
6893 SourceLocation LParenLoc,
6894 ArrayRef<Expr *> Args,
6895 SourceLocation RParenLoc, Expr *Config,
6896 bool IsExecConfig, ADLCallKind UsesADL) {
6897 FunctionDecl *FDecl = dyn_cast_or_null<FunctionDecl>(NDecl);
6898 unsigned BuiltinID = (FDecl ? FDecl->getBuiltinID() : 0);
6899
6900 // Functions with 'interrupt' attribute cannot be called directly.
6901 if (FDecl && FDecl->hasAttr<AnyX86InterruptAttr>()) {
6902 Diag(Fn->getExprLoc(), diag::err_anyx86_interrupt_called);
6903 return ExprError();
6904 }
6905
6906 // Interrupt handlers don't save off the VFP regs automatically on ARM,
6907 // so there's some risk when calling out to non-interrupt handler functions
6908 // that the callee might not preserve them. This is easy to diagnose here,
6909 // but can be very challenging to debug.
6910 // Likewise, X86 interrupt handlers may only call routines with attribute
6911 // no_caller_saved_registers since there is no efficient way to
6912 // save and restore the non-GPR state.
6913 if (auto *Caller = getCurFunctionDecl()) {
6914 if (Caller->hasAttr<ARMInterruptAttr>()) {
6915 bool VFP = Context.getTargetInfo().hasFeature("vfp");
6916 if (VFP && (!FDecl || !FDecl->hasAttr<ARMInterruptAttr>())) {
6917 Diag(Fn->getExprLoc(), diag::warn_arm_interrupt_calling_convention);
6918 if (FDecl)
6919 Diag(FDecl->getLocation(), diag::note_callee_decl) << FDecl;
6920 }
6921 }
6922 if (Caller->hasAttr<AnyX86InterruptAttr>() &&
6923 ((!FDecl || !FDecl->hasAttr<AnyX86NoCallerSavedRegistersAttr>()))) {
6924 Diag(Fn->getExprLoc(), diag::warn_anyx86_interrupt_regsave);
6925 if (FDecl)
6926 Diag(FDecl->getLocation(), diag::note_callee_decl) << FDecl;
6927 }
6928 }
6929
6930 // Promote the function operand.
6931 // We special-case function promotion here because we only allow promoting
6932 // builtin functions to function pointers in the callee of a call.
6933 ExprResult Result;
6934 QualType ResultTy;
6935 if (BuiltinID &&
6936 Fn->getType()->isSpecificBuiltinType(BuiltinType::BuiltinFn)) {
6937 // Extract the return type from the (builtin) function pointer type.
6938 // FIXME Several builtins still have setType in
6939 // Sema::CheckBuiltinFunctionCall. One should review their definitions in
6940 // Builtins.def to ensure they are correct before removing setType calls.
6941 QualType FnPtrTy = Context.getPointerType(FDecl->getType());
6942 Result = ImpCastExprToType(Fn, FnPtrTy, CK_BuiltinFnToFnPtr).get();
6943 ResultTy = FDecl->getCallResultType();
6944 } else {
6945 Result = CallExprUnaryConversions(Fn);
6946 ResultTy = Context.BoolTy;
6947 }
6948 if (Result.isInvalid())
6949 return ExprError();
6950 Fn = Result.get();
6951
6952 // Check for a valid function type, but only if it is not a builtin which
6953 // requires custom type checking. These will be handled by
6954 // CheckBuiltinFunctionCall below just after creation of the call expression.
6955 const FunctionType *FuncT = nullptr;
6956 if (!BuiltinID || !Context.BuiltinInfo.hasCustomTypechecking(BuiltinID)) {
6957 retry:
6958 if (const PointerType *PT = Fn->getType()->getAs<PointerType>()) {
6959 // C99 6.5.2.2p1 - "The expression that denotes the called function shall
6960 // have type pointer to function".
6961 FuncT = PT->getPointeeType()->getAs<FunctionType>();
6962 if (!FuncT)
6963 return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function)
6964 << Fn->getType() << Fn->getSourceRange());
6965 } else if (const BlockPointerType *BPT =
6966 Fn->getType()->getAs<BlockPointerType>()) {
6967 FuncT = BPT->getPointeeType()->castAs<FunctionType>();
6968 } else {
6969 // Handle calls to expressions of unknown-any type.
6970 if (Fn->getType() == Context.UnknownAnyTy) {
6971 ExprResult rewrite = rebuildUnknownAnyFunction(*this, Fn);
6972 if (rewrite.isInvalid())
6973 return ExprError();
6974 Fn = rewrite.get();
6975 goto retry;
6976 }
6977
6978 return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function)
6979 << Fn->getType() << Fn->getSourceRange());
6980 }
6981 }
6982
6983 // Get the number of parameters in the function prototype, if any.
6984 // We will allocate space for max(Args.size(), NumParams) arguments
6985 // in the call expression.
6986 const auto *Proto = dyn_cast_or_null<FunctionProtoType>(FuncT);
6987 unsigned NumParams = Proto ? Proto->getNumParams() : 0;
6988
6989 CallExpr *TheCall;
6990 if (Config) {
6991 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", 6992, __extension__ __PRETTY_FUNCTION__
))
6992 "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", 6992, __extension__ __PRETTY_FUNCTION__
))
;
6993 TheCall = CUDAKernelCallExpr::Create(Context, Fn, cast<CallExpr>(Config),
6994 Args, ResultTy, VK_PRValue, RParenLoc,
6995 CurFPFeatureOverrides(), NumParams);
6996 } else {
6997 TheCall =
6998 CallExpr::Create(Context, Fn, Args, ResultTy, VK_PRValue, RParenLoc,
6999 CurFPFeatureOverrides(), NumParams, UsesADL);
7000 }
7001
7002 if (!Context.isDependenceAllowed()) {
7003 // Forget about the nulled arguments since typo correction
7004 // do not handle them well.
7005 TheCall->shrinkNumArgs(Args.size());
7006 // C cannot always handle TypoExpr nodes in builtin calls and direct
7007 // function calls as their argument checking don't necessarily handle
7008 // dependent types properly, so make sure any TypoExprs have been
7009 // dealt with.
7010 ExprResult Result = CorrectDelayedTyposInExpr(TheCall);
7011 if (!Result.isUsable()) return ExprError();
7012 CallExpr *TheOldCall = TheCall;
7013 TheCall = dyn_cast<CallExpr>(Result.get());
7014 bool CorrectedTypos = TheCall != TheOldCall;
7015 if (!TheCall) return Result;
7016 Args = llvm::makeArrayRef(TheCall->getArgs(), TheCall->getNumArgs());
7017
7018 // A new call expression node was created if some typos were corrected.
7019 // However it may not have been constructed with enough storage. In this
7020 // case, rebuild the node with enough storage. The waste of space is
7021 // immaterial since this only happens when some typos were corrected.
7022 if (CorrectedTypos && Args.size() < NumParams) {
7023 if (Config)
7024 TheCall = CUDAKernelCallExpr::Create(
7025 Context, Fn, cast<CallExpr>(Config), Args, ResultTy, VK_PRValue,
7026 RParenLoc, CurFPFeatureOverrides(), NumParams);
7027 else
7028 TheCall =
7029 CallExpr::Create(Context, Fn, Args, ResultTy, VK_PRValue, RParenLoc,
7030 CurFPFeatureOverrides(), NumParams, UsesADL);
7031 }
7032 // We can now handle the nulled arguments for the default arguments.
7033 TheCall->setNumArgsUnsafe(std::max<unsigned>(Args.size(), NumParams));
7034 }
7035
7036 // Bail out early if calling a builtin with custom type checking.
7037 if (BuiltinID && Context.BuiltinInfo.hasCustomTypechecking(BuiltinID))
7038 return CheckBuiltinFunctionCall(FDecl, BuiltinID, TheCall);
7039
7040 if (getLangOpts().CUDA) {
7041 if (Config) {
7042 // CUDA: Kernel calls must be to global functions
7043 if (FDecl && !FDecl->hasAttr<CUDAGlobalAttr>())
7044 return ExprError(Diag(LParenLoc,diag::err_kern_call_not_global_function)
7045 << FDecl << Fn->getSourceRange());
7046
7047 // CUDA: Kernel function must have 'void' return type
7048 if (!FuncT->getReturnType()->isVoidType() &&
7049 !FuncT->getReturnType()->getAs<AutoType>() &&
7050 !FuncT->getReturnType()->isInstantiationDependentType())
7051 return ExprError(Diag(LParenLoc, diag::err_kern_type_not_void_return)
7052 << Fn->getType() << Fn->getSourceRange());
7053 } else {
7054 // CUDA: Calls to global functions must be configured
7055 if (FDecl && FDecl->hasAttr<CUDAGlobalAttr>())
7056 return ExprError(Diag(LParenLoc, diag::err_global_call_not_config)
7057 << FDecl << Fn->getSourceRange());
7058 }
7059 }
7060
7061 // Check for a valid return type
7062 if (CheckCallReturnType(FuncT->getReturnType(), Fn->getBeginLoc(), TheCall,
7063 FDecl))
7064 return ExprError();
7065
7066 // We know the result type of the call, set it.
7067 TheCall->setType(FuncT->getCallResultType(Context));
7068 TheCall->setValueKind(Expr::getValueKindForType(FuncT->getReturnType()));
7069
7070 if (Proto) {
7071 if (ConvertArgumentsForCall(TheCall, Fn, FDecl, Proto, Args, RParenLoc,
7072 IsExecConfig))
7073 return ExprError();
7074 } else {
7075 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", 7075, __extension__ __PRETTY_FUNCTION__
))
;
7076
7077 if (FDecl) {
7078 // Check if we have too few/too many template arguments, based
7079 // on our knowledge of the function definition.
7080 const FunctionDecl *Def = nullptr;
7081 if (FDecl->hasBody(Def) && Args.size() != Def->param_size()) {
7082 Proto = Def->getType()->getAs<FunctionProtoType>();
7083 if (!Proto || !(Proto->isVariadic() && Args.size() >= Def->param_size()))
7084 Diag(RParenLoc, diag::warn_call_wrong_number_of_arguments)
7085 << (Args.size() > Def->param_size()) << FDecl << Fn->getSourceRange();
7086 }
7087
7088 // If the function we're calling isn't a function prototype, but we have
7089 // a function prototype from a prior declaratiom, use that prototype.
7090 if (!FDecl->hasPrototype())
7091 Proto = FDecl->getType()->getAs<FunctionProtoType>();
7092 }
7093
7094 // If we still haven't found a prototype to use but there are arguments to
7095 // the call, diagnose this as calling a function without a prototype.
7096 // However, if we found a function declaration, check to see if
7097 // -Wdeprecated-non-prototype was disabled where the function was declared.
7098 // If so, we will silence the diagnostic here on the assumption that this
7099 // interface is intentional and the user knows what they're doing. We will
7100 // also silence the diagnostic if there is a function declaration but it
7101 // was implicitly defined (the user already gets diagnostics about the
7102 // creation of the implicit function declaration, so the additional warning
7103 // is not helpful).
7104 if (!Proto && !Args.empty() &&
7105 (!FDecl || (!FDecl->isImplicit() &&
7106 !Diags.isIgnored(diag::warn_strict_uses_without_prototype,
7107 FDecl->getLocation()))))
7108 Diag(LParenLoc, diag::warn_strict_uses_without_prototype)
7109 << (FDecl != nullptr) << FDecl;
7110
7111 // Promote the arguments (C99 6.5.2.2p6).
7112 for (unsigned i = 0, e = Args.size(); i != e; i++) {
7113 Expr *Arg = Args[i];
7114
7115 if (Proto && i < Proto->getNumParams()) {
7116 InitializedEntity Entity = InitializedEntity::InitializeParameter(
7117 Context, Proto->getParamType(i), Proto->isParamConsumed(i));
7118 ExprResult ArgE =
7119 PerformCopyInitialization(Entity, SourceLocation(), Arg);
7120 if (ArgE.isInvalid())
7121 return true;
7122
7123 Arg = ArgE.getAs<Expr>();
7124
7125 } else {
7126 ExprResult ArgE = DefaultArgumentPromotion(Arg);
7127
7128 if (ArgE.isInvalid())
7129 return true;
7130
7131 Arg = ArgE.getAs<Expr>();
7132 }
7133
7134 if (RequireCompleteType(Arg->getBeginLoc(), Arg->getType(),
7135 diag::err_call_incomplete_argument, Arg))
7136 return ExprError();
7137
7138 TheCall->setArg(i, Arg);
7139 }
7140 TheCall->computeDependence();
7141 }
7142
7143 if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(FDecl))
7144 if (!Method->isStatic())
7145 return ExprError(Diag(LParenLoc, diag::err_member_call_without_object)
7146 << Fn->getSourceRange());
7147
7148 // Check for sentinels
7149 if (NDecl)
7150 DiagnoseSentinelCalls(NDecl, LParenLoc, Args);
7151
7152 // Warn for unions passing across security boundary (CMSE).
7153 if (FuncT != nullptr && FuncT->getCmseNSCallAttr()) {
7154 for (unsigned i = 0, e = Args.size(); i != e; i++) {
7155 if (const auto *RT =
7156 dyn_cast<RecordType>(Args[i]->getType().getCanonicalType())) {
7157 if (RT->getDecl()->isOrContainsUnion())
7158 Diag(Args[i]->getBeginLoc(), diag::warn_cmse_nonsecure_union)
7159 << 0 << i;
7160 }
7161 }
7162 }
7163
7164 // Do special checking on direct calls to functions.
7165 if (FDecl) {
7166 if (CheckFunctionCall(FDecl, TheCall, Proto))
7167 return ExprError();
7168
7169 checkFortifiedBuiltinMemoryFunction(FDecl, TheCall);
7170
7171 if (BuiltinID)
7172 return CheckBuiltinFunctionCall(FDecl, BuiltinID, TheCall);
7173 } else if (NDecl) {
7174 if (CheckPointerCall(NDecl, TheCall, Proto))
7175 return ExprError();
7176 } else {
7177 if (CheckOtherCall(TheCall, Proto))
7178 return ExprError();
7179 }
7180
7181 return CheckForImmediateInvocation(MaybeBindToTemporary(TheCall), FDecl);
7182}
7183
7184ExprResult
7185Sema::ActOnCompoundLiteral(SourceLocation LParenLoc, ParsedType Ty,
7186 SourceLocation RParenLoc, Expr *InitExpr) {
7187 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", 7187, __extension__ __PRETTY_FUNCTION__
))
;
7188 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", 7188, __extension__ __PRETTY_FUNCTION__
))
;
7189
7190 TypeSourceInfo *TInfo;
7191 QualType literalType = GetTypeFromParser(Ty, &TInfo);
7192 if (!TInfo)
7193 TInfo = Context.getTrivialTypeSourceInfo(literalType);
7194
7195 return BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc, InitExpr);
7196}
7197
7198ExprResult
7199Sema::BuildCompoundLiteralExpr(SourceLocation LParenLoc, TypeSourceInfo *TInfo,
7200 SourceLocation RParenLoc, Expr *LiteralExpr) {
7201 QualType literalType = TInfo->getType();
7202
7203 if (literalType->isArrayType()) {
7204 if (RequireCompleteSizedType(
7205 LParenLoc, Context.getBaseElementType(literalType),
7206 diag::err_array_incomplete_or_sizeless_type,
7207 SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd())))
7208 return ExprError();
7209 if (literalType->isVariableArrayType()) {
7210 if (!tryToFixVariablyModifiedVarType(TInfo, literalType, LParenLoc,
7211 diag::err_variable_object_no_init)) {
7212 return ExprError();
7213 }
7214 }
7215 } else if (!literalType->isDependentType() &&
7216 RequireCompleteType(LParenLoc, literalType,
7217 diag::err_typecheck_decl_incomplete_type,
7218 SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd())))
7219 return ExprError();
7220
7221 InitializedEntity Entity
7222 = InitializedEntity::InitializeCompoundLiteralInit(TInfo);
7223 InitializationKind Kind
7224 = InitializationKind::CreateCStyleCast(LParenLoc,
7225 SourceRange(LParenLoc, RParenLoc),
7226 /*InitList=*/true);
7227 InitializationSequence InitSeq(*this, Entity, Kind, LiteralExpr);
7228 ExprResult Result = InitSeq.Perform(*this, Entity, Kind, LiteralExpr,
7229 &literalType);
7230 if (Result.isInvalid())
7231 return ExprError();
7232 LiteralExpr = Result.get();
7233
7234 bool isFileScope = !CurContext->isFunctionOrMethod();
7235
7236 // In C, compound literals are l-values for some reason.
7237 // For GCC compatibility, in C++, file-scope array compound literals with
7238 // constant initializers are also l-values, and compound literals are
7239 // otherwise prvalues.
7240 //
7241 // (GCC also treats C++ list-initialized file-scope array prvalues with
7242 // constant initializers as l-values, but that's non-conforming, so we don't
7243 // follow it there.)
7244 //
7245 // FIXME: It would be better to handle the lvalue cases as materializing and
7246 // lifetime-extending a temporary object, but our materialized temporaries
7247 // representation only supports lifetime extension from a variable, not "out
7248 // of thin air".
7249 // FIXME: For C++, we might want to instead lifetime-extend only if a pointer
7250 // is bound to the result of applying array-to-pointer decay to the compound
7251 // literal.
7252 // FIXME: GCC supports compound literals of reference type, which should
7253 // obviously have a value kind derived from the kind of reference involved.
7254 ExprValueKind VK =
7255 (getLangOpts().CPlusPlus && !(isFileScope && literalType->isArrayType()))
7256 ? VK_PRValue
7257 : VK_LValue;
7258
7259 if (isFileScope)
7260 if (auto ILE = dyn_cast<InitListExpr>(LiteralExpr))
7261 for (unsigned i = 0, j = ILE->getNumInits(); i != j; i++) {
7262 Expr *Init = ILE->getInit(i);
7263 ILE->setInit(i, ConstantExpr::Create(Context, Init));
7264 }
7265
7266 auto *E = new (Context) CompoundLiteralExpr(LParenLoc, TInfo, literalType,
7267 VK, LiteralExpr, isFileScope);
7268 if (isFileScope) {
7269 if (!LiteralExpr->isTypeDependent() &&
7270 !LiteralExpr->isValueDependent() &&
7271 !literalType->isDependentType()) // C99 6.5.2.5p3
7272 if (CheckForConstantInitializer(LiteralExpr, literalType))
7273 return ExprError();
7274 } else if (literalType.getAddressSpace() != LangAS::opencl_private &&
7275 literalType.getAddressSpace() != LangAS::Default) {
7276 // Embedded-C extensions to C99 6.5.2.5:
7277 // "If the compound literal occurs inside the body of a function, the
7278 // type name shall not be qualified by an address-space qualifier."
7279 Diag(LParenLoc, diag::err_compound_literal_with_address_space)
7280 << SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd());
7281 return ExprError();
7282 }
7283
7284 if (!isFileScope && !getLangOpts().CPlusPlus) {
7285 // Compound literals that have automatic storage duration are destroyed at
7286 // the end of the scope in C; in C++, they're just temporaries.
7287
7288 // Emit diagnostics if it is or contains a C union type that is non-trivial
7289 // to destruct.
7290 if (E->getType().hasNonTrivialToPrimitiveDestructCUnion())
7291 checkNonTrivialCUnion(E->getType(), E->getExprLoc(),
7292 NTCUC_CompoundLiteral, NTCUK_Destruct);
7293
7294 // Diagnose jumps that enter or exit the lifetime of the compound literal.
7295 if (literalType.isDestructedType()) {
7296 Cleanup.setExprNeedsCleanups(true);
7297 ExprCleanupObjects.push_back(E);
7298 getCurFunction()->setHasBranchProtectedScope();
7299 }
7300 }
7301
7302 if (E->getType().hasNonTrivialToPrimitiveDefaultInitializeCUnion() ||
7303 E->getType().hasNonTrivialToPrimitiveCopyCUnion())
7304 checkNonTrivialCUnionInInitializer(E->getInitializer(),
7305 E->getInitializer()->getExprLoc());
7306
7307 return MaybeBindToTemporary(E);
7308}
7309
7310ExprResult
7311Sema::ActOnInitList(SourceLocation LBraceLoc, MultiExprArg InitArgList,
7312 SourceLocation RBraceLoc) {
7313 // Only produce each kind of designated initialization diagnostic once.
7314 SourceLocation FirstDesignator;
7315 bool DiagnosedArrayDesignator = false;
7316 bool DiagnosedNestedDesignator = false;
7317 bool DiagnosedMixedDesignator = false;
7318
7319 // Check that any designated initializers are syntactically valid in the
7320 // current language mode.
7321 for (unsigned I = 0, E = InitArgList.size(); I != E; ++I) {
7322 if (auto *DIE = dyn_cast<DesignatedInitExpr>(InitArgList[I])) {
7323 if (FirstDesignator.isInvalid())
7324 FirstDesignator = DIE->getBeginLoc();
7325
7326 if (!getLangOpts().CPlusPlus)
7327 break;
7328
7329 if (!DiagnosedNestedDesignator && DIE->size() > 1) {
7330 DiagnosedNestedDesignator = true;
7331 Diag(DIE->getBeginLoc(), diag::ext_designated_init_nested)
7332 << DIE->getDesignatorsSourceRange();
7333 }
7334
7335 for (auto &Desig : DIE->designators()) {
7336 if (!Desig.isFieldDesignator() && !DiagnosedArrayDesignator) {
7337 DiagnosedArrayDesignator = true;
7338 Diag(Desig.getBeginLoc(), diag::ext_designated_init_array)
7339 << Desig.getSourceRange();
7340 }
7341 }
7342
7343 if (!DiagnosedMixedDesignator &&
7344 !isa<DesignatedInitExpr>(InitArgList[0])) {
7345 DiagnosedMixedDesignator = true;
7346 Diag(DIE->getBeginLoc(), diag::ext_designated_init_mixed)
7347 << DIE->getSourceRange();
7348 Diag(InitArgList[0]->getBeginLoc(), diag::note_designated_init_mixed)
7349 << InitArgList[0]->getSourceRange();
7350 }
7351 } else if (getLangOpts().CPlusPlus && !DiagnosedMixedDesignator &&
7352 isa<DesignatedInitExpr>(InitArgList[0])) {
7353 DiagnosedMixedDesignator = true;
7354 auto *DIE = cast<DesignatedInitExpr>(InitArgList[0]);
7355 Diag(DIE->getBeginLoc(), diag::ext_designated_init_mixed)
7356 << DIE->getSourceRange();
7357 Diag(InitArgList[I]->getBeginLoc(), diag::note_designated_init_mixed)
7358 << InitArgList[I]->getSourceRange();
7359 }
7360 }
7361
7362 if (FirstDesignator.isValid()) {
7363 // Only diagnose designated initiaization as a C++20 extension if we didn't
7364 // already diagnose use of (non-C++20) C99 designator syntax.
7365 if (getLangOpts().CPlusPlus && !DiagnosedArrayDesignator &&
7366 !DiagnosedNestedDesignator && !DiagnosedMixedDesignator) {
7367 Diag(FirstDesignator, getLangOpts().CPlusPlus20
7368 ? diag::warn_cxx17_compat_designated_init
7369 : diag::ext_cxx_designated_init);
7370 } else if (!getLangOpts().CPlusPlus && !getLangOpts().C99) {
7371 Diag(FirstDesignator, diag::ext_designated_init);
7372 }
7373 }
7374
7375 return BuildInitList(LBraceLoc, InitArgList, RBraceLoc);
7376}
7377
7378ExprResult
7379Sema::BuildInitList(SourceLocation LBraceLoc, MultiExprArg InitArgList,
7380 SourceLocation RBraceLoc) {
7381 // Semantic analysis for initializers is done by ActOnDeclarator() and
7382 // CheckInitializer() - it requires knowledge of the object being initialized.
7383
7384 // Immediately handle non-overload placeholders. Overloads can be
7385 // resolved contextually, but everything else here can't.
7386 for (unsigned I = 0, E = InitArgList.size(); I != E; ++I) {
7387 if (InitArgList[I]->getType()->isNonOverloadPlaceholderType()) {
7388 ExprResult result = CheckPlaceholderExpr(InitArgList[I]);
7389
7390 // Ignore failures; dropping the entire initializer list because
7391 // of one failure would be terrible for indexing/etc.
7392 if (result.isInvalid()) continue;
7393
7394 InitArgList[I] = result.get();
7395 }
7396 }
7397
7398 InitListExpr *E = new (Context) InitListExpr(Context, LBraceLoc, InitArgList,
7399 RBraceLoc);
7400 E->setType(Context.VoidTy); // FIXME: just a place holder for now.
7401 return E;
7402}
7403
7404/// Do an explicit extend of the given block pointer if we're in ARC.
7405void Sema::maybeExtendBlockObject(ExprResult &E) {
7406 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", 7406, __extension__ __PRETTY_FUNCTION__
))
;
7407 assert(E.get()->isPRValue())(static_cast <bool> (E.get()->isPRValue()) ? void (0
) : __assert_fail ("E.get()->isPRValue()", "clang/lib/Sema/SemaExpr.cpp"
, 7407, __extension__ __PRETTY_FUNCTION__))
;
7408
7409 // Only do this in an r-value context.
7410 if (!getLangOpts().ObjCAutoRefCount) return;
7411
7412 E = ImplicitCastExpr::Create(
7413 Context, E.get()->getType(), CK_ARCExtendBlockObject, E.get(),
7414 /*base path*/ nullptr, VK_PRValue, FPOptionsOverride());
7415 Cleanup.setExprNeedsCleanups(true);
7416}
7417
7418/// Prepare a conversion of the given expression to an ObjC object
7419/// pointer type.
7420CastKind Sema::PrepareCastToObjCObjectPointer(ExprResult &E) {
7421 QualType type = E.get()->getType();
7422 if (type->isObjCObjectPointerType()) {
7423 return CK_BitCast;
7424 } else if (type->isBlockPointerType()) {
7425 maybeExtendBlockObject(E);
7426 return CK_BlockPointerToObjCPointerCast;
7427 } else {
7428 assert(type->isPointerType())(static_cast <bool> (type->isPointerType()) ? void (
0) : __assert_fail ("type->isPointerType()", "clang/lib/Sema/SemaExpr.cpp"
, 7428, __extension__ __PRETTY_FUNCTION__))
;
7429 return CK_CPointerToObjCPointerCast;
7430 }
7431}
7432
7433/// Prepares for a scalar cast, performing all the necessary stages
7434/// except the final cast and returning the kind required.
7435CastKind Sema::PrepareScalarCast(ExprResult &Src, QualType DestTy) {
7436 // Both Src and Dest are scalar types, i.e. arithmetic or pointer.
7437 // Also, callers should have filtered out the invalid cases with
7438 // pointers. Everything else should be possible.
7439
7440 QualType SrcTy = Src.get()->getType();
7441 if (Context.hasSameUnqualifiedType(SrcTy, DestTy))
7442 return CK_NoOp;
7443
7444 switch (Type::ScalarTypeKind SrcKind = SrcTy->getScalarTypeKind()) {
7445 case Type::STK_MemberPointer:
7446 llvm_unreachable("member pointer type in C")::llvm::llvm_unreachable_internal("member pointer type in C",
"clang/lib/Sema/SemaExpr.cpp", 7446)
;
7447
7448 case Type::STK_CPointer:
7449 case Type::STK_BlockPointer:
7450 case Type::STK_ObjCObjectPointer:
7451 switch (DestTy->getScalarTypeKind()) {
7452 case Type::STK_CPointer: {
7453 LangAS SrcAS = SrcTy->getPointeeType().getAddressSpace();
7454 LangAS DestAS = DestTy->getPointeeType().getAddressSpace();
7455 if (SrcAS != DestAS)
7456 return CK_AddressSpaceConversion;
7457 if (Context.hasCvrSimilarType(SrcTy, DestTy))
7458 return CK_NoOp;
7459 return CK_BitCast;
7460 }
7461 case Type::STK_BlockPointer:
7462 return (SrcKind == Type::STK_BlockPointer
7463 ? CK_BitCast : CK_AnyPointerToBlockPointerCast);
7464 case Type::STK_ObjCObjectPointer:
7465 if (SrcKind == Type::STK_ObjCObjectPointer)
7466 return CK_BitCast;
7467 if (SrcKind == Type::STK_CPointer)
7468 return CK_CPointerToObjCPointerCast;
7469 maybeExtendBlockObject(Src);
7470 return CK_BlockPointerToObjCPointerCast;
7471 case Type::STK_Bool:
7472 return CK_PointerToBoolean;
7473 case Type::STK_Integral:
7474 return CK_PointerToIntegral;
7475 case Type::STK_Floating:
7476 case Type::STK_FloatingComplex:
7477 case Type::STK_IntegralComplex:
7478 case Type::STK_MemberPointer:
7479 case Type::STK_FixedPoint:
7480 llvm_unreachable("illegal cast from pointer")::llvm::llvm_unreachable_internal("illegal cast from pointer"
, "clang/lib/Sema/SemaExpr.cpp", 7480)
;
7481 }
7482 llvm_unreachable("Should have returned before this")::llvm::llvm_unreachable_internal("Should have returned before this"
, "clang/lib/Sema/SemaExpr.cpp", 7482)
;
7483
7484 case Type::STK_FixedPoint:
7485 switch (DestTy->getScalarTypeKind()) {
7486 case Type::STK_FixedPoint:
7487 return CK_FixedPointCast;
7488 case Type::STK_Bool:
7489 return CK_FixedPointToBoolean;
7490 case Type::STK_Integral:
7491 return CK_FixedPointToIntegral;
7492 case Type::STK_Floating:
7493 return CK_FixedPointToFloating;
7494 case Type::STK_IntegralComplex:
7495 case Type::STK_FloatingComplex:
7496 Diag(Src.get()->getExprLoc(),
7497 diag::err_unimplemented_conversion_with_fixed_point_type)
7498 << DestTy;
7499 return CK_IntegralCast;
7500 case Type::STK_CPointer:
7501 case Type::STK_ObjCObjectPointer:
7502 case Type::STK_BlockPointer:
7503 case Type::STK_MemberPointer:
7504 llvm_unreachable("illegal cast to pointer type")::llvm::llvm_unreachable_internal("illegal cast to pointer type"
, "clang/lib/Sema/SemaExpr.cpp", 7504)
;
7505 }
7506 llvm_unreachable("Should have returned before this")::llvm::llvm_unreachable_internal("Should have returned before this"
, "clang/lib/Sema/SemaExpr.cpp", 7506)
;
7507
7508 case Type::STK_Bool: // casting from bool is like casting from an integer
7509 case Type::STK_Integral:
7510 switch (DestTy->getScalarTypeKind()) {
7511 case Type::STK_CPointer:
7512 case Type::STK_ObjCObjectPointer:
7513 case Type::STK_BlockPointer:
7514 if (Src.get()->isNullPointerConstant(Context,
7515 Expr::NPC_ValueDependentIsNull))
7516 return CK_NullToPointer;
7517 return CK_IntegralToPointer;
7518 case Type::STK_Bool:
7519 return CK_IntegralToBoolean;
7520 case Type::STK_Integral:
7521 return CK_IntegralCast;
7522 case Type::STK_Floating:
7523 return CK_IntegralToFloating;
7524 case Type::STK_IntegralComplex:
7525 Src = ImpCastExprToType(Src.get(),
7526 DestTy->castAs<ComplexType>()->getElementType(),
7527 CK_IntegralCast);
7528 return CK_IntegralRealToComplex;
7529 case Type::STK_FloatingComplex:
7530 Src = ImpCastExprToType(Src.get(),
7531 DestTy->castAs<ComplexType>()->getElementType(),
7532 CK_IntegralToFloating);
7533 return CK_FloatingRealToComplex;
7534 case Type::STK_MemberPointer:
7535 llvm_unreachable("member pointer type in C")::llvm::llvm_unreachable_internal("member pointer type in C",
"clang/lib/Sema/SemaExpr.cpp", 7535)
;
7536 case Type::STK_FixedPoint:
7537 return CK_IntegralToFixedPoint;
7538 }
7539 llvm_unreachable("Should have returned before this")::llvm::llvm_unreachable_internal("Should have returned before this"
, "clang/lib/Sema/SemaExpr.cpp", 7539)
;
7540
7541 case Type::STK_Floating:
7542 switch (DestTy->getScalarTypeKind()) {
7543 case Type::STK_Floating:
7544 return CK_FloatingCast;
7545 case Type::STK_Bool:
7546 return CK_FloatingToBoolean;
7547 case Type::STK_Integral:
7548 return CK_FloatingToIntegral;
7549 case Type::STK_FloatingComplex:
7550 Src = ImpCastExprToType(Src.get(),
7551 DestTy->castAs<ComplexType>()->getElementType(),
7552 CK_FloatingCast);
7553 return CK_FloatingRealToComplex;
7554 case Type::STK_IntegralComplex:
7555 Src = ImpCastExprToType(Src.get(),
7556 DestTy->castAs<ComplexType>()->getElementType(),
7557 CK_FloatingToIntegral);
7558 return CK_IntegralRealToComplex;
7559 case Type::STK_CPointer:
7560 case Type::STK_ObjCObjectPointer:
7561 case Type::STK_BlockPointer:
7562 llvm_unreachable("valid float->pointer cast?")::llvm::llvm_unreachable_internal("valid float->pointer cast?"
, "clang/lib/Sema/SemaExpr.cpp", 7562)
;
7563 case Type::STK_MemberPointer:
7564 llvm_unreachable("member pointer type in C")::llvm::llvm_unreachable_internal("member pointer type in C",
"clang/lib/Sema/SemaExpr.cpp", 7564)
;
7565 case Type::STK_FixedPoint:
7566 return CK_FloatingToFixedPoint;
7567 }
7568 llvm_unreachable("Should have returned before this")::llvm::llvm_unreachable_internal("Should have returned before this"
, "clang/lib/Sema/SemaExpr.cpp", 7568)
;
7569
7570 case Type::STK_FloatingComplex:
7571 switch (DestTy->getScalarTypeKind()) {
7572 case Type::STK_FloatingComplex:
7573 return CK_FloatingComplexCast;
7574 case Type::STK_IntegralComplex:
7575 return CK_FloatingComplexToIntegralComplex;
7576 case Type::STK_Floating: {
7577 QualType ET = SrcTy->castAs<ComplexType>()->getElementType();
7578 if (Context.hasSameType(ET, DestTy))
7579 return CK_FloatingComplexToReal;
7580 Src = ImpCastExprToType(Src.get(), ET, CK_FloatingComplexToReal);
7581 return CK_FloatingCast;
7582 }
7583 case Type::STK_Bool:
7584 return CK_FloatingComplexToBoolean;
7585 case Type::STK_Integral:
7586 Src = ImpCastExprToType(Src.get(),
7587 SrcTy->castAs<ComplexType>()->getElementType(),
7588 CK_FloatingComplexToReal);
7589 return CK_FloatingToIntegral;
7590 case Type::STK_CPointer:
7591 case Type::STK_ObjCObjectPointer:
7592 case Type::STK_BlockPointer:
7593 llvm_unreachable("valid complex float->pointer cast?")::llvm::llvm_unreachable_internal("valid complex float->pointer cast?"
, "clang/lib/Sema/SemaExpr.cpp", 7593)
;
7594 case Type::STK_MemberPointer:
7595 llvm_unreachable("member pointer type in C")::llvm::llvm_unreachable_internal("member pointer type in C",
"clang/lib/Sema/SemaExpr.cpp", 7595)
;
7596 case Type::STK_FixedPoint:
7597 Diag(Src.get()->getExprLoc(),
7598 diag::err_unimplemented_conversion_with_fixed_point_type)
7599 << SrcTy;
7600 return CK_IntegralCast;
7601 }
7602 llvm_unreachable("Should have returned before this")::llvm::llvm_unreachable_internal("Should have returned before this"
, "clang/lib/Sema/SemaExpr.cpp", 7602)
;
7603
7604 case Type::STK_IntegralComplex:
7605 switch (DestTy->getScalarTypeKind()) {
7606 case Type::STK_FloatingComplex:
7607 return CK_IntegralComplexToFloatingComplex;
7608 case Type::STK_IntegralComplex:
7609 return CK_IntegralComplexCast;
7610 case Type::STK_Integral: {
7611 QualType ET = SrcTy->castAs<ComplexType>()->getElementType();
7612 if (Context.hasSameType(ET, DestTy))
7613 return CK_IntegralComplexToReal;
7614 Src = ImpCastExprToType(Src.get(), ET, CK_IntegralComplexToReal);
7615 return CK_IntegralCast;
7616 }
7617 case Type::STK_Bool:
7618 return CK_IntegralComplexToBoolean;
7619 case Type::STK_Floating:
7620 Src = ImpCastExprToType(Src.get(),
7621 SrcTy->castAs<ComplexType>()->getElementType(),
7622 CK_IntegralComplexToReal);
7623 return CK_IntegralToFloating;
7624 case Type::STK_CPointer:
7625 case Type::STK_ObjCObjectPointer:
7626 case Type::STK_BlockPointer:
7627 llvm_unreachable("valid complex int->pointer cast?")::llvm::llvm_unreachable_internal("valid complex int->pointer cast?"
, "clang/lib/Sema/SemaExpr.cpp", 7627)
;
7628 case Type::STK_MemberPointer:
7629 llvm_unreachable("member pointer type in C")::llvm::llvm_unreachable_internal("member pointer type in C",
"clang/lib/Sema/SemaExpr.cpp", 7629)
;
7630 case Type::STK_FixedPoint:
7631 Diag(Src.get()->getExprLoc(),
7632 diag::err_unimplemented_conversion_with_fixed_point_type)
7633 << SrcTy;
7634 return CK_IntegralCast;
7635 }
7636 llvm_unreachable("Should have returned before this")::llvm::llvm_unreachable_internal("Should have returned before this"
, "clang/lib/Sema/SemaExpr.cpp", 7636)
;
7637 }
7638
7639 llvm_unreachable("Unhandled scalar cast")::llvm::llvm_unreachable_internal("Unhandled scalar cast", "clang/lib/Sema/SemaExpr.cpp"
, 7639)
;
7640}
7641
7642static bool breakDownVectorType(QualType type, uint64_t &len,
7643 QualType &eltType) {
7644 // Vectors are simple.
7645 if (const VectorType *vecType = type->getAs<VectorType>()) {
7646 len = vecType->getNumElements();
7647 eltType = vecType->getElementType();
7648 assert(eltType->isScalarType())(static_cast <bool> (eltType->isScalarType()) ? void
(0) : __assert_fail ("eltType->isScalarType()", "clang/lib/Sema/SemaExpr.cpp"
, 7648, __extension__ __PRETTY_FUNCTION__))
;
7649 return true;
7650 }
7651
7652 // We allow lax conversion to and from non-vector types, but only if
7653 // they're real types (i.e. non-complex, non-pointer scalar types).
7654 if (!type->isRealType()) return false;
7655
7656 len = 1;
7657 eltType = type;
7658 return true;
7659}
7660
7661/// Are the two types SVE-bitcast-compatible types? I.e. is bitcasting from the
7662/// first SVE type (e.g. an SVE VLAT) to the second type (e.g. an SVE VLST)
7663/// allowed?
7664///
7665/// This will also return false if the two given types do not make sense from
7666/// the perspective of SVE bitcasts.
7667bool Sema::isValidSveBitcast(QualType srcTy, QualType destTy) {
7668 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", 7668, __extension__ __PRETTY_FUNCTION__
))
;
7669
7670 auto ValidScalableConversion = [](QualType FirstType, QualType SecondType) {
7671 if (!FirstType->isSizelessBuiltinType())
7672 return false;
7673
7674 const auto *VecTy = SecondType->getAs<VectorType>();
7675 return VecTy &&
7676 VecTy->getVectorKind() == VectorType::SveFixedLengthDataVector;
7677 };
7678
7679 return ValidScalableConversion(srcTy, destTy) ||
7680 ValidScalableConversion(destTy, srcTy);
7681}
7682
7683/// Are the two types matrix types and do they have the same dimensions i.e.
7684/// do they have the same number of rows and the same number of columns?
7685bool Sema::areMatrixTypesOfTheSameDimension(QualType srcTy, QualType destTy) {
7686 if (!destTy->isMatrixType() || !srcTy->isMatrixType())
3
Taking false branch
7687 return false;
7688
7689 const ConstantMatrixType *matSrcType = srcTy->getAs<ConstantMatrixType>();
4
Assuming the object is not a 'ConstantMatrixType'
5
'matSrcType' initialized to a null pointer value
7690 const ConstantMatrixType *matDestType = destTy->getAs<ConstantMatrixType>();
6
Assuming the object is not a 'ConstantMatrixType'
7691
7692 return matSrcType->getNumRows() == matDestType->getNumRows() &&
7
Called C++ object pointer is null
7693 matSrcType->getNumColumns() == matDestType->getNumColumns();
7694}
7695
7696bool Sema::areVectorTypesSameSize(QualType SrcTy, QualType DestTy) {
7697 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", 7697, __extension__ __PRETTY_FUNCTION__
))
;
7698
7699 uint64_t SrcLen, DestLen;
7700 QualType SrcEltTy, DestEltTy;
7701 if (!breakDownVectorType(SrcTy, SrcLen, SrcEltTy))
7702 return false;
7703 if (!breakDownVectorType(DestTy, DestLen, DestEltTy))
7704 return false;
7705
7706 // ASTContext::getTypeSize will return the size rounded up to a
7707 // power of 2, so instead of using that, we need to use the raw
7708 // element size multiplied by the element count.
7709 uint64_t SrcEltSize = Context.getTypeSize(SrcEltTy);
7710 uint64_t DestEltSize = Context.getTypeSize(DestEltTy);
7711
7712 return (SrcLen * SrcEltSize == DestLen * DestEltSize);
7713}
7714
7715/// Are the two types lax-compatible vector types? That is, given
7716/// that one of them is a vector, do they have equal storage sizes,
7717/// where the storage size is the number of elements times the element
7718/// size?
7719///
7720/// This will also return false if either of the types is neither a
7721/// vector nor a real type.
7722bool Sema::areLaxCompatibleVectorTypes(QualType srcTy, QualType destTy) {
7723 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", 7723, __extension__ __PRETTY_FUNCTION__
))
;
7724
7725 // Disallow lax conversions between scalars and ExtVectors (these
7726 // conversions are allowed for other vector types because common headers
7727 // depend on them). Most scalar OP ExtVector cases are handled by the
7728 // splat path anyway, which does what we want (convert, not bitcast).
7729 // What this rules out for ExtVectors is crazy things like char4*float.
7730 if (srcTy->isScalarType() && destTy->isExtVectorType()) return false;
7731 if (destTy->isScalarType() && srcTy->isExtVectorType()) return false;
7732
7733 return areVectorTypesSameSize(srcTy, destTy);
7734}
7735
7736/// Is this a legal conversion between two types, one of which is
7737/// known to be a vector type?
7738bool Sema::isLaxVectorConversion(QualType srcTy, QualType destTy) {
7739 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", 7739, __extension__ __PRETTY_FUNCTION__
))
;
7740
7741 switch (Context.getLangOpts().getLaxVectorConversions()) {
7742 case LangOptions::LaxVectorConversionKind::None:
7743 return false;
7744
7745 case LangOptions::LaxVectorConversionKind::Integer:
7746 if (!srcTy->isIntegralOrEnumerationType()) {
7747 auto *Vec = srcTy->getAs<VectorType>();
7748 if (!Vec || !Vec->getElementType()->isIntegralOrEnumerationType())
7749 return false;
7750 }
7751 if (!destTy->isIntegralOrEnumerationType()) {
7752 auto *Vec = destTy->getAs<VectorType>();
7753 if (!Vec || !Vec->getElementType()->isIntegralOrEnumerationType())
7754 return false;
7755 }
7756 // OK, integer (vector) -> integer (vector) bitcast.
7757 break;
7758
7759 case LangOptions::LaxVectorConversionKind::All:
7760 break;
7761 }
7762
7763 return areLaxCompatibleVectorTypes(srcTy, destTy);
7764}
7765
7766bool Sema::CheckMatrixCast(SourceRange R, QualType DestTy, QualType SrcTy,
7767 CastKind &Kind) {
7768 if (SrcTy->isMatrixType() && DestTy->isMatrixType()) {
1
Taking true branch
7769 if (!areMatrixTypesOfTheSameDimension(SrcTy, DestTy)) {
2
Calling 'Sema::areMatrixTypesOfTheSameDimension'
7770 return Diag(R.getBegin(), diag::err_invalid_conversion_between_matrixes)
7771 << DestTy << SrcTy << R;
7772 }
7773 } else if (SrcTy->isMatrixType()) {
7774 return Diag(R.getBegin(),
7775 diag::err_invalid_conversion_between_matrix_and_type)
7776 << SrcTy << DestTy << R;
7777 } else if (DestTy->isMatrixType()) {
7778 return Diag(R.getBegin(),
7779 diag::err_invalid_conversion_between_matrix_and_type)
7780 << DestTy << SrcTy << R;
7781 }
7782
7783 Kind = CK_MatrixCast;
7784 return false;
7785}
7786
7787bool Sema::CheckVectorCast(SourceRange R, QualType VectorTy, QualType Ty,
7788 CastKind &Kind) {
7789 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", 7789, __extension__ __PRETTY_FUNCTION__
))
;
7790
7791 if (Ty->isVectorType() || Ty->isIntegralType(Context)) {
7792 if (!areLaxCompatibleVectorTypes(Ty, VectorTy))
7793 return Diag(R.getBegin(),
7794 Ty->isVectorType() ?
7795 diag::err_invalid_conversion_between_vectors :
7796 diag::err_invalid_conversion_between_vector_and_integer)
7797 << VectorTy << Ty << R;
7798 } else
7799 return Diag(R.getBegin(),
7800 diag::err_invalid_conversion_between_vector_and_scalar)
7801 << VectorTy << Ty << R;
7802
7803 Kind = CK_BitCast;
7804 return false;
7805}
7806
7807ExprResult Sema::prepareVectorSplat(QualType VectorTy, Expr *SplattedExpr) {
7808 QualType DestElemTy = VectorTy->castAs<VectorType>()->getElementType();
7809
7810 if (DestElemTy == SplattedExpr->getType())
7811 return SplattedExpr;
7812
7813 assert(DestElemTy->isFloatingType() ||(static_cast <bool> (DestElemTy->isFloatingType() ||
DestElemTy->isIntegralOrEnumerationType()) ? void (0) : __assert_fail
("DestElemTy->isFloatingType() || DestElemTy->isIntegralOrEnumerationType()"
, "clang/lib/Sema/SemaExpr.cpp", 7814, __extension__ __PRETTY_FUNCTION__
))
7814 DestElemTy->isIntegralOrEnumerationType())(static_cast <bool> (DestElemTy->isFloatingType() ||
DestElemTy->isIntegralOrEnumerationType()) ? void (0) : __assert_fail
("DestElemTy->isFloatingType() || DestElemTy->isIntegralOrEnumerationType()"
, "clang/lib/Sema/SemaExpr.cpp", 7814, __extension__ __PRETTY_FUNCTION__
))
;
7815
7816 CastKind CK;
7817 if (VectorTy->isExtVectorType() && SplattedExpr->getType()->isBooleanType()) {
7818 // OpenCL requires that we convert `true` boolean expressions to -1, but
7819 // only when splatting vectors.
7820 if (DestElemTy->isFloatingType()) {
7821 // To avoid having to have a CK_BooleanToSignedFloating cast kind, we cast
7822 // in two steps: boolean to signed integral, then to floating.
7823 ExprResult CastExprRes = ImpCastExprToType(SplattedExpr, Context.IntTy,
7824 CK_BooleanToSignedIntegral);
7825 SplattedExpr = CastExprRes.get();
7826 CK = CK_IntegralToFloating;
7827 } else {
7828 CK = CK_BooleanToSignedIntegral;
7829 }
7830 } else {
7831 ExprResult CastExprRes = SplattedExpr;
7832 CK = PrepareScalarCast(CastExprRes, DestElemTy);
7833 if (CastExprRes.isInvalid())
7834 return ExprError();
7835 SplattedExpr = CastExprRes.get();
7836 }
7837 return ImpCastExprToType(SplattedExpr, DestElemTy, CK);
7838}
7839
7840ExprResult Sema::CheckExtVectorCast(SourceRange R, QualType DestTy,
7841 Expr *CastExpr, CastKind &Kind) {
7842 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", 7842, __extension__ __PRETTY_FUNCTION__
))
;
7843
7844 QualType SrcTy = CastExpr->getType();
7845
7846 // If SrcTy is a VectorType, the total size must match to explicitly cast to
7847 // an ExtVectorType.
7848 // In OpenCL, casts between vectors of different types are not allowed.
7849 // (See OpenCL 6.2).
7850 if (SrcTy->isVectorType()) {
7851 if (!areLaxCompatibleVectorTypes(SrcTy, DestTy) ||
7852 (getLangOpts().OpenCL &&
7853 !Context.hasSameUnqualifiedType(DestTy, SrcTy))) {
7854 Diag(R.getBegin(),diag::err_invalid_conversion_between_ext_vectors)
7855 << DestTy << SrcTy << R;
7856 return ExprError();
7857 }
7858 Kind = CK_BitCast;
7859 return CastExpr;
7860 }
7861
7862 // All non-pointer scalars can be cast to ExtVector type. The appropriate
7863 // conversion will take place first from scalar to elt type, and then
7864 // splat from elt type to vector.
7865 if (SrcTy->isPointerType())
7866 return Diag(R.getBegin(),
7867 diag::err_invalid_conversion_between_vector_and_scalar)
7868 << DestTy << SrcTy << R;
7869
7870 Kind = CK_VectorSplat;
7871 return prepareVectorSplat(DestTy, CastExpr);
7872}
7873
7874ExprResult
7875Sema::ActOnCastExpr(Scope *S, SourceLocation LParenLoc,
7876 Declarator &D, ParsedType &Ty,
7877 SourceLocation RParenLoc, Expr *CastExpr) {
7878 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", 7879, __extension__ __PRETTY_FUNCTION__
))
7879 "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", 7879, __extension__ __PRETTY_FUNCTION__
))
;
7880
7881 TypeSourceInfo *castTInfo = GetTypeForDeclaratorCast(D, CastExpr->getType());
7882 if (D.isInvalidType())
7883 return ExprError();
7884
7885 if (getLangOpts().CPlusPlus) {
7886 // Check that there are no default arguments (C++ only).
7887 CheckExtraCXXDefaultArguments(D);
7888 } else {
7889 // Make sure any TypoExprs have been dealt with.
7890 ExprResult Res = CorrectDelayedTyposInExpr(CastExpr);
7891 if (!Res.isUsable())
7892 return ExprError();
7893 CastExpr = Res.get();
7894 }
7895
7896 checkUnusedDeclAttributes(D);
7897
7898 QualType castType = castTInfo->getType();
7899 Ty = CreateParsedType(castType, castTInfo);
7900
7901 bool isVectorLiteral = false;
7902
7903 // Check for an altivec or OpenCL literal,
7904 // i.e. all the elements are integer constants.
7905 ParenExpr *PE = dyn_cast<ParenExpr>(CastExpr);
7906 ParenListExpr *PLE = dyn_cast<ParenListExpr>(CastExpr);
7907 if ((getLangOpts().AltiVec || getLangOpts().ZVector || getLangOpts().OpenCL)
7908 && castType->isVectorType() && (PE || PLE)) {
7909 if (PLE && PLE->getNumExprs() == 0) {
7910 Diag(PLE->getExprLoc(), diag::err_altivec_empty_initializer);
7911 return ExprError();
7912 }
7913 if (PE || PLE->getNumExprs() == 1) {
7914 Expr *E = (PE ? PE->getSubExpr() : PLE->getExpr(0));
7915 if (!E->isTypeDependent() && !E->getType()->isVectorType())
7916 isVectorLiteral = true;
7917 }
7918 else
7919 isVectorLiteral = true;
7920 }
7921
7922 // If this is a vector initializer, '(' type ')' '(' init, ..., init ')'
7923 // then handle it as such.
7924 if (isVectorLiteral)
7925 return BuildVectorLiteral(LParenLoc, RParenLoc, CastExpr, castTInfo);
7926
7927 // If the Expr being casted is a ParenListExpr, handle it specially.
7928 // This is not an AltiVec-style cast, so turn the ParenListExpr into a
7929 // sequence of BinOp comma operators.
7930 if (isa<ParenListExpr>(CastExpr)) {
7931 ExprResult Result = MaybeConvertParenListExprToParenExpr(S, CastExpr);
7932 if (Result.isInvalid()) return ExprError();
7933 CastExpr = Result.get();
7934 }
7935
7936 if (getLangOpts().CPlusPlus && !castType->isVoidType())
7937 Diag(LParenLoc, diag::warn_old_style_cast) << CastExpr->getSourceRange();
7938
7939 CheckTollFreeBridgeCast(castType, CastExpr);
7940
7941 CheckObjCBridgeRelatedCast(castType, CastExpr);
7942
7943 DiscardMisalignedMemberAddress(castType.getTypePtr(), CastExpr);
7944
7945 return BuildCStyleCastExpr(LParenLoc, castTInfo, RParenLoc, CastExpr);
7946}
7947
7948ExprResult Sema::BuildVectorLiteral(SourceLocation LParenLoc,
7949 SourceLocation RParenLoc, Expr *E,
7950 TypeSourceInfo *TInfo) {
7951 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", 7952, __extension__ __PRETTY_FUNCTION__
))
7952 "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", 7952, __extension__ __PRETTY_FUNCTION__
))
;
7953
7954 Expr **exprs;
7955 unsigned numExprs;
7956 Expr *subExpr;
7957 SourceLocation LiteralLParenLoc, LiteralRParenLoc;
7958 if (ParenListExpr *PE = dyn_cast<ParenListExpr>(E)) {
7959 LiteralLParenLoc = PE->getLParenLoc();
7960 LiteralRParenLoc = PE->getRParenLoc();
7961 exprs = PE->getExprs();
7962 numExprs = PE->getNumExprs();
7963 } else { // isa<ParenExpr> by assertion at function entrance
7964 LiteralLParenLoc = cast<ParenExpr>(E)->getLParen();
7965 LiteralRParenLoc = cast<ParenExpr>(E)->getRParen();
7966 subExpr = cast<ParenExpr>(E)->getSubExpr();
7967 exprs = &subExpr;
7968 numExprs = 1;
7969 }
7970
7971 QualType Ty = TInfo->getType();
7972 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", 7972, __extension__ __PRETTY_FUNCTION__
))
;
7973
7974 SmallVector<Expr *, 8> initExprs;
7975 const VectorType *VTy = Ty->castAs<VectorType>();
7976 unsigned numElems = VTy->getNumElements();
7977
7978 // '(...)' form of vector initialization in AltiVec: the number of
7979 // initializers must be one or must match the size of the vector.
7980 // If a single value is specified in the initializer then it will be
7981 // replicated to all the components of the vector
7982 if (CheckAltivecInitFromScalar(E->getSourceRange(), Ty,
7983 VTy->getElementType()))
7984 return ExprError();
7985 if (ShouldSplatAltivecScalarInCast(VTy)) {
7986 // The number of initializers must be one or must match the size of the
7987 // vector. If a single value is specified in the initializer then it will
7988 // be replicated to all the components of the vector
7989 if (numExprs == 1) {
7990 QualType ElemTy = VTy->getElementType();
7991 ExprResult Literal = DefaultLvalueConversion(exprs[0]);
7992 if (Literal.isInvalid())
7993 return ExprError();
7994 Literal = ImpCastExprToType(Literal.get(), ElemTy,
7995 PrepareScalarCast(Literal, ElemTy));
7996 return BuildCStyleCastExpr(LParenLoc, TInfo, RParenLoc, Literal.get());
7997 }
7998 else if (numExprs < numElems) {
7999 Diag(E->getExprLoc(),
8000 diag::err_incorrect_number_of_vector_initializers);
8001 return ExprError();
8002 }
8003 else
8004 initExprs.append(exprs, exprs + numExprs);
8005 }
8006 else {
8007 // For OpenCL, when the number of initializers is a single value,
8008 // it will be replicated to all components of the vector.
8009 if (getLangOpts().OpenCL &&
8010 VTy->getVectorKind() == VectorType::GenericVector &&
8011 numExprs == 1) {
8012 QualType ElemTy = VTy->getElementType();
8013 ExprResult Literal = DefaultLvalueConversion(exprs[0]);
8014 if (Literal.isInvalid())
8015 return ExprError();
8016 Literal = ImpCastExprToType(Literal.get(), ElemTy,
8017 PrepareScalarCast(Literal, ElemTy));
8018 return BuildCStyleCastExpr(LParenLoc, TInfo, RParenLoc, Literal.get());
8019 }
8020
8021 initExprs.append(exprs, exprs + numExprs);
8022 }
8023 // FIXME: This means that pretty-printing the final AST will produce curly
8024 // braces instead of the original commas.
8025 InitListExpr *initE = new (Context) InitListExpr(Context, LiteralLParenLoc,
8026 initExprs, LiteralRParenLoc);
8027 initE->setType(Ty);
8028 return BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc, initE);
8029}
8030
8031/// This is not an AltiVec-style cast or or C++ direct-initialization, so turn
8032/// the ParenListExpr into a sequence of comma binary operators.
8033ExprResult
8034Sema::MaybeConvertParenListExprToParenExpr(Scope *S, Expr *OrigExpr) {
8035 ParenListExpr *E = dyn_cast<ParenListExpr>(OrigExpr);
8036 if (!E)
8037 return OrigExpr;
8038
8039 ExprResult Result(E->getExpr(0));
8040
8041 for (unsigned i = 1, e = E->getNumExprs(); i != e && !Result.isInvalid(); ++i)
8042 Result = ActOnBinOp(S, E->getExprLoc(), tok::comma, Result.get(),
8043 E->getExpr(i));
8044
8045 if (Result.isInvalid()) return ExprError();
8046
8047 return ActOnParenExpr(E->getLParenLoc(), E->getRParenLoc(), Result.get());
8048}
8049
8050ExprResult Sema::ActOnParenListExpr(SourceLocation L,
8051 SourceLocation R,
8052 MultiExprArg Val) {
8053 return ParenListExpr::Create(Context, L, Val, R);
8054}
8055
8056/// Emit a specialized diagnostic when one expression is a null pointer
8057/// constant and the other is not a pointer. Returns true if a diagnostic is
8058/// emitted.
8059bool Sema::DiagnoseConditionalForNull(Expr *LHSExpr, Expr *RHSExpr,
8060 SourceLocation QuestionLoc) {
8061 Expr *NullExpr = LHSExpr;
8062 Expr *NonPointerExpr = RHSExpr;
8063 Expr::NullPointerConstantKind NullKind =
8064 NullExpr->isNullPointerConstant(Context,
8065 Expr::NPC_ValueDependentIsNotNull);
8066
8067 if (NullKind == Expr::NPCK_NotNull) {
8068 NullExpr = RHSExpr;
8069 NonPointerExpr = LHSExpr;
8070 NullKind =
8071 NullExpr->isNullPointerConstant(Context,
8072 Expr::NPC_ValueDependentIsNotNull);
8073 }
8074
8075 if (NullKind == Expr::NPCK_NotNull)
8076 return false;
8077
8078 if (NullKind == Expr::NPCK_ZeroExpression)
8079 return false;
8080
8081 if (NullKind == Expr::NPCK_ZeroLiteral) {
8082 // In this case, check to make sure that we got here from a "NULL"
8083 // string in the source code.
8084 NullExpr = NullExpr->IgnoreParenImpCasts();
8085 SourceLocation loc = NullExpr->getExprLoc();
8086 if (!findMacroSpelling(loc, "NULL"))
8087 return false;
8088 }
8089
8090 int DiagType = (NullKind == Expr::NPCK_CXX11_nullptr);
8091 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands_null)
8092 << NonPointerExpr->getType() << DiagType
8093 << NonPointerExpr->getSourceRange();
8094 return true;
8095}
8096
8097/// Return false if the condition expression is valid, true otherwise.
8098static bool checkCondition(Sema &S, Expr *Cond, SourceLocation QuestionLoc) {
8099 QualType CondTy = Cond->getType();
8100
8101 // OpenCL v1.1 s6.3.i says the condition cannot be a floating point type.
8102 if (S.getLangOpts().OpenCL && CondTy->isFloatingType()) {
8103 S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_nonfloat)
8104 << CondTy << Cond->getSourceRange();
8105 return true;
8106 }
8107
8108 // C99 6.5.15p2
8109 if (CondTy->isScalarType()) return false;
8110
8111 S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_scalar)
8112 << CondTy << Cond->getSourceRange();
8113 return true;
8114}
8115
8116/// Handle when one or both operands are void type.
8117static QualType checkConditionalVoidType(Sema &S, ExprResult &LHS,
8118 ExprResult &RHS) {
8119 Expr *LHSExpr = LHS.get();
8120 Expr *RHSExpr = RHS.get();
8121
8122 if (!LHSExpr->getType()->isVoidType())
8123 S.Diag(RHSExpr->getBeginLoc(), diag::ext_typecheck_cond_one_void)
8124 << RHSExpr->getSourceRange();
8125 if (!RHSExpr->getType()->isVoidType())
8126 S.Diag(LHSExpr->getBeginLoc(), diag::ext_typecheck_cond_one_void)
8127 << LHSExpr->getSourceRange();
8128 LHS = S.ImpCastExprToType(LHS.get(), S.Context.VoidTy, CK_ToVoid);
8129 RHS = S.ImpCastExprToType(RHS.get(), S.Context.VoidTy, CK_ToVoid);
8130 return S.Context.VoidTy;
8131}
8132
8133/// Return false if the NullExpr can be promoted to PointerTy,
8134/// true otherwise.
8135static bool checkConditionalNullPointer(Sema &S, ExprResult &NullExpr,
8136 QualType PointerTy) {
8137 if ((!PointerTy->isAnyPointerType() && !PointerTy->isBlockPointerType()) ||
8138 !NullExpr.get()->isNullPointerConstant(S.Context,
8139 Expr::NPC_ValueDependentIsNull))
8140 return true;
8141
8142 NullExpr = S.ImpCastExprToType(NullExpr.get(), PointerTy, CK_NullToPointer);
8143 return false;
8144}
8145
8146/// Checks compatibility between two pointers and return the resulting
8147/// type.
8148static QualType checkConditionalPointerCompatibility(Sema &S, ExprResult &LHS,
8149 ExprResult &RHS,
8150 SourceLocation Loc) {
8151 QualType LHSTy = LHS.get()->getType();
8152 QualType RHSTy = RHS.get()->getType();
8153
8154 if (S.Context.hasSameType(LHSTy, RHSTy)) {
8155 // Two identical pointers types are always compatible.
8156 return LHSTy;
8157 }
8158
8159 QualType lhptee, rhptee;
8160
8161 // Get the pointee types.
8162 bool IsBlockPointer = false;
8163 if (const BlockPointerType *LHSBTy = LHSTy->getAs<BlockPointerType>()) {
8164 lhptee = LHSBTy->getPointeeType();
8165 rhptee = RHSTy->castAs<BlockPointerType>()->getPointeeType();
8166 IsBlockPointer = true;
8167 } else {
8168 lhptee = LHSTy->castAs<PointerType>()->getPointeeType();
8169 rhptee = RHSTy->castAs<PointerType>()->getPointeeType();
8170 }
8171
8172 // C99 6.5.15p6: If both operands are pointers to compatible types or to
8173 // differently qualified versions of compatible types, the result type is
8174 // a pointer to an appropriately qualified version of the composite
8175 // type.
8176
8177 // Only CVR-qualifiers exist in the standard, and the differently-qualified
8178 // clause doesn't make sense for our extensions. E.g. address space 2 should
8179 // be incompatible with address space 3: they may live on different devices or
8180 // anything.
8181 Qualifiers lhQual = lhptee.getQualifiers();
8182 Qualifiers rhQual = rhptee.getQualifiers();
8183
8184 LangAS ResultAddrSpace = LangAS::Default;
8185 LangAS LAddrSpace = lhQual.getAddressSpace();
8186 LangAS RAddrSpace = rhQual.getAddressSpace();
8187
8188 // OpenCL v1.1 s6.5 - Conversion between pointers to distinct address
8189 // spaces is disallowed.
8190 if (lhQual.isAddressSpaceSupersetOf(rhQual))
8191 ResultAddrSpace = LAddrSpace;
8192 else if (rhQual.isAddressSpaceSupersetOf(lhQual))
8193 ResultAddrSpace = RAddrSpace;
8194 else {
8195 S.Diag(Loc, diag::err_typecheck_op_on_nonoverlapping_address_space_pointers)
8196 << LHSTy << RHSTy << 2 << LHS.get()->getSourceRange()
8197 << RHS.get()->getSourceRange();
8198 return QualType();
8199 }
8200
8201 unsigned MergedCVRQual = lhQual.getCVRQualifiers() | rhQual.getCVRQualifiers();
8202 auto LHSCastKind = CK_BitCast, RHSCastKind = CK_BitCast;
8203 lhQual.removeCVRQualifiers();
8204 rhQual.removeCVRQualifiers();
8205
8206 // OpenCL v2.0 specification doesn't extend compatibility of type qualifiers
8207 // (C99 6.7.3) for address spaces. We assume that the check should behave in
8208 // the same manner as it's defined for CVR qualifiers, so for OpenCL two
8209 // qual types are compatible iff
8210 // * corresponded types are compatible
8211 // * CVR qualifiers are equal
8212 // * address spaces are equal
8213 // Thus for conditional operator we merge CVR and address space unqualified
8214 // pointees and if there is a composite type we return a pointer to it with
8215 // merged qualifiers.
8216 LHSCastKind =
8217 LAddrSpace == ResultAddrSpace ? CK_BitCast : CK_AddressSpaceConversion;
8218 RHSCastKind =
8219 RAddrSpace == ResultAddrSpace ? CK_BitCast : CK_AddressSpaceConversion;
8220 lhQual.removeAddressSpace();
8221 rhQual.removeAddressSpace();
8222
8223 lhptee = S.Context.getQualifiedType(lhptee.getUnqualifiedType(), lhQual);
8224 rhptee = S.Context.getQualifiedType(rhptee.getUnqualifiedType(), rhQual);
8225
8226 QualType CompositeTy = S.Context.mergeTypes(lhptee, rhptee);
8227
8228 if (CompositeTy.isNull()) {
8229 // In this situation, we assume void* type. No especially good
8230 // reason, but this is what gcc does, and we do have to pick
8231 // to get a consistent AST.
8232 QualType incompatTy;
8233 incompatTy = S.Context.getPointerType(
8234 S.Context.getAddrSpaceQualType(S.Context.VoidTy, ResultAddrSpace));
8235 LHS = S.ImpCastExprToType(LHS.get(), incompatTy, LHSCastKind);
8236 RHS = S.ImpCastExprToType(RHS.get(), incompatTy, RHSCastKind);
8237
8238 // FIXME: For OpenCL the warning emission and cast to void* leaves a room
8239 // for casts between types with incompatible address space qualifiers.
8240 // For the following code the compiler produces casts between global and
8241 // local address spaces of the corresponded innermost pointees:
8242 // local int *global *a;
8243 // global int *global *b;
8244 // a = (0 ? a : b); // see C99 6.5.16.1.p1.
8245 S.Diag(Loc, diag::ext_typecheck_cond_incompatible_pointers)
8246 << LHSTy << RHSTy << LHS.get()->getSourceRange()
8247 << RHS.get()->getSourceRange();
8248
8249 return incompatTy;
8250 }
8251
8252 // The pointer types are compatible.
8253 // In case of OpenCL ResultTy should have the address space qualifier
8254 // which is a superset of address spaces of both the 2nd and the 3rd
8255 // operands of the conditional operator.
8256 QualType ResultTy = [&, ResultAddrSpace]() {
8257 if (S.getLangOpts().OpenCL) {
8258 Qualifiers CompositeQuals = CompositeTy.getQualifiers();
8259 CompositeQuals.setAddressSpace(ResultAddrSpace);
8260 return S.Context
8261 .getQualifiedType(CompositeTy.getUnqualifiedType(), CompositeQuals)
8262 .withCVRQualifiers(MergedCVRQual);
8263 }
8264 return CompositeTy.withCVRQualifiers(MergedCVRQual);
8265 }();
8266 if (IsBlockPointer)
8267 ResultTy = S.Context.getBlockPointerType(ResultTy);
8268 else
8269 ResultTy = S.Context.getPointerType(ResultTy);
8270
8271 LHS = S.ImpCastExprToType(LHS.get(), ResultTy, LHSCastKind);
8272 RHS = S.ImpCastExprToType(RHS.get(), ResultTy, RHSCastKind);
8273 return ResultTy;
8274}
8275
8276/// Return the resulting type when the operands are both block pointers.
8277static QualType checkConditionalBlockPointerCompatibility(Sema &S,
8278 ExprResult &LHS,
8279 ExprResult &RHS,
8280 SourceLocation Loc) {
8281 QualType LHSTy = LHS.get()->getType();
8282 QualType RHSTy = RHS.get()->getType();
8283
8284 if (!LHSTy->isBlockPointerType() || !RHSTy->isBlockPointerType()) {
8285 if (LHSTy->isVoidPointerType() || RHSTy->isVoidPointerType()) {
8286 QualType destType = S.Context.getPointerType(S.Context.VoidTy);
8287 LHS = S.ImpCastExprToType(LHS.get(), destType, CK_BitCast);
8288 RHS = S.ImpCastExprToType(RHS.get(), destType, CK_BitCast);
8289 return destType;
8290 }
8291 S.Diag(Loc, diag::err_typecheck_cond_incompatible_operands)
8292 << LHSTy << RHSTy << LHS.get()->getSourceRange()
8293 << RHS.get()->getSourceRange();
8294 return QualType();
8295 }
8296
8297 // We have 2 block pointer types.
8298 return checkConditionalPointerCompatibility(S, LHS, RHS, Loc);
8299}
8300
8301/// Return the resulting type when the operands are both pointers.
8302static QualType
8303checkConditionalObjectPointersCompatibility(Sema &S, ExprResult &LHS,
8304 ExprResult &RHS,
8305 SourceLocation Loc) {
8306 // get the pointer types
8307 QualType LHSTy = LHS.get()->getType();
8308 QualType RHSTy = RHS.get()->getType();
8309
8310 // get the "pointed to" types
8311 QualType lhptee = LHSTy->castAs<PointerType>()->getPointeeType();
8312 QualType rhptee = RHSTy->castAs<PointerType>()->getPointeeType();
8313
8314 // ignore qualifiers on void (C99 6.5.15p3, clause 6)
8315 if (lhptee->isVoidType() && rhptee->isIncompleteOrObjectType()) {
8316 // Figure out necessary qualifiers (C99 6.5.15p6)
8317 QualType destPointee
8318 = S.Context.getQualifiedType(lhptee, rhptee.getQualifiers());
8319 QualType destType = S.Context.getPointerType(destPointee);
8320 // Add qualifiers if necessary.
8321 LHS = S.ImpCastExprToType(LHS.get(), destType, CK_NoOp);
8322 // Promote to void*.
8323 RHS = S.ImpCastExprToType(RHS.get(), destType, CK_BitCast);
8324 return destType;
8325 }
8326 if (rhptee->isVoidType() && lhptee->isIncompleteOrObjectType()) {
8327 QualType destPointee
8328 = S.Context.getQualifiedType(rhptee, lhptee.getQualifiers());
8329 QualType destType = S.Context.getPointerType(destPointee);
8330 // Add qualifiers if necessary.
8331 RHS = S.ImpCastExprToType(RHS.get(), destType, CK_NoOp);
8332 // Promote to void*.
8333 LHS = S.ImpCastExprToType(LHS.get(), destType, CK_BitCast);
8334 return destType;
8335 }
8336
8337 return checkConditionalPointerCompatibility(S, LHS, RHS, Loc);
8338}
8339
8340/// Return false if the first expression is not an integer and the second
8341/// expression is not a pointer, true otherwise.
8342static bool checkPointerIntegerMismatch(Sema &S, ExprResult &Int,
8343 Expr* PointerExpr, SourceLocation Loc,
8344 bool IsIntFirstExpr) {
8345 if (!PointerExpr->getType()->isPointerType() ||
8346 !Int.get()->getType()->isIntegerType())
8347 return false;
8348
8349 Expr *Expr1 = IsIntFirstExpr ? Int.get() : PointerExpr;
8350 Expr *Expr2 = IsIntFirstExpr ? PointerExpr : Int.get();
8351
8352 S.Diag(Loc, diag::ext_typecheck_cond_pointer_integer_mismatch)
8353 << Expr1->getType() << Expr2->getType()
8354 << Expr1->getSourceRange() << Expr2->getSourceRange();
8355 Int = S.ImpCastExprToType(Int.get(), PointerExpr->getType(),
8356 CK_IntegralToPointer);
8357 return true;
8358}
8359
8360/// Simple conversion between integer and floating point types.
8361///
8362/// Used when handling the OpenCL conditional operator where the
8363/// condition is a vector while the other operands are scalar.
8364///
8365/// OpenCL v1.1 s6.3.i and s6.11.6 together require that the scalar
8366/// types are either integer or floating type. Between the two
8367/// operands, the type with the higher rank is defined as the "result
8368/// type". The other operand needs to be promoted to the same type. No
8369/// other type promotion is allowed. We cannot use
8370/// UsualArithmeticConversions() for this purpose, since it always
8371/// promotes promotable types.
8372static QualType OpenCLArithmeticConversions(Sema &S, ExprResult &LHS,
8373 ExprResult &RHS,
8374 SourceLocation QuestionLoc) {
8375 LHS = S.DefaultFunctionArrayLvalueConversion(LHS.get());
8376 if (LHS.isInvalid())
8377 return QualType();
8378 RHS = S.DefaultFunctionArrayLvalueConversion(RHS.get());
8379 if (RHS.isInvalid())
8380 return QualType();
8381
8382 // For conversion purposes, we ignore any qualifiers.
8383 // For example, "const float" and "float" are equivalent.
8384 QualType LHSType =
8385 S.Context.getCanonicalType(LHS.get()->getType()).getUnqualifiedType();
8386 QualType RHSType =
8387 S.Context.getCanonicalType(RHS.get()->getType()).getUnqualifiedType();
8388
8389 if (!LHSType->isIntegerType() && !LHSType->isRealFloatingType()) {
8390 S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_int_float)
8391 << LHSType << LHS.get()->getSourceRange();
8392 return QualType();
8393 }
8394
8395 if (!RHSType->isIntegerType() && !RHSType->isRealFloatingType()) {
8396 S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_int_float)
8397 << RHSType << RHS.get()->getSourceRange();
8398 return QualType();
8399 }
8400
8401 // If both types are identical, no conversion is needed.
8402 if (LHSType == RHSType)
8403 return LHSType;
8404
8405 // Now handle "real" floating types (i.e. float, double, long double).
8406 if (LHSType->isRealFloatingType() || RHSType->isRealFloatingType())
8407 return handleFloatConversion(S, LHS, RHS, LHSType, RHSType,
8408 /*IsCompAssign = */ false);
8409
8410 // Finally, we have two differing integer types.
8411 return handleIntegerConversion<doIntegralCast, doIntegralCast>
8412 (S, LHS, RHS, LHSType, RHSType, /*IsCompAssign = */ false);
8413}
8414
8415/// Convert scalar operands to a vector that matches the
8416/// condition in length.
8417///
8418/// Used when handling the OpenCL conditional operator where the
8419/// condition is a vector while the other operands are scalar.
8420///
8421/// We first compute the "result type" for the scalar operands
8422/// according to OpenCL v1.1 s6.3.i. Both operands are then converted
8423/// into a vector of that type where the length matches the condition
8424/// vector type. s6.11.6 requires that the element types of the result
8425/// and the condition must have the same number of bits.
8426static QualType
8427OpenCLConvertScalarsToVectors(Sema &S, ExprResult &LHS, ExprResult &RHS,
8428 QualType CondTy, SourceLocation QuestionLoc) {
8429 QualType ResTy = OpenCLArithmeticConversions(S, LHS, RHS, QuestionLoc);
8430 if (ResTy.isNull()) return QualType();
8431
8432 const VectorType *CV = CondTy->getAs<VectorType>();
8433 assert(CV)(static_cast <bool> (CV) ? void (0) : __assert_fail ("CV"
, "clang/lib/Sema/SemaExpr.cpp", 8433, __extension__ __PRETTY_FUNCTION__
))
;
8434
8435 // Determine the vector result type
8436 unsigned NumElements = CV->getNumElements();
8437 QualType VectorTy = S.Context.getExtVectorType(ResTy, NumElements);
8438
8439 // Ensure that all types have the same number of bits
8440 if (S.Context.getTypeSize(CV->getElementType())
8441 != S.Context.getTypeSize(ResTy)) {
8442 // Since VectorTy is created internally, it does not pretty print
8443 // with an OpenCL name. Instead, we just print a description.
8444 std::string EleTyName = ResTy.getUnqualifiedType().getAsString();
8445 SmallString<64> Str;
8446 llvm::raw_svector_ostream OS(Str);
8447 OS << "(vector of " << NumElements << " '" << EleTyName << "' values)";
8448 S.Diag(QuestionLoc, diag::err_conditional_vector_element_size)
8449 << CondTy << OS.str();
8450 return QualType();
8451 }
8452
8453 // Convert operands to the vector result type
8454 LHS = S.ImpCastExprToType(LHS.get(), VectorTy, CK_VectorSplat);
8455 RHS = S.ImpCastExprToType(RHS.get(), VectorTy, CK_VectorSplat);
8456
8457 return VectorTy;
8458}
8459
8460/// Return false if this is a valid OpenCL condition vector
8461static bool checkOpenCLConditionVector(Sema &S, Expr *Cond,
8462 SourceLocation QuestionLoc) {
8463 // OpenCL v1.1 s6.11.6 says the elements of the vector must be of
8464 // integral type.
8465 const VectorType *CondTy = Cond->getType()->getAs<VectorType>();
8466 assert(CondTy)(static_cast <bool> (CondTy) ? void (0) : __assert_fail
("CondTy", "clang/lib/Sema/SemaExpr.cpp", 8466, __extension__
__PRETTY_FUNCTION__))
;
8467 QualType EleTy = CondTy->getElementType();
8468 if (EleTy->isIntegerType()) return false;
8469
8470 S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_nonfloat)
8471 << Cond->getType() << Cond->getSourceRange();
8472 return true;
8473}
8474
8475/// Return false if the vector condition type and the vector
8476/// result type are compatible.
8477///
8478/// OpenCL v1.1 s6.11.6 requires that both vector types have the same
8479/// number of elements, and their element types have the same number
8480/// of bits.
8481static bool checkVectorResult(Sema &S, QualType CondTy, QualType VecResTy,
8482 SourceLocation QuestionLoc) {
8483 const VectorType *CV = CondTy->getAs<VectorType>();
8484 const VectorType *RV = VecResTy->getAs<VectorType>();
8485 assert(CV && RV)(static_cast <bool> (CV && RV) ? void (0) : __assert_fail
("CV && RV", "clang/lib/Sema/SemaExpr.cpp", 8485, __extension__
__PRETTY_FUNCTION__))
;
8486
8487 if (CV->getNumElements() != RV->getNumElements()) {
8488 S.Diag(QuestionLoc, diag::err_conditional_vector_size)
8489 << CondTy << VecResTy;
8490 return true;
8491 }
8492
8493 QualType CVE = CV->getElementType();
8494 QualType RVE = RV->getElementType();
8495
8496 if (S.Context.getTypeSize(CVE) != S.Context.getTypeSize(RVE)) {
8497 S.Diag(QuestionLoc, diag::err_conditional_vector_element_size)
8498 << CondTy << VecResTy;
8499 return true;
8500 }
8501
8502 return false;
8503}
8504
8505/// Return the resulting type for the conditional operator in
8506/// OpenCL (aka "ternary selection operator", OpenCL v1.1
8507/// s6.3.i) when the condition is a vector type.
8508static QualType
8509OpenCLCheckVectorConditional(Sema &S, ExprResult &Cond,
8510 ExprResult &LHS, ExprResult &RHS,
8511 SourceLocation QuestionLoc) {
8512 Cond = S.DefaultFunctionArrayLvalueConversion(Cond.get());
8513 if (Cond.isInvalid())
8514 return QualType();
8515 QualType CondTy = Cond.get()->getType();
8516
8517 if (checkOpenCLConditionVector(S, Cond.get(), QuestionLoc))
8518 return QualType();
8519
8520 // If either operand is a vector then find the vector type of the
8521 // result as specified in OpenCL v1.1 s6.3.i.
8522 if (LHS.get()->getType()->isVectorType() ||
8523 RHS.get()->getType()->isVectorType()) {
8524 bool IsBoolVecLang =
8525 !S.getLangOpts().OpenCL && !S.getLangOpts().OpenCLCPlusPlus;
8526 QualType VecResTy =
8527 S.CheckVectorOperands(LHS, RHS, QuestionLoc,
8528 /*isCompAssign*/ false,
8529 /*AllowBothBool*/ true,
8530 /*AllowBoolConversions*/ false,
8531 /*AllowBooleanOperation*/ IsBoolVecLang,
8532 /*ReportInvalid*/ true);
8533 if (VecResTy.isNull())
8534 return QualType();
8535 // The result type must match the condition type as specified in
8536 // OpenCL v1.1 s6.11.6.
8537 if (checkVectorResult(S, CondTy, VecResTy, QuestionLoc))
8538 return QualType();
8539 return VecResTy;
8540 }
8541
8542 // Both operands are scalar.
8543 return OpenCLConvertScalarsToVectors(S, LHS, RHS, CondTy, QuestionLoc);
8544}
8545
8546/// Return true if the Expr is block type
8547static bool checkBlockType(Sema &S, const Expr *E) {
8548 if (const CallExpr *CE = dyn_cast<CallExpr>(E)) {
8549 QualType Ty = CE->getCallee()->getType();
8550 if (Ty->isBlockPointerType()) {
8551 S.Diag(E->getExprLoc(), diag::err_opencl_ternary_with_block);
8552 return true;
8553 }
8554 }
8555 return false;
8556}
8557
8558/// Note that LHS is not null here, even if this is the gnu "x ?: y" extension.
8559/// In that case, LHS = cond.
8560/// C99 6.5.15
8561QualType Sema::CheckConditionalOperands(ExprResult &Cond, ExprResult &LHS,
8562 ExprResult &RHS, ExprValueKind &VK,
8563 ExprObjectKind &OK,
8564 SourceLocation QuestionLoc) {
8565
8566 ExprResult LHSResult = CheckPlaceholderExpr(LHS.get());
8567 if (!LHSResult.isUsable()) return QualType();
8568 LHS = LHSResult;
8569
8570 ExprResult RHSResult = CheckPlaceholderExpr(RHS.get());
8571 if (!RHSResult.isUsable()) return QualType();
8572 RHS = RHSResult;
8573
8574 // C++ is sufficiently different to merit its own checker.
8575 if (getLangOpts().CPlusPlus)
8576 return CXXCheckConditionalOperands(Cond, LHS, RHS, VK, OK, QuestionLoc);
8577
8578 VK = VK_PRValue;
8579 OK = OK_Ordinary;
8580
8581 if (Context.isDependenceAllowed() &&
8582 (Cond.get()->isTypeDependent() || LHS.get()->isTypeDependent() ||
8583 RHS.get()->isTypeDependent())) {
8584 assert(!getLangOpts().CPlusPlus)(static_cast <bool> (!getLangOpts().CPlusPlus) ? void (
0) : __assert_fail ("!getLangOpts().CPlusPlus", "clang/lib/Sema/SemaExpr.cpp"
, 8584, __extension__ __PRETTY_FUNCTION__))
;
8585 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", 8587, __extension__ __PRETTY_FUNCTION__
))
8586 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", 8587, __extension__ __PRETTY_FUNCTION__
))
8587 "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", 8587, __extension__ __PRETTY_FUNCTION__
))
;
8588 return Context.DependentTy;
8589 }
8590
8591 // The OpenCL operator with a vector condition is sufficiently
8592 // different to merit its own checker.
8593 if ((getLangOpts().OpenCL && Cond.get()->getType()->isVectorType()) ||
8594 Cond.get()->getType()->isExtVectorType())
8595 return OpenCLCheckVectorConditional(*this, Cond, LHS, RHS, QuestionLoc);
8596
8597 // First, check the condition.
8598 Cond = UsualUnaryConversions(Cond.get());
8599 if (Cond.isInvalid())
8600 return QualType();
8601 if (checkCondition(*this, Cond.get(), QuestionLoc))
8602 return QualType();
8603
8604 // Now check the two expressions.
8605 if (LHS.get()->getType()->isVectorType() ||
8606 RHS.get()->getType()->isVectorType())
8607 return CheckVectorOperands(LHS, RHS, QuestionLoc, /*isCompAssign*/ false,
8608 /*AllowBothBool*/ true,
8609 /*AllowBoolConversions*/ false,
8610 /*AllowBooleanOperation*/ false,
8611 /*ReportInvalid*/ true);
8612
8613 QualType ResTy =
8614 UsualArithmeticConversions(LHS, RHS, QuestionLoc, ACK_Conditional);
8615 if (LHS.isInvalid() || RHS.isInvalid())
8616 return QualType();
8617
8618 QualType LHSTy = LHS.get()->getType();
8619 QualType RHSTy = RHS.get()->getType();
8620
8621 // Diagnose attempts to convert between __ibm128, __float128 and long double
8622 // where such conversions currently can't be handled.
8623 if (unsupportedTypeConversion(*this, LHSTy, RHSTy)) {
8624 Diag(QuestionLoc,
8625 diag::err_typecheck_cond_incompatible_operands) << LHSTy << RHSTy
8626 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
8627 return QualType();
8628 }
8629
8630 // OpenCL v2.0 s6.12.5 - Blocks cannot be used as expressions of the ternary
8631 // selection operator (?:).
8632 if (getLangOpts().OpenCL &&
8633 ((int)checkBlockType(*this, LHS.get()) | (int)checkBlockType(*this, RHS.get()))) {
8634 return QualType();
8635 }
8636
8637 // If both operands have arithmetic type, do the usual arithmetic conversions
8638 // to find a common type: C99 6.5.15p3,5.
8639 if (LHSTy->isArithmeticType() && RHSTy->isArithmeticType()) {
8640 // Disallow invalid arithmetic conversions, such as those between bit-
8641 // precise integers types of different sizes, or between a bit-precise
8642 // integer and another type.
8643 if (ResTy.isNull() && (LHSTy->isBitIntType() || RHSTy->isBitIntType())) {
8644 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands)
8645 << LHSTy << RHSTy << LHS.get()->getSourceRange()
8646 << RHS.get()->getSourceRange();
8647 return QualType();
8648 }
8649
8650 LHS = ImpCastExprToType(LHS.get(), ResTy, PrepareScalarCast(LHS, ResTy));
8651 RHS = ImpCastExprToType(RHS.get(), ResTy, PrepareScalarCast(RHS, ResTy));
8652
8653 return ResTy;
8654 }
8655
8656 // And if they're both bfloat (which isn't arithmetic), that's fine too.
8657 if (LHSTy->isBFloat16Type() && RHSTy->isBFloat16Type()) {
8658 return LHSTy;
8659 }
8660
8661 // If both operands are the same structure or union type, the result is that
8662 // type.
8663 if (const RecordType *LHSRT = LHSTy->getAs<RecordType>()) { // C99 6.5.15p3
8664 if (const RecordType *RHSRT = RHSTy->getAs<RecordType>())
8665 if (LHSRT->getDecl() == RHSRT->getDecl())
8666 // "If both the operands have structure or union type, the result has
8667 // that type." This implies that CV qualifiers are dropped.
8668 return LHSTy.getUnqualifiedType();
8669 // FIXME: Type of conditional expression must be complete in C mode.
8670 }
8671
8672 // C99 6.5.15p5: "If both operands have void type, the result has void type."
8673 // The following || allows only one side to be void (a GCC-ism).
8674 if (LHSTy->isVoidType() || RHSTy->isVoidType()) {
8675 return checkConditionalVoidType(*this, LHS, RHS);
8676 }
8677
8678 // C99 6.5.15p6 - "if one operand is a null pointer constant, the result has
8679 // the type of the other operand."
8680 if (!checkConditionalNullPointer(*this, RHS, LHSTy)) return LHSTy;
8681 if (!checkConditionalNullPointer(*this, LHS, RHSTy)) return RHSTy;
8682
8683 // All objective-c pointer type analysis is done here.
8684 QualType compositeType = FindCompositeObjCPointerType(LHS, RHS,
8685 QuestionLoc);
8686 if (LHS.isInvalid() || RHS.isInvalid())
8687 return QualType();
8688 if (!compositeType.isNull())
8689 return compositeType;
8690
8691
8692 // Handle block pointer types.
8693 if (LHSTy->isBlockPointerType() || RHSTy->isBlockPointerType())
8694 return checkConditionalBlockPointerCompatibility(*this, LHS, RHS,
8695 QuestionLoc);
8696
8697 // Check constraints for C object pointers types (C99 6.5.15p3,6).
8698 if (LHSTy->isPointerType() && RHSTy->isPointerType())
8699 return checkConditionalObjectPointersCompatibility(*this, LHS, RHS,
8700 QuestionLoc);
8701
8702 // GCC compatibility: soften pointer/integer mismatch. Note that
8703 // null pointers have been filtered out by this point.
8704 if (checkPointerIntegerMismatch(*this, LHS, RHS.get(), QuestionLoc,
8705 /*IsIntFirstExpr=*/true))
8706 return RHSTy;
8707 if (checkPointerIntegerMismatch(*this, RHS, LHS.get(), QuestionLoc,
8708 /*IsIntFirstExpr=*/false))
8709 return LHSTy;
8710
8711 // Allow ?: operations in which both operands have the same
8712 // built-in sizeless type.
8713 if (LHSTy->isSizelessBuiltinType() && Context.hasSameType(LHSTy, RHSTy))
8714 return LHSTy;
8715
8716 // Emit a better diagnostic if one of the expressions is a null pointer
8717 // constant and the other is not a pointer type. In this case, the user most
8718 // likely forgot to take the address of the other expression.
8719 if (DiagnoseConditionalForNull(LHS.get(), RHS.get(), QuestionLoc))
8720 return QualType();
8721
8722 // Otherwise, the operands are not compatible.
8723 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands)
8724 << LHSTy << RHSTy << LHS.get()->getSourceRange()
8725 << RHS.get()->getSourceRange();
8726 return QualType();
8727}
8728
8729/// FindCompositeObjCPointerType - Helper method to find composite type of
8730/// two objective-c pointer types of the two input expressions.
8731QualType Sema::FindCompositeObjCPointerType(ExprResult &LHS, ExprResult &RHS,
8732 SourceLocation QuestionLoc) {
8733 QualType LHSTy = LHS.get()->getType();
8734 QualType RHSTy = RHS.get()->getType();
8735
8736 // Handle things like Class and struct objc_class*. Here we case the result
8737 // to the pseudo-builtin, because that will be implicitly cast back to the
8738 // redefinition type if an attempt is made to access its fields.
8739 if (LHSTy->isObjCClassType() &&
8740 (Context.hasSameType(RHSTy, Context.getObjCClassRedefinitionType()))) {
8741 RHS = ImpCastExprToType(RHS.get(), LHSTy, CK_CPointerToObjCPointerCast);
8742 return LHSTy;
8743 }
8744 if (RHSTy->isObjCClassType() &&
8745 (Context.hasSameType(LHSTy, Context.getObjCClassRedefinitionType()))) {
8746 LHS = ImpCastExprToType(LHS.get(), RHSTy, CK_CPointerToObjCPointerCast);
8747 return RHSTy;
8748 }
8749 // And the same for struct objc_object* / id
8750 if (LHSTy->isObjCIdType() &&
8751 (Context.hasSameType(RHSTy, Context.getObjCIdRedefinitionType()))) {
8752 RHS = ImpCastExprToType(RHS.get(), LHSTy, CK_CPointerToObjCPointerCast);
8753 return LHSTy;
8754 }
8755 if (RHSTy->isObjCIdType() &&
8756 (Context.hasSameType(LHSTy, Context.getObjCIdRedefinitionType()))) {
8757 LHS = ImpCastExprToType(LHS.get(), RHSTy, CK_CPointerToObjCPointerCast);
8758 return RHSTy;
8759 }
8760 // And the same for struct objc_selector* / SEL
8761 if (Context.isObjCSelType(LHSTy) &&
8762 (Context.hasSameType(RHSTy, Context.getObjCSelRedefinitionType()))) {
8763 RHS = ImpCastExprToType(RHS.get(), LHSTy, CK_BitCast);
8764 return LHSTy;
8765 }
8766 if (Context.isObjCSelType(RHSTy) &&
8767 (Context.hasSameType(LHSTy, Context.getObjCSelRedefinitionType()))) {
8768 LHS = ImpCastExprToType(LHS.get(), RHSTy, CK_BitCast);
8769 return RHSTy;
8770 }
8771 // Check constraints for Objective-C object pointers types.
8772 if (LHSTy->isObjCObjectPointerType() && RHSTy->isObjCObjectPointerType()) {
8773
8774 if (Context.getCanonicalType(LHSTy) == Context.getCanonicalType(RHSTy)) {
8775 // Two identical object pointer types are always compatible.
8776 return LHSTy;
8777 }
8778 const ObjCObjectPointerType *LHSOPT = LHSTy->castAs<ObjCObjectPointerType>();
8779 const ObjCObjectPointerType *RHSOPT = RHSTy->castAs<ObjCObjectPointerType>();
8780 QualType compositeType = LHSTy;
8781
8782 // If both operands are interfaces and either operand can be
8783 // assigned to the other, use that type as the composite
8784 // type. This allows
8785 // xxx ? (A*) a : (B*) b
8786 // where B is a subclass of A.
8787 //
8788 // Additionally, as for assignment, if either type is 'id'
8789 // allow silent coercion. Finally, if the types are
8790 // incompatible then make sure to use 'id' as the composite
8791 // type so the result is acceptable for sending messages to.
8792
8793 // FIXME: Consider unifying with 'areComparableObjCPointerTypes'.
8794 // It could return the composite type.
8795 if (!(compositeType =
8796 Context.areCommonBaseCompatible(LHSOPT, RHSOPT)).isNull()) {
8797 // Nothing more to do.
8798 } else if (Context.canAssignObjCInterfaces(LHSOPT, RHSOPT)) {
8799 compositeType = RHSOPT->isObjCBuiltinType() ? RHSTy : LHSTy;
8800 } else if (Context.canAssignObjCInterfaces(RHSOPT, LHSOPT)) {
8801 compositeType = LHSOPT->isObjCBuiltinType() ? LHSTy : RHSTy;
8802 } else if ((LHSOPT->isObjCQualifiedIdType() ||
8803 RHSOPT->isObjCQualifiedIdType()) &&
8804 Context.ObjCQualifiedIdTypesAreCompatible(LHSOPT, RHSOPT,
8805 true)) {
8806 // Need to handle "id<xx>" explicitly.
8807 // GCC allows qualified id and any Objective-C type to devolve to
8808 // id. Currently localizing to here until clear this should be
8809 // part of ObjCQualifiedIdTypesAreCompatible.
8810 compositeType = Context.getObjCIdType();
8811 } else if (LHSTy->isObjCIdType() || RHSTy->isObjCIdType()) {
8812 compositeType = Context.getObjCIdType();
8813 } else {
8814 Diag(QuestionLoc, diag::ext_typecheck_cond_incompatible_operands)
8815 << LHSTy << RHSTy
8816 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
8817 QualType incompatTy = Context.getObjCIdType();
8818 LHS = ImpCastExprToType(LHS.get(), incompatTy, CK_BitCast);
8819 RHS = ImpCastExprToType(RHS.get(), incompatTy, CK_BitCast);
8820 return incompatTy;
8821 }
8822 // The object pointer types are compatible.
8823 LHS = ImpCastExprToType(LHS.get(), compositeType, CK_BitCast);
8824 RHS = ImpCastExprToType(RHS.get(), compositeType, CK_BitCast);
8825 return compositeType;
8826 }
8827 // Check Objective-C object pointer types and 'void *'
8828 if (LHSTy->isVoidPointerType() && RHSTy->isObjCObjectPointerType()) {
8829 if (getLangOpts().ObjCAutoRefCount) {
8830 // ARC forbids the implicit conversion of object pointers to 'void *',
8831 // so these types are not compatible.
8832 Diag(QuestionLoc, diag::err_cond_voidptr_arc) << LHSTy << RHSTy
8833 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
8834 LHS = RHS = true;
8835 return QualType();
8836 }
8837 QualType lhptee = LHSTy->castAs<PointerType>()->getPointeeType();
8838 QualType rhptee = RHSTy->castAs<ObjCObjectPointerType>()->getPointeeType();
8839 QualType destPointee
8840 = Context.getQualifiedType(lhptee, rhptee.getQualifiers());
8841 QualType destType = Context.getPointerType(destPointee);
8842 // Add qualifiers if necessary.
8843 LHS = ImpCastExprToType(LHS.get(), destType, CK_NoOp);
8844 // Promote to void*.
8845 RHS = ImpCastExprToType(RHS.get(), destType, CK_BitCast);
8846 return destType;
8847 }
8848 if (LHSTy->isObjCObjectPointerType() && RHSTy->isVoidPointerType()) {
8849 if (getLangOpts().ObjCAutoRefCount) {
8850 // ARC forbids the implicit conversion of object pointers to 'void *',
8851 // so these types are not compatible.
8852 Diag(QuestionLoc, diag::err_cond_voidptr_arc) << LHSTy << RHSTy
8853 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
8854 LHS = RHS = true;
8855 return QualType();
8856 }
8857 QualType lhptee = LHSTy->castAs<ObjCObjectPointerType>()->getPointeeType();
8858 QualType rhptee = RHSTy->castAs<PointerType>()->getPointeeType();
8859 QualType destPointee
8860 = Context.getQualifiedType(rhptee, lhptee.getQualifiers());
8861 QualType destType = Context.getPointerType(destPointee);
8862 // Add qualifiers if necessary.
8863 RHS = ImpCastExprToType(RHS.get(), destType, CK_NoOp);
8864 // Promote to void*.
8865 LHS = ImpCastExprToType(LHS.get(), destType, CK_BitCast);
8866 return destType;
8867 }
8868 return QualType();
8869}
8870
8871/// SuggestParentheses - Emit a note with a fixit hint that wraps
8872/// ParenRange in parentheses.
8873static void SuggestParentheses(Sema &Self, SourceLocation Loc,
8874 const PartialDiagnostic &Note,
8875 SourceRange ParenRange) {
8876 SourceLocation EndLoc = Self.getLocForEndOfToken(ParenRange.getEnd());
8877 if (ParenRange.getBegin().isFileID() && ParenRange.getEnd().isFileID() &&
8878 EndLoc.isValid()) {
8879 Self.Diag(Loc, Note)
8880 << FixItHint::CreateInsertion(ParenRange.getBegin(), "(")
8881 << FixItHint::CreateInsertion(EndLoc, ")");
8882 } else {
8883 // We can't display the parentheses, so just show the bare note.
8884 Self.Diag(Loc, Note) << ParenRange;
8885 }
8886}
8887
8888static bool IsArithmeticOp(BinaryOperatorKind Opc) {
8889 return BinaryOperator::isAdditiveOp(Opc) ||
8890 BinaryOperator::isMultiplicativeOp(Opc) ||
8891 BinaryOperator::isShiftOp(Opc) || Opc == BO_And || Opc == BO_Or;
8892 // This only checks for bitwise-or and bitwise-and, but not bitwise-xor and
8893 // not any of the logical operators. Bitwise-xor is commonly used as a
8894 // logical-xor because there is no logical-xor operator. The logical
8895 // operators, including uses of xor, have a high false positive rate for
8896 // precedence warnings.
8897}
8898
8899/// IsArithmeticBinaryExpr - Returns true if E is an arithmetic binary
8900/// expression, either using a built-in or overloaded operator,
8901/// and sets *OpCode to the opcode and *RHSExprs to the right-hand side
8902/// expression.
8903static bool IsArithmeticBinaryExpr(Expr *E, BinaryOperatorKind *Opcode,
8904 Expr **RHSExprs) {
8905 // Don't strip parenthesis: we should not warn if E is in parenthesis.
8906 E = E->IgnoreImpCasts();
8907 E = E->IgnoreConversionOperatorSingleStep();
8908 E = E->IgnoreImpCasts();
8909 if (auto *MTE = dyn_cast<MaterializeTemporaryExpr>(E)) {
8910 E = MTE->getSubExpr();
8911 E = E->IgnoreImpCasts();
8912 }
8913
8914 // Built-in binary operator.
8915 if (BinaryOperator *OP = dyn_cast<BinaryOperator>(E)) {
8916 if (IsArithmeticOp(OP->getOpcode())) {
8917 *Opcode = OP->getOpcode();
8918 *RHSExprs = OP->getRHS();
8919 return true;
8920 }
8921 }
8922
8923 // Overloaded operator.
8924 if (CXXOperatorCallExpr *Call = dyn_cast<CXXOperatorCallExpr>(E)) {
8925 if (Call->getNumArgs() != 2)
8926 return false;
8927
8928 // Make sure this is really a binary operator that is safe to pass into
8929 // BinaryOperator::getOverloadedOpcode(), e.g. it's not a subscript op.
8930 OverloadedOperatorKind OO = Call->getOperator();
8931 if (OO < OO_Plus || OO > OO_Arrow ||
8932 OO == OO_PlusPlus || OO == OO_MinusMinus)
8933 return false;
8934
8935 BinaryOperatorKind OpKind = BinaryOperator::getOverloadedOpcode(OO);
8936 if (IsArithmeticOp(OpKind)) {
8937 *Opcode = OpKind;
8938 *RHSExprs = Call->getArg(1);
8939 return true;
8940 }
8941 }
8942
8943 return false;
8944}
8945
8946/// ExprLooksBoolean - Returns true if E looks boolean, i.e. it has boolean type
8947/// or is a logical expression such as (x==y) which has int type, but is
8948/// commonly interpreted as boolean.
8949static bool ExprLooksBoolean(Expr *E) {
8950 E = E->IgnoreParenImpCasts();
8951
8952 if (E->getType()->isBooleanType())
8953 return true;
8954 if (BinaryOperator *OP = dyn_cast<BinaryOperator>(E))
8955 return OP->isComparisonOp() || OP->isLogicalOp();
8956 if (UnaryOperator *OP = dyn_cast<UnaryOperator>(E))
8957 return OP->getOpcode() == UO_LNot;
8958 if (E->getType()->isPointerType())
8959 return true;
8960 // FIXME: What about overloaded operator calls returning "unspecified boolean
8961 // type"s (commonly pointer-to-members)?
8962
8963 return false;
8964}
8965
8966/// DiagnoseConditionalPrecedence - Emit a warning when a conditional operator
8967/// and binary operator are mixed in a way that suggests the programmer assumed
8968/// the conditional operator has higher precedence, for example:
8969/// "int x = a + someBinaryCondition ? 1 : 2".
8970static void DiagnoseConditionalPrecedence(Sema &Self,
8971 SourceLocation OpLoc,
8972 Expr *Condition,
8973 Expr *LHSExpr,
8974 Expr *RHSExpr) {
8975 BinaryOperatorKind CondOpcode;
8976 Expr *CondRHS;
8977
8978 if (!IsArithmeticBinaryExpr(Condition, &CondOpcode, &CondRHS))
8979 return;
8980 if (!ExprLooksBoolean(CondRHS))
8981 return;
8982
8983 // The condition is an arithmetic binary expression, with a right-
8984 // hand side that looks boolean, so warn.
8985
8986 unsigned DiagID = BinaryOperator::isBitwiseOp(CondOpcode)
8987 ? diag::warn_precedence_bitwise_conditional
8988 : diag::warn_precedence_conditional;
8989
8990 Self.Diag(OpLoc, DiagID)
8991 << Condition->getSourceRange()
8992 << BinaryOperator::getOpcodeStr(CondOpcode);
8993
8994 SuggestParentheses(
8995 Self, OpLoc,
8996 Self.PDiag(diag::note_precedence_silence)
8997 << BinaryOperator::getOpcodeStr(CondOpcode),
8998 SourceRange(Condition->getBeginLoc(), Condition->getEndLoc()));
8999
9000 SuggestParentheses(Self, OpLoc,
9001 Self.PDiag(diag::note_precedence_conditional_first),
9002 SourceRange(CondRHS->getBeginLoc(), RHSExpr->getEndLoc()));
9003}
9004
9005/// Compute the nullability of a conditional expression.
9006static QualType computeConditionalNullability(QualType ResTy, bool IsBin,
9007 QualType LHSTy, QualType RHSTy,
9008 ASTContext &Ctx) {
9009 if (!ResTy->isAnyPointerType())
9010 return ResTy;
9011
9012 auto GetNullability = [&Ctx](QualType Ty) {
9013 Optional<NullabilityKind> Kind = Ty->getNullability(Ctx);
9014 if (Kind) {
9015 // For our purposes, treat _Nullable_result as _Nullable.
9016 if (*Kind == NullabilityKind::NullableResult)
9017 return NullabilityKind::Nullable;
9018 return *Kind;
9019 }
9020 return NullabilityKind::Unspecified;
9021 };
9022
9023 auto LHSKind = GetNullability(LHSTy), RHSKind = GetNullability(RHSTy);
9024 NullabilityKind MergedKind;
9025
9026 // Compute nullability of a binary conditional expression.
9027 if (IsBin) {
9028 if (LHSKind == NullabilityKind::NonNull)
9029 MergedKind = NullabilityKind::NonNull;
9030 else
9031 MergedKind = RHSKind;
9032 // Compute nullability of a normal conditional expression.
9033 } else {
9034 if (LHSKind == NullabilityKind::Nullable ||
9035 RHSKind == NullabilityKind::Nullable)
9036 MergedKind = NullabilityKind::Nullable;
9037 else if (LHSKind == NullabilityKind::NonNull)
9038 MergedKind = RHSKind;
9039 else if (RHSKind == NullabilityKind::NonNull)
9040 MergedKind = LHSKind;
9041 else
9042 MergedKind = NullabilityKind::Unspecified;
9043 }
9044
9045 // Return if ResTy already has the correct nullability.
9046 if (GetNullability(ResTy) == MergedKind)
9047 return ResTy;
9048
9049 // Strip all nullability from ResTy.
9050 while (ResTy->getNullability(Ctx))
9051 ResTy = ResTy.getSingleStepDesugaredType(Ctx);
9052
9053 // Create a new AttributedType with the new nullability kind.
9054 auto NewAttr = AttributedType::getNullabilityAttrKind(MergedKind);
9055 return Ctx.getAttributedType(NewAttr, ResTy, ResTy);
9056}
9057
9058/// ActOnConditionalOp - Parse a ?: operation. Note that 'LHS' may be null
9059/// in the case of a the GNU conditional expr extension.
9060ExprResult Sema::ActOnConditionalOp(SourceLocation QuestionLoc,
9061 SourceLocation ColonLoc,
9062 Expr *CondExpr, Expr *LHSExpr,
9063 Expr *RHSExpr) {
9064 if (!Context.isDependenceAllowed()) {
9065 // C cannot handle TypoExpr nodes in the condition because it
9066 // doesn't handle dependent types properly, so make sure any TypoExprs have
9067 // been dealt with before checking the operands.
9068 ExprResult CondResult = CorrectDelayedTyposInExpr(CondExpr);
9069 ExprResult LHSResult = CorrectDelayedTyposInExpr(LHSExpr);
9070 ExprResult RHSResult = CorrectDelayedTyposInExpr(RHSExpr);
9071
9072 if (!CondResult.isUsable())
9073 return ExprError();
9074
9075 if (LHSExpr) {
9076 if (!LHSResult.isUsable())
9077 return ExprError();
9078 }
9079
9080 if (!RHSResult.isUsable())
9081 return ExprError();
9082
9083 CondExpr = CondResult.get();
9084 LHSExpr = LHSResult.get();
9085 RHSExpr = RHSResult.get();
9086 }
9087
9088 // If this is the gnu "x ?: y" extension, analyze the types as though the LHS
9089 // was the condition.
9090 OpaqueValueExpr *opaqueValue = nullptr;
9091 Expr *commonExpr = nullptr;
9092 if (!LHSExpr) {
9093 commonExpr = CondExpr;
9094 // Lower out placeholder types first. This is important so that we don't
9095 // try to capture a placeholder. This happens in few cases in C++; such
9096 // as Objective-C++'s dictionary subscripting syntax.
9097 if (commonExpr->hasPlaceholderType()) {
9098 ExprResult result = CheckPlaceholderExpr(commonExpr);
9099 if (!result.isUsable()) return ExprError();
9100 commonExpr = result.get();
9101 }
9102 // We usually want to apply unary conversions *before* saving, except
9103 // in the special case of a C++ l-value conditional.
9104 if (!(getLangOpts().CPlusPlus
9105 && !commonExpr->isTypeDependent()
9106 && commonExpr->getValueKind() == RHSExpr->getValueKind()
9107 && commonExpr->isGLValue()
9108 && commonExpr->isOrdinaryOrBitFieldObject()
9109 && RHSExpr->isOrdinaryOrBitFieldObject()
9110 && Context.hasSameType(commonExpr->getType(), RHSExpr->getType()))) {
9111 ExprResult commonRes = UsualUnaryConversions(commonExpr);
9112 if (commonRes.isInvalid())
9113 return ExprError();
9114 commonExpr = commonRes.get();
9115 }
9116
9117 // If the common expression is a class or array prvalue, materialize it
9118 // so that we can safely refer to it multiple times.
9119 if (commonExpr->isPRValue() && (commonExpr->getType()->isRecordType() ||
9120 commonExpr->getType()->isArrayType())) {
9121 ExprResult MatExpr = TemporaryMaterializationConversion(commonExpr);
9122 if (MatExpr.isInvalid())
9123 return ExprError();
9124 commonExpr = MatExpr.get();
9125 }
9126
9127 opaqueValue = new (Context) OpaqueValueExpr(commonExpr->getExprLoc(),
9128 commonExpr->getType(),
9129 commonExpr->getValueKind(),
9130 commonExpr->getObjectKind(),
9131 commonExpr);
9132 LHSExpr = CondExpr = opaqueValue;
9133 }
9134
9135 QualType LHSTy = LHSExpr->getType(), RHSTy = RHSExpr->getType();
9136 ExprValueKind VK = VK_PRValue;
9137 ExprObjectKind OK = OK_Ordinary;
9138 ExprResult Cond = CondExpr, LHS = LHSExpr, RHS = RHSExpr;
9139 QualType result = CheckConditionalOperands(Cond, LHS, RHS,
9140 VK, OK, QuestionLoc);
9141 if (result.isNull() || Cond.isInvalid() || LHS.isInvalid() ||
9142 RHS.isInvalid())
9143 return ExprError();
9144
9145 DiagnoseConditionalPrecedence(*this, QuestionLoc, Cond.get(), LHS.get(),
9146 RHS.get());
9147
9148 CheckBoolLikeConversion(Cond.get(), QuestionLoc);
9149
9150 result = computeConditionalNullability(result, commonExpr, LHSTy, RHSTy,
9151 Context);
9152
9153 if (!commonExpr)
9154 return new (Context)
9155 ConditionalOperator(Cond.get(), QuestionLoc, LHS.get(), ColonLoc,
9156 RHS.get(), result, VK, OK);
9157
9158 return new (Context) BinaryConditionalOperator(
9159 commonExpr, opaqueValue, Cond.get(), LHS.get(), RHS.get(), QuestionLoc,
9160 ColonLoc, result, VK, OK);
9161}
9162
9163// Check if we have a conversion between incompatible cmse function pointer
9164// types, that is, a conversion between a function pointer with the
9165// cmse_nonsecure_call attribute and one without.
9166static bool IsInvalidCmseNSCallConversion(Sema &S, QualType FromType,
9167 QualType ToType) {
9168 if (const auto *ToFn =
9169 dyn_cast<FunctionType>(S.Context.getCanonicalType(ToType))) {
9170 if (const auto *FromFn =
9171 dyn_cast<FunctionType>(S.Context.getCanonicalType(FromType))) {
9172 FunctionType::ExtInfo ToEInfo = ToFn->getExtInfo();
9173 FunctionType::ExtInfo FromEInfo = FromFn->getExtInfo();
9174
9175 return ToEInfo.getCmseNSCall() != FromEInfo.getCmseNSCall();
9176 }
9177 }
9178 return false;
9179}
9180
9181// checkPointerTypesForAssignment - This is a very tricky routine (despite
9182// being closely modeled after the C99 spec:-). The odd characteristic of this
9183// routine is it effectively iqnores the qualifiers on the top level pointee.
9184// This circumvents the usual type rules specified in 6.2.7p1 & 6.7.5.[1-3].
9185// FIXME: add a couple examples in this comment.
9186static Sema::AssignConvertType
9187checkPointerTypesForAssignment(Sema &S, QualType LHSType, QualType RHSType) {
9188 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", 9188, __extension__ __PRETTY_FUNCTION__
))
;
9189 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", 9189, __extension__ __PRETTY_FUNCTION__
))
;
9190
9191 // get the "pointed to" type (ignoring qualifiers at the top level)
9192 const Type *lhptee, *rhptee;
9193 Qualifiers lhq, rhq;
9194 std::tie(lhptee, lhq) =
9195 cast<PointerType>(LHSType)->getPointeeType().split().asPair();
9196 std::tie(rhptee, rhq) =
9197 cast<PointerType>(RHSType)->getPointeeType().split().asPair();
9198
9199 Sema::AssignConvertType ConvTy = Sema::Compatible;
9200
9201 // C99 6.5.16.1p1: This following citation is common to constraints
9202 // 3 & 4 (below). ...and the type *pointed to* by the left has all the
9203 // qualifiers of the type *pointed to* by the right;
9204
9205 // As a special case, 'non-__weak A *' -> 'non-__weak const *' is okay.
9206 if (lhq.getObjCLifetime() != rhq.getObjCLifetime() &&
9207 lhq.compatiblyIncludesObjCLifetime(rhq)) {
9208 // Ignore lifetime for further calculation.
9209 lhq.removeObjCLifetime();
9210 rhq.removeObjCLifetime();
9211 }
9212
9213 if (!lhq.compatiblyIncludes(rhq)) {
9214 // Treat address-space mismatches as fatal.
9215 if (!lhq.isAddressSpaceSupersetOf(rhq))
9216 return Sema::IncompatiblePointerDiscardsQualifiers;
9217
9218 // It's okay to add or remove GC or lifetime qualifiers when converting to
9219 // and from void*.
9220 else if (lhq.withoutObjCGCAttr().withoutObjCLifetime()
9221 .compatiblyIncludes(
9222 rhq.withoutObjCGCAttr().withoutObjCLifetime())
9223 && (lhptee->isVoidType() || rhptee->isVoidType()))
9224 ; // keep old
9225
9226 // Treat lifetime mismatches as fatal.
9227 else if (lhq.getObjCLifetime() != rhq.getObjCLifetime())
9228 ConvTy = Sema::IncompatiblePointerDiscardsQualifiers;
9229
9230 // For GCC/MS compatibility, other qualifier mismatches are treated
9231 // as still compatible in C.
9232 else ConvTy = Sema::CompatiblePointerDiscardsQualifiers;
9233 }
9234
9235 // C99 6.5.16.1p1 (constraint 4): If one operand is a pointer to an object or
9236 // incomplete type and the other is a pointer to a qualified or unqualified
9237 // version of void...
9238 if (lhptee->isVoidType()) {
9239 if (rhptee->isIncompleteOrObjectType())
9240 return ConvTy;
9241
9242 // As an extension, we allow cast to/from void* to function pointer.
9243 assert(rhptee->isFunctionType())(static_cast <bool> (rhptee->isFunctionType()) ? void
(0) : __assert_fail ("rhptee->isFunctionType()", "clang/lib/Sema/SemaExpr.cpp"
, 9243, __extension__ __PRETTY_FUNCTION__))
;
9244 return Sema::FunctionVoidPointer;
9245 }
9246
9247 if (rhptee->isVoidType()) {
9248 if (lhptee->isIncompleteOrObjectType())
9249 return ConvTy;
9250
9251 // As an extension, we allow cast to/from void* to function pointer.
9252 assert(lhptee->isFunctionType())(static_cast <bool> (lhptee->isFunctionType()) ? void
(0) : __assert_fail ("lhptee->isFunctionType()", "clang/lib/Sema/SemaExpr.cpp"
, 9252, __extension__ __PRETTY_FUNCTION__))
;
9253 return Sema::FunctionVoidPointer;
9254 }
9255
9256 // C99 6.5.16.1p1 (constraint 3): both operands are pointers to qualified or
9257 // unqualified versions of compatible types, ...
9258 QualType ltrans = QualType(lhptee, 0), rtrans = QualType(rhptee, 0);
9259 if (!S.Context.typesAreCompatible(ltrans, rtrans)) {
9260 // Check if the pointee types are compatible ignoring the sign.
9261 // We explicitly check for char so that we catch "char" vs
9262 // "unsigned char" on systems where "char" is unsigned.
9263 if (lhptee->isCharType())
9264 ltrans = S.Context.UnsignedCharTy;
9265 else if (lhptee->hasSignedIntegerRepresentation())
9266 ltrans = S.Context.getCorrespondingUnsignedType(ltrans);
9267
9268 if (rhptee->isCharType())
9269 rtrans = S.Context.UnsignedCharTy;
9270 else if (rhptee->hasSignedIntegerRepresentation())
9271 rtrans = S.Context.getCorrespondingUnsignedType(rtrans);
9272
9273 if (ltrans == rtrans) {
9274 // Types are compatible ignoring the sign. Qualifier incompatibility
9275 // takes priority over sign incompatibility because the sign
9276 // warning can be disabled.
9277 if (ConvTy != Sema::Compatible)
9278 return ConvTy;
9279
9280 return Sema::IncompatiblePointerSign;
9281 }
9282
9283 // If we are a multi-level pointer, it's possible that our issue is simply
9284 // one of qualification - e.g. char ** -> const char ** is not allowed. If
9285 // the eventual target type is the same and the pointers have the same
9286 // level of indirection, this must be the issue.
9287 if (isa<PointerType>(lhptee) && isa<PointerType>(rhptee)) {
9288 do {
9289 std::tie(lhptee, lhq) =
9290 cast<PointerType>(lhptee)->getPointeeType().split().asPair();
9291 std::tie(rhptee, rhq) =
9292 cast<PointerType>(rhptee)->getPointeeType().split().asPair();
9293
9294 // Inconsistent address spaces at this point is invalid, even if the
9295 // address spaces would be compatible.
9296 // FIXME: This doesn't catch address space mismatches for pointers of
9297 // different nesting levels, like:
9298 // __local int *** a;
9299 // int ** b = a;
9300 // It's not clear how to actually determine when such pointers are
9301 // invalidly incompatible.
9302 if (lhq.getAddressSpace() != rhq.getAddressSpace())
9303 return Sema::IncompatibleNestedPointerAddressSpaceMismatch;
9304
9305 } while (isa<PointerType>(lhptee) && isa<PointerType>(rhptee));
9306
9307 if (lhptee == rhptee)
9308 return Sema::IncompatibleNestedPointerQualifiers;
9309 }
9310
9311 // General pointer incompatibility takes priority over qualifiers.
9312 if (RHSType->isFunctionPointerType() && LHSType->isFunctionPointerType())
9313 return Sema::IncompatibleFunctionPointer;
9314 return Sema::IncompatiblePointer;
9315 }
9316 if (!S.getLangOpts().CPlusPlus &&
9317 S.IsFunctionConversion(ltrans, rtrans, ltrans))
9318 return Sema::IncompatibleFunctionPointer;
9319 if (IsInvalidCmseNSCallConversion(S, ltrans, rtrans))
9320 return Sema::IncompatibleFunctionPointer;
9321 return ConvTy;
9322}
9323
9324/// checkBlockPointerTypesForAssignment - This routine determines whether two
9325/// block pointer types are compatible or whether a block and normal pointer
9326/// are compatible. It is more restrict than comparing two function pointer
9327// types.
9328static Sema::AssignConvertType
9329checkBlockPointerTypesForAssignment(Sema &S, QualType LHSType,
9330 QualType RHSType) {
9331 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", 9331, __extension__ __PRETTY_FUNCTION__
))
;
9332 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", 9332, __extension__ __PRETTY_FUNCTION__
))
;
9333
9334 QualType lhptee, rhptee;
9335
9336 // get the "pointed to" type (ignoring qualifiers at the top level)
9337 lhptee = cast<BlockPointerType>(LHSType)->getPointeeType();
9338 rhptee = cast<BlockPointerType>(RHSType)->getPointeeType();
9339
9340 // In C++, the types have to match exactly.
9341 if (S.getLangOpts().CPlusPlus)
9342 return Sema::IncompatibleBlockPointer;
9343
9344 Sema::AssignConvertType ConvTy = Sema::Compatible;
9345
9346 // For blocks we enforce that qualifiers are identical.
9347 Qualifiers LQuals = lhptee.getLocalQualifiers();
9348 Qualifiers RQuals = rhptee.getLocalQualifiers();
9349 if (S.getLangOpts().OpenCL) {
9350 LQuals.removeAddressSpace();
9351 RQuals.removeAddressSpace();
9352 }
9353 if (LQuals != RQuals)
9354 ConvTy = Sema::CompatiblePointerDiscardsQualifiers;
9355
9356 // FIXME: OpenCL doesn't define the exact compile time semantics for a block
9357 // assignment.
9358 // The current behavior is similar to C++ lambdas. A block might be
9359 // assigned to a variable iff its return type and parameters are compatible
9360 // (C99 6.2.7) with the corresponding return type and parameters of the LHS of
9361 // an assignment. Presumably it should behave in way that a function pointer
9362 // assignment does in C, so for each parameter and return type:
9363 // * CVR and address space of LHS should be a superset of CVR and address
9364 // space of RHS.
9365 // * unqualified types should be compatible.
9366 if (S.getLangOpts().OpenCL) {
9367 if (!S.Context.typesAreBlockPointerCompatible(
9368 S.Context.getQualifiedType(LHSType.getUnqualifiedType(), LQuals),
9369 S.Context.getQualifiedType(RHSType.getUnqualifiedType(), RQuals)))
9370 return Sema::IncompatibleBlockPointer;
9371 } else if (!S.Context.typesAreBlockPointerCompatible(LHSType, RHSType))
9372 return Sema::IncompatibleBlockPointer;
9373
9374 return ConvTy;
9375}
9376
9377/// checkObjCPointerTypesForAssignment - Compares two objective-c pointer types
9378/// for assignment compatibility.
9379static Sema::AssignConvertType
9380checkObjCPointerTypesForAssignment(Sema &S, QualType LHSType,
9381 QualType RHSType) {
9382 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", 9382, __extension__ __PRETTY_FUNCTION__
))
;
9383 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", 9383, __extension__ __PRETTY_FUNCTION__
))
;
9384
9385 if (LHSType->isObjCBuiltinType()) {
9386 // Class is not compatible with ObjC object pointers.
9387 if (LHSType->isObjCClassType() && !RHSType->isObjCBuiltinType() &&
9388 !RHSType->isObjCQualifiedClassType())
9389 return Sema::IncompatiblePointer;
9390 return Sema::Compatible;
9391 }
9392 if (RHSType->isObjCBuiltinType()) {
9393 if (RHSType->isObjCClassType() && !LHSType->isObjCBuiltinType() &&
9394 !LHSType->isObjCQualifiedClassType())
9395 return Sema::IncompatiblePointer;
9396 return Sema::Compatible;
9397 }
9398 QualType lhptee = LHSType->castAs<ObjCObjectPointerType>()->getPointeeType();
9399 QualType rhptee = RHSType->castAs<ObjCObjectPointerType>()->getPointeeType();
9400
9401 if (!lhptee.isAtLeastAsQualifiedAs(rhptee) &&
9402 // make an exception for id<P>
9403 !LHSType->isObjCQualifiedIdType())
9404 return Sema::CompatiblePointerDiscardsQualifiers;
9405
9406 if (S.Context.typesAreCompatible(LHSType, RHSType))
9407 return Sema::Compatible;
9408 if (LHSType->isObjCQualifiedIdType() || RHSType->isObjCQualifiedIdType())
9409 return Sema::IncompatibleObjCQualifiedId;
9410 return Sema::IncompatiblePointer;
9411}
9412
9413Sema::AssignConvertType
9414Sema::CheckAssignmentConstraints(SourceLocation Loc,
9415 QualType LHSType, QualType RHSType) {
9416 // Fake up an opaque expression. We don't actually care about what
9417 // cast operations are required, so if CheckAssignmentConstraints
9418 // adds casts to this they'll be wasted, but fortunately that doesn't
9419 // usually happen on valid code.
9420 OpaqueValueExpr RHSExpr(Loc, RHSType, VK_PRValue);
9421 ExprResult RHSPtr = &RHSExpr;
9422 CastKind K;
9423
9424 return CheckAssignmentConstraints(LHSType, RHSPtr, K, /*ConvertRHS=*/false);
9425}
9426
9427/// This helper function returns true if QT is a vector type that has element
9428/// type ElementType.
9429static bool isVector(QualType QT, QualType ElementType) {
9430 if (const VectorType *VT = QT->getAs<VectorType>())
9431 return VT->getElementType().getCanonicalType() == ElementType;
9432 return false;
9433}
9434
9435/// CheckAssignmentConstraints (C99 6.5.16) - This routine currently
9436/// has code to accommodate several GCC extensions when type checking
9437/// pointers. Here are some objectionable examples that GCC considers warnings:
9438///
9439/// int a, *pint;
9440/// short *pshort;
9441/// struct foo *pfoo;
9442///
9443/// pint = pshort; // warning: assignment from incompatible pointer type
9444/// a = pint; // warning: assignment makes integer from pointer without a cast
9445/// pint = a; // warning: assignment makes pointer from integer without a cast
9446/// pint = pfoo; // warning: assignment from incompatible pointer type
9447///
9448/// As a result, the code for dealing with pointers is more complex than the
9449/// C99 spec dictates.
9450///
9451/// Sets 'Kind' for any result kind except Incompatible.
9452Sema::AssignConvertType
9453Sema::CheckAssignmentConstraints(QualType LHSType, ExprResult &RHS,
9454 CastKind &Kind, bool ConvertRHS) {
9455 QualType RHSType = RHS.get()->getType();
9456 QualType OrigLHSType = LHSType;
9457
9458 // Get canonical types. We're not formatting these types, just comparing
9459 // them.
9460 LHSType = Context.getCanonicalType(LHSType).getUnqualifiedType();
9461 RHSType = Context.getCanonicalType(RHSType).getUnqualifiedType();
9462
9463 // Common case: no conversion required.
9464 if (LHSType == RHSType) {
9465 Kind = CK_NoOp;
9466 return Compatible;
9467 }
9468
9469 // If the LHS has an __auto_type, there are no additional type constraints
9470 // to be worried about.
9471 if (const auto *AT = dyn_cast<AutoType>(LHSType)) {
9472 if (AT->isGNUAutoType()) {
9473 Kind = CK_NoOp;
9474 return Compatible;
9475 }
9476 }
9477
9478 // If we have an atomic type, try a non-atomic assignment, then just add an
9479 // atomic qualification step.
9480 if (const AtomicType *AtomicTy = dyn_cast<AtomicType>(LHSType)) {
9481 Sema::AssignConvertType result =
9482 CheckAssignmentConstraints(AtomicTy->getValueType(), RHS, Kind);
9483 if (result != Compatible)
9484 return result;
9485 if (Kind != CK_NoOp && ConvertRHS)
9486 RHS = ImpCastExprToType(RHS.get(), AtomicTy->getValueType(), Kind);
9487 Kind = CK_NonAtomicToAtomic;
9488 return Compatible;
9489 }
9490
9491 // If the left-hand side is a reference type, then we are in a
9492 // (rare!) case where we've allowed the use of references in C,
9493 // e.g., as a parameter type in a built-in function. In this case,
9494 // just make sure that the type referenced is compatible with the
9495 // right-hand side type. The caller is responsible for adjusting
9496 // LHSType so that the resulting expression does not have reference
9497 // type.
9498 if (const ReferenceType *LHSTypeRef = LHSType->getAs<ReferenceType>()) {
9499 if (Context.typesAreCompatible(LHSTypeRef->getPointeeType(), RHSType)) {
9500 Kind = CK_LValueBitCast;
9501 return Compatible;
9502 }
9503 return Incompatible;
9504 }
9505
9506 // Allow scalar to ExtVector assignments, and assignments of an ExtVector type
9507 // to the same ExtVector type.
9508 if (LHSType->isExtVectorType()) {
9509 if (RHSType->isExtVectorType())
9510 return Incompatible;
9511 if (RHSType->isArithmeticType()) {
9512 // CK_VectorSplat does T -> vector T, so first cast to the element type.
9513 if (ConvertRHS)
9514 RHS = prepareVectorSplat(LHSType, RHS.get());
9515 Kind = CK_VectorSplat;
9516 return Compatible;
9517 }
9518 }
9519
9520 // Conversions to or from vector type.
9521 if (LHSType->isVectorType() || RHSType->isVectorType()) {
9522 if (LHSType->isVectorType() && RHSType->isVectorType()) {
9523 // Allow assignments of an AltiVec vector type to an equivalent GCC
9524 // vector type and vice versa
9525 if (Context.areCompatibleVectorTypes(LHSType, RHSType)) {
9526 Kind = CK_BitCast;
9527 return Compatible;
9528 }
9529
9530 // If we are allowing lax vector conversions, and LHS and RHS are both
9531 // vectors, the total size only needs to be the same. This is a bitcast;
9532 // no bits are changed but the result type is different.
9533 if (isLaxVectorConversion(RHSType, LHSType)) {
9534 Kind = CK_BitCast;
9535 return IncompatibleVectors;
9536 }
9537 }
9538
9539 // When the RHS comes from another lax conversion (e.g. binops between
9540 // scalars and vectors) the result is canonicalized as a vector. When the
9541 // LHS is also a vector, the lax is allowed by the condition above. Handle
9542 // the case where LHS is a scalar.
9543 if (LHSType->isScalarType()) {
9544 const VectorType *VecType = RHSType->getAs<VectorType>();
9545 if (VecType && VecType->getNumElements() == 1 &&
9546 isLaxVectorConversion(RHSType, LHSType)) {
9547 ExprResult *VecExpr = &RHS;
9548 *VecExpr = ImpCastExprToType(VecExpr->get(), LHSType, CK_BitCast);
9549 Kind = CK_BitCast;
9550 return Compatible;
9551 }
9552 }
9553
9554 // Allow assignments between fixed-length and sizeless SVE vectors.
9555 if ((LHSType->isSizelessBuiltinType() && RHSType->isVectorType()) ||
9556 (LHSType->isVectorType() && RHSType->isSizelessBuiltinType()))
9557 if (Context.areCompatibleSveTypes(LHSType, RHSType) ||
9558 Context.areLaxCompatibleSveTypes(LHSType, RHSType)) {
9559 Kind = CK_BitCast;
9560 return Compatible;
9561 }
9562
9563 return Incompatible;
9564 }
9565
9566 // Diagnose attempts to convert between __ibm128, __float128 and long double
9567 // where such conversions currently can't be handled.
9568 if (unsupportedTypeConversion(*this, LHSType, RHSType))
9569 return Incompatible;
9570
9571 // Disallow assigning a _Complex to a real type in C++ mode since it simply
9572 // discards the imaginary part.
9573 if (getLangOpts().CPlusPlus && RHSType->getAs<ComplexType>() &&
9574 !LHSType->getAs<ComplexType>())
9575 return Incompatible;
9576
9577 // Arithmetic conversions.
9578 if (LHSType->isArithmeticType() && RHSType->isArithmeticType() &&
9579 !(getLangOpts().CPlusPlus && LHSType->isEnumeralType())) {
9580 if (ConvertRHS)
9581 Kind = PrepareScalarCast(RHS, LHSType);
9582 return Compatible;
9583 }
9584
9585 // Conversions to normal pointers.
9586 if (const PointerType *LHSPointer = dyn_cast<PointerType>(LHSType)) {
9587 // U* -> T*
9588 if (isa<PointerType>(RHSType)) {
9589 LangAS AddrSpaceL = LHSPointer->getPointeeType().getAddressSpace();
9590 LangAS AddrSpaceR = RHSType->getPointeeType().getAddressSpace();
9591 if (AddrSpaceL != AddrSpaceR)
9592 Kind = CK_AddressSpaceConversion;
9593 else if (Context.hasCvrSimilarType(RHSType, LHSType))
9594 Kind = CK_NoOp;
9595 else
9596 Kind = CK_BitCast;
9597 return checkPointerTypesForAssignment(*this, LHSType, RHSType);
9598 }
9599
9600 // int -> T*
9601 if (RHSType->isIntegerType()) {
9602 Kind = CK_IntegralToPointer; // FIXME: null?
9603 return IntToPointer;
9604 }
9605
9606 // C pointers are not compatible with ObjC object pointers,
9607 // with two exceptions:
9608 if (isa<ObjCObjectPointerType>(RHSType)) {
9609 // - conversions to void*
9610 if (LHSPointer->getPointeeType()->isVoidType()) {
9611 Kind = CK_BitCast;
9612 return Compatible;
9613 }
9614
9615 // - conversions from 'Class' to the redefinition type
9616 if (RHSType->isObjCClassType() &&
9617 Context.hasSameType(LHSType,
9618 Context.getObjCClassRedefinitionType())) {
9619 Kind = CK_BitCast;
9620 return Compatible;
9621 }
9622
9623 Kind = CK_BitCast;
9624 return IncompatiblePointer;
9625 }
9626
9627 // U^ -> void*
9628 if (RHSType->getAs<BlockPointerType>()) {
9629 if (LHSPointer->getPointeeType()->isVoidType()) {
9630 LangAS AddrSpaceL = LHSPointer->getPointeeType().getAddressSpace();
9631 LangAS AddrSpaceR = RHSType->getAs<BlockPointerType>()
9632 ->getPointeeType()
9633 .getAddressSpace();
9634 Kind =
9635 AddrSpaceL != AddrSpaceR ? CK_AddressSpaceConversion : CK_BitCast;
9636 return Compatible;
9637 }
9638 }
9639
9640 return Incompatible;
9641 }
9642
9643 // Conversions to block pointers.
9644 if (isa<BlockPointerType>(LHSType)) {
9645 // U^ -> T^
9646 if (RHSType->isBlockPointerType()) {
9647 LangAS AddrSpaceL = LHSType->getAs<BlockPointerType>()
9648 ->getPointeeType()
9649 .getAddressSpace();
9650 LangAS AddrSpaceR = RHSType->getAs<BlockPointerType>()
9651 ->getPointeeType()
9652 .getAddressSpace();
9653 Kind = AddrSpaceL != AddrSpaceR ? CK_AddressSpaceConversion : CK_BitCast;
9654 return checkBlockPointerTypesForAssignment(*this, LHSType, RHSType);
9655 }
9656
9657 // int or null -> T^
9658 if (RHSType->isIntegerType()) {
9659 Kind = CK_IntegralToPointer; // FIXME: null
9660 return IntToBlockPointer;
9661 }
9662
9663 // id -> T^
9664 if (getLangOpts().ObjC && RHSType->isObjCIdType()) {
9665 Kind = CK_AnyPointerToBlockPointerCast;
9666 return Compatible;
9667 }
9668
9669 // void* -> T^
9670 if (const PointerType *RHSPT = RHSType->getAs<PointerType>())
9671 if (RHSPT->getPointeeType()->isVoidType()) {
9672 Kind = CK_AnyPointerToBlockPointerCast;
9673 return Compatible;
9674 }
9675
9676 return Incompatible;
9677 }
9678
9679 // Conversions to Objective-C pointers.
9680 if (isa<ObjCObjectPointerType>(LHSType)) {
9681 // A* -> B*
9682 if (RHSType->isObjCObjectPointerType()) {
9683 Kind = CK_BitCast;
9684 Sema::AssignConvertType result =
9685 checkObjCPointerTypesForAssignment(*this, LHSType, RHSType);
9686 if (getLangOpts().allowsNonTrivialObjCLifetimeQualifiers() &&
9687 result == Compatible &&
9688 !CheckObjCARCUnavailableWeakConversion(OrigLHSType, RHSType))
9689 result = IncompatibleObjCWeakRef;
9690 return result;
9691 }
9692
9693 // int or null -> A*
9694 if (RHSType->isIntegerType()) {
9695 Kind = CK_IntegralToPointer; // FIXME: null
9696 return IntToPointer;
9697 }
9698
9699 // In general, C pointers are not compatible with ObjC object pointers,
9700 // with two exceptions:
9701 if (isa<PointerType>(RHSType)) {
9702 Kind = CK_CPointerToObjCPointerCast;
9703
9704 // - conversions from 'void*'
9705 if (RHSType->isVoidPointerType()) {
9706 return Compatible;
9707 }
9708
9709 // - conversions to 'Class' from its redefinition type
9710 if (LHSType->isObjCClassType() &&
9711 Context.hasSameType(RHSType,
9712 Context.getObjCClassRedefinitionType())) {
9713 return Compatible;
9714 }
9715
9716 return IncompatiblePointer;
9717 }
9718
9719 // Only under strict condition T^ is compatible with an Objective-C pointer.
9720 if (RHSType->isBlockPointerType() &&
9721 LHSType->isBlockCompatibleObjCPointerType(Context)) {
9722 if (ConvertRHS)
9723 maybeExtendBlockObject(RHS);
9724 Kind = CK_BlockPointerToObjCPointerCast;
9725 return Compatible;
9726 }
9727
9728 return Incompatible;
9729 }
9730
9731 // Conversions from pointers that are not covered by the above.
9732 if (isa<PointerType>(RHSType)) {
9733 // T* -> _Bool
9734 if (LHSType == Context.BoolTy) {
9735 Kind = CK_PointerToBoolean;
9736 return Compatible;
9737 }
9738
9739 // T* -> int
9740 if (LHSType->isIntegerType()) {
9741 Kind = CK_PointerToIntegral;
9742 return PointerToInt;
9743 }
9744
9745 return Incompatible;
9746 }
9747
9748 // Conversions from Objective-C pointers that are not covered by the above.
9749 if (isa<ObjCObjectPointerType>(RHSType)) {
9750 // T* -> _Bool
9751 if (LHSType == Context.BoolTy) {
9752 Kind = CK_PointerToBoolean;
9753 return Compatible;
9754 }
9755
9756 // T* -> int
9757 if (LHSType->isIntegerType()) {
9758 Kind = CK_PointerToIntegral;
9759 return PointerToInt;
9760 }
9761
9762 return Incompatible;
9763 }
9764
9765 // struct A -> struct B
9766 if (isa<TagType>(LHSType) && isa<TagType>(RHSType)) {
9767 if (Context.typesAreCompatible(LHSType, RHSType)) {
9768 Kind = CK_NoOp;
9769 return Compatible;
9770 }
9771 }
9772
9773 if (LHSType->isSamplerT() && RHSType->isIntegerType()) {
9774 Kind = CK_IntToOCLSampler;
9775 return Compatible;
9776 }
9777
9778 return Incompatible;
9779}
9780
9781/// Constructs a transparent union from an expression that is
9782/// used to initialize the transparent union.
9783static void ConstructTransparentUnion(Sema &S, ASTContext &C,
9784 ExprResult &EResult, QualType UnionType,
9785 FieldDecl *Field) {
9786 // Build an initializer list that designates the appropriate member
9787 // of the transparent union.
9788 Expr *E = EResult.get();
9789 InitListExpr *Initializer = new (C) InitListExpr(C, SourceLocation(),
9790 E, SourceLocation());
9791 Initializer->setType(UnionType);
9792 Initializer->setInitializedFieldInUnion(Field);
9793
9794 // Build a compound literal constructing a value of the transparent
9795 // union type from this initializer list.
9796 TypeSourceInfo *unionTInfo = C.getTrivialTypeSourceInfo(UnionType);
9797 EResult = new (C) CompoundLiteralExpr(SourceLocation(), unionTInfo, UnionType,
9798 VK_PRValue, Initializer, false);
9799}
9800
9801Sema::AssignConvertType
9802Sema::CheckTransparentUnionArgumentConstraints(QualType ArgType,
9803 ExprResult &RHS) {
9804 QualType RHSType = RHS.get()->getType();
9805
9806 // If the ArgType is a Union type, we want to handle a potential
9807 // transparent_union GCC extension.
9808 const RecordType *UT = ArgType->getAsUnionType();
9809 if (!UT || !UT->getDecl()->hasAttr<TransparentUnionAttr>())
9810 return Incompatible;
9811
9812 // The field to initialize within the transparent union.
9813 RecordDecl *UD = UT->getDecl();
9814 FieldDecl *InitField = nullptr;
9815 // It's compatible if the expression matches any of the fields.
9816 for (auto *it : UD->fields()) {
9817 if (it->getType()->isPointerType()) {
9818 // If the transparent union contains a pointer type, we allow:
9819 // 1) void pointer
9820 // 2) null pointer constant
9821 if (RHSType->isPointerType())
9822 if (RHSType->castAs<PointerType>()->getPointeeType()->isVoidType()) {
9823 RHS = ImpCastExprToType(RHS.get(), it->getType(), CK_BitCast);
9824 InitField = it;
9825 break;
9826 }
9827
9828 if (RHS.get()->isNullPointerConstant(Context,
9829 Expr::NPC_ValueDependentIsNull)) {
9830 RHS = ImpCastExprToType(RHS.get(), it->getType(),
9831 CK_NullToPointer);
9832 InitField = it;
9833 break;
9834 }
9835 }
9836
9837 CastKind Kind;
9838 if (CheckAssignmentConstraints(it->getType(), RHS, Kind)
9839 == Compatible) {
9840 RHS = ImpCastExprToType(RHS.get(), it->getType(), Kind);
9841 InitField = it;
9842 break;
9843 }
9844 }
9845
9846 if (!InitField)
9847 return Incompatible;
9848
9849 ConstructTransparentUnion(*this, Context, RHS, ArgType, InitField);
9850 return Compatible;
9851}
9852
9853Sema::AssignConvertType
9854Sema::CheckSingleAssignmentConstraints(QualType LHSType, ExprResult &CallerRHS,
9855 bool Diagnose,
9856 bool DiagnoseCFAudited,
9857 bool ConvertRHS) {
9858 // We need to be able to tell the caller whether we diagnosed a problem, if
9859 // they ask us to issue diagnostics.
9860 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", 9860, __extension__ __PRETTY_FUNCTION__
))
;
9861
9862 // If ConvertRHS is false, we want to leave the caller's RHS untouched. Sadly,
9863 // we can't avoid *all* modifications at the moment, so we need some somewhere
9864 // to put the updated value.
9865 ExprResult LocalRHS = CallerRHS;
9866 ExprResult &RHS = ConvertRHS ? CallerRHS : LocalRHS;
9867
9868 if (const auto *LHSPtrType = LHSType->getAs<PointerType>()) {
9869 if (const auto *RHSPtrType = RHS.get()->getType()->getAs<PointerType>()) {
9870 if (RHSPtrType->getPointeeType()->hasAttr(attr::NoDeref) &&
9871 !LHSPtrType->getPointeeType()->hasAttr(attr::NoDeref)) {
9872 Diag(RHS.get()->getExprLoc(),
9873 diag::warn_noderef_to_dereferenceable_pointer)
9874 << RHS.get()->getSourceRange();
9875 }
9876 }
9877 }
9878
9879 if (getLangOpts().CPlusPlus) {
9880 if (!LHSType->isRecordType() && !LHSType->isAtomicType()) {
9881 // C++ 5.17p3: If the left operand is not of class type, the
9882 // expression is implicitly converted (C++ 4) to the
9883 // cv-unqualified type of the left operand.
9884 QualType RHSType = RHS.get()->getType();
9885 if (Diagnose) {
9886 RHS = PerformImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(),
9887 AA_Assigning);
9888 } else {
9889 ImplicitConversionSequence ICS =
9890 TryImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(),
9891 /*SuppressUserConversions=*/false,
9892 AllowedExplicit::None,
9893 /*InOverloadResolution=*/false,
9894 /*CStyle=*/false,
9895 /*AllowObjCWritebackConversion=*/false);
9896 if (ICS.isFailure())
9897 return Incompatible;
9898 RHS = PerformImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(),
9899 ICS, AA_Assigning);
9900 }
9901 if (RHS.isInvalid())
9902 return Incompatible;
9903 Sema::AssignConvertType result = Compatible;
9904 if (getLangOpts().allowsNonTrivialObjCLifetimeQualifiers() &&
9905 !CheckObjCARCUnavailableWeakConversion(LHSType, RHSType))
9906 result = IncompatibleObjCWeakRef;
9907 return result;
9908 }
9909
9910 // FIXME: Currently, we fall through and treat C++ classes like C
9911 // structures.
9912 // FIXME: We also fall through for atomics; not sure what should
9913 // happen there, though.
9914 } else if (RHS.get()->getType() == Context.OverloadTy) {
9915 // As a set of extensions to C, we support overloading on functions. These
9916 // functions need to be resolved here.
9917 DeclAccessPair DAP;
9918 if (FunctionDecl *FD = ResolveAddressOfOverloadedFunction(
9919 RHS.get(), LHSType, /*Complain=*/false, DAP))
9920 RHS = FixOverloadedFunctionReference(RHS.get(), DAP, FD);
9921 else
9922 return Incompatible;
9923 }
9924
9925 // C99 6.5.16.1p1: the left operand is a pointer and the right is
9926 // a null pointer constant.
9927 if ((LHSType->isPointerType() || LHSType->isObjCObjectPointerType() ||
9928 LHSType->isBlockPointerType()) &&
9929 RHS.get()->isNullPointerConstant(Context,
9930 Expr::NPC_ValueDependentIsNull)) {
9931 if (Diagnose || ConvertRHS) {
9932 CastKind Kind;
9933 CXXCastPath Path;
9934 CheckPointerConversion(RHS.get(), LHSType, Kind, Path,
9935 /*IgnoreBaseAccess=*/false, Diagnose);
9936 if (ConvertRHS)
9937 RHS = ImpCastExprToType(RHS.get(), LHSType, Kind, VK_PRValue, &Path);
9938 }
9939 return Compatible;
9940 }
9941
9942 // OpenCL queue_t type assignment.
9943 if (LHSType->isQueueT() && RHS.get()->isNullPointerConstant(
9944 Context, Expr::NPC_ValueDependentIsNull)) {
9945 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer);
9946 return Compatible;
9947 }
9948
9949 // This check seems unnatural, however it is necessary to ensure the proper
9950 // conversion of functions/arrays. If the conversion were done for all
9951 // DeclExpr's (created by ActOnIdExpression), it would mess up the unary
9952 // expressions that suppress this implicit conversion (&, sizeof).
9953 //
9954 // Suppress this for references: C++ 8.5.3p5.
9955 if (!LHSType->isReferenceType()) {
9956 // FIXME: We potentially allocate here even if ConvertRHS is false.
9957 RHS = DefaultFunctionArrayLvalueConversion(RHS.get(), Diagnose);
9958 if (RHS.isInvalid())
9959 return Incompatible;
9960 }
9961 CastKind Kind;
9962 Sema::AssignConvertType result =
9963 CheckAssignmentConstraints(LHSType, RHS, Kind, ConvertRHS);
9964
9965 // C99 6.5.16.1p2: The value of the right operand is converted to the
9966 // type of the assignment expression.
9967 // CheckAssignmentConstraints allows the left-hand side to be a reference,
9968 // so that we can use references in built-in functions even in C.
9969 // The getNonReferenceType() call makes sure that the resulting expression
9970 // does not have reference type.
9971 if (result != Incompatible && RHS.get()->getType() != LHSType) {
9972 QualType Ty = LHSType.getNonLValueExprType(Context);
9973 Expr *E = RHS.get();
9974
9975 // Check for various Objective-C errors. If we are not reporting
9976 // diagnostics and just checking for errors, e.g., during overload
9977 // resolution, return Incompatible to indicate the failure.
9978 if (getLangOpts().allowsNonTrivialObjCLifetimeQualifiers() &&
9979 CheckObjCConversion(SourceRange(), Ty, E, CCK_ImplicitConversion,
9980 Diagnose, DiagnoseCFAudited) != ACR_okay) {
9981 if (!Diagnose)
9982 return Incompatible;
9983 }
9984 if (getLangOpts().ObjC &&
9985 (CheckObjCBridgeRelatedConversions(E->getBeginLoc(), LHSType,
9986 E->getType(), E, Diagnose) ||
9987 CheckConversionToObjCLiteral(LHSType, E, Diagnose))) {
9988 if (!Diagnose)
9989 return Incompatible;
9990 // Replace the expression with a corrected version and continue so we
9991 // can find further errors.
9992 RHS = E;
9993 return Compatible;
9994 }
9995
9996 if (ConvertRHS)
9997 RHS = ImpCastExprToType(E, Ty, Kind);
9998 }
9999
10000 return result;
10001}
10002
10003namespace {
10004/// The original operand to an operator, prior to the application of the usual
10005/// arithmetic conversions and converting the arguments of a builtin operator
10006/// candidate.
10007struct OriginalOperand {
10008 explicit OriginalOperand(Expr *Op) : Orig(Op), Conversion(nullptr) {
10009 if (auto *MTE = dyn_cast<MaterializeTemporaryExpr>(Op))
10010 Op = MTE->getSubExpr();
10011 if (auto *BTE = dyn_cast<CXXBindTemporaryExpr>(Op))
10012 Op = BTE->getSubExpr();
10013 if (auto *ICE = dyn_cast<ImplicitCastExpr>(Op)) {
10014 Orig = ICE->getSubExprAsWritten();
10015 Conversion = ICE->getConversionFunction();
10016 }
10017 }
10018
10019 QualType getType() const { return Orig->getType(); }
10020
10021 Expr *Orig;
10022 NamedDecl *Conversion;
10023};
10024}
10025
10026QualType Sema::InvalidOperands(SourceLocation Loc, ExprResult &LHS,
10027 ExprResult &RHS) {
10028 OriginalOperand OrigLHS(LHS.get()), OrigRHS(RHS.get());
10029
10030 Diag(Loc, diag::err_typecheck_invalid_operands)
10031 << OrigLHS.getType() << OrigRHS.getType()
10032 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
10033
10034 // If a user-defined conversion was applied to either of the operands prior
10035 // to applying the built-in operator rules, tell the user about it.
10036 if (OrigLHS.Conversion) {
10037 Diag(OrigLHS.Conversion->getLocation(),
10038 diag::note_typecheck_invalid_operands_converted)
10039 << 0 << LHS.get()->getType();
10040 }
10041 if (OrigRHS.Conversion) {
10042 Diag(OrigRHS.Conversion->getLocation(),
10043 diag::note_typecheck_invalid_operands_converted)
10044 << 1 << RHS.get()->getType();
10045 }
10046
10047 return QualType();
10048}
10049
10050// Diagnose cases where a scalar was implicitly converted to a vector and
10051// diagnose the underlying types. Otherwise, diagnose the error
10052// as invalid vector logical operands for non-C++ cases.
10053QualType Sema::InvalidLogicalVectorOperands(SourceLocation Loc, ExprResult &LHS,
10054 ExprResult &RHS) {
10055 QualType LHSType = LHS.get()->IgnoreImpCasts()->getType();
10056 QualType RHSType = RHS.get()->IgnoreImpCasts()->getType();
10057
10058 bool LHSNatVec = LHSType->isVectorType();
10059 bool RHSNatVec = RHSType->isVectorType();
10060
10061 if (!(LHSNatVec && RHSNatVec)) {
10062 Expr *Vector = LHSNatVec ? LHS.get() : RHS.get();
10063 Expr *NonVector = !LHSNatVec ? LHS.get() : RHS.get();
10064 Diag(Loc, diag::err_typecheck_logical_vector_expr_gnu_cpp_restrict)
10065 << 0 << Vector->getType() << NonVector->IgnoreImpCasts()->getType()
10066 << Vector->getSourceRange();
10067 return QualType();
10068 }
10069
10070 Diag(Loc, diag::err_typecheck_logical_vector_expr_gnu_cpp_restrict)
10071 << 1 << LHSType << RHSType << LHS.get()->getSourceRange()
10072 << RHS.get()->getSourceRange();
10073
10074 return QualType();
10075}
10076
10077/// Try to convert a value of non-vector type to a vector type by converting
10078/// the type to the element type of the vector and then performing a splat.
10079/// If the language is OpenCL, we only use conversions that promote scalar
10080/// rank; for C, Obj-C, and C++ we allow any real scalar conversion except
10081/// for float->int.
10082///
10083/// OpenCL V2.0 6.2.6.p2:
10084/// An error shall occur if any scalar operand type has greater rank
10085/// than the type of the vector element.
10086///
10087/// \param scalar - if non-null, actually perform the conversions
10088/// \return true if the operation fails (but without diagnosing the failure)
10089static bool tryVectorConvertAndSplat(Sema &S, ExprResult *scalar,
10090 QualType scalarTy,
10091 QualType vectorEltTy,
10092 QualType vectorTy,
10093 unsigned &DiagID) {
10094 // The conversion to apply to the scalar before splatting it,
10095 // if necessary.
10096 CastKind scalarCast = CK_NoOp;
10097
10098 if (vectorEltTy->isIntegralType(S.Context)) {
10099 if (S.getLangOpts().OpenCL && (scalarTy->isRealFloatingType() ||
10100 (scalarTy->isIntegerType() &&
10101 S.Context.getIntegerTypeOrder(vectorEltTy, scalarTy) < 0))) {
10102 DiagID = diag::err_opencl_scalar_type_rank_greater_than_vector_type;
10103 return true;
10104 }
10105 if (!scalarTy->isIntegralType(S.Context))
10106 return true;
10107 scalarCast = CK_IntegralCast;
10108 } else if (vectorEltTy->isRealFloatingType()) {
10109 if (scalarTy->isRealFloatingType()) {
10110 if (S.getLangOpts().OpenCL &&
10111 S.Context.getFloatingTypeOrder(vectorEltTy, scalarTy) < 0) {
10112 DiagID = diag::err_opencl_scalar_type_rank_greater_than_vector_type;
10113 return true;
10114 }
10115 scalarCast = CK_FloatingCast;
10116 }
10117 else if (scalarTy->isIntegralType(S.Context))
10118 scalarCast = CK_IntegralToFloating;
10119 else
10120 return true;
10121 } else {
10122 return true;
10123 }
10124
10125 // Adjust scalar if desired.
10126 if (scalar) {
10127 if (scalarCast != CK_NoOp)
10128 *scalar = S.ImpCastExprToType(scalar->get(), vectorEltTy, scalarCast);
10129 *scalar = S.ImpCastExprToType(scalar->get(), vectorTy, CK_VectorSplat);
10130 }
10131 return false;
10132}
10133
10134/// Convert vector E to a vector with the same number of elements but different
10135/// element type.
10136static ExprResult convertVector(Expr *E, QualType ElementType, Sema &S) {
10137 const auto *VecTy = E->getType()->getAs<VectorType>();
10138 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", 10138, __extension__ __PRETTY_FUNCTION__
))
;
10139 QualType NewVecTy =
10140 VecTy->isExtVectorType()
10141 ? S.Context.getExtVectorType(ElementType, VecTy->getNumElements())
10142 : S.Context.getVectorType(ElementType, VecTy->getNumElements(),
10143 VecTy->getVectorKind());
10144
10145 // Look through the implicit cast. Return the subexpression if its type is
10146 // NewVecTy.
10147 if (auto *ICE = dyn_cast<ImplicitCastExpr>(E))
10148 if (ICE->getSubExpr()->getType() == NewVecTy)
10149 return ICE->getSubExpr();
10150
10151 auto Cast = ElementType->isIntegerType() ? CK_IntegralCast : CK_FloatingCast;
10152 return S.ImpCastExprToType(E, NewVecTy, Cast);
10153}
10154
10155/// Test if a (constant) integer Int can be casted to another integer type
10156/// IntTy without losing precision.
10157static bool canConvertIntToOtherIntTy(Sema &S, ExprResult *Int,
10158 QualType OtherIntTy) {
10159 QualType IntTy = Int->get()->getType().getUnqualifiedType();
10160
10161 // Reject cases where the value of the Int is unknown as that would
10162 // possibly cause truncation, but accept cases where the scalar can be
10163 // demoted without loss of precision.
10164 Expr::EvalResult EVResult;
10165 bool CstInt = Int->get()->EvaluateAsInt(EVResult, S.Context);
10166 int Order = S.Context.getIntegerTypeOrder(OtherIntTy, IntTy);
10167 bool IntSigned = IntTy->hasSignedIntegerRepresentation();
10168 bool OtherIntSigned = OtherIntTy->hasSignedIntegerRepresentation();
10169
10170 if (CstInt) {
10171 // If the scalar is constant and is of a higher order and has more active
10172 // bits that the vector element type, reject it.
10173 llvm::APSInt Result = EVResult.Val.getInt();
10174 unsigned NumBits = IntSigned
10175 ? (Result.isNegative() ? Result.getMinSignedBits()
10176 : Result.getActiveBits())
10177 : Result.getActiveBits();
10178 if (Order < 0 && S.Context.getIntWidth(OtherIntTy) < NumBits)
10179 return true;
10180
10181 // If the signedness of the scalar type and the vector element type
10182 // differs and the number of bits is greater than that of the vector
10183 // element reject it.
10184 return (IntSigned != OtherIntSigned &&
10185 NumBits > S.Context.getIntWidth(OtherIntTy));
10186 }
10187
10188 // Reject cases where the value of the scalar is not constant and it's
10189 // order is greater than that of the vector element type.
10190 return (Order < 0);
10191}
10192
10193/// Test if a (constant) integer Int can be casted to floating point type
10194/// FloatTy without losing precision.
10195static bool canConvertIntTyToFloatTy(Sema &S, ExprResult *Int,
10196 QualType FloatTy) {
10197 QualType IntTy = Int->get()->getType().getUnqualifiedType();
10198
10199 // Determine if the integer constant can be expressed as a floating point
10200 // number of the appropriate type.
10201 Expr::EvalResult EVResult;
10202 bool CstInt = Int->get()->EvaluateAsInt(EVResult, S.Context);
10203
10204 uint64_t Bits = 0;
10205 if (CstInt) {
10206 // Reject constants that would be truncated if they were converted to
10207 // the floating point type. Test by simple to/from conversion.
10208 // FIXME: Ideally the conversion to an APFloat and from an APFloat
10209 // could be avoided if there was a convertFromAPInt method
10210 // which could signal back if implicit truncation occurred.
10211 llvm::APSInt Result = EVResult.Val.getInt();
10212 llvm::APFloat Float(S.Context.getFloatTypeSemantics(FloatTy));
10213 Float.convertFromAPInt(Result, IntTy->hasSignedIntegerRepresentation(),
10214 llvm::APFloat::rmTowardZero);
10215 llvm::APSInt ConvertBack(S.Context.getIntWidth(IntTy),
10216 !IntTy->hasSignedIntegerRepresentation());
10217 bool Ignored = false;
10218 Float.convertToInteger(ConvertBack, llvm::APFloat::rmNearestTiesToEven,
10219 &Ignored);
10220 if (Result != ConvertBack)
10221 return true;
10222 } else {
10223 // Reject types that cannot be fully encoded into the mantissa of
10224 // the float.
10225 Bits = S.Context.getTypeSize(IntTy);
10226 unsigned FloatPrec = llvm::APFloat::semanticsPrecision(
10227 S.Context.getFloatTypeSemantics(FloatTy));
10228 if (Bits > FloatPrec)
10229 return true;
10230 }
10231
10232 return false;
10233}
10234
10235/// Attempt to convert and splat Scalar into a vector whose types matches
10236/// Vector following GCC conversion rules. The rule is that implicit
10237/// conversion can occur when Scalar can be casted to match Vector's element
10238/// type without causing truncation of Scalar.
10239static bool tryGCCVectorConvertAndSplat(Sema &S, ExprResult *Scalar,
10240 ExprResult *Vector) {
10241 QualType ScalarTy = Scalar->get()->getType().getUnqualifiedType();
10242 QualType VectorTy = Vector->get()->getType().getUnqualifiedType();
10243 const auto *VT = VectorTy->castAs<VectorType>();
10244
10245 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", 10246, __extension__ __PRETTY_FUNCTION__
))
10246 "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", 10246, __extension__ __PRETTY_FUNCTION__
))
;
10247
10248 QualType VectorEltTy = VT->getElementType();
10249
10250 // Reject cases where the vector element type or the scalar element type are
10251 // not integral or floating point types.
10252 if (!VectorEltTy->isArithmeticType() || !ScalarTy->isArithmeticType())
10253 return true;
10254
10255 // The conversion to apply to the scalar before splatting it,
10256 // if necessary.
10257 CastKind ScalarCast = CK_NoOp;
10258
10259 // Accept cases where the vector elements are integers and the scalar is
10260 // an integer.
10261 // FIXME: Notionally if the scalar was a floating point value with a precise
10262 // integral representation, we could cast it to an appropriate integer
10263 // type and then perform the rest of the checks here. GCC will perform
10264 // this conversion in some cases as determined by the input language.
10265 // We should accept it on a language independent basis.
10266 if (VectorEltTy->isIntegralType(S.Context) &&
10267 ScalarTy->isIntegralType(S.Context) &&
10268 S.Context.getIntegerTypeOrder(VectorEltTy, ScalarTy)) {
10269
10270 if (canConvertIntToOtherIntTy(S, Scalar, VectorEltTy))
10271 return true;
10272
10273 ScalarCast = CK_IntegralCast;
10274 } else if (VectorEltTy->isIntegralType(S.Context) &&
10275 ScalarTy->isRealFloatingType()) {
10276 if (S.Context.getTypeSize(VectorEltTy) == S.Context.getTypeSize(ScalarTy))
10277 ScalarCast = CK_FloatingToIntegral;
10278 else
10279 return true;
10280 } else if (VectorEltTy->isRealFloatingType()) {
10281 if (ScalarTy->isRealFloatingType()) {
10282
10283 // Reject cases where the scalar type is not a constant and has a higher
10284 // Order than the vector element type.
10285 llvm::APFloat Result(0.0);
10286
10287 // Determine whether this is a constant scalar. In the event that the
10288 // value is dependent (and thus cannot be evaluated by the constant
10289 // evaluator), skip the evaluation. This will then diagnose once the
10290 // expression is instantiated.
10291 bool CstScalar = Scalar->get()->isValueDependent() ||
10292 Scalar->get()->EvaluateAsFloat(Result, S.Context);
10293 int Order = S.Context.getFloatingTypeOrder(VectorEltTy, ScalarTy);
10294 if (!CstScalar && Order < 0)
10295 return true;
10296
10297 // If the scalar cannot be safely casted to the vector element type,
10298 // reject it.
10299 if (CstScalar) {
10300 bool Truncated = false;
10301 Result.convert(S.Context.getFloatTypeSemantics(VectorEltTy),
10302 llvm::APFloat::rmNearestTiesToEven, &Truncated);
10303 if (Truncated)
10304 return true;
10305 }
10306
10307 ScalarCast = CK_FloatingCast;
10308 } else if (ScalarTy->isIntegralType(S.Context)) {
10309 if (canConvertIntTyToFloatTy(S, Scalar, VectorEltTy))
10310 return true;
10311
10312 ScalarCast = CK_IntegralToFloating;
10313 } else
10314 return true;
10315 } else if (ScalarTy->isEnumeralType())
10316 return true;
10317
10318 // Adjust scalar if desired.
10319 if (Scalar) {
10320 if (ScalarCast != CK_NoOp)
10321 *Scalar = S.ImpCastExprToType(Scalar->get(), VectorEltTy, ScalarCast);
10322 *Scalar = S.ImpCastExprToType(Scalar->get(), VectorTy, CK_VectorSplat);
10323 }
10324 return false;
10325}
10326
10327QualType Sema::CheckVectorOperands(ExprResult &LHS, ExprResult &RHS,
10328 SourceLocation Loc, bool IsCompAssign,
10329 bool AllowBothBool,
10330 bool AllowBoolConversions,
10331 bool AllowBoolOperation,
10332 bool ReportInvalid) {
10333 if (!IsCompAssign) {
10334 LHS = DefaultFunctionArrayLvalueConversion(LHS.get());
10335 if (LHS.isInvalid())
10336 return QualType();
10337 }
10338 RHS = DefaultFunctionArrayLvalueConversion(RHS.get());
10339 if (RHS.isInvalid())
10340 return QualType();
10341
10342 // For conversion purposes, we ignore any qualifiers.
10343 // For example, "const float" and "float" are equivalent.
10344 QualType LHSType = LHS.get()->getType().getUnqualifiedType();
10345 QualType RHSType = RHS.get()->getType().getUnqualifiedType();
10346
10347 const VectorType *LHSVecType = LHSType->getAs<VectorType>();
10348 const VectorType *RHSVecType = RHSType->getAs<VectorType>();
10349 assert(LHSVecType || RHSVecType)(static_cast <bool> (LHSVecType || RHSVecType) ? void (
0) : __assert_fail ("LHSVecType || RHSVecType", "clang/lib/Sema/SemaExpr.cpp"
, 10349, __extension__ __PRETTY_FUNCTION__))
;
10350
10351 if ((LHSVecType && LHSVecType->getElementType()->isBFloat16Type()) ||
10352 (RHSVecType && RHSVecType->getElementType()->isBFloat16Type()))
10353 return ReportInvalid ? InvalidOperands(Loc, LHS, RHS) : QualType();
10354
10355 // AltiVec-style "vector bool op vector bool" combinations are allowed
10356 // for some operators but not others.
10357 if (!AllowBothBool &&
10358 LHSVecType && LHSVecType->getVectorKind() == VectorType::AltiVecBool &&
10359 RHSVecType && RHSVecType->getVectorKind() == VectorType::AltiVecBool)
10360 return ReportInvalid ? InvalidOperands(Loc, LHS, RHS) : QualType();
10361
10362 // This operation may not be performed on boolean vectors.
10363 if (!AllowBoolOperation &&
10364 (LHSType->isExtVectorBoolType() || RHSType->isExtVectorBoolType()))
10365 return ReportInvalid ? InvalidOperands(Loc, LHS, RHS) : QualType();
10366
10367 // If the vector types are identical, return.
10368 if (Context.hasSameType(LHSType, RHSType))
10369 return LHSType;
10370
10371 // If we have compatible AltiVec and GCC vector types, use the AltiVec type.
10372 if (LHSVecType && RHSVecType &&
10373 Context.areCompatibleVectorTypes(LHSType, RHSType)) {
10374 if (isa<ExtVectorType>(LHSVecType)) {
10375 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast);
10376 return LHSType;
10377 }
10378
10379 if (!IsCompAssign)
10380 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_BitCast);
10381 return RHSType;
10382 }
10383
10384 // AllowBoolConversions says that bool and non-bool AltiVec vectors
10385 // can be mixed, with the result being the non-bool type. The non-bool
10386 // operand must have integer element type.
10387 if (AllowBoolConversions && LHSVecType && RHSVecType &&
10388 LHSVecType->getNumElements() == RHSVecType->getNumElements() &&
10389 (Context.getTypeSize(LHSVecType->getElementType()) ==
10390 Context.getTypeSize(RHSVecType->getElementType()))) {
10391 if (LHSVecType->getVectorKind() == VectorType::AltiVecVector &&
10392 LHSVecType->getElementType()->isIntegerType() &&
10393 RHSVecType->getVectorKind() == VectorType::AltiVecBool) {
10394 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast);
10395 return LHSType;
10396 }
10397 if (!IsCompAssign &&
10398 LHSVecType->getVectorKind() == VectorType::AltiVecBool &&
10399 RHSVecType->getVectorKind() == VectorType::AltiVecVector &&
10400 RHSVecType->getElementType()->isIntegerType()) {
10401 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_BitCast);
10402 return RHSType;
10403 }
10404 }
10405
10406 // Expressions containing fixed-length and sizeless SVE vectors are invalid
10407 // since the ambiguity can affect the ABI.
10408 auto IsSveConversion = [](QualType FirstType, QualType SecondType) {
10409 const VectorType *VecType = SecondType->getAs<VectorType>();
10410 return FirstType->isSizelessBuiltinType() && VecType &&
10411 (VecType->getVectorKind() == VectorType::SveFixedLengthDataVector ||
10412 VecType->getVectorKind() ==
10413 VectorType::SveFixedLengthPredicateVector);
10414 };
10415
10416 if (IsSveConversion(LHSType, RHSType) || IsSveConversion(RHSType, LHSType)) {
10417 Diag(Loc, diag::err_typecheck_sve_ambiguous) << LHSType << RHSType;
10418 return QualType();
10419 }
10420
10421 // Expressions containing GNU and SVE (fixed or sizeless) vectors are invalid
10422 // since the ambiguity can affect the ABI.
10423 auto IsSveGnuConversion = [](QualType FirstType, QualType SecondType) {
10424 const VectorType *FirstVecType = FirstType->getAs<VectorType>();
10425 const VectorType *SecondVecType = SecondType->getAs<VectorType>();
10426
10427 if (FirstVecType && SecondVecType)
10428 return FirstVecType->getVectorKind() == VectorType::GenericVector &&
10429 (SecondVecType->getVectorKind() ==
10430 VectorType::SveFixedLengthDataVector ||
10431 SecondVecType->getVectorKind() ==
10432 VectorType::SveFixedLengthPredicateVector);
10433
10434 return FirstType->isSizelessBuiltinType() && SecondVecType &&
10435 SecondVecType->getVectorKind() == VectorType::GenericVector;
10436 };
10437
10438 if (IsSveGnuConversion(LHSType, RHSType) ||
10439 IsSveGnuConversion(RHSType, LHSType)) {
10440 Diag(Loc, diag::err_typecheck_sve_gnu_ambiguous) << LHSType << RHSType;
10441 return QualType();
10442 }
10443
10444 // If there's a vector type and a scalar, try to convert the scalar to
10445 // the vector element type and splat.
10446 unsigned DiagID = diag::err_typecheck_vector_not_convertable;
10447 if (!RHSVecType) {
10448 if (isa<ExtVectorType>(LHSVecType)) {
10449 if (!tryVectorConvertAndSplat(*this, &RHS, RHSType,
10450 LHSVecType->getElementType(), LHSType,
10451 DiagID))
10452 return LHSType;
10453 } else {
10454 if (!tryGCCVectorConvertAndSplat(*this, &RHS, &LHS))
10455 return LHSType;
10456 }
10457 }
10458 if (!LHSVecType) {
10459 if (isa<ExtVectorType>(RHSVecType)) {
10460 if (!tryVectorConvertAndSplat(*this, (IsCompAssign ? nullptr : &LHS),
10461 LHSType, RHSVecType->getElementType(),
10462 RHSType, DiagID))
10463 return RHSType;
10464 } else {
10465 if (LHS.get()->isLValue() ||
10466 !tryGCCVectorConvertAndSplat(*this, &LHS, &RHS))
10467 return RHSType;
10468 }
10469 }
10470
10471 // FIXME: The code below also handles conversion between vectors and
10472 // non-scalars, we should break this down into fine grained specific checks
10473 // and emit proper diagnostics.
10474 QualType VecType = LHSVecType ? LHSType : RHSType;
10475 const VectorType *VT = LHSVecType ? LHSVecType : RHSVecType;
10476 QualType OtherType = LHSVecType ? RHSType : LHSType;
10477 ExprResult *OtherExpr = LHSVecType ? &RHS : &LHS;
10478 if (isLaxVectorConversion(OtherType, VecType)) {
10479 // If we're allowing lax vector conversions, only the total (data) size
10480 // needs to be the same. For non compound assignment, if one of the types is
10481 // scalar, the result is always the vector type.
10482 if (!IsCompAssign) {
10483 *OtherExpr = ImpCastExprToType(OtherExpr->get(), VecType, CK_BitCast);
10484 return VecType;
10485 // In a compound assignment, lhs += rhs, 'lhs' is a lvalue src, forbidding
10486 // any implicit cast. Here, the 'rhs' should be implicit casted to 'lhs'
10487 // type. Note that this is already done by non-compound assignments in
10488 // CheckAssignmentConstraints. If it's a scalar type, only bitcast for
10489 // <1 x T> -> T. The result is also a vector type.
10490 } else if (OtherType->isExtVectorType() || OtherType->isVectorType() ||
10491 (OtherType->isScalarType() && VT->getNumElements() == 1)) {
10492 ExprResult *RHSExpr = &RHS;
10493 *RHSExpr = ImpCastExprToType(RHSExpr->get(), LHSType, CK_BitCast);
10494 return VecType;
10495 }
10496 }
10497
10498 // Okay, the expression is invalid.
10499
10500 // If there's a non-vector, non-real operand, diagnose that.
10501 if ((!RHSVecType && !RHSType->isRealType()) ||
10502 (!LHSVecType && !LHSType->isRealType())) {
10503 Diag(Loc, diag::err_typecheck_vector_not_convertable_non_scalar)
10504 << LHSType << RHSType
10505 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
10506 return QualType();
10507 }
10508
10509 // OpenCL V1.1 6.2.6.p1:
10510 // If the operands are of more than one vector type, then an error shall
10511 // occur. Implicit conversions between vector types are not permitted, per
10512 // section 6.2.1.
10513 if (getLangOpts().OpenCL &&
10514 RHSVecType && isa<ExtVectorType>(RHSVecType) &&
10515 LHSVecType && isa<ExtVectorType>(LHSVecType)) {
10516 Diag(Loc, diag::err_opencl_implicit_vector_conversion) << LHSType
10517 << RHSType;
10518 return QualType();
10519 }
10520
10521
10522 // If there is a vector type that is not a ExtVector and a scalar, we reach
10523 // this point if scalar could not be converted to the vector's element type
10524 // without truncation.
10525 if ((RHSVecType && !isa<ExtVectorType>(RHSVecType)) ||
10526 (LHSVecType && !isa<ExtVectorType>(LHSVecType))) {
10527 QualType Scalar = LHSVecType ? RHSType : LHSType;
10528 QualType Vector = LHSVecType ? LHSType : RHSType;
10529 unsigned ScalarOrVector = LHSVecType && RHSVecType ? 1 : 0;
10530 Diag(Loc,
10531 diag::err_typecheck_vector_not_convertable_implict_truncation)
10532 << ScalarOrVector << Scalar << Vector;
10533
10534 return QualType();
10535 }
10536
10537 // Otherwise, use the generic diagnostic.
10538 Diag(Loc, DiagID)
10539 << LHSType << RHSType
10540 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
10541 return QualType();
10542}
10543
10544QualType Sema::CheckSizelessVectorOperands(ExprResult &LHS, ExprResult &RHS,
10545 SourceLocation Loc,
10546 bool IsCompAssign,
10547 ArithConvKind OperationKind) {
10548 if (!IsCompAssign) {
10549 LHS = DefaultFunctionArrayLvalueConversion(LHS.get());
10550 if (LHS.isInvalid())
10551 return QualType();
10552 }
10553 RHS = DefaultFunctionArrayLvalueConversion(RHS.get());
10554 if (RHS.isInvalid())
10555 return QualType();
10556
10557 QualType LHSType = LHS.get()->getType().getUnqualifiedType();
10558 QualType RHSType = RHS.get()->getType().getUnqualifiedType();
10559
10560 unsigned DiagID = diag::err_typecheck_invalid_operands;
10561 if ((OperationKind == ACK_Arithmetic) &&
10562 (LHSType->castAs<BuiltinType>()->isSVEBool() ||
10563 RHSType->castAs<BuiltinType>()->isSVEBool())) {
10564 Diag(Loc, DiagID) << LHSType << RHSType << LHS.get()->getSourceRange()
10565 << RHS.get()->getSourceRange();
10566 return QualType();
10567 }
10568
10569 if (Context.hasSameType(LHSType, RHSType))
10570 return LHSType;
10571
10572 auto tryScalableVectorConvert = [this](ExprResult *Src, QualType SrcType,
10573 QualType DestType) {
10574 const QualType DestBaseType = DestType->getSveEltType(Context);
10575 if (DestBaseType->getUnqualifiedDesugaredType() ==
10576 SrcType->getUnqualifiedDesugaredType()) {
10577 unsigned DiagID = diag::err_typecheck_invalid_operands;
10578 if (!tryVectorConvertAndSplat(*this, Src, SrcType, DestBaseType, DestType,
10579 DiagID))
10580 return DestType;
10581 }
10582 return QualType();
10583 };
10584
10585 if (LHSType->isVLSTBuiltinType() && !RHSType->isVLSTBuiltinType()) {
10586 auto DestType = tryScalableVectorConvert(&RHS, RHSType, LHSType);
10587 if (DestType == QualType())
10588 return InvalidOperands(Loc, LHS, RHS);
10589 return DestType;
10590 }
10591
10592 if (RHSType->isVLSTBuiltinType() && !LHSType->isVLSTBuiltinType()) {
10593 auto DestType = tryScalableVectorConvert((IsCompAssign ? nullptr : &LHS),
10594 LHSType, RHSType);
10595 if (DestType == QualType())
10596 return InvalidOperands(Loc, LHS, RHS);
10597 return DestType;
10598 }
10599
10600 Diag(Loc, DiagID) << LHSType << RHSType << LHS.get()->getSourceRange()
10601 << RHS.get()->getSourceRange();
10602 return QualType();
10603}
10604
10605// checkArithmeticNull - Detect when a NULL constant is used improperly in an
10606// expression. These are mainly cases where the null pointer is used as an
10607// integer instead of a pointer.
10608static void checkArithmeticNull(Sema &S, ExprResult &LHS, ExprResult &RHS,
10609 SourceLocation Loc, bool IsCompare) {
10610 // The canonical way to check for a GNU null is with isNullPointerConstant,
10611 // but we use a bit of a hack here for speed; this is a relatively
10612 // hot path, and isNullPointerConstant is slow.
10613 bool LHSNull = isa<GNUNullExpr>(LHS.get()->IgnoreParenImpCasts());
10614 bool RHSNull = isa<GNUNullExpr>(RHS.get()->IgnoreParenImpCasts());
10615
10616 QualType NonNullType = LHSNull ? RHS.get()->getType() : LHS.get()->getType();
10617
10618 // Avoid analyzing cases where the result will either be invalid (and
10619 // diagnosed as such) or entirely valid and not something to warn about.
10620 if ((!LHSNull && !RHSNull) || NonNullType->isBlockPointerType() ||
10621 NonNullType->isMemberPointerType() || NonNullType->isFunctionType())
10622 return;
10623
10624 // Comparison operations would not make sense with a null pointer no matter
10625 // what the other expression is.
10626 if (!IsCompare) {
10627 S.Diag(Loc, diag::warn_null_in_arithmetic_operation)
10628 << (LHSNull ? LHS.get()->getSourceRange() : SourceRange())
10629 << (RHSNull ? RHS.get()->getSourceRange() : SourceRange());
10630 return;
10631 }
10632
10633 // The rest of the operations only make sense with a null pointer
10634 // if the other expression is a pointer.
10635 if (LHSNull == RHSNull || NonNullType->isAnyPointerType() ||
10636 NonNullType->canDecayToPointerType())
10637 return;
10638
10639 S.Diag(Loc, diag::warn_null_in_comparison_operation)
10640 << LHSNull /* LHS is NULL */ << NonNullType
10641 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
10642}
10643
10644static void DiagnoseDivisionSizeofPointerOrArray(Sema &S, Expr *LHS, Expr *RHS,
10645 SourceLocation Loc) {
10646 const auto *LUE = dyn_cast<UnaryExprOrTypeTraitExpr>(LHS);
10647 const auto *RUE = dyn_cast<UnaryExprOrTypeTraitExpr>(RHS);
10648 if (!LUE || !RUE)
10649 return;
10650 if (LUE->getKind() != UETT_SizeOf || LUE->isArgumentType() ||
10651 RUE->getKind() != UETT_SizeOf)
10652 return;
10653
10654 const Expr *LHSArg = LUE->getArgumentExpr()->IgnoreParens();
10655 QualType LHSTy = LHSArg->getType();
10656 QualType RHSTy;
10657
10658 if (RUE->isArgumentType())
10659 RHSTy = RUE->getArgumentType().getNonReferenceType();
10660 else
10661 RHSTy = RUE->getArgumentExpr()->IgnoreParens()->getType();
10662
10663 if (LHSTy->isPointerType() && !RHSTy->isPointerType()) {
10664 if (!S.Context.hasSameUnqualifiedType(LHSTy->getPointeeType(), RHSTy))
10665 return;
10666
10667 S.Diag(Loc, diag::warn_division_sizeof_ptr) << LHS << LHS->getSourceRange();
10668 if (const auto *DRE = dyn_cast<DeclRefExpr>(LHSArg)) {
10669 if (const ValueDecl *LHSArgDecl = DRE->getDecl())
10670 S.Diag(LHSArgDecl->getLocation(), diag::note_pointer_declared_here)
10671 << LHSArgDecl;
10672 }
10673 } else if (const auto *ArrayTy = S.Context.getAsArrayType(LHSTy)) {
10674 QualType ArrayElemTy = ArrayTy->getElementType();
10675 if (ArrayElemTy != S.Context.getBaseElementType(ArrayTy) ||
10676 ArrayElemTy->isDependentType() || RHSTy->isDependentType() ||
10677 RHSTy->isReferenceType() || ArrayElemTy->isCharType() ||
10678 S.Context.getTypeSize(ArrayElemTy) == S.Context.getTypeSize(RHSTy))
10679 return;
10680 S.Diag(Loc, diag::warn_division_sizeof_array)
10681 << LHSArg->getSourceRange() << ArrayElemTy << RHSTy;
10682 if (const auto *DRE = dyn_cast<DeclRefExpr>(LHSArg)) {
10683 if (const ValueDecl *LHSArgDecl = DRE->getDecl())
10684 S.Diag(LHSArgDecl->getLocation(), diag::note_array_declared_here)
10685 << LHSArgDecl;
10686 }
10687
10688 S.Diag(Loc, diag::note_precedence_silence) << RHS;
10689 }
10690}
10691
10692static void DiagnoseBadDivideOrRemainderValues(Sema& S, ExprResult &LHS,
10693 ExprResult &RHS,
10694 SourceLocation Loc, bool IsDiv) {
10695 // Check for division/remainder by zero.
10696 Expr::EvalResult RHSValue;
10697 if (!RHS.get()->isValueDependent() &&
10698 RHS.get()->EvaluateAsInt(RHSValue, S.Context) &&
10699 RHSValue.Val.getInt() == 0)
10700 S.DiagRuntimeBehavior(Loc, RHS.get(),
10701 S.PDiag(diag::warn_remainder_division_by_zero)
10702 << IsDiv << RHS.get()->getSourceRange());
10703}
10704
10705QualType Sema::CheckMultiplyDivideOperands(ExprResult &LHS, ExprResult &RHS,
10706 SourceLocation Loc,
10707 bool IsCompAssign, bool IsDiv) {
10708 checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/false);
10709
10710 QualType LHSTy = LHS.get()->getType();
10711 QualType RHSTy = RHS.get()->getType();
10712 if (LHSTy->isVectorType() || RHSTy->isVectorType())
10713 return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign,
10714 /*AllowBothBool*/ getLangOpts().AltiVec,
10715 /*AllowBoolConversions*/ false,
10716 /*AllowBooleanOperation*/ false,
10717 /*ReportInvalid*/ true);
10718 if (LHSTy->isVLSTBuiltinType() || RHSTy->isVLSTBuiltinType())
10719 return CheckSizelessVectorOperands(LHS, RHS, Loc, IsCompAssign,
10720 ACK_Arithmetic);
10721 if (!IsDiv &&
10722 (LHSTy->isConstantMatrixType() || RHSTy->isConstantMatrixType()))
10723 return CheckMatrixMultiplyOperands(LHS, RHS, Loc, IsCompAssign);
10724 // For division, only matrix-by-scalar is supported. Other combinations with
10725 // matrix types are invalid.
10726 if (IsDiv && LHSTy->isConstantMatrixType() && RHSTy->isArithmeticType())
10727 return CheckMatrixElementwiseOperands(LHS, RHS, Loc, IsCompAssign);
10728
10729 QualType compType = UsualArithmeticConversions(
10730 LHS, RHS, Loc, IsCompAssign ? ACK_CompAssign : ACK_Arithmetic);
10731 if (LHS.isInvalid() || RHS.isInvalid())
10732 return QualType();
10733
10734
10735 if (compType.isNull() || !compType->isArithmeticType())
10736 return InvalidOperands(Loc, LHS, RHS);
10737 if (IsDiv) {
10738 DiagnoseBadDivideOrRemainderValues(*this, LHS, RHS, Loc, IsDiv);
10739 DiagnoseDivisionSizeofPointerOrArray(*this, LHS.get(), RHS.get(), Loc);
10740 }
10741 return compType;
10742}
10743
10744QualType Sema::CheckRemainderOperands(
10745 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, bool IsCompAssign) {
10746 checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/false);
10747
10748 if (LHS.get()->getType()->isVectorType() ||
10749 RHS.get()->getType()->isVectorType()) {
10750 if (LHS.get()->getType()->hasIntegerRepresentation() &&
10751 RHS.get()->getType()->hasIntegerRepresentation())
10752 return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign,
10753 /*AllowBothBool*/ getLangOpts().AltiVec,
10754 /*AllowBoolConversions*/ false,
10755 /*AllowBooleanOperation*/ false,
10756 /*ReportInvalid*/ true);
10757 return InvalidOperands(Loc, LHS, RHS);
10758 }
10759
10760 if (LHS.get()->getType()->isVLSTBuiltinType() ||
10761 RHS.get()->getType()->isVLSTBuiltinType()) {
10762 if (LHS.get()->getType()->hasIntegerRepresentation() &&
10763 RHS.get()->getType()->hasIntegerRepresentation())
10764 return CheckSizelessVectorOperands(LHS, RHS, Loc, IsCompAssign,
10765 ACK_Arithmetic);
10766
10767 return InvalidOperands(Loc, LHS, RHS);
10768 }
10769
10770 QualType compType = UsualArithmeticConversions(
10771 LHS, RHS, Loc, IsCompAssign ? ACK_CompAssign : ACK_Arithmetic);
10772 if (LHS.isInvalid() || RHS.isInvalid())
10773 return QualType();
10774
10775 if (compType.isNull() || !compType->isIntegerType())
10776 return InvalidOperands(Loc, LHS, RHS);
10777 DiagnoseBadDivideOrRemainderValues(*this, LHS, RHS, Loc, false /* IsDiv */);
10778 return compType;
10779}
10780
10781/// Diagnose invalid arithmetic on two void pointers.
10782static void diagnoseArithmeticOnTwoVoidPointers(Sema &S, SourceLocation Loc,
10783 Expr *LHSExpr, Expr *RHSExpr) {
10784 S.Diag(Loc, S.getLangOpts().CPlusPlus
10785 ? diag::err_typecheck_pointer_arith_void_type
10786 : diag::ext_gnu_void_ptr)
10787 << 1 /* two pointers */ << LHSExpr->getSourceRange()
10788 << RHSExpr->getSourceRange();
10789}
10790
10791/// Diagnose invalid arithmetic on a void pointer.
10792static void diagnoseArithmeticOnVoidPointer(Sema &S, SourceLocation Loc,
10793 Expr *Pointer) {
10794 S.Diag(Loc, S.getLangOpts().CPlusPlus
10795 ? diag::err_typecheck_pointer_arith_void_type
10796 : diag::ext_gnu_void_ptr)
10797 << 0 /* one pointer */ << Pointer->getSourceRange();
10798}
10799
10800/// Diagnose invalid arithmetic on a null pointer.
10801///
10802/// If \p IsGNUIdiom is true, the operation is using the 'p = (i8*)nullptr + n'
10803/// idiom, which we recognize as a GNU extension.
10804///
10805static void diagnoseArithmeticOnNullPointer(Sema &S, SourceLocation Loc,
10806 Expr *Pointer, bool IsGNUIdiom) {
10807 if (IsGNUIdiom)
10808 S.Diag(Loc, diag::warn_gnu_null_ptr_arith)
10809 << Pointer->getSourceRange();
10810 else
10811 S.Diag(Loc, diag::warn_pointer_arith_null_ptr)
10812 << S.getLangOpts().CPlusPlus << Pointer->getSourceRange();
10813}
10814
10815/// Diagnose invalid subraction on a null pointer.
10816///
10817static void diagnoseSubtractionOnNullPointer(Sema &S, SourceLocation Loc,
10818 Expr *Pointer, bool BothNull) {
10819 // Null - null is valid in C++ [expr.add]p7
10820 if (BothNull && S.getLangOpts().CPlusPlus)
10821 return;
10822
10823 // Is this s a macro from a system header?
10824 if (S.Diags.getSuppressSystemWarnings() && S.SourceMgr.isInSystemMacro(Loc))
10825 return;
10826
10827 S.Diag(Loc, diag::warn_pointer_sub_null_ptr)
10828 << S.getLangOpts().CPlusPlus << Pointer->getSourceRange();
10829}
10830
10831/// Diagnose invalid arithmetic on two function pointers.
10832static void diagnoseArithmeticOnTwoFunctionPointers(Sema &S, SourceLocation Loc,
10833 Expr *LHS, Expr *RHS) {
10834 assert(LHS->getType()->isAnyPointerType())(static_cast <bool> (LHS->getType()->isAnyPointerType
()) ? void (0) : __assert_fail ("LHS->getType()->isAnyPointerType()"
, "clang/lib/Sema/SemaExpr.cpp", 10834, __extension__ __PRETTY_FUNCTION__
))
;
10835 assert(RHS->getType()->isAnyPointerType())(static_cast <bool> (RHS->getType()->isAnyPointerType
()) ? void (0) : __assert_fail ("RHS->getType()->isAnyPointerType()"
, "clang/lib/Sema/SemaExpr.cpp", 10835, __extension__ __PRETTY_FUNCTION__
))
;
10836 S.Diag(Loc, S.getLangOpts().CPlusPlus
10837 ? diag::err_typecheck_pointer_arith_function_type
10838 : diag::ext_gnu_ptr_func_arith)
10839 << 1 /* two pointers */ << LHS->getType()->getPointeeType()
10840 // We only show the second type if it differs from the first.
10841 << (unsigned)!S.Context.hasSameUnqualifiedType(LHS->getType(),
10842 RHS->getType())
10843 << RHS->getType()->getPointeeType()
10844 << LHS->getSourceRange() << RHS->getSourceRange();
10845}
10846
10847/// Diagnose invalid arithmetic on a function pointer.
10848static void diagnoseArithmeticOnFunctionPointer(Sema &S, SourceLocation Loc,
10849 Expr *Pointer) {
10850 assert(Pointer->getType()->isAnyPointerType())(static_cast <bool> (Pointer->getType()->isAnyPointerType
()) ? void (0) : __assert_fail ("Pointer->getType()->isAnyPointerType()"
, "clang/lib/Sema/SemaExpr.cpp", 10850, __extension__ __PRETTY_FUNCTION__
))
;
10851 S.Diag(Loc, S.getLangOpts().CPlusPlus
10852 ? diag::err_typecheck_pointer_arith_function_type
10853 : diag::ext_gnu_ptr_func_arith)
10854 << 0 /* one pointer */ << Pointer->getType()->getPointeeType()
10855 << 0 /* one pointer, so only one type */
10856 << Pointer->getSourceRange();
10857}
10858
10859/// Emit error if Operand is incomplete pointer type
10860///
10861/// \returns True if pointer has incomplete type
10862static bool checkArithmeticIncompletePointerType(Sema &S, SourceLocation Loc,
10863 Expr *Operand) {
10864 QualType ResType = Operand->getType();
10865 if (const AtomicType *ResAtomicType = ResType->getAs<AtomicType>())
10866 ResType = ResAtomicType->getValueType();
10867
10868 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", 10868, __extension__ __PRETTY_FUNCTION__
))
;
10869 QualType PointeeTy = ResType->getPointeeType();
10870 return S.RequireCompleteSizedType(
10871 Loc, PointeeTy,
10872 diag::err_typecheck_arithmetic_incomplete_or_sizeless_type,
10873 Operand->getSourceRange());
10874}
10875
10876/// Check the validity of an arithmetic pointer operand.
10877///
10878/// If the operand has pointer type, this code will check for pointer types
10879/// which are invalid in arithmetic operations. These will be diagnosed
10880/// appropriately, including whether or not the use is supported as an
10881/// extension.
10882///
10883/// \returns True when the operand is valid to use (even if as an extension).
10884static bool checkArithmeticOpPointerOperand(Sema &S, SourceLocation Loc,
10885 Expr *Operand) {
10886 QualType ResType = Operand->getType();
10887 if (const AtomicType *ResAtomicType = ResType->getAs<AtomicType>())
10888 ResType = ResAtomicType->getValueType();
10889
10890 if (!ResType->isAnyPointerType()) return true;
10891
10892 QualType PointeeTy = ResType->getPointeeType();
10893 if (PointeeTy->isVoidType()) {
10894 diagnoseArithmeticOnVoidPointer(S, Loc, Operand);
10895 return !S.getLangOpts().CPlusPlus;
10896 }
10897 if (PointeeTy->isFunctionType()) {
10898 diagnoseArithmeticOnFunctionPointer(S, Loc, Operand);
10899 return !S.getLangOpts().CPlusPlus;
10900 }
10901
10902 if (checkArithmeticIncompletePointerType(S, Loc, Operand)) return false;
10903
10904 return true;
10905}
10906
10907/// Check the validity of a binary arithmetic operation w.r.t. pointer
10908/// operands.
10909///
10910/// This routine will diagnose any invalid arithmetic on pointer operands much
10911/// like \see checkArithmeticOpPointerOperand. However, it has special logic
10912/// for emitting a single diagnostic even for operations where both LHS and RHS
10913/// are (potentially problematic) pointers.
10914///
10915/// \returns True when the operand is valid to use (even if as an extension).
10916static bool checkArithmeticBinOpPointerOperands(Sema &S, SourceLocation Loc,
10917 Expr *LHSExpr, Expr *RHSExpr) {
10918 bool isLHSPointer = LHSExpr->getType()->isAnyPointerType();
10919 bool isRHSPointer = RHSExpr->getType()->isAnyPointerType();
10920 if (!isLHSPointer && !isRHSPointer) return true;
10921
10922 QualType LHSPointeeTy, RHSPointeeTy;
10923 if (isLHSPointer) LHSPointeeTy = LHSExpr->getType()->getPointeeType();
10924 if (isRHSPointer) RHSPointeeTy = RHSExpr->getType()->getPointeeType();
10925
10926 // if both are pointers check if operation is valid wrt address spaces
10927 if (isLHSPointer && isRHSPointer) {
10928 if (!LHSPointeeTy.isAddressSpaceOverlapping(RHSPointeeTy)) {
10929 S.Diag(Loc,
10930 diag::err_typecheck_op_on_nonoverlapping_address_space_pointers)
10931 << LHSExpr->getType() << RHSExpr->getType() << 1 /*arithmetic op*/
10932 << LHSExpr->getSourceRange() << RHSExpr->getSourceRange();
10933 return false;
10934 }
10935 }
10936
10937 // Check for arithmetic on pointers to incomplete types.
10938 bool isLHSVoidPtr = isLHSPointer && LHSPointeeTy->isVoidType();
10939 bool isRHSVoidPtr = isRHSPointer && RHSPointeeTy->isVoidType();
10940 if (isLHSVoidPtr || isRHSVoidPtr) {
10941 if (!isRHSVoidPtr) diagnoseArithmeticOnVoidPointer(S, Loc, LHSExpr);
10942 else if (!isLHSVoidPtr) diagnoseArithmeticOnVoidPointer(S, Loc, RHSExpr);
10943 else diagnoseArithmeticOnTwoVoidPointers(S, Loc, LHSExpr, RHSExpr);
10944
10945 return !S.getLangOpts().CPlusPlus;
10946 }
10947
10948 bool isLHSFuncPtr = isLHSPointer && LHSPointeeTy->isFunctionType();
10949 bool isRHSFuncPtr = isRHSPointer && RHSPointeeTy->isFunctionType();
10950 if (isLHSFuncPtr || isRHSFuncPtr) {
10951 if (!isRHSFuncPtr) diagnoseArithmeticOnFunctionPointer(S, Loc, LHSExpr);
10952 else if (!isLHSFuncPtr) diagnoseArithmeticOnFunctionPointer(S, Loc,
10953 RHSExpr);
10954 else diagnoseArithmeticOnTwoFunctionPointers(S, Loc, LHSExpr, RHSExpr);
10955
10956 return !S.getLangOpts().CPlusPlus;
10957 }
10958
10959 if (isLHSPointer && checkArithmeticIncompletePointerType(S, Loc, LHSExpr))
10960 return false;
10961 if (isRHSPointer && checkArithmeticIncompletePointerType(S, Loc, RHSExpr))
10962 return false;
10963
10964 return true;
10965}
10966
10967/// diagnoseStringPlusInt - Emit a warning when adding an integer to a string
10968/// literal.
10969static void diagnoseStringPlusInt(Sema &Self, SourceLocation OpLoc,
10970 Expr *LHSExpr, Expr *RHSExpr) {
10971 StringLiteral* StrExpr = dyn_cast<StringLiteral>(LHSExpr->IgnoreImpCasts());
10972 Expr* IndexExpr = RHSExpr;
10973 if (!StrExpr) {
10974 StrExpr = dyn_cast<StringLiteral>(RHSExpr->IgnoreImpCasts());
10975 IndexExpr = LHSExpr;
10976 }
10977
10978 bool IsStringPlusInt = StrExpr &&
10979 IndexExpr->getType()->isIntegralOrUnscopedEnumerationType();
10980 if (!IsStringPlusInt || IndexExpr->isValueDependent())
10981 return;
10982
10983 SourceRange DiagRange(LHSExpr->getBeginLoc(), RHSExpr->getEndLoc());
10984 Self.Diag(OpLoc, diag::warn_string_plus_int)
10985 << DiagRange << IndexExpr->IgnoreImpCasts()->getType();
10986
10987 // Only print a fixit for "str" + int, not for int + "str".
10988 if (IndexExpr == RHSExpr) {
10989 SourceLocation EndLoc = Self.getLocForEndOfToken(RHSExpr->getEndLoc());
10990 Self.Diag(OpLoc, diag::note_string_plus_scalar_silence)
10991 << FixItHint::CreateInsertion(LHSExpr->getBeginLoc(), "&")
10992 << FixItHint::CreateReplacement(SourceRange(OpLoc), "[")
10993 << FixItHint::CreateInsertion(EndLoc, "]");
10994 } else
10995 Self.Diag(OpLoc, diag::note_string_plus_scalar_silence);
10996}
10997
10998/// Emit a warning when adding a char literal to a string.
10999static void diagnoseStringPlusChar(Sema &Self, SourceLocation OpLoc,
11000 Expr *LHSExpr, Expr *RHSExpr) {
11001 const Expr *StringRefExpr = LHSExpr;
11002 const CharacterLiteral *CharExpr =
11003 dyn_cast<CharacterLiteral>(RHSExpr->IgnoreImpCasts());
11004
11005 if (!CharExpr) {
11006 CharExpr = dyn_cast<CharacterLiteral>(LHSExpr->IgnoreImpCasts());
11007 StringRefExpr = RHSExpr;
11008 }
11009
11010 if (!CharExpr || !StringRefExpr)
11011 return;
11012
11013 const QualType StringType = StringRefExpr->getType();
11014
11015 // Return if not a PointerType.
11016 if (!StringType->isAnyPointerType())
11017 return;
11018
11019 // Return if not a CharacterType.
11020 if (!StringType->getPointeeType()->isAnyCharacterType())
11021 return;
11022
11023 ASTContext &Ctx = Self.getASTContext();
11024 SourceRange DiagRange(LHSExpr->getBeginLoc(), RHSExpr->getEndLoc());
11025
11026 const QualType CharType = CharExpr->getType();
11027 if (!CharType->isAnyCharacterType() &&
11028 CharType->isIntegerType() &&
11029 llvm::isUIntN(Ctx.getCharWidth(), CharExpr->getValue())) {
11030 Self.Diag(OpLoc, diag::warn_string_plus_char)
11031 << DiagRange << Ctx.CharTy;
11032 } else {
11033 Self.Diag(OpLoc, diag::warn_string_plus_char)
11034 << DiagRange << CharExpr->getType();
11035 }
11036
11037 // Only print a fixit for str + char, not for char + str.
11038 if (isa<CharacterLiteral>(RHSExpr->IgnoreImpCasts())) {
11039 SourceLocation EndLoc = Self.getLocForEndOfToken(RHSExpr->getEndLoc());
11040 Self.Diag(OpLoc, diag::note_string_plus_scalar_silence)
11041 << FixItHint::CreateInsertion(LHSExpr->getBeginLoc(), "&")
11042 << FixItHint::CreateReplacement(SourceRange(OpLoc), "[")
11043 << FixItHint::CreateInsertion(EndLoc, "]");
11044 } else {
11045 Self.Diag(OpLoc, diag::note_string_plus_scalar_silence);
11046 }
11047}
11048
11049/// Emit error when two pointers are incompatible.
11050static void diagnosePointerIncompatibility(Sema &S, SourceLocation Loc,
11051 Expr *LHSExpr, Expr *RHSExpr) {
11052 assert(LHSExpr->getType()->isAnyPointerType())(static_cast <bool> (LHSExpr->getType()->isAnyPointerType
()) ? void (0) : __assert_fail ("LHSExpr->getType()->isAnyPointerType()"
, "clang/lib/Sema/SemaExpr.cpp", 11052, __extension__ __PRETTY_FUNCTION__
))
;
11053 assert(RHSExpr->getType()->isAnyPointerType())(static_cast <bool> (RHSExpr->getType()->isAnyPointerType
()) ? void (0) : __assert_fail ("RHSExpr->getType()->isAnyPointerType()"
, "clang/lib/Sema/SemaExpr.cpp", 11053, __extension__ __PRETTY_FUNCTION__
))
;
11054 S.Diag(Loc, diag::err_typecheck_sub_ptr_compatible)
11055 << LHSExpr->getType() << RHSExpr->getType() << LHSExpr->getSourceRange()
11056 << RHSExpr->getSourceRange();
11057}
11058
11059// C99 6.5.6
11060QualType Sema::CheckAdditionOperands(ExprResult &LHS, ExprResult &RHS,
11061 SourceLocation Loc, BinaryOperatorKind Opc,
11062 QualType* CompLHSTy) {
11063 checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/false);
11064
11065 if (LHS.get()->getType()->isVectorType() ||
11066 RHS.get()->getType()->isVectorType()) {
11067 QualType compType =
11068 CheckVectorOperands(LHS, RHS, Loc, CompLHSTy,
11069 /*AllowBothBool*/ getLangOpts().AltiVec,
11070 /*AllowBoolConversions*/ getLangOpts().ZVector,
11071 /*AllowBooleanOperation*/ false,
11072 /*ReportInvalid*/ true);
11073 if (CompLHSTy) *CompLHSTy = compType;
11074 return compType;
11075 }
11076
11077 if (LHS.get()->getType()->isVLSTBuiltinType() ||
11078 RHS.get()->getType()->isVLSTBuiltinType()) {
11079 QualType compType =
11080 CheckSizelessVectorOperands(LHS, RHS, Loc, CompLHSTy, ACK_Arithmetic);
11081 if (CompLHSTy)
11082 *CompLHSTy = compType;
11083 return compType;
11084 }
11085
11086 if (LHS.get()->getType()->isConstantMatrixType() ||
11087 RHS.get()->getType()->isConstantMatrixType()) {
11088 QualType compType =
11089 CheckMatrixElementwiseOperands(LHS, RHS, Loc, CompLHSTy);
11090 if (CompLHSTy)
11091 *CompLHSTy = compType;
11092 return compType;
11093 }
11094
11095 QualType compType = UsualArithmeticConversions(
11096 LHS, RHS, Loc, CompLHSTy ? ACK_CompAssign : ACK_Arithmetic);
11097 if (LHS.isInvalid() || RHS.isInvalid())
11098 return QualType();
11099
11100 // Diagnose "string literal" '+' int and string '+' "char literal".
11101 if (Opc == BO_Add) {
11102 diagnoseStringPlusInt(*this, Loc, LHS.get(), RHS.get());
11103 diagnoseStringPlusChar(*this, Loc, LHS.get(), RHS.get());
11104 }
11105
11106 // handle the common case first (both operands are arithmetic).
11107 if (!compType.isNull() && compType->isArithmeticType()) {
11108 if (CompLHSTy) *CompLHSTy = compType;
11109 return compType;
11110 }
11111
11112 // Type-checking. Ultimately the pointer's going to be in PExp;
11113 // note that we bias towards the LHS being the pointer.
11114 Expr *PExp = LHS.get(), *IExp = RHS.get();
11115
11116 bool isObjCPointer;
11117 if (PExp->getType()->isPointerType()) {
11118 isObjCPointer = false;
11119 } else if (PExp->getType()->isObjCObjectPointerType()) {
11120 isObjCPointer = true;
11121 } else {
11122 std::swap(PExp, IExp);
11123 if (PExp->getType()->isPointerType()) {
11124 isObjCPointer = false;
11125 } else if (PExp->getType()->isObjCObjectPointerType()) {
11126 isObjCPointer = true;
11127 } else {
11128 return InvalidOperands(Loc, LHS, RHS);
11129 }
11130 }
11131 assert(PExp->getType()->isAnyPointerType())(static_cast <bool> (PExp->getType()->isAnyPointerType
()) ? void (0) : __assert_fail ("PExp->getType()->isAnyPointerType()"
, "clang/lib/Sema/SemaExpr.cpp", 11131, __extension__ __PRETTY_FUNCTION__
))
;
11132
11133 if (!IExp->getType()->isIntegerType())
11134 return InvalidOperands(Loc, LHS, RHS);
11135
11136 // Adding to a null pointer results in undefined behavior.
11137 if (PExp->IgnoreParenCasts()->isNullPointerConstant(
11138 Context, Expr::NPC_ValueDependentIsNotNull)) {
11139 // In C++ adding zero to a null pointer is defined.
11140 Expr::EvalResult KnownVal;
11141 if (!getLangOpts().CPlusPlus ||
11142 (!IExp->isValueDependent() &&
11143 (!IExp->EvaluateAsInt(KnownVal, Context) ||
11144 KnownVal.Val.getInt() != 0))) {
11145 // Check the conditions to see if this is the 'p = nullptr + n' idiom.
11146 bool IsGNUIdiom = BinaryOperator::isNullPointerArithmeticExtension(
11147 Context, BO_Add, PExp, IExp);
11148 diagnoseArithmeticOnNullPointer(*this, Loc, PExp, IsGNUIdiom);
11149 }
11150 }
11151
11152 if (!checkArithmeticOpPointerOperand(*this, Loc, PExp))
11153 return QualType();
11154
11155 if (isObjCPointer && checkArithmeticOnObjCPointer(*this, Loc, PExp))
11156 return QualType();
11157
11158 // Check array bounds for pointer arithemtic
11159 CheckArrayAccess(PExp, IExp);
11160
11161 if (CompLHSTy) {
11162 QualType LHSTy = Context.isPromotableBitField(LHS.get());
11163 if (LHSTy.isNull()) {
11164 LHSTy = LHS.get()->getType();
11165 if (LHSTy->isPromotableIntegerType())
11166 LHSTy = Context.getPromotedIntegerType(LHSTy);
11167 }
11168 *CompLHSTy = LHSTy;
11169 }
11170
11171 return PExp->getType();
11172}
11173
11174// C99 6.5.6
11175QualType Sema::CheckSubtractionOperands(ExprResult &LHS, ExprResult &RHS,
11176 SourceLocation Loc,
11177 QualType* CompLHSTy) {
11178 checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/false);
11179
11180 if (LHS.get()->getType()->isVectorType() ||
11181 RHS.get()->getType()->isVectorType()) {
11182 QualType compType =
11183 CheckVectorOperands(LHS, RHS, Loc, CompLHSTy,
11184 /*AllowBothBool*/ getLangOpts().AltiVec,
11185 /*AllowBoolConversions*/ getLangOpts().ZVector,
11186 /*AllowBooleanOperation*/ false,
11187 /*ReportInvalid*/ true);
11188 if (CompLHSTy) *CompLHSTy = compType;
11189 return compType;
11190 }
11191
11192 if (LHS.get()->getType()->isVLSTBuiltinType() ||
11193 RHS.get()->getType()->isVLSTBuiltinType()) {
11194 QualType compType =
11195 CheckSizelessVectorOperands(LHS, RHS, Loc, CompLHSTy, ACK_Arithmetic);
11196 if (CompLHSTy)
11197 *CompLHSTy = compType;
11198 return compType;
11199 }
11200
11201 if (LHS.get()->getType()->isConstantMatrixType() ||
11202 RHS.get()->getType()->isConstantMatrixType()) {
11203 QualType compType =
11204 CheckMatrixElementwiseOperands(LHS, RHS, Loc, CompLHSTy);
11205 if (CompLHSTy)
11206 *CompLHSTy = compType;
11207 return compType;
11208 }
11209
11210 QualType compType = UsualArithmeticConversions(
11211 LHS, RHS, Loc, CompLHSTy ? ACK_CompAssign : ACK_Arithmetic);
11212 if (LHS.isInvalid() || RHS.isInvalid())
11213 return QualType();
11214
11215 // Enforce type constraints: C99 6.5.6p3.
11216
11217 // Handle the common case first (both operands are arithmetic).
11218 if (!compType.isNull() && compType->isArithmeticType()) {
11219 if (CompLHSTy) *CompLHSTy = compType;
11220 return compType;
11221 }
11222
11223 // Either ptr - int or ptr - ptr.
11224 if (LHS.get()->getType()->isAnyPointerType()) {
11225 QualType lpointee = LHS.get()->getType()->getPointeeType();
11226
11227 // Diagnose bad cases where we step over interface counts.
11228 if (LHS.get()->getType()->isObjCObjectPointerType() &&
11229 checkArithmeticOnObjCPointer(*this, Loc, LHS.get()))
11230 return QualType();
11231
11232 // The result type of a pointer-int computation is the pointer type.
11233 if (RHS.get()->getType()->isIntegerType()) {
11234 // Subtracting from a null pointer should produce a warning.
11235 // The last argument to the diagnose call says this doesn't match the
11236 // GNU int-to-pointer idiom.
11237 if (LHS.get()->IgnoreParenCasts()->isNullPointerConstant(Context,
11238 Expr::NPC_ValueDependentIsNotNull)) {
11239 // In C++ adding zero to a null pointer is defined.
11240 Expr::EvalResult KnownVal;
11241 if (!getLangOpts().CPlusPlus ||
11242 (!RHS.get()->isValueDependent() &&
11243 (!RHS.get()->EvaluateAsInt(KnownVal, Context) ||
11244 KnownVal.Val.getInt() != 0))) {
11245 diagnoseArithmeticOnNullPointer(*this, Loc, LHS.get(), false);
11246 }
11247 }
11248
11249 if (!checkArithmeticOpPointerOperand(*this, Loc, LHS.get()))
11250 return QualType();
11251
11252 // Check array bounds for pointer arithemtic
11253 CheckArrayAccess(LHS.get(), RHS.get(), /*ArraySubscriptExpr*/nullptr,
11254 /*AllowOnePastEnd*/true, /*IndexNegated*/true);
11255
11256 if (CompLHSTy) *CompLHSTy = LHS.get()->getType();
11257 return LHS.get()->getType();
11258 }
11259
11260 // Handle pointer-pointer subtractions.
11261 if (const PointerType *RHSPTy
11262 = RHS.get()->getType()->getAs<PointerType>()) {
11263 QualType rpointee = RHSPTy->getPointeeType();
11264
11265 if (getLangOpts().CPlusPlus) {
11266 // Pointee types must be the same: C++ [expr.add]
11267 if (!Context.hasSameUnqualifiedType(lpointee, rpointee)) {
11268 diagnosePointerIncompatibility(*this, Loc, LHS.get(), RHS.get());
11269 }
11270 } else {
11271 // Pointee types must be compatible C99 6.5.6p3
11272 if (!Context.typesAreCompatible(
11273 Context.getCanonicalType(lpointee).getUnqualifiedType(),
11274 Context.getCanonicalType(rpointee).getUnqualifiedType())) {
11275 diagnosePointerIncompatibility(*this, Loc, LHS.get(), RHS.get());
11276 return QualType();
11277 }
11278 }
11279
11280 if (!checkArithmeticBinOpPointerOperands(*this, Loc,
11281 LHS.get(), RHS.get()))
11282 return QualType();
11283
11284 bool LHSIsNullPtr = LHS.get()->IgnoreParenCasts()->isNullPointerConstant(
11285 Context, Expr::NPC_ValueDependentIsNotNull);
11286 bool RHSIsNullPtr = RHS.get()->IgnoreParenCasts()->isNullPointerConstant(
11287 Context, Expr::NPC_ValueDependentIsNotNull);
11288
11289 // Subtracting nullptr or from nullptr is suspect
11290 if (LHSIsNullPtr)
11291 diagnoseSubtractionOnNullPointer(*this, Loc, LHS.get(), RHSIsNullPtr);
11292 if (RHSIsNullPtr)
11293 diagnoseSubtractionOnNullPointer(*this, Loc, RHS.get(), LHSIsNullPtr);
11294
11295 // The pointee type may have zero size. As an extension, a structure or
11296 // union may have zero size or an array may have zero length. In this
11297 // case subtraction does not make sense.
11298 if (!rpointee->isVoidType() && !rpointee->isFunctionType()) {
11299 CharUnits ElementSize = Context.getTypeSizeInChars(rpointee);
11300 if (ElementSize.isZero()) {
11301 Diag(Loc,diag::warn_sub_ptr_zero_size_types)
11302 << rpointee.getUnqualifiedType()
11303 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
11304 }
11305 }
11306
11307 if (CompLHSTy) *CompLHSTy = LHS.get()->getType();
11308 return Context.getPointerDiffType();
11309 }
11310 }
11311
11312 return InvalidOperands(Loc, LHS, RHS);
11313}
11314
11315static bool isScopedEnumerationType(QualType T) {
11316 if (const EnumType *ET = T->getAs<EnumType>())
11317 return ET->getDecl()->isScoped();
11318 return false;
11319}
11320
11321static void DiagnoseBadShiftValues(Sema& S, ExprResult &LHS, ExprResult &RHS,
11322 SourceLocation Loc, BinaryOperatorKind Opc,
11323 QualType LHSType) {
11324 // OpenCL 6.3j: shift values are effectively % word size of LHS (more defined),
11325 // so skip remaining warnings as we don't want to modify values within Sema.
11326 if (S.getLangOpts().OpenCL)
11327 return;
11328
11329 // Check right/shifter operand
11330 Expr::EvalResult RHSResult;
11331 if (RHS.get()->isValueDependent() ||
11332 !RHS.get()->EvaluateAsInt(RHSResult, S.Context))
11333 return;
11334 llvm::APSInt Right = RHSResult.Val.getInt();
11335
11336 if (Right.isNegative()) {
11337 S.DiagRuntimeBehavior(Loc, RHS.get(),
11338 S.PDiag(diag::warn_shift_negative)
11339 << RHS.get()->getSourceRange());
11340 return;
11341 }
11342
11343 QualType LHSExprType = LHS.get()->getType();
11344 uint64_t LeftSize = S.Context.getTypeSize(LHSExprType);
11345 if (LHSExprType->isBitIntType())
11346 LeftSize = S.Context.getIntWidth(LHSExprType);
11347 else if (LHSExprType->isFixedPointType()) {
11348 auto FXSema = S.Context.getFixedPointSemantics(LHSExprType);
11349 LeftSize = FXSema.getWidth() - (unsigned)FXSema.hasUnsignedPadding();
11350 }
11351 llvm::APInt LeftBits(Right.getBitWidth(), LeftSize);
11352 if (Right.uge(LeftBits)) {
11353 S.DiagRuntimeBehavior(Loc, RHS.get(),
11354 S.PDiag(diag::warn_shift_gt_typewidth)
11355 << RHS.get()->getSourceRange());
11356 return;
11357 }
11358
11359 // FIXME: We probably need to handle fixed point types specially here.
11360 if (Opc != BO_Shl || LHSExprType->isFixedPointType())
11361 return;
11362
11363 // When left shifting an ICE which is signed, we can check for overflow which
11364 // according to C++ standards prior to C++2a has undefined behavior
11365 // ([expr.shift] 5.8/2). Unsigned integers have defined behavior modulo one
11366 // more than the maximum value representable in the result type, so never
11367 // warn for those. (FIXME: Unsigned left-shift overflow in a constant
11368 // expression is still probably a bug.)
11369 Expr::EvalResult LHSResult;
11370 if (LHS.get()->isValueDependent() ||
11371 LHSType->hasUnsignedIntegerRepresentation() ||
11372 !LHS.get()->EvaluateAsInt(LHSResult, S.Context))
11373 return;
11374 llvm::APSInt Left = LHSResult.Val.getInt();
11375
11376 // If LHS does not have a signed type and non-negative value
11377 // then, the behavior is undefined before C++2a. Warn about it.
11378 if (Left.isNegative() && !S.getLangOpts().isSignedOverflowDefined() &&
11379 !S.getLangOpts().CPlusPlus20) {
11380 S.DiagRuntimeBehavior(Loc, LHS.get(),
11381 S.PDiag(diag::warn_shift_lhs_negative)
11382 << LHS.get()->getSourceRange());
11383 return;
11384 }
11385
11386 llvm::APInt ResultBits =
11387 static_cast<llvm::APInt&>(Right) + Left.getMinSignedBits();
11388 if (LeftBits.uge(ResultBits))
11389 return;
11390 llvm::APSInt Result = Left.extend(ResultBits.getLimitedValue());
11391 Result = Result.shl(Right);
11392
11393 // Print the bit representation of the signed integer as an unsigned
11394 // hexadecimal number.
11395 SmallString<40> HexResult;
11396 Result.toString(HexResult, 16, /*Signed =*/false, /*Literal =*/true);
11397
11398 // If we are only missing a sign bit, this is less likely to result in actual
11399 // bugs -- if the result is cast back to an unsigned type, it will have the
11400 // expected value. Thus we place this behind a different warning that can be
11401 // turned off separately if needed.
11402 if (LeftBits == ResultBits - 1) {
11403 S.Diag(Loc, diag::warn_shift_result_sets_sign_bit)
11404 << HexResult << LHSType
11405 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
11406 return;
11407 }
11408
11409 S.Diag(Loc, diag::warn_shift_result_gt_typewidth)
11410 << HexResult.str() << Result.getMinSignedBits() << LHSType
11411 << Left.getBitWidth() << LHS.get()->getSourceRange()
11412 << RHS.get()->getSourceRange();
11413}
11414
11415/// Return the resulting type when a vector is shifted
11416/// by a scalar or vector shift amount.
11417static QualType checkVectorShift(Sema &S, ExprResult &LHS, ExprResult &RHS,
11418 SourceLocation Loc, bool IsCompAssign) {
11419 // OpenCL v1.1 s6.3.j says RHS can be a vector only if LHS is a vector.
11420 if ((S.LangOpts.OpenCL || S.LangOpts.ZVector) &&
11421 !LHS.get()->getType()->isVectorType()) {
11422 S.Diag(Loc, diag::err_shift_rhs_only_vector)
11423 << RHS.get()->getType() << LHS.get()->getType()
11424 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
11425 return QualType();
11426 }
11427
11428 if (!IsCompAssign) {
11429 LHS = S.UsualUnaryConversions(LHS.get());
11430 if (LHS.isInvalid()) return QualType();
11431 }
11432
11433 RHS = S.UsualUnaryConversions(RHS.get());
11434 if (RHS.isInvalid()) return QualType();
11435
11436 QualType LHSType = LHS.get()->getType();
11437 // Note that LHS might be a scalar because the routine calls not only in
11438 // OpenCL case.
11439 const VectorType *LHSVecTy = LHSType->getAs<VectorType>();
11440 QualType LHSEleType = LHSVecTy ? LHSVecTy->getElementType() : LHSType;
11441
11442 // Note that RHS might not be a vector.
11443 QualType RHSType = RHS.get()->getType();
11444 const VectorType *RHSVecTy = RHSType->getAs<VectorType>();
11445 QualType RHSEleType = RHSVecTy ? RHSVecTy->getElementType() : RHSType;
11446
11447 // Do not allow shifts for boolean vectors.
11448 if ((LHSVecTy && LHSVecTy->isExtVectorBoolType()) ||
11449 (RHSVecTy && RHSVecTy->isExtVectorBoolType())) {
11450 S.Diag(Loc, diag::err_typecheck_invalid_operands)
11451 << LHS.get()->getType() << RHS.get()->getType()
11452 << LHS.get()->getSourceRange();
11453 return QualType();
11454 }
11455
11456 // The operands need to be integers.
11457 if (!LHSEleType->isIntegerType()) {
11458 S.Diag(Loc, diag::err_typecheck_expect_int)
11459 << LHS.get()->getType() << LHS.get()->getSourceRange();
11460 return QualType();
11461 }
11462
11463 if (!RHSEleType->isIntegerType()) {
11464 S.Diag(Loc, diag::err_typecheck_expect_int)
11465 << RHS.get()->getType() << RHS.get()->getSourceRange();
11466 return QualType();
11467 }
11468
11469 if (!LHSVecTy) {
11470 assert(RHSVecTy)(static_cast <bool> (RHSVecTy) ? void (0) : __assert_fail
("RHSVecTy", "clang/lib/Sema/SemaExpr.cpp", 11470, __extension__
__PRETTY_FUNCTION__))
;
11471 if (IsCompAssign)
11472 return RHSType;
11473 if (LHSEleType != RHSEleType) {
11474 LHS = S.ImpCastExprToType(LHS.get(),RHSEleType, CK_IntegralCast);
11475 LHSEleType = RHSEleType;
11476 }
11477 QualType VecTy =
11478 S.Context.getExtVectorType(LHSEleType, RHSVecTy->getNumElements());
11479 LHS = S.ImpCastExprToType(LHS.get(), VecTy, CK_VectorSplat);
11480 LHSType = VecTy;
11481 } else if (RHSVecTy) {
11482 // OpenCL v1.1 s6.3.j says that for vector types, the operators
11483 // are applied component-wise. So if RHS is a vector, then ensure
11484 // that the number of elements is the same as LHS...
11485 if (RHSVecTy->getNumElements() != LHSVecTy->getNumElements()) {
11486 S.Diag(Loc, diag::err_typecheck_vector_lengths_not_equal)
11487 << LHS.get()->getType() << RHS.get()->getType()
11488 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
11489 return QualType();
11490 }
11491 if (!S.LangOpts.OpenCL && !S.LangOpts.ZVector) {
11492 const BuiltinType *LHSBT = LHSEleType->getAs<clang::BuiltinType>();
11493 const BuiltinType *RHSBT = RHSEleType->getAs<clang::BuiltinType>();
11494 if (LHSBT != RHSBT &&
11495 S.Context.getTypeSize(LHSBT) != S.Context.getTypeSize(RHSBT)) {
11496 S.Diag(Loc, diag::warn_typecheck_vector_element_sizes_not_equal)
11497 << LHS.get()->getType() << RHS.get()->getType()
11498 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
11499 }
11500 }
11501 } else {
11502 // ...else expand RHS to match the number of elements in LHS.
11503 QualType VecTy =
11504 S.Context.getExtVectorType(RHSEleType, LHSVecTy->getNumElements());
11505 RHS = S.ImpCastExprToType(RHS.get(), VecTy, CK_VectorSplat);
11506 }
11507
11508 return LHSType;
11509}
11510
11511static QualType checkSizelessVectorShift(Sema &S, ExprResult &LHS,
11512 ExprResult &RHS, SourceLocation Loc,
11513 bool IsCompAssign) {
11514 if (!IsCompAssign) {
11515 LHS = S.UsualUnaryConversions(LHS.get());
11516 if (LHS.isInvalid())
11517 return QualType();
11518 }
11519
11520 RHS = S.UsualUnaryConversions(RHS.get());
11521 if (RHS.isInvalid())
11522 return QualType();
11523
11524 QualType LHSType = LHS.get()->getType();
11525 const BuiltinType *LHSBuiltinTy = LHSType->getAs<BuiltinType>();
11526 QualType LHSEleType = LHSType->isVLSTBuiltinType()
11527 ? LHSBuiltinTy->getSveEltType(S.getASTContext())
11528 : LHSType;
11529
11530 // Note that RHS might not be a vector
11531 QualType RHSType = RHS.get()->getType();
11532 const BuiltinType *RHSBuiltinTy = RHSType->getAs<BuiltinType>();
11533 QualType RHSEleType = RHSType->isVLSTBuiltinType()
11534 ? RHSBuiltinTy->getSveEltType(S.getASTContext())
11535 : RHSType;
11536
11537 if ((LHSBuiltinTy && LHSBuiltinTy->isSVEBool()) ||
11538 (RHSBuiltinTy && RHSBuiltinTy->isSVEBool())) {
11539 S.Diag(Loc, diag::err_typecheck_invalid_operands)
11540 << LHSType << RHSType << LHS.get()->getSourceRange();
11541 return QualType();
11542 }
11543
11544 if (!LHSEleType->isIntegerType()) {
11545 S.Diag(Loc, diag::err_typecheck_expect_int)
11546 << LHS.get()->getType() << LHS.get()->getSourceRange();
11547 return QualType();
11548 }
11549
11550 if (!RHSEleType->isIntegerType()) {
11551 S.Diag(Loc, diag::err_typecheck_expect_int)
11552 << RHS.get()->getType() << RHS.get()->getSourceRange();
11553 return QualType();
11554 }
11555
11556 if (LHSType->isVLSTBuiltinType() && RHSType->isVLSTBuiltinType() &&
11557 (S.Context.getBuiltinVectorTypeInfo(LHSBuiltinTy).EC !=
11558 S.Context.getBuiltinVectorTypeInfo(RHSBuiltinTy).EC)) {
11559 S.Diag(Loc, diag::err_typecheck_invalid_operands)
11560 << LHSType << RHSType << LHS.get()->getSourceRange()
11561 << RHS.get()->getSourceRange();
11562 return QualType();
11563 }
11564
11565 if (!LHSType->isVLSTBuiltinType()) {
11566 assert(RHSType->isVLSTBuiltinType())(static_cast <bool> (RHSType->isVLSTBuiltinType()) ?
void (0) : __assert_fail ("RHSType->isVLSTBuiltinType()",
"clang/lib/Sema/SemaExpr.cpp", 11566, __extension__ __PRETTY_FUNCTION__
))
;
11567 if (IsCompAssign)
11568 return RHSType;
11569 if (LHSEleType != RHSEleType) {
11570 LHS = S.ImpCastExprToType(LHS.get(), RHSEleType, clang::CK_IntegralCast);
11571 LHSEleType = RHSEleType;
11572 }
11573 const llvm::ElementCount VecSize =
11574 S.Context.getBuiltinVectorTypeInfo(RHSBuiltinTy).EC;
11575 QualType VecTy =
11576 S.Context.getScalableVectorType(LHSEleType, VecSize.getKnownMinValue());
11577 LHS = S.ImpCastExprToType(LHS.get(), VecTy, clang::CK_VectorSplat);
11578 LHSType = VecTy;
11579 } else if (RHSBuiltinTy && RHSBuiltinTy->isVLSTBuiltinType()) {
11580 if (S.Context.getTypeSize(RHSBuiltinTy) !=
11581 S.Context.getTypeSize(LHSBuiltinTy)) {
11582 S.Diag(Loc, diag::err_typecheck_vector_lengths_not_equal)
11583 << LHSType << RHSType << LHS.get()->getSourceRange()
11584 << RHS.get()->getSourceRange();
11585 return QualType();
11586 }
11587 } else {
11588 const llvm::ElementCount VecSize =
11589 S.Context.getBuiltinVectorTypeInfo(LHSBuiltinTy).EC;
11590 if (LHSEleType != RHSEleType) {
11591 RHS = S.ImpCastExprToType(RHS.get(), LHSEleType, clang::CK_IntegralCast);
11592 RHSEleType = LHSEleType;
11593 }
11594 QualType VecTy =
11595 S.Context.getScalableVectorType(RHSEleType, VecSize.getKnownMinValue());
11596 RHS = S.ImpCastExprToType(RHS.get(), VecTy, CK_VectorSplat);
11597 }
11598
11599 return LHSType;
11600}
11601
11602// C99 6.5.7
11603QualType Sema::CheckShiftOperands(ExprResult &LHS, ExprResult &RHS,
11604 SourceLocation Loc, BinaryOperatorKind Opc,
11605 bool IsCompAssign) {
11606 checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/false);
11607
11608 // Vector shifts promote their scalar inputs to vector type.
11609 if (LHS.get()->getType()->isVectorType() ||
11610 RHS.get()->getType()->isVectorType()) {
11611 if (LangOpts.ZVector) {
11612 // The shift operators for the z vector extensions work basically
11613 // like general shifts, except that neither the LHS nor the RHS is
11614 // allowed to be a "vector bool".
11615 if (auto LHSVecType = LHS.get()->getType()->getAs<VectorType>())
11616 if (LHSVecType->getVectorKind() == VectorType::AltiVecBool)
11617 return InvalidOperands(Loc, LHS, RHS);
11618 if (auto RHSVecType = RHS.get()->getType()->getAs<VectorType>())
11619 if (RHSVecType->getVectorKind() == VectorType::AltiVecBool)
11620 return InvalidOperands(Loc, LHS, RHS);
11621 }
11622 return checkVectorShift(*this, LHS, RHS, Loc, IsCompAssign);
11623 }
11624
11625 if (LHS.get()->getType()->isVLSTBuiltinType() ||
11626 RHS.get()->getType()->isVLSTBuiltinType())
11627 return checkSizelessVectorShift(*this, LHS, RHS, Loc, IsCompAssign);
11628
11629 // Shifts don't perform usual arithmetic conversions, they just do integer
11630 // promotions on each operand. C99 6.5.7p3
11631
11632 // For the LHS, do usual unary conversions, but then reset them away
11633 // if this is a compound assignment.
11634 ExprResult OldLHS = LHS;
11635 LHS = UsualUnaryConversions(LHS.get());
11636 if (LHS.isInvalid())
11637 return QualType();
11638 QualType LHSType = LHS.get()->getType();
11639 if (IsCompAssign) LHS = OldLHS;
11640
11641 // The RHS is simpler.
11642 RHS = UsualUnaryConversions(RHS.get());
11643 if (RHS.isInvalid())
11644 return QualType();
11645 QualType RHSType = RHS.get()->getType();
11646
11647 // C99 6.5.7p2: Each of the operands shall have integer type.
11648 // Embedded-C 4.1.6.2.2: The LHS may also be fixed-point.
11649 if ((!LHSType->isFixedPointOrIntegerType() &&
11650 !LHSType->hasIntegerRepresentation()) ||
11651 !RHSType->hasIntegerRepresentation())
11652 return InvalidOperands(Loc, LHS, RHS);
11653
11654 // C++0x: Don't allow scoped enums. FIXME: Use something better than
11655 // hasIntegerRepresentation() above instead of this.
11656 if (isScopedEnumerationType(LHSType) ||
11657 isScopedEnumerationType(RHSType)) {
11658 return InvalidOperands(Loc, LHS, RHS);
11659 }
11660 DiagnoseBadShiftValues(*this, LHS, RHS, Loc, Opc, LHSType);
11661
11662 // "The type of the result is that of the promoted left operand."
11663 return LHSType;
11664}
11665
11666/// Diagnose bad pointer comparisons.
11667static void diagnoseDistinctPointerComparison(Sema &S, SourceLocation Loc,
11668 ExprResult &LHS, ExprResult &RHS,
11669 bool IsError) {
11670 S.Diag(Loc, IsError ? diag::err_typecheck_comparison_of_distinct_pointers
11671 : diag::ext_typecheck_comparison_of_distinct_pointers)
11672 << LHS.get()->getType() << RHS.get()->getType()
11673 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
11674}
11675
11676/// Returns false if the pointers are converted to a composite type,
11677/// true otherwise.
11678static bool convertPointersToCompositeType(Sema &S, SourceLocation Loc,
11679 ExprResult &LHS, ExprResult &RHS) {
11680 // C++ [expr.rel]p2:
11681 // [...] Pointer conversions (4.10) and qualification
11682 // conversions (4.4) are performed on pointer operands (or on
11683 // a pointer operand and a null pointer constant) to bring
11684 // them to their composite pointer type. [...]
11685 //
11686 // C++ [expr.eq]p1 uses the same notion for (in)equality
11687 // comparisons of pointers.
11688
11689 QualType LHSType = LHS.get()->getType();
11690 QualType RHSType = RHS.get()->getType();
11691 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", 11692, __extension__ __PRETTY_FUNCTION__
))
11692 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", 11692, __extension__ __PRETTY_FUNCTION__
))
;
11693
11694 QualType T = S.FindCompositePointerType(Loc, LHS, RHS);
11695 if (T.isNull()) {
11696 if ((LHSType->isAnyPointerType() || LHSType->isMemberPointerType()) &&
11697 (RHSType->isAnyPointerType() || RHSType->isMemberPointerType()))
11698 diagnoseDistinctPointerComparison(S, Loc, LHS, RHS, /*isError*/true);
11699 else
11700 S.InvalidOperands(Loc, LHS, RHS);
11701 return true;
11702 }
11703
11704 return false;
11705}
11706
11707static void diagnoseFunctionPointerToVoidComparison(Sema &S, SourceLocation Loc,
11708 ExprResult &LHS,
11709 ExprResult &RHS,
11710 bool IsError) {
11711 S.Diag(Loc, IsError ? diag::err_typecheck_comparison_of_fptr_to_void
11712 : diag::ext_typecheck_comparison_of_fptr_to_void)
11713 << LHS.get()->getType() << RHS.get()->getType()
11714 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
11715}
11716
11717static bool isObjCObjectLiteral(ExprResult &E) {
11718 switch (E.get()->IgnoreParenImpCasts()->getStmtClass()) {
11719 case Stmt::ObjCArrayLiteralClass:
11720 case Stmt::ObjCDictionaryLiteralClass:
11721 case Stmt::ObjCStringLiteralClass:
11722 case Stmt::ObjCBoxedExprClass:
11723 return true;
11724 default:
11725 // Note that ObjCBoolLiteral is NOT an object literal!
11726 return false;
11727 }
11728}
11729
11730static bool hasIsEqualMethod(Sema &S, const Expr *LHS, const Expr *RHS) {
11731 const ObjCObjectPointerType *Type =
11732 LHS->getType()->getAs<ObjCObjectPointerType>();
11733
11734 // If this is not actually an Objective-C object, bail out.
11735 if (!Type)
11736 return false;
11737
11738 // Get the LHS object's interface type.
11739 QualType InterfaceType = Type->getPointeeType();
11740
11741 // If the RHS isn't an Objective-C object, bail out.
11742 if (!RHS->getType()->isObjCObjectPointerType())
11743 return false;
11744
11745 // Try to find the -isEqual: method.
11746 Selector IsEqualSel = S.NSAPIObj->getIsEqualSelector();
11747 ObjCMethodDecl *Method = S.LookupMethodInObjectType(IsEqualSel,
11748 InterfaceType,
11749 /*IsInstance=*/true);
11750 if (!Method) {
11751 if (Type->isObjCIdType()) {
11752 // For 'id', just check the global pool.
11753 Method = S.LookupInstanceMethodInGlobalPool(IsEqualSel, SourceRange(),
11754 /*receiverId=*/true);
11755 } else {
11756 // Check protocols.
11757 Method = S.LookupMethodInQualifiedType(IsEqualSel, Type,
11758 /*IsInstance=*/true);
11759 }
11760 }
11761
11762 if (!Method)
11763 return false;
11764
11765 QualType T = Method->parameters()[0]->getType();
11766 if (!T->isObjCObjectPointerType())
11767 return false;
11768
11769 QualType R = Method->getReturnType();
11770 if (!R->isScalarType())
11771 return false;
11772
11773 return true;
11774}
11775
11776Sema::ObjCLiteralKind Sema::CheckLiteralKind(Expr *FromE) {
11777 FromE = FromE->IgnoreParenImpCasts();
11778 switch (FromE->getStmtClass()) {
11779 default:
11780 break;
11781 case Stmt::ObjCStringLiteralClass:
11782 // "string literal"
11783 return LK_String;
11784 case Stmt::ObjCArrayLiteralClass:
11785 // "array literal"
11786 return LK_Array;
11787 case Stmt::ObjCDictionaryLiteralClass:
11788 // "dictionary literal"
11789 return LK_Dictionary;
11790 case Stmt::BlockExprClass:
11791 return LK_Block;
11792 case Stmt::ObjCBoxedExprClass: {
11793 Expr *Inner = cast<ObjCBoxedExpr>(FromE)->getSubExpr()->IgnoreParens();
11794 switch (Inner->getStmtClass()) {
11795 case Stmt::IntegerLiteralClass:
11796 case Stmt::FloatingLiteralClass:
11797 case Stmt::CharacterLiteralClass:
11798 case Stmt::ObjCBoolLiteralExprClass:
11799 case Stmt::CXXBoolLiteralExprClass:
11800 // "numeric literal"
11801 return LK_Numeric;
11802 case Stmt::ImplicitCastExprClass: {
11803 CastKind CK = cast<CastExpr>(Inner)->getCastKind();
11804 // Boolean literals can be represented by implicit casts.
11805 if (CK == CK_IntegralToBoolean || CK == CK_IntegralCast)
11806 return LK_Numeric;
11807 break;
11808 }
11809 default:
11810 break;
11811 }
11812 return LK_Boxed;
11813 }
11814 }
11815 return LK_None;
11816}
11817
11818static void diagnoseObjCLiteralComparison(Sema &S, SourceLocation Loc,
11819 ExprResult &LHS, ExprResult &RHS,
11820 BinaryOperator::Opcode Opc){
11821 Expr *Literal;
11822 Expr *Other;
11823 if (isObjCObjectLiteral(LHS)) {
11824 Literal = LHS.get();
11825 Other = RHS.get();
11826 } else {
11827 Literal = RHS.get();
11828 Other = LHS.get();
11829 }
11830
11831 // Don't warn on comparisons against nil.
11832 Other = Other->IgnoreParenCasts();
11833 if (Other->isNullPointerConstant(S.getASTContext(),
11834 Expr::NPC_ValueDependentIsNotNull))
11835 return;
11836
11837 // This should be kept in sync with warn_objc_literal_comparison.
11838 // LK_String should always be after the other literals, since it has its own
11839 // warning flag.
11840 Sema::ObjCLiteralKind LiteralKind = S.CheckLiteralKind(Literal);
11841 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"
, 11841, __extension__ __PRETTY_FUNCTION__))
;
11842 if (LiteralKind == Sema::LK_None) {
11843 llvm_unreachable("Unknown Objective-C object literal kind")::llvm::llvm_unreachable_internal("Unknown Objective-C object literal kind"
, "clang/lib/Sema/SemaExpr.cpp", 11843)
;
11844 }
11845
11846 if (LiteralKind == Sema::LK_String)
11847 S.Diag(Loc, diag::warn_objc_string_literal_comparison)
11848 << Literal->getSourceRange();
11849 else
11850 S.Diag(Loc, diag::warn_objc_literal_comparison)
11851 << LiteralKind << Literal->getSourceRange();
11852
11853 if (BinaryOperator::isEqualityOp(Opc) &&
11854 hasIsEqualMethod(S, LHS.get(), RHS.get())) {
11855 SourceLocation Start = LHS.get()->getBeginLoc();
11856 SourceLocation End = S.getLocForEndOfToken(RHS.get()->getEndLoc());
11857 CharSourceRange OpRange =
11858 CharSourceRange::getCharRange(Loc, S.getLocForEndOfToken(Loc));
11859
11860 S.Diag(Loc, diag::note_objc_literal_comparison_isequal)
11861 << FixItHint::CreateInsertion(Start, Opc == BO_EQ ? "[" : "![")
11862 << FixItHint::CreateReplacement(OpRange, " isEqual:")
11863 << FixItHint::CreateInsertion(End, "]");
11864 }
11865}
11866
11867/// Warns on !x < y, !x & y where !(x < y), !(x & y) was probably intended.
11868static void diagnoseLogicalNotOnLHSofCheck(Sema &S, ExprResult &LHS,
11869 ExprResult &RHS, SourceLocation Loc,
11870 BinaryOperatorKind Opc) {
11871 // Check that left hand side is !something.
11872 UnaryOperator *UO = dyn_cast<UnaryOperator>(LHS.get()->IgnoreImpCasts());
11873 if (!UO || UO->getOpcode() != UO_LNot) return;
11874
11875 // Only check if the right hand side is non-bool arithmetic type.
11876 if (RHS.get()->isKnownToHaveBooleanValue()) return;
11877
11878 // Make sure that the something in !something is not bool.
11879 Expr *SubExpr = UO->getSubExpr()->IgnoreImpCasts();
11880 if (SubExpr->isKnownToHaveBooleanValue()) return;
11881
11882 // Emit warning.
11883 bool IsBitwiseOp = Opc == BO_And || Opc == BO_Or || Opc == BO_Xor;
11884 S.Diag(UO->getOperatorLoc(), diag::warn_logical_not_on_lhs_of_check)
11885 << Loc << IsBitwiseOp;
11886
11887 // First note suggest !(x < y)
11888 SourceLocation FirstOpen = SubExpr->getBeginLoc();
11889 SourceLocation FirstClose = RHS.get()->getEndLoc();
11890 FirstClose = S.getLocForEndOfToken(FirstClose);
11891 if (FirstClose.isInvalid())
11892 FirstOpen = SourceLocation();
11893 S.Diag(UO->getOperatorLoc(), diag::note_logical_not_fix)
11894 << IsBitwiseOp
11895 << FixItHint::CreateInsertion(FirstOpen, "(")
11896 << FixItHint::CreateInsertion(FirstClose, ")");
11897
11898 // Second note suggests (!x) < y
11899 SourceLocation SecondOpen = LHS.get()->getBeginLoc();
11900 SourceLocation SecondClose = LHS.get()->getEndLoc();
11901 SecondClose = S.getLocForEndOfToken(SecondClose);
11902 if (SecondClose.isInvalid())
11903 SecondOpen = SourceLocation();
11904 S.Diag(UO->getOperatorLoc(), diag::note_logical_not_silence_with_parens)
11905 << FixItHint::CreateInsertion(SecondOpen, "(")
11906 << FixItHint::CreateInsertion(SecondClose, ")");
11907}
11908
11909// Returns true if E refers to a non-weak array.
11910static bool checkForArray(const Expr *E) {
11911 const ValueDecl *D = nullptr;
11912 if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(E)) {
11913 D = DR->getDecl();
11914 } else if (const MemberExpr *Mem = dyn_cast<MemberExpr>(E)) {
11915 if (Mem->isImplicitAccess())
11916 D = Mem->getMemberDecl();
11917 }
11918 if (!D)
11919 return false;
11920 return D->getType()->isArrayType() && !D->isWeak();
11921}
11922
11923/// Diagnose some forms of syntactically-obvious tautological comparison.
11924static void diagnoseTautologicalComparison(Sema &S, SourceLocation Loc,
11925 Expr *LHS, Expr *RHS,
11926 BinaryOperatorKind Opc) {
11927 Expr *LHSStripped = LHS->IgnoreParenImpCasts();
11928 Expr *RHSStripped = RHS->IgnoreParenImpCasts();
11929
11930 QualType LHSType = LHS->getType();
11931 QualType RHSType = RHS->getType();
11932 if (LHSType->hasFloatingRepresentation() ||
11933 (LHSType->isBlockPointerType() && !BinaryOperator::isEqualityOp(Opc)) ||
11934 S.inTemplateInstantiation())
11935 return;
11936
11937 // Comparisons between two array types are ill-formed for operator<=>, so
11938 // we shouldn't emit any additional warnings about it.
11939 if (Opc == BO_Cmp && LHSType->isArrayType() && RHSType->isArrayType())
11940 return;
11941
11942 // For non-floating point types, check for self-comparisons of the form
11943 // x == x, x != x, x < x, etc. These always evaluate to a constant, and
11944 // often indicate logic errors in the program.
11945 //
11946 // NOTE: Don't warn about comparison expressions resulting from macro
11947 // expansion. Also don't warn about comparisons which are only self
11948 // comparisons within a template instantiation. The warnings should catch
11949 // obvious cases in the definition of the template anyways. The idea is to
11950 // warn when the typed comparison operator will always evaluate to the same
11951 // result.
11952
11953 // Used for indexing into %select in warn_comparison_always
11954 enum {
11955 AlwaysConstant,
11956 AlwaysTrue,
11957 AlwaysFalse,
11958 AlwaysEqual, // std::strong_ordering::equal from operator<=>
11959 };
11960
11961 // C++2a [depr.array.comp]:
11962 // Equality and relational comparisons ([expr.eq], [expr.rel]) between two
11963 // operands of array type are deprecated.
11964 if (S.getLangOpts().CPlusPlus20 && LHSStripped->getType()->isArrayType() &&
11965 RHSStripped->getType()->isArrayType()) {
11966 S.Diag(Loc, diag::warn_depr_array_comparison)
11967 << LHS->getSourceRange() << RHS->getSourceRange()
11968 << LHSStripped->getType() << RHSStripped->getType();
11969 // Carry on to produce the tautological comparison warning, if this
11970 // expression is potentially-evaluated, we can resolve the array to a
11971 // non-weak declaration, and so on.
11972 }
11973
11974 if (!LHS->getBeginLoc().isMacroID() && !RHS->getBeginLoc().isMacroID()) {
11975 if (Expr::isSameComparisonOperand(LHS, RHS)) {
11976 unsigned Result;
11977 switch (Opc) {
11978 case BO_EQ:
11979 case BO_LE:
11980 case BO_GE:
11981 Result = AlwaysTrue;
11982 break;
11983 case BO_NE:
11984 case BO_LT:
11985 case BO_GT:
11986 Result = AlwaysFalse;
11987 break;
11988 case BO_Cmp:
11989 Result = AlwaysEqual;
11990 break;
11991 default:
11992 Result = AlwaysConstant;
11993 break;
11994 }
11995 S.DiagRuntimeBehavior(Loc, nullptr,
11996 S.PDiag(diag::warn_comparison_always)
11997 << 0 /*self-comparison*/
11998 << Result);
11999 } else if (checkForArray(LHSStripped) && checkForArray(RHSStripped)) {
12000 // What is it always going to evaluate to?
12001 unsigned Result;
12002 switch (Opc) {
12003 case BO_EQ: // e.g. array1 == array2
12004 Result = AlwaysFalse;
12005 break;
12006 case BO_NE: // e.g. array1 != array2
12007 Result = AlwaysTrue;
12008 break;
12009 default: // e.g. array1 <= array2
12010 // The best we can say is 'a constant'
12011 Result = AlwaysConstant;
12012 break;
12013 }
12014 S.DiagRuntimeBehavior(Loc, nullptr,
12015 S.PDiag(diag::warn_comparison_always)
12016 << 1 /*array comparison*/
12017 << Result);
12018 }
12019 }
12020
12021 if (isa<CastExpr>(LHSStripped))
12022 LHSStripped = LHSStripped->IgnoreParenCasts();
12023 if (isa<CastExpr>(RHSStripped))
12024 RHSStripped = RHSStripped->IgnoreParenCasts();
12025
12026 // Warn about comparisons against a string constant (unless the other
12027 // operand is null); the user probably wants string comparison function.
12028 Expr *LiteralString = nullptr;
12029 Expr *LiteralStringStripped = nullptr;
12030 if ((isa<StringLiteral>(LHSStripped) || isa<ObjCEncodeExpr>(LHSStripped)) &&
12031 !RHSStripped->isNullPointerConstant(S.Context,
12032 Expr::NPC_ValueDependentIsNull)) {
12033 LiteralString = LHS;
12034 LiteralStringStripped = LHSStripped;
12035 } else if ((isa<StringLiteral>(RHSStripped) ||
12036 isa<ObjCEncodeExpr>(RHSStripped)) &&
12037 !LHSStripped->isNullPointerConstant(S.Context,
12038 Expr::NPC_ValueDependentIsNull)) {
12039 LiteralString = RHS;
12040 LiteralStringStripped = RHSStripped;
12041 }
12042
12043 if (LiteralString) {
12044 S.DiagRuntimeBehavior(Loc, nullptr,
12045 S.PDiag(diag::warn_stringcompare)
12046 << isa<ObjCEncodeExpr>(LiteralStringStripped)
12047 << LiteralString->getSourceRange());
12048 }
12049}
12050
12051static ImplicitConversionKind castKindToImplicitConversionKind(CastKind CK) {
12052 switch (CK) {
12053 default: {
12054#ifndef NDEBUG
12055 llvm::errs() << "unhandled cast kind: " << CastExpr::getCastKindName(CK)
12056 << "\n";
12057#endif
12058 llvm_unreachable("unhandled cast kind")::llvm::llvm_unreachable_internal("unhandled cast kind", "clang/lib/Sema/SemaExpr.cpp"
, 12058)
;
12059 }
12060 case CK_UserDefinedConversion:
12061 return ICK_Identity;
12062 case CK_LValueToRValue:
12063 return ICK_Lvalue_To_Rvalue;
12064 case CK_ArrayToPointerDecay:
12065 return ICK_Array_To_Pointer;
12066 case CK_FunctionToPointerDecay:
12067 return ICK_Function_To_Pointer;
12068 case CK_IntegralCast:
12069 return ICK_Integral_Conversion;
12070 case CK_FloatingCast:
12071 return ICK_Floating_Conversion;
12072 case CK_IntegralToFloating:
12073 case CK_FloatingToIntegral:
12074 return ICK_Floating_Integral;
12075 case CK_IntegralComplexCast:
12076 case CK_FloatingComplexCast:
12077 case CK_FloatingComplexToIntegralComplex:
12078 case CK_IntegralComplexToFloatingComplex:
12079 return ICK_Complex_Conversion;
12080 case CK_FloatingComplexToReal:
12081 case CK_FloatingRealToComplex:
12082 case CK_IntegralComplexToReal:
12083 case CK_IntegralRealToComplex:
12084 return ICK_Complex_Real;
12085 }
12086}
12087
12088static bool checkThreeWayNarrowingConversion(Sema &S, QualType ToType, Expr *E,
12089 QualType FromType,
12090 SourceLocation Loc) {
12091 // Check for a narrowing implicit conversion.
12092 StandardConversionSequence SCS;
12093 SCS.setAsIdentityConversion();
12094 SCS.setToType(0, FromType);
12095 SCS.setToType(1, ToType);
12096 if (const auto *ICE = dyn_cast<ImplicitCastExpr>(E))
12097 SCS.Second = castKindToImplicitConversionKind(ICE->getCastKind());
12098
12099 APValue PreNarrowingValue;
12100 QualType PreNarrowingType;
12101 switch (SCS.getNarrowingKind(S.Context, E, PreNarrowingValue,
12102 PreNarrowingType,
12103 /*IgnoreFloatToIntegralConversion*/ true)) {
12104 case NK_Dependent_Narrowing:
12105 // Implicit conversion to a narrower type, but the expression is
12106 // value-dependent so we can't tell whether it's actually narrowing.
12107 case NK_Not_Narrowing:
12108 return false;
12109
12110 case NK_Constant_Narrowing:
12111 // Implicit conversion to a narrower type, and the value is not a constant
12112 // expression.
12113 S.Diag(E->getBeginLoc(), diag::err_spaceship_argument_narrowing)
12114 << /*Constant*/ 1
12115 << PreNarrowingValue.getAsString(S.Context, PreNarrowingType) << ToType;
12116 return true;
12117
12118 case NK_Variable_Narrowing:
12119 // Implicit conversion to a narrower type, and the value is not a constant
12120 // expression.
12121 case NK_Type_Narrowing:
12122 S.Diag(E->getBeginLoc(), diag::err_spaceship_argument_narrowing)
12123 << /*Constant*/ 0 << FromType << ToType;
12124 // TODO: It's not a constant expression, but what if the user intended it
12125 // to be? Can we produce notes to help them figure out why it isn't?
12126 return true;
12127 }
12128 llvm_unreachable("unhandled case in switch")::llvm::llvm_unreachable_internal("unhandled case in switch",
"clang/lib/Sema/SemaExpr.cpp", 12128)
;
12129}
12130
12131static QualType checkArithmeticOrEnumeralThreeWayCompare(Sema &S,
12132 ExprResult &LHS,
12133 ExprResult &RHS,
12134 SourceLocation Loc) {
12135 QualType LHSType = LHS.get()->getType();
12136 QualType RHSType = RHS.get()->getType();
12137 // Dig out the original argument type and expression before implicit casts
12138 // were applied. These are the types/expressions we need to check the
12139 // [expr.spaceship] requirements against.
12140 ExprResult LHSStripped = LHS.get()->IgnoreParenImpCasts();
12141 ExprResult RHSStripped = RHS.get()->IgnoreParenImpCasts();
12142 QualType LHSStrippedType = LHSStripped.get()->getType();
12143 QualType RHSStrippedType = RHSStripped.get()->getType();
12144
12145 // C++2a [expr.spaceship]p3: If one of the operands is of type bool and the
12146 // other is not, the program is ill-formed.
12147 if (LHSStrippedType->isBooleanType() != RHSStrippedType->isBooleanType()) {
12148 S.InvalidOperands(Loc, LHSStripped, RHSStripped);
12149 return QualType();
12150 }
12151
12152 // FIXME: Consider combining this with checkEnumArithmeticConversions.
12153 int NumEnumArgs = (int)LHSStrippedType->isEnumeralType() +
12154 RHSStrippedType->isEnumeralType();
12155 if (NumEnumArgs == 1) {
12156 bool LHSIsEnum = LHSStrippedType->isEnumeralType();
12157 QualType OtherTy = LHSIsEnum ? RHSStrippedType : LHSStrippedType;
12158 if (OtherTy->hasFloatingRepresentation()) {
12159 S.InvalidOperands(Loc, LHSStripped, RHSStripped);
12160 return QualType();
12161 }
12162 }
12163 if (NumEnumArgs == 2) {
12164 // C++2a [expr.spaceship]p5: If both operands have the same enumeration
12165 // type E, the operator yields the result of converting the operands
12166 // to the underlying type of E and applying <=> to the converted operands.
12167 if (!S.Context.hasSameUnqualifiedType(LHSStrippedType, RHSStrippedType)) {
12168 S.InvalidOperands(Loc, LHS, RHS);
12169 return QualType();
12170 }
12171 QualType IntType =
12172 LHSStrippedType->castAs<EnumType>()->getDecl()->getIntegerType();
12173 assert(IntType->isArithmeticType())(static_cast <bool> (IntType->isArithmeticType()) ? void
(0) : __assert_fail ("IntType->isArithmeticType()", "clang/lib/Sema/SemaExpr.cpp"
, 12173, __extension__ __PRETTY_FUNCTION__))
;
12174
12175 // We can't use `CK_IntegralCast` when the underlying type is 'bool', so we
12176 // promote the boolean type, and all other promotable integer types, to
12177 // avoid this.
12178 if (IntType->isPromotableIntegerType())
12179 IntType = S.Context.getPromotedIntegerType(IntType);
12180
12181 LHS = S.ImpCastExprToType(LHS.get(), IntType, CK_IntegralCast);
12182 RHS = S.ImpCastExprToType(RHS.get(), IntType, CK_IntegralCast);
12183 LHSType = RHSType = IntType;
12184 }
12185
12186 // C++2a [expr.spaceship]p4: If both operands have arithmetic types, the
12187 // usual arithmetic conversions are applied to the operands.
12188 QualType Type =
12189 S.UsualArithmeticConversions(LHS, RHS, Loc, Sema::ACK_Comparison);
12190 if (LHS.isInvalid() || RHS.isInvalid())
12191 return QualType();
12192 if (Type.isNull())
12193 return S.InvalidOperands(Loc, LHS, RHS);
12194
12195 Optional<ComparisonCategoryType> CCT =
12196 getComparisonCategoryForBuiltinCmp(Type);
12197 if (!CCT)
12198 return S.InvalidOperands(Loc, LHS, RHS);
12199
12200 bool HasNarrowing = checkThreeWayNarrowingConversion(
12201 S, Type, LHS.get(), LHSType, LHS.get()->getBeginLoc());
12202 HasNarrowing |= checkThreeWayNarrowingConversion(S, Type, RHS.get(), RHSType,
12203 RHS.get()->getBeginLoc());
12204 if (HasNarrowing)
12205 return QualType();
12206
12207 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", 12207, __extension__ __PRETTY_FUNCTION__
))
;
12208
12209 return S.CheckComparisonCategoryType(
12210 *CCT, Loc, Sema::ComparisonCategoryUsage::OperatorInExpression);
12211}
12212
12213static QualType checkArithmeticOrEnumeralCompare(Sema &S, ExprResult &LHS,
12214 ExprResult &RHS,
12215 SourceLocation Loc,
12216 BinaryOperatorKind Opc) {
12217 if (Opc == BO_Cmp)
12218 return checkArithmeticOrEnumeralThreeWayCompare(S, LHS, RHS, Loc);
12219
12220 // C99 6.5.8p3 / C99 6.5.9p4
12221 QualType Type =
12222 S.UsualArithmeticConversions(LHS, RHS, Loc, Sema::ACK_Comparison);
12223 if (LHS.isInvalid() || RHS.isInvalid())
12224 return QualType();
12225 if (Type.isNull())
12226 return S.InvalidOperands(Loc, LHS, RHS);
12227 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", 12227, __extension__ __PRETTY_FUNCTION__
))
;
12228
12229 if (Type->isAnyComplexType() && BinaryOperator::isRelationalOp(Opc))
12230 return S.InvalidOperands(Loc, LHS, RHS);
12231
12232 // Check for comparisons of floating point operands using != and ==.
12233 if (Type->hasFloatingRepresentation() && BinaryOperator::isEqualityOp(Opc))
12234 S.CheckFloatComparison(Loc, LHS.get(), RHS.get(), Opc);
12235
12236 // The result of comparisons is 'bool' in C++, 'int' in C.
12237 return S.Context.getLogicalOperationType();
12238}
12239
12240void Sema::CheckPtrComparisonWithNullChar(ExprResult &E, ExprResult &NullE) {
12241 if (!NullE.get()->getType()->isAnyPointerType())
12242 return;
12243 int NullValue = PP.isMacroDefined("NULL") ? 0 : 1;
12244 if (!E.get()->getType()->isAnyPointerType() &&
12245 E.get()->isNullPointerConstant(Context,
12246 Expr::NPC_ValueDependentIsNotNull) ==
12247 Expr::NPCK_ZeroExpression) {
12248 if (const auto *CL = dyn_cast<CharacterLiteral>(E.get())) {
12249 if (CL->getValue() == 0)
12250 Diag(E.get()->getExprLoc(), diag::warn_pointer_compare)
12251 << NullValue
12252 << FixItHint::CreateReplacement(E.get()->getExprLoc(),
12253 NullValue ? "NULL" : "(void *)0");
12254 } else if (const auto *CE = dyn_cast<CStyleCastExpr>(E.get())) {
12255 TypeSourceInfo *TI = CE->getTypeInfoAsWritten();
12256 QualType T = Context.getCanonicalType(TI->getType()).getUnqualifiedType();
12257 if (T == Context.CharTy)
12258 Diag(E.get()->getExprLoc(), diag::warn_pointer_compare)
12259 << NullValue
12260 << FixItHint::CreateReplacement(E.get()->getExprLoc(),
12261 NullValue ? "NULL" : "(void *)0");
12262 }
12263 }
12264}
12265
12266// C99 6.5.8, C++ [expr.rel]
12267QualType Sema::CheckCompareOperands(ExprResult &LHS, ExprResult &RHS,
12268 SourceLocation Loc,
12269 BinaryOperatorKind Opc) {
12270 bool IsRelational = BinaryOperator::isRelationalOp(Opc);
12271 bool IsThreeWay = Opc == BO_Cmp;
12272 bool IsOrdered = IsRelational || IsThreeWay;
12273 auto IsAnyPointerType = [](ExprResult E) {
12274 QualType Ty = E.get()->getType();
12275 return Ty->isPointerType() || Ty->isMemberPointerType();
12276 };
12277
12278 // C++2a [expr.spaceship]p6: If at least one of the operands is of pointer
12279 // type, array-to-pointer, ..., conversions are performed on both operands to
12280 // bring them to their composite type.
12281 // Otherwise, all comparisons expect an rvalue, so convert to rvalue before
12282 // any type-related checks.
12283 if (!IsThreeWay || IsAnyPointerType(LHS) || IsAnyPointerType(RHS)) {
12284 LHS = DefaultFunctionArrayLvalueConversion(LHS.get());
12285 if (LHS.isInvalid())
12286 return QualType();
12287 RHS = DefaultFunctionArrayLvalueConversion(RHS.get());
12288 if (RHS.isInvalid())
12289 return QualType();
12290 } else {
12291 LHS = DefaultLvalueConversion(LHS.get());
12292 if (LHS.isInvalid())
12293 return QualType();
12294 RHS = DefaultLvalueConversion(RHS.get());
12295 if (RHS.isInvalid())
12296 return QualType();
12297 }
12298
12299 checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/true);
12300 if (!getLangOpts().CPlusPlus && BinaryOperator::isEqualityOp(Opc)) {
12301 CheckPtrComparisonWithNullChar(LHS, RHS);
12302 CheckPtrComparisonWithNullChar(RHS, LHS);
12303 }
12304
12305 // Handle vector comparisons separately.
12306 if (LHS.get()->getType()->isVectorType() ||
12307 RHS.get()->getType()->isVectorType())
12308 return CheckVectorCompareOperands(LHS, RHS, Loc, Opc);
12309
12310 if (LHS.get()->getType()->isVLSTBuiltinType() ||
12311 RHS.get()->getType()->isVLSTBuiltinType())
12312 return CheckSizelessVectorCompareOperands(LHS, RHS, Loc, Opc);
12313
12314 diagnoseLogicalNotOnLHSofCheck(*this, LHS, RHS, Loc, Opc);
12315 diagnoseTautologicalComparison(*this, Loc, LHS.get(), RHS.get(), Opc);
12316
12317 QualType LHSType = LHS.get()->getType();
12318 QualType RHSType = RHS.get()->getType();
12319 if ((LHSType->isArithmeticType() || LHSType->isEnumeralType()) &&
12320 (RHSType->isArithmeticType() || RHSType->isEnumeralType()))
12321 return checkArithmeticOrEnumeralCompare(*this, LHS, RHS, Loc, Opc);
12322
12323 const Expr::NullPointerConstantKind LHSNullKind =
12324 LHS.get()->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull);
12325 const Expr::NullPointerConstantKind RHSNullKind =
12326 RHS.get()->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull);
12327 bool LHSIsNull = LHSNullKind != Expr::NPCK_NotNull;
12328 bool RHSIsNull = RHSNullKind != Expr::NPCK_NotNull;
12329
12330 auto computeResultTy = [&]() {
12331 if (Opc != BO_Cmp)
12332 return Context.getLogicalOperationType();
12333 assert(getLangOpts().CPlusPlus)(static_cast <bool> (getLangOpts().CPlusPlus) ? void (0
) : __assert_fail ("getLangOpts().CPlusPlus", "clang/lib/Sema/SemaExpr.cpp"
, 12333, __extension__ __PRETTY_FUNCTION__))
;
12334 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", 12334, __extension__ __PRETTY_FUNCTION__
))
;
12335
12336 QualType CompositeTy = LHS.get()->getType();
12337 assert(!CompositeTy->isReferenceType())(static_cast <bool> (!CompositeTy->isReferenceType()
) ? void (0) : __assert_fail ("!CompositeTy->isReferenceType()"
, "clang/lib/Sema/SemaExpr.cpp", 12337, __extension__ __PRETTY_FUNCTION__
))
;
12338
12339 Optional<ComparisonCategoryType> CCT =
12340 getComparisonCategoryForBuiltinCmp(CompositeTy);
12341 if (!CCT)
12342 return InvalidOperands(Loc, LHS, RHS);
12343
12344 if (CompositeTy->isPointerType() && LHSIsNull != RHSIsNull) {
12345 // P0946R0: Comparisons between a null pointer constant and an object
12346 // pointer result in std::strong_equality, which is ill-formed under
12347 // P1959R0.
12348 Diag(Loc, diag::err_typecheck_three_way_comparison_of_pointer_and_zero)
12349 << (LHSIsNull ? LHS.get()->getSourceRange()
12350 : RHS.get()->getSourceRange());
12351 return QualType();
12352 }
12353
12354 return CheckComparisonCategoryType(
12355 *CCT, Loc, ComparisonCategoryUsage::OperatorInExpression);
12356 };
12357
12358 if (!IsOrdered && LHSIsNull != RHSIsNull) {
12359 bool IsEquality = Opc == BO_EQ;
12360 if (RHSIsNull)
12361 DiagnoseAlwaysNonNullPointer(LHS.get(), RHSNullKind, IsEquality,
12362 RHS.get()->getSourceRange());
12363 else
12364 DiagnoseAlwaysNonNullPointer(RHS.get(), LHSNullKind, IsEquality,
12365 LHS.get()->getSourceRange());
12366 }
12367
12368 if (IsOrdered && LHSType->isFunctionPointerType() &&
12369 RHSType->isFunctionPointerType()) {
12370 // Valid unless a relational comparison of function pointers
12371 bool IsError = Opc == BO_Cmp;
12372 auto DiagID =
12373 IsError ? diag::err_typecheck_ordered_comparison_of_function_pointers
12374 : getLangOpts().CPlusPlus
12375 ? diag::warn_typecheck_ordered_comparison_of_function_pointers
12376 : diag::ext_typecheck_ordered_comparison_of_function_pointers;
12377 Diag(Loc, DiagID) << LHSType << RHSType << LHS.get()->getSourceRange()
12378 << RHS.get()->getSourceRange();
12379 if (IsError)
12380 return QualType();
12381 }
12382
12383 if ((LHSType->isIntegerType() && !LHSIsNull) ||
12384 (RHSType->isIntegerType() && !RHSIsNull)) {
12385 // Skip normal pointer conversion checks in this case; we have better
12386 // diagnostics for this below.
12387 } else if (getLangOpts().CPlusPlus) {
12388 // Equality comparison of a function pointer to a void pointer is invalid,
12389 // but we allow it as an extension.
12390 // FIXME: If we really want to allow this, should it be part of composite
12391 // pointer type computation so it works in conditionals too?
12392 if (!IsOrdered &&
12393 ((LHSType->isFunctionPointerType() && RHSType->isVoidPointerType()) ||
12394 (RHSType->isFunctionPointerType() && LHSType->isVoidPointerType()))) {
12395 // This is a gcc extension compatibility comparison.
12396 // In a SFINAE context, we treat this as a hard error to maintain
12397 // conformance with the C++ standard.
12398 diagnoseFunctionPointerToVoidComparison(
12399 *this, Loc, LHS, RHS, /*isError*/ (bool)isSFINAEContext());
12400
12401 if (isSFINAEContext())
12402 return QualType();
12403
12404 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast);
12405 return computeResultTy();
12406 }
12407
12408 // C++ [expr.eq]p2:
12409 // If at least one operand is a pointer [...] bring them to their
12410 // composite pointer type.
12411 // C++ [expr.spaceship]p6
12412 // If at least one of the operands is of pointer type, [...] bring them
12413 // to their composite pointer type.
12414 // C++ [expr.rel]p2:
12415 // If both operands are pointers, [...] bring them to their composite
12416 // pointer type.
12417 // For <=>, the only valid non-pointer types are arrays and functions, and
12418 // we already decayed those, so this is really the same as the relational
12419 // comparison rule.
12420 if ((int)LHSType->isPointerType() + (int)RHSType->isPointerType() >=
12421 (IsOrdered ? 2 : 1) &&
12422 (!LangOpts.ObjCAutoRefCount || !(LHSType->isObjCObjectPointerType() ||
12423 RHSType->isObjCObjectPointerType()))) {
12424 if (convertPointersToCompositeType(*this, Loc, LHS, RHS))
12425 return QualType();
12426 return computeResultTy();
12427 }
12428 } else if (LHSType->isPointerType() &&
12429 RHSType->isPointerType()) { // C99 6.5.8p2
12430 // All of the following pointer-related warnings are GCC extensions, except
12431 // when handling null pointer constants.
12432 QualType LCanPointeeTy =
12433 LHSType->castAs<PointerType>()->getPointeeType().getCanonicalType();
12434 QualType RCanPointeeTy =
12435 RHSType->castAs<PointerType>()->getPointeeType().getCanonicalType();
12436
12437 // C99 6.5.9p2 and C99 6.5.8p2
12438 if (Context.typesAreCompatible(LCanPointeeTy.getUnqualifiedType(),
12439 RCanPointeeTy.getUnqualifiedType())) {
12440 if (IsRelational) {
12441 // Pointers both need to point to complete or incomplete types
12442 if ((LCanPointeeTy->isIncompleteType() !=
12443 RCanPointeeTy->isIncompleteType()) &&
12444 !getLangOpts().C11) {
12445 Diag(Loc, diag::ext_typecheck_compare_complete_incomplete_pointers)
12446 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange()
12447 << LHSType << RHSType << LCanPointeeTy->isIncompleteType()
12448 << RCanPointeeTy->isIncompleteType();
12449 }
12450 }
12451 } else if (!IsRelational &&
12452 (LCanPointeeTy->isVoidType() || RCanPointeeTy->isVoidType())) {
12453 // Valid unless comparison between non-null pointer and function pointer
12454 if ((LCanPointeeTy->isFunctionType() || RCanPointeeTy->isFunctionType())
12455 && !LHSIsNull && !RHSIsNull)
12456 diagnoseFunctionPointerToVoidComparison(*this, Loc, LHS, RHS,
12457 /*isError*/false);
12458 } else {
12459 // Invalid
12460 diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS, /*isError*/false);
12461 }
12462 if (LCanPointeeTy != RCanPointeeTy) {
12463 // Treat NULL constant as a special case in OpenCL.
12464 if (getLangOpts().OpenCL && !LHSIsNull && !RHSIsNull) {
12465 if (!LCanPointeeTy.isAddressSpaceOverlapping(RCanPointeeTy)) {
12466 Diag(Loc,
12467 diag::err_typecheck_op_on_nonoverlapping_address_space_pointers)
12468 << LHSType << RHSType << 0 /* comparison */
12469 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
12470 }
12471 }
12472 LangAS AddrSpaceL = LCanPointeeTy.getAddressSpace();
12473 LangAS AddrSpaceR = RCanPointeeTy.getAddressSpace();
12474 CastKind Kind = AddrSpaceL != AddrSpaceR ? CK_AddressSpaceConversion
12475 : CK_BitCast;
12476 if (LHSIsNull && !RHSIsNull)
12477 LHS = ImpCastExprToType(LHS.get(), RHSType, Kind);
12478 else
12479 RHS = ImpCastExprToType(RHS.get(), LHSType, Kind);
12480 }
12481 return computeResultTy();
12482 }
12483
12484 if (getLangOpts().CPlusPlus) {
12485 // C++ [expr.eq]p4:
12486 // Two operands of type std::nullptr_t or one operand of type
12487 // std::nullptr_t and the other a null pointer constant compare equal.
12488 if (!IsOrdered && LHSIsNull && RHSIsNull) {
12489 if (LHSType->isNullPtrType()) {
12490 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer);
12491 return computeResultTy();
12492 }
12493 if (RHSType->isNullPtrType()) {
12494 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer);
12495 return computeResultTy();
12496 }
12497 }
12498
12499 // Comparison of Objective-C pointers and block pointers against nullptr_t.
12500 // These aren't covered by the composite pointer type rules.
12501 if (!IsOrdered && RHSType->isNullPtrType() &&
12502 (LHSType->isObjCObjectPointerType() || LHSType->isBlockPointerType())) {
12503 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer);
12504 return computeResultTy();
12505 }
12506 if (!IsOrdered && LHSType->isNullPtrType() &&
12507 (RHSType->isObjCObjectPointerType() || RHSType->isBlockPointerType())) {
12508 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer);
12509 return computeResultTy();
12510 }
12511
12512 if (IsRelational &&
12513 ((LHSType->isNullPtrType() && RHSType->isPointerType()) ||
12514 (RHSType->isNullPtrType() && LHSType->isPointerType()))) {
12515 // HACK: Relational comparison of nullptr_t against a pointer type is
12516 // invalid per DR583, but we allow it within std::less<> and friends,
12517 // since otherwise common uses of it break.
12518 // FIXME: Consider removing this hack once LWG fixes std::less<> and
12519 // friends to have std::nullptr_t overload candidates.
12520 DeclContext *DC = CurContext;
12521 if (isa<FunctionDecl>(DC))
12522 DC = DC->getParent();
12523 if (auto *CTSD = dyn_cast<ClassTemplateSpecializationDecl>(DC)) {
12524 if (CTSD->isInStdNamespace() &&
12525 llvm::StringSwitch<bool>(CTSD->getName())
12526 .Cases("less", "less_equal", "greater", "greater_equal", true)
12527 .Default(false)) {
12528 if (RHSType->isNullPtrType())
12529 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer);
12530 else
12531 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer);
12532 return computeResultTy();
12533 }
12534 }
12535 }
12536
12537 // C++ [expr.eq]p2:
12538 // If at least one operand is a pointer to member, [...] bring them to
12539 // their composite pointer type.
12540 if (!IsOrdered &&
12541 (LHSType->isMemberPointerType() || RHSType->isMemberPointerType())) {
12542 if (convertPointersToCompositeType(*this, Loc, LHS, RHS))
12543 return QualType();
12544 else
12545 return computeResultTy();
12546 }
12547 }
12548
12549 // Handle block pointer types.
12550 if (!IsOrdered && LHSType->isBlockPointerType() &&
12551 RHSType->isBlockPointerType()) {
12552 QualType lpointee = LHSType->castAs<BlockPointerType>()->getPointeeType();
12553 QualType rpointee = RHSType->castAs<BlockPointerType>()->getPointeeType();
12554
12555 if (!LHSIsNull && !RHSIsNull &&
12556 !Context.typesAreCompatible(lpointee, rpointee)) {
12557 Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks)
12558 << LHSType << RHSType << LHS.get()->getSourceRange()
12559 << RHS.get()->getSourceRange();
12560 }
12561 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast);
12562 return computeResultTy();
12563 }
12564
12565 // Allow block pointers to be compared with null pointer constants.
12566 if (!IsOrdered
12567 && ((LHSType->isBlockPointerType() && RHSType->isPointerType())
12568 || (LHSType->isPointerType() && RHSType->isBlockPointerType()))) {
12569 if (!LHSIsNull && !RHSIsNull) {
12570 if (!((RHSType->isPointerType() && RHSType->castAs<PointerType>()
12571 ->getPointeeType()->isVoidType())
12572 || (LHSType->isPointerType() && LHSType->castAs<PointerType>()
12573 ->getPointeeType()->isVoidType())))
12574 Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks)
12575 << LHSType << RHSType << LHS.get()->getSourceRange()
12576 << RHS.get()->getSourceRange();
12577 }
12578 if (LHSIsNull && !RHSIsNull)
12579 LHS = ImpCastExprToType(LHS.get(), RHSType,
12580 RHSType->isPointerType() ? CK_BitCast
12581 : CK_AnyPointerToBlockPointerCast);
12582 else
12583 RHS = ImpCastExprToType(RHS.get(), LHSType,
12584 LHSType->isPointerType() ? CK_BitCast
12585 : CK_AnyPointerToBlockPointerCast);
12586 return computeResultTy();
12587 }
12588
12589 if (LHSType->isObjCObjectPointerType() ||
12590 RHSType->isObjCObjectPointerType()) {
12591 const PointerType *LPT = LHSType->getAs<PointerType>();
12592 const PointerType *RPT = RHSType->getAs<PointerType>();
12593 if (LPT || RPT) {
12594 bool LPtrToVoid = LPT ? LPT->getPointeeType()->isVoidType() : false;
12595 bool RPtrToVoid = RPT ? RPT->getPointeeType()->isVoidType() : false;
12596
12597 if (!LPtrToVoid && !RPtrToVoid &&
12598 !Context.typesAreCompatible(LHSType, RHSType)) {
12599 diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS,
12600 /*isError*/false);
12601 }
12602 // FIXME: If LPtrToVoid, we should presumably convert the LHS rather than
12603 // the RHS, but we have test coverage for this behavior.
12604 // FIXME: Consider using convertPointersToCompositeType in C++.
12605 if (LHSIsNull && !RHSIsNull) {
12606 Expr *E = LHS.get();
12607 if (getLangOpts().ObjCAutoRefCount)
12608 CheckObjCConversion(SourceRange(), RHSType, E,
12609 CCK_ImplicitConversion);
12610 LHS = ImpCastExprToType(E, RHSType,
12611 RPT ? CK_BitCast :CK_CPointerToObjCPointerCast);
12612 }
12613 else {
12614 Expr *E = RHS.get();
12615 if (getLangOpts().ObjCAutoRefCount)
12616 CheckObjCConversion(SourceRange(), LHSType, E, CCK_ImplicitConversion,
12617 /*Diagnose=*/true,
12618 /*DiagnoseCFAudited=*/false, Opc);
12619 RHS = ImpCastExprToType(E, LHSType,
12620 LPT ? CK_BitCast :CK_CPointerToObjCPointerCast);
12621 }
12622 return computeResultTy();
12623 }
12624 if (LHSType->isObjCObjectPointerType() &&
12625 RHSType->isObjCObjectPointerType()) {
12626 if (!Context.areComparableObjCPointerTypes(LHSType, RHSType))
12627 diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS,
12628 /*isError*/false);
12629 if (isObjCObjectLiteral(LHS) || isObjCObjectLiteral(RHS))
12630 diagnoseObjCLiteralComparison(*this, Loc, LHS, RHS, Opc);
12631
12632 if (LHSIsNull && !RHSIsNull)
12633 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_BitCast);
12634 else
12635 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast);
12636 return computeResultTy();
12637 }
12638
12639 if (!IsOrdered && LHSType->isBlockPointerType() &&
12640 RHSType->isBlockCompatibleObjCPointerType(Context)) {
12641 LHS = ImpCastExprToType(LHS.get(), RHSType,
12642 CK_BlockPointerToObjCPointerCast);
12643 return computeResultTy();
12644 } else if (!IsOrdered &&
12645 LHSType->isBlockCompatibleObjCPointerType(Context) &&
12646 RHSType->isBlockPointerType()) {
12647 RHS = ImpCastExprToType(RHS.get(), LHSType,
12648 CK_BlockPointerToObjCPointerCast);
12649 return computeResultTy();
12650 }
12651 }
12652 if ((LHSType->isAnyPointerType() && RHSType->isIntegerType()) ||
12653 (LHSType->isIntegerType() && RHSType->isAnyPointerType())) {
12654 unsigned DiagID = 0;
12655 bool isError = false;
12656 if (LangOpts.DebuggerSupport) {
12657 // Under a debugger, allow the comparison of pointers to integers,
12658 // since users tend to want to compare addresses.
12659 } else if ((LHSIsNull && LHSType->isIntegerType()) ||
12660 (RHSIsNull && RHSType->isIntegerType())) {
12661 if (IsOrdered) {
12662 isError = getLangOpts().CPlusPlus;
12663 DiagID =
12664 isError ? diag::err_typecheck_ordered_comparison_of_pointer_and_zero
12665 : diag::ext_typecheck_ordered_comparison_of_pointer_and_zero;
12666 }
12667 } else if (getLangOpts().CPlusPlus) {
12668 DiagID = diag::err_typecheck_comparison_of_pointer_integer;
12669 isError = true;
12670 } else if (IsOrdered)
12671 DiagID = diag::ext_typecheck_ordered_comparison_of_pointer_integer;
12672 else
12673 DiagID = diag::ext_typecheck_comparison_of_pointer_integer;
12674
12675 if (DiagID) {
12676 Diag(Loc, DiagID)
12677 << LHSType << RHSType << LHS.get()->getSourceRange()
12678 << RHS.get()->getSourceRange();
12679 if (isError)
12680 return QualType();
12681 }
12682
12683 if (LHSType->isIntegerType())
12684 LHS = ImpCastExprToType(LHS.get(), RHSType,
12685 LHSIsNull ? CK_NullToPointer : CK_IntegralToPointer);
12686 else
12687 RHS = ImpCastExprToType(RHS.get(), LHSType,
12688 RHSIsNull ? CK_NullToPointer : CK_IntegralToPointer);
12689 return computeResultTy();
12690 }
12691
12692 // Handle block pointers.
12693 if (!IsOrdered && RHSIsNull
12694 && LHSType->isBlockPointerType() && RHSType->isIntegerType()) {
12695 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer);
12696 return computeResultTy();
12697 }
12698 if (!IsOrdered && LHSIsNull
12699 && LHSType->isIntegerType() && RHSType->isBlockPointerType()) {
12700 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer);
12701 return computeResultTy();
12702 }
12703
12704 if (getLangOpts().getOpenCLCompatibleVersion() >= 200) {
12705 if (LHSType->isClkEventT() && RHSType->isClkEventT()) {
12706 return computeResultTy();
12707 }
12708
12709 if (LHSType->isQueueT() && RHSType->isQueueT()) {
12710 return computeResultTy();
12711 }
12712
12713 if (LHSIsNull && RHSType->isQueueT()) {
12714 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer);
12715 return computeResultTy();
12716 }
12717
12718 if (LHSType->isQueueT() && RHSIsNull) {
12719 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer);
12720 return computeResultTy();
12721 }
12722 }
12723
12724 return InvalidOperands(Loc, LHS, RHS);
12725}
12726
12727// Return a signed ext_vector_type that is of identical size and number of
12728// elements. For floating point vectors, return an integer type of identical
12729// size and number of elements. In the non ext_vector_type case, search from
12730// the largest type to the smallest type to avoid cases where long long == long,
12731// where long gets picked over long long.
12732QualType Sema::GetSignedVectorType(QualType V) {
12733 const VectorType *VTy = V->castAs<VectorType>();
12734 unsigned TypeSize = Context.getTypeSize(VTy->getElementType());
12735
12736 if (isa<ExtVectorType>(VTy)) {
12737 if (VTy->isExtVectorBoolType())
12738 return Context.getExtVectorType(Context.BoolTy, VTy->getNumElements());
12739 if (TypeSize == Context.getTypeSize(Context.CharTy))
12740 return Context.getExtVectorType(Context.CharTy, VTy->getNumElements());
12741 if (TypeSize == Context.getTypeSize(Context.ShortTy))
12742 return Context.getExtVectorType(Context.ShortTy, VTy->getNumElements());
12743 if (TypeSize == Context.getTypeSize(Context.IntTy))
12744 return Context.getExtVectorType(Context.IntTy, VTy->getNumElements());
12745 if (TypeSize == Context.getTypeSize(Context.Int128Ty))
12746 return Context.getExtVectorType(Context.Int128Ty, VTy->getNumElements());
12747 if (TypeSize == Context.getTypeSize(Context.LongTy))
12748 return Context.getExtVectorType(Context.LongTy, VTy->getNumElements());
12749 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", 12750, __extension__ __PRETTY_FUNCTION__
))
12750 "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", 12750, __extension__ __PRETTY_FUNCTION__
))
;
12751 return Context.getExtVectorType(Context.LongLongTy, VTy->getNumElements());
12752 }
12753
12754 if (TypeSize == Context.getTypeSize(Context.Int128Ty))
12755 return Context.getVectorType(Context.Int128Ty, VTy->getNumElements(),
12756 VectorType::GenericVector);
12757 if (TypeSize == Context.getTypeSize(Context.LongLongTy))
12758 return Context.getVectorType(Context.LongLongTy, VTy->getNumElements(),
12759 VectorType::GenericVector);
12760 if (TypeSize == Context.getTypeSize(Context.LongTy))
12761 return Context.getVectorType(Context.LongTy, VTy->getNumElements(),
12762 VectorType::GenericVector);
12763 if (TypeSize == Context.getTypeSize(Context.IntTy))
12764 return Context.getVectorType(Context.IntTy, VTy->getNumElements(),
12765 VectorType::GenericVector);
12766 if (TypeSize == Context.getTypeSize(Context.ShortTy))
12767 return Context.getVectorType(Context.ShortTy, VTy->getNumElements(),
12768 VectorType::GenericVector);
12769 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", 12770, __extension__ __PRETTY_FUNCTION__
))
12770 "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", 12770, __extension__ __PRETTY_FUNCTION__
))
;
12771 return Context.getVectorType(Context.CharTy, VTy->getNumElements(),
12772 VectorType::GenericVector);
12773}
12774
12775QualType Sema::GetSignedSizelessVectorType(QualType V) {
12776 const BuiltinType *VTy = V->castAs<BuiltinType>();
12777 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", 12777, __extension__ __PRETTY_FUNCTION__
))
;
12778
12779 const QualType ETy = V->getSveEltType(Context);
12780 const auto TypeSize = Context.getTypeSize(ETy);
12781
12782 const QualType IntTy = Context.getIntTypeForBitwidth(TypeSize, true);
12783 const llvm::ElementCount VecSize = Context.getBuiltinVectorTypeInfo(VTy).EC;
12784 return Context.getScalableVectorType(IntTy, VecSize.getKnownMinValue());
12785}
12786
12787/// CheckVectorCompareOperands - vector comparisons are a clang extension that
12788/// operates on extended vector types. Instead of producing an IntTy result,
12789/// like a scalar comparison, a vector comparison produces a vector of integer
12790/// types.
12791QualType Sema::CheckVectorCompareOperands(ExprResult &LHS, ExprResult &RHS,
12792 SourceLocation Loc,
12793 BinaryOperatorKind Opc) {
12794 if (Opc == BO_Cmp) {
12795 Diag(Loc, diag::err_three_way_vector_comparison);
12796 return QualType();
12797 }
12798
12799 // Check to make sure we're operating on vectors of the same type and width,
12800 // Allowing one side to be a scalar of element type.
12801 QualType vType =
12802 CheckVectorOperands(LHS, RHS, Loc, /*isCompAssign*/ false,
12803 /*AllowBothBool*/ true,
12804 /*AllowBoolConversions*/ getLangOpts().ZVector,
12805 /*AllowBooleanOperation*/ true,
12806 /*ReportInvalid*/ true);
12807 if (vType.isNull())
12808 return vType;
12809
12810 QualType LHSType = LHS.get()->getType();
12811
12812 // Determine the return type of a vector compare. By default clang will return
12813 // a scalar for all vector compares except vector bool and vector pixel.
12814 // With the gcc compiler we will always return a vector type and with the xl
12815 // compiler we will always return a scalar type. This switch allows choosing
12816 // which behavior is prefered.
12817 if (getLangOpts().AltiVec) {
12818 switch (getLangOpts().getAltivecSrcCompat()) {
12819 case LangOptions::AltivecSrcCompatKind::Mixed:
12820 // If AltiVec, the comparison results in a numeric type, i.e.
12821 // bool for C++, int for C
12822 if (vType->castAs<VectorType>()->getVectorKind() ==
12823 VectorType::AltiVecVector)
12824 return Context.getLogicalOperationType();
12825 else
12826 Diag(Loc, diag::warn_deprecated_altivec_src_compat);
12827 break;
12828 case LangOptions::AltivecSrcCompatKind::GCC:
12829 // For GCC we always return the vector type.
12830 break;
12831 case LangOptions::AltivecSrcCompatKind::XL:
12832 return Context.getLogicalOperationType();
12833 break;
12834 }
12835 }
12836
12837 // For non-floating point types, check for self-comparisons of the form
12838 // x == x, x != x, x < x, etc. These always evaluate to a constant, and
12839 // often indicate logic errors in the program.
12840 diagnoseTautologicalComparison(*this, Loc, LHS.get(), RHS.get(), Opc);
12841
12842 // Check for comparisons of floating point operands using != and ==.
12843 if (BinaryOperator::isEqualityOp(Opc) &&
12844 LHSType->hasFloatingRepresentation()) {
12845 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", 12845, __extension__ __PRETTY_FUNCTION__
))
;
12846 CheckFloatComparison(Loc, LHS.get(), RHS.get(), Opc);
12847 }
12848
12849 // Return a signed type for the vector.
12850 return GetSignedVectorType(vType);
12851}
12852
12853QualType Sema::CheckSizelessVectorCompareOperands(ExprResult &LHS,
12854 ExprResult &RHS,
12855 SourceLocation Loc,
12856 BinaryOperatorKind Opc) {
12857 if (Opc == BO_Cmp) {
12858 Diag(Loc, diag::err_three_way_vector_comparison);
12859 return QualType();
12860 }
12861
12862 // Check to make sure we're operating on vectors of the same type and width,
12863 // Allowing one side to be a scalar of element type.
12864 QualType vType = CheckSizelessVectorOperands(
12865 LHS, RHS, Loc, /*isCompAssign*/ false, ACK_Comparison);
12866
12867 if (vType.isNull())
12868 return vType;
12869
12870 QualType LHSType = LHS.get()->getType();
12871
12872 // For non-floating point types, check for self-comparisons of the form
12873 // x == x, x != x, x < x, etc. These always evaluate to a constant, and
12874 // often indicate logic errors in the program.
12875 diagnoseTautologicalComparison(*this, Loc, LHS.get(), RHS.get(), Opc);
12876
12877 // Check for comparisons of floating point operands using != and ==.
12878 if (BinaryOperator::isEqualityOp(Opc) &&
12879 LHSType->hasFloatingRepresentation()) {
12880 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", 12880, __extension__ __PRETTY_FUNCTION__
))
;
12881 CheckFloatComparison(Loc, LHS.get(), RHS.get(), Opc);
12882 }
12883
12884 const BuiltinType *LHSBuiltinTy = LHSType->getAs<BuiltinType>();
12885 const BuiltinType *RHSBuiltinTy = RHS.get()->getType()->getAs<BuiltinType>();
12886
12887 if (LHSBuiltinTy && RHSBuiltinTy && LHSBuiltinTy->isSVEBool() &&
12888 RHSBuiltinTy->isSVEBool())
12889 return LHSType;
12890
12891 // Return a signed type for the vector.
12892 return GetSignedSizelessVectorType(vType);
12893}
12894
12895static void diagnoseXorMisusedAsPow(Sema &S, const ExprResult &XorLHS,
12896 const ExprResult &XorRHS,
12897 const SourceLocation Loc) {
12898 // Do not diagnose macros.
12899 if (Loc.isMacroID())
12900 return;
12901
12902 // Do not diagnose if both LHS and RHS are macros.
12903 if (XorLHS.get()->getExprLoc().isMacroID() &&
12904 XorRHS.get()->getExprLoc().isMacroID())
12905 return;
12906
12907 bool Negative = false;
12908 bool ExplicitPlus = false;
12909 const auto *LHSInt = dyn_cast<IntegerLiteral>(XorLHS.get());
12910 const auto *RHSInt = dyn_cast<IntegerLiteral>(XorRHS.get());
12911
12912 if (!LHSInt)
12913 return;
12914 if (!RHSInt) {
12915 // Check negative literals.
12916 if (const auto *UO = dyn_cast<UnaryOperator>(XorRHS.get())) {
12917 UnaryOperatorKind Opc = UO->getOpcode();
12918 if (Opc != UO_Minus && Opc != UO_Plus)
12919 return;
12920 RHSInt = dyn_cast<IntegerLiteral>(UO->getSubExpr());
12921 if (!RHSInt)
12922 return;
12923 Negative = (Opc == UO_Minus);
12924 ExplicitPlus = !Negative;
12925 } else {
12926 return;
12927 }
12928 }
12929
12930 const llvm::APInt &LeftSideValue = LHSInt->getValue();
12931 llvm::APInt RightSideValue = RHSInt->getValue();
12932 if (LeftSideValue != 2 && LeftSideValue != 10)
12933 return;
12934
12935 if (LeftSideValue.getBitWidth() != RightSideValue.getBitWidth())
12936 return;
12937
12938 CharSourceRange ExprRange = CharSourceRange::getCharRange(
12939 LHSInt->getBeginLoc(), S.getLocForEndOfToken(RHSInt->getLocation()));
12940 llvm::StringRef ExprStr =
12941 Lexer::getSourceText(ExprRange, S.getSourceManager(), S.getLangOpts());
12942
12943 CharSourceRange XorRange =
12944 CharSourceRange::getCharRange(Loc, S.getLocForEndOfToken(Loc));
12945 llvm::StringRef XorStr =
12946 Lexer::getSourceText(XorRange, S.getSourceManager(), S.getLangOpts());
12947 // Do not diagnose if xor keyword/macro is used.
12948 if (XorStr == "xor")
12949 return;
12950
12951 std::string LHSStr = std::string(Lexer::getSourceText(
12952 CharSourceRange::getTokenRange(LHSInt->getSourceRange()),
12953 S.getSourceManager(), S.getLangOpts()));
12954 std::string RHSStr = std::string(Lexer::getSourceText(
12955 CharSourceRange::getTokenRange(RHSInt->getSourceRange()),
12956 S.getSourceManager(), S.getLangOpts()));
12957
12958 if (Negative) {
12959 RightSideValue = -RightSideValue;
12960 RHSStr = "-" + RHSStr;
12961 } else if (ExplicitPlus) {
12962 RHSStr = "+" + RHSStr;
12963 }
12964
12965 StringRef LHSStrRef = LHSStr;
12966 StringRef RHSStrRef = RHSStr;
12967 // Do not diagnose literals with digit separators, binary, hexadecimal, octal
12968 // literals.
12969 if (LHSStrRef.startswith("0b") || LHSStrRef.startswith("0B") ||
12970 RHSStrRef.startswith("0b") || RHSStrRef.startswith("0B") ||
12971 LHSStrRef.startswith("0x") || LHSStrRef.startswith("0X") ||
12972 RHSStrRef.startswith("0x") || RHSStrRef.startswith("0X") ||
12973 (LHSStrRef.size() > 1 && LHSStrRef.startswith("0")) ||
12974 (RHSStrRef.size() > 1 && RHSStrRef.startswith("0")) ||
12975 LHSStrRef.contains('\'') || RHSStrRef.contains('\''))
12976 return;
12977
12978 bool SuggestXor =
12979 S.getLangOpts().CPlusPlus || S.getPreprocessor().isMacroDefined("xor");
12980 const llvm::APInt XorValue = LeftSideValue ^ RightSideValue;
12981 int64_t RightSideIntValue = RightSideValue.getSExtValue();
12982 if (LeftSideValue == 2 && RightSideIntValue >= 0) {
12983 std::string SuggestedExpr = "1 << " + RHSStr;
12984 bool Overflow = false;
12985 llvm::APInt One = (LeftSideValue - 1);
12986 llvm::APInt PowValue = One.sshl_ov(RightSideValue, Overflow);
12987 if (Overflow) {
12988 if (RightSideIntValue < 64)
12989 S.Diag(Loc, diag::warn_xor_used_as_pow_base)
12990 << ExprStr << toString(XorValue, 10, true) << ("1LL << " + RHSStr)
12991 << FixItHint::CreateReplacement(ExprRange, "1LL << " + RHSStr);
12992 else if (RightSideIntValue == 64)
12993 S.Diag(Loc, diag::warn_xor_used_as_pow)
12994 << ExprStr << toString(XorValue, 10, true);
12995 else
12996 return;
12997 } else {
12998 S.Diag(Loc, diag::warn_xor_used_as_pow_base_extra)
12999 << ExprStr << toString(XorValue, 10, true) << SuggestedExpr
13000 << toString(PowValue, 10, true)
13001 << FixItHint::CreateReplacement(
13002 ExprRange, (RightSideIntValue == 0) ? "1" : SuggestedExpr);
13003 }
13004
13005 S.Diag(Loc, diag::note_xor_used_as_pow_silence)
13006 << ("0x2 ^ " + RHSStr) << SuggestXor;
13007 } else if (LeftSideValue == 10) {
13008 std::string SuggestedValue = "1e" + std::to_string(RightSideIntValue);
13009 S.Diag(Loc, diag::warn_xor_used_as_pow_base)
13010 << ExprStr << toString(XorValue, 10, true) << SuggestedValue
13011 << FixItHint::CreateReplacement(ExprRange, SuggestedValue);
13012 S.Diag(Loc, diag::note_xor_used_as_pow_silence)
13013 << ("0xA ^ " + RHSStr) << SuggestXor;
13014 }
13015}
13016
13017QualType Sema::CheckVectorLogicalOperands(ExprResult &LHS, ExprResult &RHS,
13018 SourceLocation Loc) {
13019 // Ensure that either both operands are of the same vector type, or
13020 // one operand is of a vector type and the other is of its element type.
13021 QualType vType = CheckVectorOperands(LHS, RHS, Loc, false,
13022 /*AllowBothBool*/ true,
13023 /*AllowBoolConversions*/ false,
13024 /*AllowBooleanOperation*/ false,
13025 /*ReportInvalid*/ false);
13026 if (vType.isNull())
13027 return InvalidOperands(Loc, LHS, RHS);
13028 if (getLangOpts().OpenCL &&
13029 getLangOpts().getOpenCLCompatibleVersion() < 120 &&
13030 vType->hasFloatingRepresentation())
13031 return InvalidOperands(Loc, LHS, RHS);
13032 // FIXME: The check for C++ here is for GCC compatibility. GCC rejects the
13033 // usage of the logical operators && and || with vectors in C. This
13034 // check could be notionally dropped.
13035 if (!getLangOpts().CPlusPlus &&
13036 !(isa<ExtVectorType>(vType->getAs<VectorType>())))
13037 return InvalidLogicalVectorOperands(Loc, LHS, RHS);
13038
13039 return GetSignedVectorType(LHS.get()->getType());
13040}
13041
13042QualType Sema::CheckMatrixElementwiseOperands(ExprResult &LHS, ExprResult &RHS,
13043 SourceLocation Loc,
13044 bool IsCompAssign) {
13045 if (!IsCompAssign) {
13046 LHS = DefaultFunctionArrayLvalueConversion(LHS.get());
13047 if (LHS.isInvalid())
13048 return QualType();
13049 }
13050 RHS = DefaultFunctionArrayLvalueConversion(RHS.get());
13051 if (RHS.isInvalid())
13052 return QualType();
13053
13054 // For conversion purposes, we ignore any qualifiers.
13055 // For example, "const float" and "float" are equivalent.
13056 QualType LHSType = LHS.get()->getType().getUnqualifiedType();
13057 QualType RHSType = RHS.get()->getType().getUnqualifiedType();
13058
13059 const MatrixType *LHSMatType = LHSType->getAs<MatrixType>();
13060 const MatrixType *RHSMatType = RHSType->getAs<MatrixType>();
13061 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", 13061, __extension__ __PRETTY_FUNCTION__
))
;
13062
13063 if (Context.hasSameType(LHSType, RHSType))
13064 return LHSType;
13065
13066 // Type conversion may change LHS/RHS. Keep copies to the original results, in
13067 // case we have to return InvalidOperands.
13068 ExprResult OriginalLHS = LHS;
13069 ExprResult OriginalRHS = RHS;
13070 if (LHSMatType && !RHSMatType) {
13071 RHS = tryConvertExprToType(RHS.get(), LHSMatType->getElementType());
13072 if (!RHS.isInvalid())
13073 return LHSType;
13074
13075 return InvalidOperands(Loc, OriginalLHS, OriginalRHS);
13076 }
13077
13078 if (!LHSMatType && RHSMatType) {
13079 LHS = tryConvertExprToType(LHS.get(), RHSMatType->getElementType());
13080 if (!LHS.isInvalid())
13081 return RHSType;
13082 return InvalidOperands(Loc, OriginalLHS, OriginalRHS);
13083 }
13084
13085 return InvalidOperands(Loc, LHS, RHS);
13086}
13087
13088QualType Sema::CheckMatrixMultiplyOperands(ExprResult &LHS, ExprResult &RHS,
13089 SourceLocation Loc,
13090 bool IsCompAssign) {
13091 if (!IsCompAssign) {
13092 LHS = DefaultFunctionArrayLvalueConversion(LHS.get());
13093 if (LHS.isInvalid())
13094 return QualType();
13095 }
13096 RHS = DefaultFunctionArrayLvalueConversion(RHS.get());
13097 if (RHS.isInvalid())
13098 return QualType();
13099
13100 auto *LHSMatType = LHS.get()->getType()->getAs<ConstantMatrixType>();
13101 auto *RHSMatType = RHS.get()->getType()->getAs<ConstantMatrixType>();
13102 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", 13102, __extension__ __PRETTY_FUNCTION__
))
;
13103
13104 if (LHSMatType && RHSMatType) {
13105 if (LHSMatType->getNumColumns() != RHSMatType->getNumRows())
13106 return InvalidOperands(Loc, LHS, RHS);
13107
13108 if (!Context.hasSameType(LHSMatType->getElementType(),
13109 RHSMatType->getElementType()))
13110 return InvalidOperands(Loc, LHS, RHS);
13111
13112 return Context.getConstantMatrixType(LHSMatType->getElementType(),
13113 LHSMatType->getNumRows(),
13114 RHSMatType->getNumColumns());
13115 }
13116 return CheckMatrixElementwiseOperands(LHS, RHS, Loc, IsCompAssign);
13117}
13118
13119static bool isLegalBoolVectorBinaryOp(BinaryOperatorKind Opc) {
13120 switch (Opc) {
13121 default:
13122 return false;
13123 case BO_And:
13124 case BO_AndAssign:
13125 case BO_Or:
13126 case BO_OrAssign:
13127 case BO_Xor:
13128 case BO_XorAssign:
13129 return true;
13130 }
13131}
13132
13133inline QualType Sema::CheckBitwiseOperands(ExprResult &LHS, ExprResult &RHS,
13134 SourceLocation Loc,
13135 BinaryOperatorKind Opc) {
13136 checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/false);
13137
13138 bool IsCompAssign =
13139 Opc == BO_AndAssign || Opc == BO_OrAssign || Opc == BO_XorAssign;
13140
13141 bool LegalBoolVecOperator = isLegalBoolVectorBinaryOp(Opc);
13142
13143 if (LHS.get()->getType()->isVectorType() ||
13144 RHS.get()->getType()->isVectorType()) {
13145 if (LHS.get()->getType()->hasIntegerRepresentation() &&
13146 RHS.get()->getType()->hasIntegerRepresentation())
13147 return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign,
13148 /*AllowBothBool*/ true,
13149 /*AllowBoolConversions*/ getLangOpts().ZVector,
13150 /*AllowBooleanOperation*/ LegalBoolVecOperator,
13151 /*ReportInvalid*/ true);
13152 return InvalidOperands(Loc, LHS, RHS);
13153 }
13154
13155 if (LHS.get()->getType()->isVLSTBuiltinType() ||
13156 RHS.get()->getType()->isVLSTBuiltinType()) {
13157 if (LHS.get()->getType()->hasIntegerRepresentation() &&
13158 RHS.get()->getType()->hasIntegerRepresentation())
13159 return CheckSizelessVectorOperands(LHS, RHS, Loc, IsCompAssign,
13160 ACK_BitwiseOp);
13161 return InvalidOperands(Loc, LHS, RHS);
13162 }
13163
13164 if (LHS.get()->getType()->isVLSTBuiltinType() ||
13165 RHS.get()->getType()->isVLSTBuiltinType()) {
13166 if (LHS.get()->getType()->hasIntegerRepresentation() &&
13167 RHS.get()->getType()->hasIntegerRepresentation())
13168 return CheckSizelessVectorOperands(LHS, RHS, Loc, IsCompAssign,
13169 ACK_BitwiseOp);
13170 return InvalidOperands(Loc, LHS, RHS);
13171 }
13172
13173 if (Opc == BO_And)
13174 diagnoseLogicalNotOnLHSofCheck(*this, LHS, RHS, Loc, Opc);
13175
13176 if (LHS.get()->getType()->hasFloatingRepresentation() ||
13177 RHS.get()->getType()->hasFloatingRepresentation())
13178 return InvalidOperands(Loc, LHS, RHS);
13179
13180 ExprResult LHSResult = LHS, RHSResult = RHS;
13181 QualType compType = UsualArithmeticConversions(
13182 LHSResult, RHSResult, Loc, IsCompAssign ? ACK_CompAssign : ACK_BitwiseOp);
13183 if (LHSResult.isInvalid() || RHSResult.isInvalid())
13184 return QualType();
13185 LHS = LHSResult.get();
13186 RHS = RHSResult.get();
13187
13188 if (Opc == BO_Xor)
13189 diagnoseXorMisusedAsPow(*this, LHS, RHS, Loc);
13190
13191 if (!compType.isNull() && compType->isIntegralOrUnscopedEnumerationType())
13192 return compType;
13193 return InvalidOperands(Loc, LHS, RHS);
13194}
13195
13196// C99 6.5.[13,14]
13197inline QualType Sema::CheckLogicalOperands(ExprResult &LHS, ExprResult &RHS,
13198 SourceLocation Loc,
13199 BinaryOperatorKind Opc) {
13200 // Check vector operands differently.
13201 if (LHS.get()->getType()->isVectorType() ||
13202 RHS.get()->getType()->isVectorType())
13203 return CheckVectorLogicalOperands(LHS, RHS, Loc);
13204
13205 bool EnumConstantInBoolContext = false;
13206 for (const ExprResult &HS : {LHS, RHS}) {
13207 if (const auto *DREHS = dyn_cast<DeclRefExpr>(HS.get())) {
13208 const auto *ECDHS = dyn_cast<EnumConstantDecl>(DREHS->getDecl());
13209 if (ECDHS && ECDHS->getInitVal() != 0 && ECDHS->getInitVal() != 1)
13210 EnumConstantInBoolContext = true;
13211 }
13212 }
13213
13214 if (EnumConstantInBoolContext)
13215 Diag(Loc, diag::warn_enum_constant_in_bool_context);
13216
13217 // Diagnose cases where the user write a logical and/or but probably meant a
13218 // bitwise one. We do this when the LHS is a non-bool integer and the RHS
13219 // is a constant.
13220 if (!EnumConstantInBoolContext && LHS.get()->getType()->isIntegerType() &&
13221 !LHS.get()->getType()->isBooleanType() &&
13222 RHS.get()->getType()->isIntegerType() && !RHS.get()->isValueDependent() &&
13223 // Don't warn in macros or template instantiations.
13224 !Loc.isMacroID() && !inTemplateInstantiation()) {
13225 // If the RHS can be constant folded, and if it constant folds to something
13226 // that isn't 0 or 1 (which indicate a potential logical operation that
13227 // happened to fold to true/false) then warn.
13228 // Parens on the RHS are ignored.
13229 Expr::EvalResult EVResult;
13230 if (RHS.get()->EvaluateAsInt(EVResult, Context)) {
13231 llvm::APSInt Result = EVResult.Val.getInt();
13232 if ((getLangOpts().Bool && !RHS.get()->getType()->isBooleanType() &&
13233 !RHS.get()->getExprLoc().isMacroID()) ||
13234 (Result != 0 && Result != 1)) {
13235 Diag(Loc, diag::warn_logical_instead_of_bitwise)
13236 << RHS.get()->getSourceRange() << (Opc == BO_LAnd ? "&&" : "||");
13237 // Suggest replacing the logical operator with the bitwise version
13238 Diag(Loc, diag::note_logical_instead_of_bitwise_change_operator)
13239 << (Opc == BO_LAnd ? "&" : "|")
13240 << FixItHint::CreateReplacement(
13241 SourceRange(Loc, getLocForEndOfToken(Loc)),
13242 Opc == BO_LAnd ? "&" : "|");
13243 if (Opc == BO_LAnd)
13244 // Suggest replacing "Foo() && kNonZero" with "Foo()"
13245 Diag(Loc, diag::note_logical_instead_of_bitwise_remove_constant)
13246 << FixItHint::CreateRemoval(
13247 SourceRange(getLocForEndOfToken(LHS.get()->getEndLoc()),
13248 RHS.get()->getEndLoc()));
13249 }
13250 }
13251 }
13252
13253 if (!Context.getLangOpts().CPlusPlus) {
13254 // OpenCL v1.1 s6.3.g: The logical operators and (&&), or (||) do
13255 // not operate on the built-in scalar and vector float types.
13256 if (Context.getLangOpts().OpenCL &&
13257 Context.getLangOpts().OpenCLVersion < 120) {
13258 if (LHS.get()->getType()->isFloatingType() ||
13259 RHS.get()->getType()->isFloatingType())
13260 return InvalidOperands(Loc, LHS, RHS);
13261 }
13262
13263 LHS = UsualUnaryConversions(LHS.get());
13264 if (LHS.isInvalid())
13265 return QualType();
13266
13267 RHS = UsualUnaryConversions(RHS.get());
13268 if (RHS.isInvalid())
13269 return QualType();
13270
13271 if (!LHS.get()->getType()->isScalarType() ||
13272 !RHS.get()->getType()->isScalarType())
13273 return InvalidOperands(Loc, LHS, RHS);
13274
13275 return Context.IntTy;
13276 }
13277
13278 // The following is safe because we only use this method for
13279 // non-overloadable operands.
13280
13281 // C++ [expr.log.and]p1
13282 // C++ [expr.log.or]p1
13283 // The operands are both contextually converted to type bool.
13284 ExprResult LHSRes = PerformContextuallyConvertToBool(LHS.get());
13285 if (LHSRes.isInvalid())
13286 return InvalidOperands(Loc, LHS, RHS);
13287 LHS = LHSRes;
13288
13289 ExprResult RHSRes = PerformContextuallyConvertToBool(RHS.get());
13290 if (RHSRes.isInvalid())
13291 return InvalidOperands(Loc, LHS, RHS);
13292 RHS = RHSRes;
13293
13294 // C++ [expr.log.and]p2
13295 // C++ [expr.log.or]p2
13296 // The result is a bool.
13297 return Context.BoolTy;
13298}
13299
13300static bool IsReadonlyMessage(Expr *E, Sema &S) {
13301 const MemberExpr *ME = dyn_cast<MemberExpr>(E);
13302 if (!ME) return false;
13303 if (!isa<FieldDecl>(ME->getMemberDecl())) return false;
13304 ObjCMessageExpr *Base = dyn_cast<ObjCMessageExpr>(
13305 ME->getBase()->IgnoreImplicit()->IgnoreParenImpCasts());
13306 if (!Base) return false;
13307 return Base->getMethodDecl() != nullptr;
13308}
13309
13310/// Is the given expression (which must be 'const') a reference to a
13311/// variable which was originally non-const, but which has become
13312/// 'const' due to being captured within a block?
13313enum NonConstCaptureKind { NCCK_None, NCCK_Block, NCCK_Lambda };
13314static NonConstCaptureKind isReferenceToNonConstCapture(Sema &S, Expr *E) {
13315 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", 13315, __extension__ __PRETTY_FUNCTION__
))
;
13316 E = E->IgnoreParens();
13317
13318 // Must be a reference to a declaration from an enclosing scope.
13319 DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E);
13320 if (!DRE) return NCCK_None;
13321 if (!DRE->refersToEnclosingVariableOrCapture()) return NCCK_None;
13322
13323 // The declaration must be a variable which is not declared 'const'.
13324 VarDecl *var = dyn_cast<VarDecl>(DRE->getDecl());
13325 if (!var) return NCCK_None;
13326 if (var->getType().isConstQualified()) return NCCK_None;
13327 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", 13327, __extension__ __PRETTY_FUNCTION__
))
;
13328
13329 // Decide whether the first capture was for a block or a lambda.
13330 DeclContext *DC = S.CurContext, *Prev = nullptr;
13331 // Decide whether the first capture was for a block or a lambda.
13332 while (DC) {
13333 // For init-capture, it is possible that the variable belongs to the
13334 // template pattern of the current context.
13335 if (auto *FD = dyn_cast<FunctionDecl>(DC))
13336 if (var->isInitCapture() &&
13337 FD->getTemplateInstantiationPattern() == var->getDeclContext())
13338 break;
13339 if (DC == var->getDeclContext())
13340 break;
13341 Prev = DC;
13342 DC = DC->getParent();
13343 }
13344 // Unless we have an init-capture, we've gone one step too far.
13345 if (!var->isInitCapture())
13346 DC = Prev;
13347 return (isa<BlockDecl>(DC) ? NCCK_Block : NCCK_Lambda);
13348}
13349
13350static bool IsTypeModifiable(QualType Ty, bool IsDereference) {
13351 Ty = Ty.getNonReferenceType();
13352 if (IsDereference && Ty->isPointerType())
13353 Ty = Ty->getPointeeType();
13354 return !Ty.isConstQualified();
13355}
13356
13357// Update err_typecheck_assign_const and note_typecheck_assign_const
13358// when this enum is changed.
13359enum {
13360 ConstFunction,
13361 ConstVariable,
13362 ConstMember,
13363 ConstMethod,
13364 NestedConstMember,
13365 ConstUnknown, // Keep as last element
13366};
13367
13368/// Emit the "read-only variable not assignable" error and print notes to give
13369/// more information about why the variable is not assignable, such as pointing
13370/// to the declaration of a const variable, showing that a method is const, or
13371/// that the function is returning a const reference.
13372static void DiagnoseConstAssignment(Sema &S, const Expr *E,
13373 SourceLocation Loc) {
13374 SourceRange ExprRange = E->getSourceRange();
13375
13376 // Only emit one error on the first const found. All other consts will emit
13377 // a note to the error.
13378 bool DiagnosticEmitted = false;
13379
13380 // Track if the current expression is the result of a dereference, and if the
13381 // next checked expression is the result of a dereference.
13382 bool IsDereference = false;
13383 bool NextIsDereference = false;
13384
13385 // Loop to process MemberExpr chains.
13386 while (true) {
13387 IsDereference = NextIsDereference;
13388
13389 E = E->IgnoreImplicit()->IgnoreParenImpCasts();
13390 if (const MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
13391 NextIsDereference = ME->isArrow();
13392 const ValueDecl *VD = ME->getMemberDecl();
13393 if (const FieldDecl *Field = dyn_cast<FieldDecl>(VD)) {
13394 // Mutable fields can be modified even if the class is const.
13395 if (Field->isMutable()) {
13396 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", 13396, __extension__ __PRETTY_FUNCTION__
))
;
13397 break;
13398 }
13399
13400 if (!IsTypeModifiable(Field->getType(), IsDereference)) {
13401 if (!DiagnosticEmitted) {
13402 S.Diag(Loc, diag::err_typecheck_assign_const)
13403 << ExprRange << ConstMember << false /*static*/ << Field
13404 << Field->getType();
13405 DiagnosticEmitted = true;
13406 }
13407 S.Diag(VD->getLocation(), diag::note_typecheck_assign_const)
13408 << ConstMember << false /*static*/ << Field << Field->getType()
13409 << Field->getSourceRange();
13410 }
13411 E = ME->getBase();
13412 continue;
13413 } else if (const VarDecl *VDecl = dyn_cast<VarDecl>(VD)) {
13414 if (VDecl->getType().isConstQualified()) {
13415 if (!DiagnosticEmitted) {
13416 S.Diag(Loc, diag::err_typecheck_assign_const)
13417 << ExprRange << ConstMember << true /*static*/ << VDecl
13418 << VDecl->getType();
13419 DiagnosticEmitted = true;
13420 }
13421 S.Diag(VD->getLocation(), diag::note_typecheck_assign_const)
13422 << ConstMember << true /*static*/ << VDecl << VDecl->getType()
13423 << VDecl->getSourceRange();
13424 }
13425 // Static fields do not inherit constness from parents.
13426 break;
13427 }
13428 break; // End MemberExpr
13429 } else if (const ArraySubscriptExpr *ASE =
13430 dyn_cast<ArraySubscriptExpr>(E)) {
13431 E = ASE->getBase()->IgnoreParenImpCasts();
13432 continue;
13433 } else if (const ExtVectorElementExpr *EVE =
13434 dyn_cast<ExtVectorElementExpr>(E)) {
13435 E = EVE->getBase()->IgnoreParenImpCasts();
13436 continue;
13437 }
13438 break;
13439 }
13440
13441 if (const CallExpr *CE = dyn_cast<CallExpr>(E)) {
13442 // Function calls
13443 const FunctionDecl *FD = CE->getDirectCallee();
13444 if (FD && !IsTypeModifiable(FD->getReturnType(), IsDereference)) {
13445 if (!DiagnosticEmitted) {
13446 S.Diag(Loc, diag::err_typecheck_assign_const) << ExprRange
13447 << ConstFunction << FD;
13448 DiagnosticEmitted = true;
13449 }
13450 S.Diag(FD->getReturnTypeSourceRange().getBegin(),
13451 diag::note_typecheck_assign_const)
13452 << ConstFunction << FD << FD->getReturnType()
13453 << FD->getReturnTypeSourceRange();
13454 }
13455 } else if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
13456 // Point to variable declaration.
13457 if (const ValueDecl *VD = DRE->getDecl()) {
13458 if (!IsTypeModifiable(VD->getType(), IsDereference)) {
13459 if (!DiagnosticEmitted) {
13460 S.Diag(Loc, diag::err_typecheck_assign_const)
13461 << ExprRange << ConstVariable << VD << VD->getType();
13462 DiagnosticEmitted = true;
13463 }
13464 S.Diag(VD->getLocation(), diag::note_typecheck_assign_const)
13465 << ConstVariable << VD << VD->getType() << VD->getSourceRange();
13466 }
13467 }
13468 } else if (isa<CXXThisExpr>(E)) {
13469 if (const DeclContext *DC = S.getFunctionLevelDeclContext()) {
13470 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(DC)) {
13471 if (MD->isConst()) {
13472 if (!DiagnosticEmitted) {
13473 S.Diag(Loc, diag::err_typecheck_assign_const) << ExprRange
13474 << ConstMethod << MD;
13475 DiagnosticEmitted = true;
13476 }
13477 S.Diag(MD->getLocation(), diag::note_typecheck_assign_const)
13478 << ConstMethod << MD << MD->getSourceRange();
13479 }
13480 }
13481 }
13482 }
13483
13484 if (DiagnosticEmitted)
13485 return;
13486
13487 // Can't determine a more specific message, so display the generic error.
13488 S.Diag(Loc, diag::err_typecheck_assign_const) << ExprRange << ConstUnknown;
13489}
13490
13491enum OriginalExprKind {
13492 OEK_Variable,
13493 OEK_Member,
13494 OEK_LValue
13495};
13496
13497static void DiagnoseRecursiveConstFields(Sema &S, const ValueDecl *VD,
13498 const RecordType *Ty,
13499 SourceLocation Loc, SourceRange Range,
13500 OriginalExprKind OEK,
13501 bool &DiagnosticEmitted) {
13502 std::vector<const RecordType *> RecordTypeList;
13503 RecordTypeList.push_back(Ty);
13504 unsigned NextToCheckIndex = 0;
13505 // We walk the record hierarchy breadth-first to ensure that we print
13506 // diagnostics in field nesting order.
13507 while (RecordTypeList.size() > NextToCheckIndex) {
13508 bool IsNested = NextToCheckIndex > 0;
13509 for (const FieldDecl *Field :
13510 RecordTypeList[NextToCheckIndex]->getDecl()->fields()) {
13511 // First, check every field for constness.
13512 QualType FieldTy = Field->getType();
13513 if (FieldTy.isConstQualified()) {
13514 if (!DiagnosticEmitted) {
13515 S.Diag(Loc, diag::err_typecheck_assign_const)
13516 << Range << NestedConstMember << OEK << VD
13517 << IsNested << Field;
13518 DiagnosticEmitted = true;
13519 }
13520 S.Diag(Field->getLocation(), diag::note_typecheck_assign_const)
13521 << NestedConstMember << IsNested << Field
13522 << FieldTy << Field->getSourceRange();
13523 }
13524
13525 // Then we append it to the list to check next in order.
13526 FieldTy = FieldTy.getCanonicalType();
13527 if (const auto *FieldRecTy = FieldTy->getAs<RecordType>()) {
13528 if (!llvm::is_contained(RecordTypeList, FieldRecTy))
13529 RecordTypeList.push_back(FieldRecTy);
13530 }
13531 }
13532 ++NextToCheckIndex;
13533 }
13534}
13535
13536/// Emit an error for the case where a record we are trying to assign to has a
13537/// const-qualified field somewhere in its hierarchy.
13538static void DiagnoseRecursiveConstFields(Sema &S, const Expr *E,
13539 SourceLocation Loc) {
13540 QualType Ty = E->getType();
13541 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", 13541, __extension__ __PRETTY_FUNCTION__
))
;
13542 SourceRange Range = E->getSourceRange();
13543 const RecordType *RTy = Ty.getCanonicalType()->getAs<RecordType>();
13544 bool DiagEmitted = false;
13545
13546 if (const MemberExpr *ME = dyn_cast<MemberExpr>(E))
13547 DiagnoseRecursiveConstFields(S, ME->getMemberDecl(), RTy, Loc,
13548 Range, OEK_Member, DiagEmitted);
13549 else if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
13550 DiagnoseRecursiveConstFields(S, DRE->getDecl(), RTy, Loc,
13551 Range, OEK_Variable, DiagEmitted);
13552 else
13553 DiagnoseRecursiveConstFields(S, nullptr, RTy, Loc,
13554 Range, OEK_LValue, DiagEmitted);
13555 if (!DiagEmitted)
13556 DiagnoseConstAssignment(S, E, Loc);
13557}
13558
13559/// CheckForModifiableLvalue - Verify that E is a modifiable lvalue. If not,
13560/// emit an error and return true. If so, return false.
13561static bool CheckForModifiableLvalue(Expr *E, SourceLocation Loc, Sema &S) {
13562 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", 13562, __extension__ __PRETTY_FUNCTION__
))
;
13563
13564 S.CheckShadowingDeclModification(E, Loc);
13565
13566 SourceLocation OrigLoc = Loc;
13567 Expr::isModifiableLvalueResult IsLV = E->isModifiableLvalue(S.Context,
13568 &Loc);
13569 if (IsLV == Expr::MLV_ClassTemporary && IsReadonlyMessage(E, S))
13570 IsLV = Expr::MLV_InvalidMessageExpression;
13571 if (IsLV == Expr::MLV_Valid)
13572 return false;
13573
13574 unsigned DiagID = 0;
13575 bool NeedType = false;
13576 switch (IsLV) { // C99 6.5.16p2
13577 case Expr::MLV_ConstQualified:
13578 // Use a specialized diagnostic when we're assigning to an object
13579 // from an enclosing function or block.
13580 if (NonConstCaptureKind NCCK = isReferenceToNonConstCapture(S, E)) {
13581 if (NCCK == NCCK_Block)
13582 DiagID = diag::err_block_decl_ref_not_modifiable_lvalue;
13583 else
13584 DiagID = diag::err_lambda_decl_ref_not_modifiable_lvalue;
13585 break;
13586 }
13587
13588 // In ARC, use some specialized diagnostics for occasions where we
13589 // infer 'const'. These are always pseudo-strong variables.
13590 if (S.getLangOpts().ObjCAutoRefCount) {
13591 DeclRefExpr *declRef = dyn_cast<DeclRefExpr>(E->IgnoreParenCasts());
13592 if (declRef && isa<VarDecl>(declRef->getDecl())) {
13593 VarDecl *var = cast<VarDecl>(declRef->getDecl());
13594
13595 // Use the normal diagnostic if it's pseudo-__strong but the
13596 // user actually wrote 'const'.
13597 if (var->isARCPseudoStrong() &&
13598 (!var->getTypeSourceInfo() ||
13599 !var->getTypeSourceInfo()->getType().isConstQualified())) {
13600 // There are three pseudo-strong cases:
13601 // - self
13602 ObjCMethodDecl *method = S.getCurMethodDecl();
13603 if (method && var == method->getSelfDecl()) {
13604 DiagID = method->isClassMethod()
13605 ? diag::err_typecheck_arc_assign_self_class_method
13606 : diag::err_typecheck_arc_assign_self;
13607
13608 // - Objective-C externally_retained attribute.
13609 } else if (var->hasAttr<ObjCExternallyRetainedAttr>() ||
13610 isa<ParmVarDecl>(var)) {
13611 DiagID = diag::err_typecheck_arc_assign_externally_retained;
13612
13613 // - fast enumeration variables
13614 } else {
13615 DiagID = diag::err_typecheck_arr_assign_enumeration;
13616 }
13617
13618 SourceRange Assign;
13619 if (Loc != OrigLoc)
13620 Assign = SourceRange(OrigLoc, OrigLoc);
13621 S.Diag(Loc, DiagID) << E->getSourceRange() << Assign;
13622 // We need to preserve the AST regardless, so migration tool
13623 // can do its job.
13624 return false;
13625 }
13626 }
13627 }
13628
13629 // If none of the special cases above are triggered, then this is a
13630 // simple const assignment.
13631 if (DiagID == 0) {
13632 DiagnoseConstAssignment(S, E, Loc);
13633 return true;
13634 }
13635
13636 break;
13637 case Expr::MLV_ConstAddrSpace:
13638 DiagnoseConstAssignment(S, E, Loc);
13639 return true;
13640 case Expr::MLV_ConstQualifiedField:
13641 DiagnoseRecursiveConstFields(S, E, Loc);
13642 return true;
13643 case Expr::MLV_ArrayType:
13644 case Expr::MLV_ArrayTemporary:
13645 DiagID = diag::err_typecheck_array_not_modifiable_lvalue;
13646 NeedType = true;
13647 break;
13648 case Expr::MLV_NotObjectType:
13649 DiagID = diag::err_typecheck_non_object_not_modifiable_lvalue;
13650 NeedType = true;
13651 break;
13652 case Expr::MLV_LValueCast:
13653 DiagID = diag::err_typecheck_lvalue_casts_not_supported;
13654 break;
13655 case Expr::MLV_Valid:
13656 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", 13656)
;
13657 case Expr::MLV_InvalidExpression:
13658 case Expr::MLV_MemberFunction:
13659 case Expr::MLV_ClassTemporary:
13660 DiagID = diag::err_typecheck_expression_not_modifiable_lvalue;
13661 break;
13662 case Expr::MLV_IncompleteType:
13663 case Expr::MLV_IncompleteVoidType:
13664 return S.RequireCompleteType(Loc, E->getType(),
13665 diag::err_typecheck_incomplete_type_not_modifiable_lvalue, E);
13666 case Expr::MLV_DuplicateVectorComponents:
13667 DiagID = diag::err_typecheck_duplicate_vector_components_not_mlvalue;
13668 break;
13669 case Expr::MLV_NoSetterProperty:
13670 llvm_unreachable("readonly properties should be processed differently")::llvm::llvm_unreachable_internal("readonly properties should be processed differently"
, "clang/lib/Sema/SemaExpr.cpp", 13670)
;
13671 case Expr::MLV_InvalidMessageExpression:
13672 DiagID = diag::err_readonly_message_assignment;
13673 break;
13674 case Expr::MLV_SubObjCPropertySetting:
13675 DiagID = diag::err_no_subobject_property_setting;
13676 break;
13677 }
13678
13679 SourceRange Assign;
13680 if (Loc != OrigLoc)
13681 Assign = SourceRange(OrigLoc, OrigLoc);
13682 if (NeedType)
13683 S.Diag(Loc, DiagID) << E->getType() << E->getSourceRange() << Assign;
13684 else
13685 S.Diag(Loc, DiagID) << E->getSourceRange() << Assign;
13686 return true;
13687}
13688
13689static void CheckIdentityFieldAssignment(Expr *LHSExpr, Expr *RHSExpr,
13690 SourceLocation Loc,
13691 Sema &Sema) {
13692 if (Sema.inTemplateInstantiation())
13693 return;
13694 if (Sema.isUnevaluatedContext())
13695 return;
13696 if (Loc.isInvalid() || Loc.isMacroID())
13697 return;
13698 if (LHSExpr->getExprLoc().isMacroID() || RHSExpr->getExprLoc().isMacroID())
13699 return;
13700
13701 // C / C++ fields
13702 MemberExpr *ML = dyn_cast<MemberExpr>(LHSExpr);
13703 MemberExpr *MR = dyn_cast<MemberExpr>(RHSExpr);
13704 if (ML && MR) {
13705 if (!(isa<CXXThisExpr>(ML->getBase()) && isa<CXXThisExpr>(MR->getBase())))
13706 return;
13707 const ValueDecl *LHSDecl =
13708 cast<ValueDecl>(ML->getMemberDecl()->getCanonicalDecl());
13709 const ValueDecl *RHSDecl =
13710 cast<ValueDecl>(MR->getMemberDecl()->getCanonicalDecl());
13711 if (LHSDecl != RHSDecl)
13712 return;
13713 if (LHSDecl->getType().isVolatileQualified())
13714 return;
13715 if (const ReferenceType *RefTy = LHSDecl->getType()->getAs<ReferenceType>())
13716 if (RefTy->getPointeeType().isVolatileQualified())
13717 return;
13718
13719 Sema.Diag(Loc, diag::warn_identity_field_assign) << 0;
13720 }
13721
13722 // Objective-C instance variables
13723 ObjCIvarRefExpr *OL = dyn_cast<ObjCIvarRefExpr>(LHSExpr);
13724 ObjCIvarRefExpr *OR = dyn_cast<ObjCIvarRefExpr>(RHSExpr);
13725 if (OL && OR && OL->getDecl() == OR->getDecl()) {
13726 DeclRefExpr *RL = dyn_cast<DeclRefExpr>(OL->getBase()->IgnoreImpCasts());
13727 DeclRefExpr *RR = dyn_cast<DeclRefExpr>(OR->getBase()->IgnoreImpCasts());
13728 if (RL && RR && RL->getDecl() == RR->getDecl())
13729 Sema.Diag(Loc, diag::warn_identity_field_assign) << 1;
13730 }
13731}
13732
13733// C99 6.5.16.1
13734QualType Sema::CheckAssignmentOperands(Expr *LHSExpr, ExprResult &RHS,
13735 SourceLocation Loc,
13736 QualType CompoundType) {
13737 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", 13737, __extension__ __PRETTY_FUNCTION__
))
;
13738
13739 // Verify that LHS is a modifiable lvalue, and emit error if not.
13740 if (CheckForModifiableLvalue(LHSExpr, Loc, *this))
13741 return QualType();
13742
13743 QualType LHSType = LHSExpr->getType();
13744 QualType RHSType = CompoundType.isNull() ? RHS.get()->getType() :
13745 CompoundType;
13746 // OpenCL v1.2 s6.1.1.1 p2:
13747 // The half data type can only be used to declare a pointer to a buffer that
13748 // contains half values
13749 if (getLangOpts().OpenCL &&
13750 !getOpenCLOptions().isAvailableOption("cl_khr_fp16", getLangOpts()) &&
13751 LHSType->isHalfType()) {
13752 Diag(Loc, diag::err_opencl_half_load_store) << 1
13753 << LHSType.getUnqualifiedType();
13754 return QualType();
13755 }
13756
13757 AssignConvertType ConvTy;
13758 if (CompoundType.isNull()) {
13759 Expr *RHSCheck = RHS.get();
13760
13761 CheckIdentityFieldAssignment(LHSExpr, RHSCheck, Loc, *this);
13762
13763 QualType LHSTy(LHSType);
13764 ConvTy = CheckSingleAssignmentConstraints(LHSTy, RHS);
13765 if (RHS.isInvalid())
13766 return QualType();
13767 // Special case of NSObject attributes on c-style pointer types.
13768 if (ConvTy == IncompatiblePointer &&
13769 ((Context.isObjCNSObjectType(LHSType) &&
13770 RHSType->isObjCObjectPointerType()) ||
13771 (Context.isObjCNSObjectType(RHSType) &&
13772 LHSType->isObjCObjectPointerType())))
13773 ConvTy = Compatible;
13774
13775 if (ConvTy == Compatible &&
13776 LHSType->isObjCObjectType())
13777 Diag(Loc, diag::err_objc_object_assignment)
13778 << LHSType;
13779
13780 // If the RHS is a unary plus or minus, check to see if they = and + are
13781 // right next to each other. If so, the user may have typo'd "x =+ 4"
13782 // instead of "x += 4".
13783 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(RHSCheck))
13784 RHSCheck = ICE->getSubExpr();
13785 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(RHSCheck)) {
13786 if ((UO->getOpcode() == UO_Plus || UO->getOpcode() == UO_Minus) &&
13787 Loc.isFileID() && UO->getOperatorLoc().isFileID() &&
13788 // Only if the two operators are exactly adjacent.
13789 Loc.getLocWithOffset(1) == UO->getOperatorLoc() &&
13790 // And there is a space or other character before the subexpr of the
13791 // unary +/-. We don't want to warn on "x=-1".
13792 Loc.getLocWithOffset(2) != UO->getSubExpr()->getBeginLoc() &&
13793 UO->getSubExpr()->getBeginLoc().isFileID()) {
13794 Diag(Loc, diag::warn_not_compound_assign)
13795 << (UO->getOpcode() == UO_Plus ? "+" : "-")
13796 << SourceRange(UO->getOperatorLoc(), UO->getOperatorLoc());
13797 }
13798 }
13799
13800 if (ConvTy == Compatible) {
13801 if (LHSType.getObjCLifetime() == Qualifiers::OCL_Strong) {
13802 // Warn about retain cycles where a block captures the LHS, but
13803 // not if the LHS is a simple variable into which the block is
13804 // being stored...unless that variable can be captured by reference!
13805 const Expr *InnerLHS = LHSExpr->IgnoreParenCasts();
13806 const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(InnerLHS);
13807 if (!DRE || DRE->getDecl()->hasAttr<BlocksAttr>())
13808 checkRetainCycles(LHSExpr, RHS.get());
13809 }
13810
13811 if (LHSType.getObjCLifetime() == Qualifiers::OCL_Strong ||
13812 LHSType.isNonWeakInMRRWithObjCWeak(Context)) {
13813 // It is safe to assign a weak reference into a strong variable.
13814 // Although this code can still have problems:
13815 // id x = self.weakProp;
13816 // id y = self.weakProp;
13817 // we do not warn to warn spuriously when 'x' and 'y' are on separate
13818 // paths through the function. This should be revisited if
13819 // -Wrepeated-use-of-weak is made flow-sensitive.
13820 // For ObjCWeak only, we do not warn if the assign is to a non-weak
13821 // variable, which will be valid for the current autorelease scope.
13822 if (!Diags.isIgnored(diag::warn_arc_repeated_use_of_weak,
13823 RHS.get()->getBeginLoc()))
13824 getCurFunction()->markSafeWeakUse(RHS.get());
13825
13826 } else if (getLangOpts().ObjCAutoRefCount || getLangOpts().ObjCWeak) {
13827 checkUnsafeExprAssigns(Loc, LHSExpr, RHS.get());
13828 }
13829 }
13830 } else {
13831 // Compound assignment "x += y"
13832 ConvTy = CheckAssignmentConstraints(Loc, LHSType, RHSType);
13833 }
13834
13835 if (DiagnoseAssignmentResult(ConvTy, Loc, LHSType, RHSType,
13836 RHS.get(), AA_Assigning))
13837 return QualType();
13838
13839 CheckForNullPointerDereference(*this, LHSExpr);
13840
13841 if (getLangOpts().CPlusPlus20 && LHSType.isVolatileQualified()) {
13842 if (CompoundType.isNull()) {
13843 // C++2a [expr.ass]p5:
13844 // A simple-assignment whose left operand is of a volatile-qualified
13845 // type is deprecated unless the assignment is either a discarded-value
13846 // expression or an unevaluated operand
13847 ExprEvalContexts.back().VolatileAssignmentLHSs.push_back(LHSExpr);
13848 } else {
13849 // C++2a [expr.ass]p6:
13850 // [Compound-assignment] expressions are deprecated if E1 has
13851 // volatile-qualified type
13852 Diag(Loc, diag::warn_deprecated_compound_assign_volatile) << LHSType;
13853 }
13854 }
13855
13856 // C11 6.5.16p3: The type of an assignment expression is the type of the
13857 // left operand would have after lvalue conversion.
13858 // C11 6.3.2.1p2: ...this is called lvalue conversion. If the lvalue has
13859 // qualified type, the value has the unqualified version of the type of the
13860 // lvalue; additionally, if the lvalue has atomic type, the value has the
13861 // non-atomic version of the type of the lvalue.
13862 // C++ 5.17p1: the type of the assignment expression is that of its left
13863 // operand.
13864 return getLangOpts().CPlusPlus ? LHSType : LHSType.getAtomicUnqualifiedType();
13865}
13866
13867// Only ignore explicit casts to void.
13868static bool IgnoreCommaOperand(const Expr *E) {
13869 E = E->IgnoreParens();
13870
13871 if (const CastExpr *CE = dyn_cast<CastExpr>(E)) {
13872 if (CE->getCastKind() == CK_ToVoid) {
13873 return true;
13874 }
13875
13876 // static_cast<void> on a dependent type will not show up as CK_ToVoid.
13877 if (CE->getCastKind() == CK_Dependent && E->getType()->isVoidType() &&
13878 CE->getSubExpr()->getType()->isDependentType()) {
13879 return true;
13880 }
13881 }
13882
13883 return false;
13884}
13885
13886// Look for instances where it is likely the comma operator is confused with
13887// another operator. There is an explicit list of acceptable expressions for
13888// the left hand side of the comma operator, otherwise emit a warning.
13889void Sema::DiagnoseCommaOperator(const Expr *LHS, SourceLocation Loc) {
13890 // No warnings in macros
13891 if (Loc.isMacroID())
13892 return;
13893
13894 // Don't warn in template instantiations.
13895 if (inTemplateInstantiation())
13896 return;
13897
13898 // Scope isn't fine-grained enough to explicitly list the specific cases, so
13899 // instead, skip more than needed, then call back into here with the
13900 // CommaVisitor in SemaStmt.cpp.
13901 // The listed locations are the initialization and increment portions
13902 // of a for loop. The additional checks are on the condition of
13903 // if statements, do/while loops, and for loops.
13904 // Differences in scope flags for C89 mode requires the extra logic.
13905 const unsigned ForIncrementFlags =
13906 getLangOpts().C99 || getLangOpts().CPlusPlus
13907 ? Scope::ControlScope | Scope::ContinueScope | Scope::BreakScope
13908 : Scope::ContinueScope | Scope::BreakScope;
13909 const unsigned ForInitFlags = Scope::ControlScope | Scope::DeclScope;
13910 const unsigned ScopeFlags = getCurScope()->getFlags();
13911 if ((ScopeFlags & ForIncrementFlags) == ForIncrementFlags ||
13912 (ScopeFlags & ForInitFlags) == ForInitFlags)
13913 return;
13914
13915 // If there are multiple comma operators used together, get the RHS of the
13916 // of the comma operator as the LHS.
13917 while (const BinaryOperator *BO = dyn_cast<BinaryOperator>(LHS)) {
13918 if (BO->getOpcode() != BO_Comma)
13919 break;
13920 LHS = BO->getRHS();
13921 }
13922
13923 // Only allow some expressions on LHS to not warn.
13924 if (IgnoreCommaOperand(LHS))
13925 return;
13926
13927 Diag(Loc, diag::warn_comma_operator);
13928 Diag(LHS->getBeginLoc(), diag::note_cast_to_void)
13929 << LHS->getSourceRange()
13930 << FixItHint::CreateInsertion(LHS->getBeginLoc(),
13931 LangOpts.CPlusPlus ? "static_cast<void>("
13932 : "(void)(")
13933 << FixItHint::CreateInsertion(PP.getLocForEndOfToken(LHS->getEndLoc()),
13934 ")");
13935}
13936
13937// C99 6.5.17
13938static QualType CheckCommaOperands(Sema &S, ExprResult &LHS, ExprResult &RHS,
13939 SourceLocation Loc) {
13940 LHS = S.CheckPlaceholderExpr(LHS.get());
13941 RHS = S.CheckPlaceholderExpr(RHS.get());
13942 if (LHS.isInvalid() || RHS.isInvalid())
13943 return QualType();
13944
13945 // C's comma performs lvalue conversion (C99 6.3.2.1) on both its
13946 // operands, but not unary promotions.
13947 // C++'s comma does not do any conversions at all (C++ [expr.comma]p1).
13948
13949 // So we treat the LHS as a ignored value, and in C++ we allow the
13950 // containing site to determine what should be done with the RHS.
13951 LHS = S.IgnoredValueConversions(LHS.get());
13952 if (LHS.isInvalid())
13953 return QualType();
13954
13955 S.DiagnoseUnusedExprResult(LHS.get(), diag::warn_unused_comma_left_operand);
13956
13957 if (!S.getLangOpts().CPlusPlus) {
13958 RHS = S.DefaultFunctionArrayLvalueConversion(RHS.get());
13959 if (RHS.isInvalid())
13960 return QualType();
13961 if (!RHS.get()->getType()->isVoidType())
13962 S.RequireCompleteType(Loc, RHS.get()->getType(),
13963 diag::err_incomplete_type);
13964 }
13965
13966 if (!S.getDiagnostics().isIgnored(diag::warn_comma_operator, Loc))
13967 S.DiagnoseCommaOperator(LHS.get(), Loc);
13968
13969 return RHS.get()->getType();
13970}
13971
13972/// CheckIncrementDecrementOperand - unlike most "Check" methods, this routine
13973/// doesn't need to call UsualUnaryConversions or UsualArithmeticConversions.
13974static QualType CheckIncrementDecrementOperand(Sema &S, Expr *Op,
13975 ExprValueKind &VK,
13976 ExprObjectKind &OK,
13977 SourceLocation OpLoc,
13978 bool IsInc, bool IsPrefix) {
13979 if (Op->isTypeDependent())
13980 return S.Context.DependentTy;
13981
13982 QualType ResType = Op->getType();
13983 // Atomic types can be used for increment / decrement where the non-atomic
13984 // versions can, so ignore the _Atomic() specifier for the purpose of
13985 // checking.
13986 if (const AtomicType *ResAtomicType = ResType->getAs<AtomicType>())
13987 ResType = ResAtomicType->getValueType();
13988
13989 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", 13989, __extension__ __PRETTY_FUNCTION__
))
;
13990
13991 if (S.getLangOpts().CPlusPlus && ResType->isBooleanType()) {
13992 // Decrement of bool is not allowed.
13993 if (!IsInc) {
13994 S.Diag(OpLoc, diag::err_decrement_bool) << Op->getSourceRange();
13995 return QualType();
13996 }
13997 // Increment of bool sets it to true, but is deprecated.
13998 S.Diag(OpLoc, S.getLangOpts().CPlusPlus17 ? diag::ext_increment_bool
13999 : diag::warn_increment_bool)
14000 << Op->getSourceRange();
14001 } else if (S.getLangOpts().CPlusPlus && ResType->isEnumeralType()) {
14002 // Error on enum increments and decrements in C++ mode
14003 S.Diag(OpLoc, diag::err_increment_decrement_enum) << IsInc << ResType;
14004 return QualType();
14005 } else if (ResType->isRealType()) {
14006 // OK!
14007 } else if (ResType->isPointerType()) {
14008 // C99 6.5.2.4p2, 6.5.6p2
14009 if (!checkArithmeticOpPointerOperand(S, OpLoc, Op))
14010 return QualType();
14011 } else if (ResType->isObjCObjectPointerType()) {
14012 // On modern runtimes, ObjC pointer arithmetic is forbidden.
14013 // Otherwise, we just need a complete type.
14014 if (checkArithmeticIncompletePointerType(S, OpLoc, Op) ||
14015 checkArithmeticOnObjCPointer(S, OpLoc, Op))
14016 return QualType();
14017 } else if (ResType->isAnyComplexType()) {
14018 // C99 does not support ++/-- on complex types, we allow as an extension.
14019 S.Diag(OpLoc, diag::ext_integer_increment_complex)
14020 << ResType << Op->getSourceRange();
14021 } else if (ResType->isPlaceholderType()) {
14022 ExprResult PR = S.CheckPlaceholderExpr(Op);
14023 if (PR.isInvalid()) return QualType();
14024 return CheckIncrementDecrementOperand(S, PR.get(), VK, OK, OpLoc,
14025 IsInc, IsPrefix);
14026 } else if (S.getLangOpts().AltiVec && ResType->isVectorType()) {
14027 // OK! ( C/C++ Language Extensions for CBEA(Version 2.6) 10.3 )
14028 } else if (S.getLangOpts().ZVector && ResType->isVectorType() &&
14029 (ResType->castAs<VectorType>()->getVectorKind() !=
14030 VectorType::AltiVecBool)) {
14031 // The z vector extensions allow ++ and -- for non-bool vectors.
14032 } else if(S.getLangOpts().OpenCL && ResType->isVectorType() &&
14033 ResType->castAs<VectorType>()->getElementType()->isIntegerType()) {
14034 // OpenCL V1.2 6.3 says dec/inc ops operate on integer vector types.
14035 } else {
14036 S.Diag(OpLoc, diag::err_typecheck_illegal_increment_decrement)
14037 << ResType << int(IsInc) << Op->getSourceRange();
14038 return QualType();
14039 }
14040 // At this point, we know we have a real, complex or pointer type.
14041 // Now make sure the operand is a modifiable lvalue.
14042 if (CheckForModifiableLvalue(Op, OpLoc, S))
14043 return QualType();
14044 if (S.getLangOpts().CPlusPlus20 && ResType.isVolatileQualified()) {
14045 // C++2a [expr.pre.inc]p1, [expr.post.inc]p1:
14046 // An operand with volatile-qualified type is deprecated
14047 S.Diag(OpLoc, diag::warn_deprecated_increment_decrement_volatile)
14048 << IsInc << ResType;
14049 }
14050 // In C++, a prefix increment is the same type as the operand. Otherwise
14051 // (in C or with postfix), the increment is the unqualified type of the
14052 // operand.
14053 if (IsPrefix && S.getLangOpts().CPlusPlus) {
14054 VK = VK_LValue;
14055 OK = Op->getObjectKind();
14056 return ResType;
14057 } else {
14058 VK = VK_PRValue;
14059 return ResType.getUnqualifiedType();
14060 }
14061}
14062
14063
14064/// getPrimaryDecl - Helper function for CheckAddressOfOperand().
14065/// This routine allows us to typecheck complex/recursive expressions
14066/// where the declaration is needed for type checking. We only need to
14067/// handle cases when the expression references a function designator
14068/// or is an lvalue. Here are some examples:
14069/// - &(x) => x
14070/// - &*****f => f for f a function designator.
14071/// - &s.xx => s
14072/// - &s.zz[1].yy -> s, if zz is an array
14073/// - *(x + 1) -> x, if x is an array
14074/// - &"123"[2] -> 0
14075/// - & __real__ x -> x
14076///
14077/// FIXME: We don't recurse to the RHS of a comma, nor handle pointers to
14078/// members.
14079static ValueDecl *getPrimaryDecl(Expr *E) {
14080 switch (E->getStmtClass()) {
14081 case Stmt::DeclRefExprClass:
14082 return cast<DeclRefExpr>(E)->getDecl();
14083 case Stmt::MemberExprClass:
14084 // If this is an arrow operator, the address is an offset from
14085 // the base's value, so the object the base refers to is
14086 // irrelevant.
14087 if (cast<MemberExpr>(E)->isArrow())
14088 return nullptr;
14089 // Otherwise, the expression refers to a part of the base
14090 return getPrimaryDecl(cast<MemberExpr>(E)->getBase());
14091 case Stmt::ArraySubscriptExprClass: {
14092 // FIXME: This code shouldn't be necessary! We should catch the implicit
14093 // promotion of register arrays earlier.
14094 Expr* Base = cast<ArraySubscriptExpr>(E)->getBase();
14095 if (ImplicitCastExpr* ICE = dyn_cast<ImplicitCastExpr>(Base)) {
14096 if (ICE->getSubExpr()->getType()->isArrayType())
14097 return getPrimaryDecl(ICE->getSubExpr());
14098 }
14099 return nullptr;
14100 }
14101 case Stmt::UnaryOperatorClass: {
14102 UnaryOperator *UO = cast<UnaryOperator>(E);
14103
14104 switch(UO->getOpcode()) {
14105 case UO_Real:
14106 case UO_Imag:
14107 case UO_Extension:
14108 return getPrimaryDecl(UO->getSubExpr());
14109 default:
14110 return nullptr;
14111 }
14112 }
14113 case Stmt::ParenExprClass:
14114 return getPrimaryDecl(cast<ParenExpr>(E)->getSubExpr());
14115 case Stmt::ImplicitCastExprClass:
14116 // If the result of an implicit cast is an l-value, we care about
14117 // the sub-expression; otherwise, the result here doesn't matter.
14118 return getPrimaryDecl(cast<ImplicitCastExpr>(E)->getSubExpr());
14119 case Stmt::CXXUuidofExprClass:
14120 return cast<CXXUuidofExpr>(E)->getGuidDecl();
14121 default:
14122 return nullptr;
14123 }
14124}
14125
14126namespace {
14127enum {
14128 AO_Bit_Field = 0,
14129 AO_Vector_Element = 1,
14130 AO_Property_Expansion = 2,
14131 AO_Register_Variable = 3,
14132 AO_Matrix_Element = 4,
14133 AO_No_Error = 5
14134};
14135}
14136/// Diagnose invalid operand for address of operations.
14137///
14138/// \param Type The type of operand which cannot have its address taken.
14139static void diagnoseAddressOfInvalidType(Sema &S, SourceLocation Loc,
14140 Expr *E, unsigned Type) {
14141 S.Diag(Loc, diag::err_typecheck_address_of) << Type << E->getSourceRange();
14142}
14143
14144/// CheckAddressOfOperand - The operand of & must be either a function
14145/// designator or an lvalue designating an object. If it is an lvalue, the
14146/// object cannot be declared with storage class register or be a bit field.
14147/// Note: The usual conversions are *not* applied to the operand of the &
14148/// operator (C99 6.3.2.1p[2-4]), and its result is never an lvalue.
14149/// In C++, the operand might be an overloaded function name, in which case
14150/// we allow the '&' but retain the overloaded-function type.
14151QualType Sema::CheckAddressOfOperand(ExprResult &OrigOp, SourceLocation OpLoc) {
14152 if (const BuiltinType *PTy = OrigOp.get()->getType()->getAsPlaceholderType()){
14153 if (PTy->getKind() == BuiltinType::Overload) {
14154 Expr *E = OrigOp.get()->IgnoreParens();
14155 if (!isa<OverloadExpr>(E)) {
14156 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", 14156, __extension__ __PRETTY_FUNCTION__
))
;
14157 Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof_addrof_function)
14158 << OrigOp.get()->getSourceRange();
14159 return QualType();
14160 }
14161
14162 OverloadExpr *Ovl = cast<OverloadExpr>(E);
14163 if (isa<UnresolvedMemberExpr>(Ovl))
14164 if (!ResolveSingleFunctionTemplateSpecialization(Ovl)) {
14165 Diag(OpLoc, diag::err_invalid_form_pointer_member_function)
14166 << OrigOp.get()->getSourceRange();
14167 return QualType();
14168 }
14169
14170 return Context.OverloadTy;
14171 }
14172
14173 if (PTy->getKind() == BuiltinType::UnknownAny)
14174 return Context.UnknownAnyTy;
14175
14176 if (PTy->getKind() == BuiltinType::BoundMember) {
14177 Diag(OpLoc, diag::err_invalid_form_pointer_member_function)
14178 << OrigOp.get()->getSourceRange();
14179 return QualType();
14180 }
14181
14182 OrigOp = CheckPlaceholderExpr(OrigOp.get());
14183 if (OrigOp.isInvalid()) return QualType();
14184 }
14185
14186 if (OrigOp.get()->isTypeDependent())
14187 return Context.DependentTy;
14188
14189 assert(!OrigOp.get()->hasPlaceholderType())(static_cast <bool> (!OrigOp.get()->hasPlaceholderType
()) ? void (0) : __assert_fail ("!OrigOp.get()->hasPlaceholderType()"
, "clang/lib/Sema/SemaExpr.cpp", 14189, __extension__ __PRETTY_FUNCTION__
))
;
14190
14191 // Make sure to ignore parentheses in subsequent checks
14192 Expr *op = OrigOp.get()->IgnoreParens();
14193
14194 // In OpenCL captures for blocks called as lambda functions
14195 // are located in the private address space. Blocks used in
14196 // enqueue_kernel can be located in a different address space
14197 // depending on a vendor implementation. Thus preventing
14198 // taking an address of the capture to avoid invalid AS casts.
14199 if (LangOpts.OpenCL) {
14200 auto* VarRef = dyn_cast<DeclRefExpr>(op);
14201 if (VarRef && VarRef->refersToEnclosingVariableOrCapture()) {
14202 Diag(op->getExprLoc(), diag::err_opencl_taking_address_capture);
14203 return QualType();
14204 }
14205 }
14206
14207 if (getLangOpts().C99) {
14208 // Implement C99-only parts of addressof rules.
14209 if (UnaryOperator* uOp = dyn_cast<UnaryOperator>(op)) {
14210 if (uOp->getOpcode() == UO_Deref)
14211 // Per C99 6.5.3.2, the address of a deref always returns a valid result
14212 // (assuming the deref expression is valid).
14213 return uOp->getSubExpr()->getType();
14214 }
14215 // Technically, there should be a check for array subscript
14216 // expressions here, but the result of one is always an lvalue anyway.
14217 }
14218 ValueDecl *dcl = getPrimaryDecl(op);
14219
14220 if (auto *FD = dyn_cast_or_null<FunctionDecl>(dcl))
14221 if (!checkAddressOfFunctionIsAvailable(FD, /*Complain=*/true,
14222 op->getBeginLoc()))
14223 return QualType();
14224
14225 Expr::LValueClassification lval = op->ClassifyLValue(Context);
14226 unsigned AddressOfError = AO_No_Error;
14227
14228 if (lval == Expr::LV_ClassTemporary || lval == Expr::LV_ArrayTemporary) {
14229 bool sfinae = (bool)isSFINAEContext();
14230 Diag(OpLoc, isSFINAEContext() ? diag::err_typecheck_addrof_temporary
14231 : diag::ext_typecheck_addrof_temporary)
14232 << op->getType() << op->getSourceRange();
14233 if (sfinae)
14234 return QualType();
14235 // Materialize the temporary as an lvalue so that we can take its address.
14236 OrigOp = op =
14237 CreateMaterializeTemporaryExpr(op->getType(), OrigOp.get(), true);
14238 } else if (isa<ObjCSelectorExpr>(op)) {
14239 return Context.getPointerType(op->getType());
14240 } else if (lval == Expr::LV_MemberFunction) {
14241 // If it's an instance method, make a member pointer.
14242 // The expression must have exactly the form &A::foo.
14243
14244 // If the underlying expression isn't a decl ref, give up.
14245 if (!isa<DeclRefExpr>(op)) {
14246 Diag(OpLoc, diag::err_invalid_form_pointer_member_function)
14247 << OrigOp.get()->getSourceRange();
14248 return QualType();
14249 }
14250 DeclRefExpr *DRE = cast<DeclRefExpr>(op);
14251 CXXMethodDecl *MD = cast<CXXMethodDecl>(DRE->getDecl());
14252
14253 // The id-expression was parenthesized.
14254 if (OrigOp.get() != DRE) {
14255 Diag(OpLoc, diag::err_parens_pointer_member_function)
14256 << OrigOp.get()->getSourceRange();
14257
14258 // The method was named without a qualifier.
14259 } else if (!DRE->getQualifier()) {
14260 if (MD->getParent()->getName().empty())
14261 Diag(OpLoc, diag::err_unqualified_pointer_member_function)
14262 << op->getSourceRange();
14263 else {
14264 SmallString<32> Str;
14265 StringRef Qual = (MD->getParent()->getName() + "::").toStringRef(Str);
14266 Diag(OpLoc, diag::err_unqualified_pointer_member_function)
14267 << op->getSourceRange()
14268 << FixItHint::CreateInsertion(op->getSourceRange().getBegin(), Qual);
14269 }
14270 }
14271
14272 // Taking the address of a dtor is illegal per C++ [class.dtor]p2.
14273 if (isa<CXXDestructorDecl>(MD))
14274 Diag(OpLoc, diag::err_typecheck_addrof_dtor) << op->getSourceRange();
14275
14276 QualType MPTy = Context.getMemberPointerType(
14277 op->getType(), Context.getTypeDeclType(MD->getParent()).getTypePtr());
14278 // Under the MS ABI, lock down the inheritance model now.
14279 if (Context.getTargetInfo().getCXXABI().isMicrosoft())
14280 (void)isCompleteType(OpLoc, MPTy);
14281 return MPTy;
14282 } else if (lval != Expr::LV_Valid && lval != Expr::LV_IncompleteVoidType) {
14283 // C99 6.5.3.2p1
14284 // The operand must be either an l-value or a function designator
14285 if (!op->getType()->isFunctionType()) {
14286 // Use a special diagnostic for loads from property references.
14287 if (isa<PseudoObjectExpr>(op)) {
14288 AddressOfError = AO_Property_Expansion;
14289 } else {
14290 Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof)
14291 << op->getType() << op->getSourceRange();
14292 return QualType();
14293 }
14294 }
14295 } else if (op->getObjectKind() == OK_BitField) { // C99 6.5.3.2p1
14296 // The operand cannot be a bit-field
14297 AddressOfError = AO_Bit_Field;
14298 } else if (op->getObjectKind() == OK_VectorComponent) {
14299 // The operand cannot be an element of a vector
14300 AddressOfError = AO_Vector_Element;
14301 } else if (op->getObjectKind() == OK_MatrixComponent) {
14302 // The operand cannot be an element of a matrix.
14303 AddressOfError = AO_Matrix_Element;
14304 } else if (dcl) { // C99 6.5.3.2p1
14305 // We have an lvalue with a decl. Make sure the decl is not declared
14306 // with the register storage-class specifier.
14307 if (const VarDecl *vd = dyn_cast<VarDecl>(dcl)) {
14308 // in C++ it is not error to take address of a register
14309 // variable (c++03 7.1.1P3)
14310 if (vd->getStorageClass() == SC_Register &&
14311 !getLangOpts().CPlusPlus) {
14312 AddressOfError = AO_Register_Variable;
14313 }
14314 } else if (isa<MSPropertyDecl>(dcl)) {
14315 AddressOfError = AO_Property_Expansion;
14316 } else if (isa<FunctionTemplateDecl>(dcl)) {
14317 return Context.OverloadTy;
14318 } else if (isa<FieldDecl>(dcl) || isa<IndirectFieldDecl>(dcl)) {
14319 // Okay: we can take the address of a field.
14320 // Could be a pointer to member, though, if there is an explicit
14321 // scope qualifier for the class.
14322 if (isa<DeclRefExpr>(op) && cast<DeclRefExpr>(op)->getQualifier()) {
14323 DeclContext *Ctx = dcl->getDeclContext();
14324 if (Ctx && Ctx->isRecord()) {
14325 if (dcl->getType()->isReferenceType()) {
14326 Diag(OpLoc,
14327 diag::err_cannot_form_pointer_to_member_of_reference_type)
14328 << dcl->getDeclName() << dcl->getType();
14329 return QualType();
14330 }
14331
14332 while (cast<RecordDecl>(Ctx)->isAnonymousStructOrUnion())
14333 Ctx = Ctx->getParent();
14334
14335 QualType MPTy = Context.getMemberPointerType(
14336 op->getType(),
14337 Context.getTypeDeclType(cast<RecordDecl>(Ctx)).getTypePtr());
14338 // Under the MS ABI, lock down the inheritance model now.
14339 if (Context.getTargetInfo().getCXXABI().isMicrosoft())
14340 (void)isCompleteType(OpLoc, MPTy);
14341 return MPTy;
14342 }
14343 }
14344 } else if (!isa<FunctionDecl, NonTypeTemplateParmDecl, BindingDecl,
14345 MSGuidDecl, UnnamedGlobalConstantDecl>(dcl))
14346 llvm_unreachable("Unknown/unexpected decl type")::llvm::llvm_unreachable_internal("Unknown/unexpected decl type"
, "clang/lib/Sema/SemaExpr.cpp", 14346)
;
14347 }
14348
14349 if (AddressOfError != AO_No_Error) {
14350 diagnoseAddressOfInvalidType(*this, OpLoc, op, AddressOfError);
14351 return QualType();
14352 }
14353
14354 if (lval == Expr::LV_IncompleteVoidType) {
14355 // Taking the address of a void variable is technically illegal, but we
14356 // allow it in cases which are otherwise valid.
14357 // Example: "extern void x; void* y = &x;".
14358 Diag(OpLoc, diag::ext_typecheck_addrof_void) << op->getSourceRange();
14359 }
14360
14361 // If the operand has type "type", the result has type "pointer to type".
14362 if (op->getType()->isObjCObjectType())
14363 return Context.getObjCObjectPointerType(op->getType());
14364
14365 CheckAddressOfPackedMember(op);
14366
14367 return Context.getPointerType(op->getType());
14368}
14369
14370static void RecordModifiableNonNullParam(Sema &S, const Expr *Exp) {
14371 const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Exp);
14372 if (!DRE)
14373 return;
14374 const Decl *D = DRE->getDecl();
14375 if (!D)
14376 return;
14377 const ParmVarDecl *Param = dyn_cast<ParmVarDecl>(D);
14378 if (!Param)
14379 return;
14380 if (const FunctionDecl* FD = dyn_cast<FunctionDecl>(Param->getDeclContext()))
14381 if (!FD->hasAttr<NonNullAttr>() && !Param->hasAttr<NonNullAttr>())
14382 return;
14383 if (FunctionScopeInfo *FD = S.getCurFunction())
14384 if (!FD->ModifiedNonNullParams.count(Param))
14385 FD->ModifiedNonNullParams.insert(Param);
14386}
14387
14388/// CheckIndirectionOperand - Type check unary indirection (prefix '*').
14389static QualType CheckIndirectionOperand(Sema &S, Expr *Op, ExprValueKind &VK,
14390 SourceLocation OpLoc) {
14391 if (Op->isTypeDependent())
14392 return S.Context.DependentTy;
14393
14394 ExprResult ConvResult = S.UsualUnaryConversions(Op);
14395 if (ConvResult.isInvalid())
14396 return QualType();
14397 Op = ConvResult.get();
14398 QualType OpTy = Op->getType();
14399 QualType Result;
14400
14401 if (isa<CXXReinterpretCastExpr>(Op)) {
14402 QualType OpOrigType = Op->IgnoreParenCasts()->getType();
14403 S.CheckCompatibleReinterpretCast(OpOrigType, OpTy, /*IsDereference*/true,
14404 Op->getSourceRange());
14405 }
14406
14407 if (const PointerType *PT = OpTy->getAs<PointerType>())
14408 {
14409 Result = PT->getPointeeType();
14410 }
14411 else if (const ObjCObjectPointerType *OPT =
14412 OpTy->getAs<ObjCObjectPointerType>())
14413 Result = OPT->getPointeeType();
14414 else {
14415 ExprResult PR = S.CheckPlaceholderExpr(Op);
14416 if (PR.isInvalid()) return QualType();
14417 if (PR.get() != Op)
14418 return CheckIndirectionOperand(S, PR.get(), VK, OpLoc);
14419 }
14420
14421 if (Result.isNull()) {
14422 S.Diag(OpLoc, diag::err_typecheck_indirection_requires_pointer)
14423 << OpTy << Op->getSourceRange();
14424 return QualType();
14425 }
14426
14427 // Note that per both C89 and C99, indirection is always legal, even if Result
14428 // is an incomplete type or void. It would be possible to warn about
14429 // dereferencing a void pointer, but it's completely well-defined, and such a
14430 // warning is unlikely to catch any mistakes. In C++, indirection is not valid
14431 // for pointers to 'void' but is fine for any other pointer type:
14432 //
14433 // C++ [expr.unary.op]p1:
14434 // [...] the expression to which [the unary * operator] is applied shall
14435 // be a pointer to an object type, or a pointer to a function type
14436 if (S.getLangOpts().CPlusPlus && Result->isVoidType())
14437 S.Diag(OpLoc, diag::ext_typecheck_indirection_through_void_pointer)
14438 << OpTy << Op->getSourceRange();
14439
14440 // Dereferences are usually l-values...
14441 VK = VK_LValue;
14442
14443 // ...except that certain expressions are never l-values in C.
14444 if (!S.getLangOpts().CPlusPlus && Result.isCForbiddenLValueType())
14445 VK = VK_PRValue;
14446
14447 return Result;
14448}
14449
14450BinaryOperatorKind Sema::ConvertTokenKindToBinaryOpcode(tok::TokenKind Kind) {
14451 BinaryOperatorKind Opc;
14452 switch (Kind) {
14453 default: llvm_unreachable("Unknown binop!")::llvm::llvm_unreachable_internal("Unknown binop!", "clang/lib/Sema/SemaExpr.cpp"
, 14453)
;
14454 case tok::periodstar: Opc = BO_PtrMemD; break;
14455 case tok::arrowstar: Opc = BO_PtrMemI; break;
14456 case tok::star: Opc = BO_Mul; break;
14457 case tok::slash: Opc = BO_Div; break;
14458 case tok::percent: Opc = BO_Rem; break;
14459 case tok::plus: Opc = BO_Add; break;
14460 case tok::minus: Opc = BO_Sub; break;
14461 case tok::lessless: Opc = BO_Shl; break;
14462 case tok::greatergreater: Opc = BO_Shr; break;
14463 case tok::lessequal: Opc = BO_LE; break;
14464 case tok::less: Opc = BO_LT; break;
14465 case tok::greaterequal: Opc = BO_GE; break;
14466 case tok::greater: Opc = BO_GT; break;
14467 case tok::exclaimequal: Opc = BO_NE; break;
14468 case tok::equalequal: Opc = BO_EQ; break;
14469 case tok::spaceship: Opc = BO_Cmp; break;
14470 case tok::amp: Opc = BO_And; break;
14471 case tok::caret: Opc = BO_Xor; break;
14472 case tok::pipe: Opc = BO_Or; break;
14473 case tok::ampamp: Opc = BO_LAnd; break;
14474 case tok::pipepipe: Opc = BO_LOr; break;
14475 case tok::equal: Opc = BO_Assign; break;
14476 case tok::starequal: Opc = BO_MulAssign; break;
14477 case tok::slashequal: Opc = BO_DivAssign; break;
14478 case tok::percentequal: Opc = BO_RemAssign; break;
14479 case tok::plusequal: Opc = BO_AddAssign; break;
14480 case tok::minusequal: Opc = BO_SubAssign; break;
14481 case tok::lesslessequal: Opc = BO_ShlAssign; break;
14482 case tok::greatergreaterequal: Opc = BO_ShrAssign; break;
14483 case tok::ampequal: Opc = BO_AndAssign; break;
14484 case tok::caretequal: Opc = BO_XorAssign; break;
14485 case tok::pipeequal: Opc = BO_OrAssign; break;
14486 case tok::comma: Opc = BO_Comma; break;
14487 }
14488 return Opc;
14489}
14490
14491static inline UnaryOperatorKind ConvertTokenKindToUnaryOpcode(
14492 tok::TokenKind Kind) {
14493 UnaryOperatorKind Opc;
14494 switch (Kind) {
14495 default: llvm_unreachable("Unknown unary op!")::llvm::llvm_unreachable_internal("Unknown unary op!", "clang/lib/Sema/SemaExpr.cpp"
, 14495)
;
14496 case tok::plusplus: Opc = UO_PreInc; break;
14497 case tok::minusminus: Opc = UO_PreDec; break;
14498 case tok::amp: Opc = UO_AddrOf; break;
14499 case tok::star: Opc = UO_Deref; break;
14500 case tok::plus: Opc = UO_Plus; break;
14501 case tok::minus: Opc = UO_Minus; break;
14502 case tok::tilde: Opc = UO_Not; break;
14503 case tok::exclaim: Opc = UO_LNot; break;
14504 case tok::kw___real: Opc = UO_Real; break;
14505 case tok::kw___imag: Opc = UO_Imag; break;
14506 case tok::kw___extension__: Opc = UO_Extension; break;
14507 }
14508 return Opc;
14509}
14510
14511/// DiagnoseSelfAssignment - Emits a warning if a value is assigned to itself.
14512/// This warning suppressed in the event of macro expansions.
14513static void DiagnoseSelfAssignment(Sema &S, Expr *LHSExpr, Expr *RHSExpr,
14514 SourceLocation OpLoc, bool IsBuiltin) {
14515 if (S.inTemplateInstantiation())
14516 return;
14517 if (S.isUnevaluatedContext())
14518 return;
14519 if (OpLoc.isInvalid() || OpLoc.isMacroID())
14520 return;
14521 LHSExpr = LHSExpr->IgnoreParenImpCasts();
14522 RHSExpr = RHSExpr->IgnoreParenImpCasts();
14523 const DeclRefExpr *LHSDeclRef = dyn_cast<DeclRefExpr>(LHSExpr);
14524 const DeclRefExpr *RHSDeclRef = dyn_cast<DeclRefExpr>(RHSExpr);
14525 if (!LHSDeclRef || !RHSDeclRef ||
14526 LHSDeclRef->getLocation().isMacroID() ||
14527 RHSDeclRef->getLocation().isMacroID())
14528 return;
14529 const ValueDecl *LHSDecl =
14530 cast<ValueDecl>(LHSDeclRef->getDecl()->getCanonicalDecl());
14531 const ValueDecl *RHSDecl =
14532 cast<ValueDecl>(RHSDeclRef->getDecl()->getCanonicalDecl());
14533 if (LHSDecl != RHSDecl)
14534 return;
14535 if (LHSDecl->getType().isVolatileQualified())
14536 return;
14537 if (const ReferenceType *RefTy = LHSDecl->getType()->getAs<ReferenceType>())
14538 if (RefTy->getPointeeType().isVolatileQualified())
14539 return;
14540
14541 S.Diag(OpLoc, IsBuiltin ? diag::warn_self_assignment_builtin
14542 : diag::warn_self_assignment_overloaded)
14543 << LHSDeclRef->getType() << LHSExpr->getSourceRange()
14544 << RHSExpr->getSourceRange();
14545}
14546
14547/// Check if a bitwise-& is performed on an Objective-C pointer. This
14548/// is usually indicative of introspection within the Objective-C pointer.
14549static void checkObjCPointerIntrospection(Sema &S, ExprResult &L, ExprResult &R,
14550 SourceLocation OpLoc) {
14551 if (!S.getLangOpts().ObjC)
14552 return;
14553
14554 const Expr *ObjCPointerExpr = nullptr, *OtherExpr = nullptr;
14555 const Expr *LHS = L.get();
14556 const Expr *RHS = R.get();
14557
14558 if (LHS->IgnoreParenCasts()->getType()->isObjCObjectPointerType()) {
14559 ObjCPointerExpr = LHS;
14560 OtherExpr = RHS;
14561 }
14562 else if (RHS->IgnoreParenCasts()->getType()->isObjCObjectPointerType()) {
14563 ObjCPointerExpr = RHS;
14564 OtherExpr = LHS;
14565 }
14566
14567 // This warning is deliberately made very specific to reduce false
14568 // positives with logic that uses '&' for hashing. This logic mainly
14569 // looks for code trying to introspect into tagged pointers, which
14570 // code should generally never do.
14571 if (ObjCPointerExpr && isa<IntegerLiteral>(OtherExpr->IgnoreParenCasts())) {
14572 unsigned Diag = diag::warn_objc_pointer_masking;
14573 // Determine if we are introspecting the result of performSelectorXXX.
14574 const Expr *Ex = ObjCPointerExpr->IgnoreParenCasts();
14575 // Special case messages to -performSelector and friends, which
14576 // can return non-pointer values boxed in a pointer value.
14577 // Some clients may wish to silence warnings in this subcase.
14578 if (const ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(Ex)) {
14579 Selector S = ME->getSelector();
14580 StringRef SelArg0 = S.getNameForSlot(0);
14581 if (SelArg0.startswith("performSelector"))
14582 Diag = diag::warn_objc_pointer_masking_performSelector;
14583 }
14584
14585 S.Diag(OpLoc, Diag)
14586 << ObjCPointerExpr->getSourceRange();
14587 }
14588}
14589
14590static NamedDecl *getDeclFromExpr(Expr *E) {
14591 if (!E)
14592 return nullptr;
14593 if (auto *DRE = dyn_cast<DeclRefExpr>(E))
14594 return DRE->getDecl();
14595 if (auto *ME = dyn_cast<MemberExpr>(E))
14596 return ME->getMemberDecl();
14597 if (auto *IRE = dyn_cast<ObjCIvarRefExpr>(E))
14598 return IRE->getDecl();
14599 return nullptr;
14600}
14601
14602// This helper function promotes a binary operator's operands (which are of a
14603// half vector type) to a vector of floats and then truncates the result to
14604// a vector of either half or short.
14605static ExprResult convertHalfVecBinOp(Sema &S, ExprResult LHS, ExprResult RHS,
14606 BinaryOperatorKind Opc, QualType ResultTy,
14607 ExprValueKind VK, ExprObjectKind OK,
14608 bool IsCompAssign, SourceLocation OpLoc,
14609 FPOptionsOverride FPFeatures) {
14610 auto &Context = S.getASTContext();
14611 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", 14613, __extension__ __PRETTY_FUNCTION__
))
14612 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", 14613, __extension__ __PRETTY_FUNCTION__
))
14613 "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", 14613, __extension__ __PRETTY_FUNCTION__
))
;
14614 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", 14616, __extension__ __PRETTY_FUNCTION__
))
14615 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", 14616, __extension__ __PRETTY_FUNCTION__
))
14616 "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", 14616, __extension__ __PRETTY_FUNCTION__
))
;
14617
14618 RHS = convertVector(RHS.get(), Context.FloatTy, S);
14619 QualType BinOpResTy = RHS.get()->getType();
14620
14621 // If Opc is a comparison, ResultType is a vector of shorts. In that case,
14622 // change BinOpResTy to a vector of ints.
14623 if (isVector(ResultTy, Context.ShortTy))
14624 BinOpResTy = S.GetSignedVectorType(BinOpResTy);
14625
14626 if (IsCompAssign)
14627 return CompoundAssignOperator::Create(Context, LHS.get(), RHS.get(), Opc,
14628 ResultTy, VK, OK, OpLoc, FPFeatures,
14629 BinOpResTy, BinOpResTy);
14630
14631 LHS = convertVector(LHS.get(), Context.FloatTy, S);
14632 auto *BO = BinaryOperator::Create(Context, LHS.get(), RHS.get(), Opc,
14633 BinOpResTy, VK, OK, OpLoc, FPFeatures);
14634 return convertVector(BO, ResultTy->castAs<VectorType>()->getElementType(), S);
14635}
14636
14637static std::pair<ExprResult, ExprResult>
14638CorrectDelayedTyposInBinOp(Sema &S, BinaryOperatorKind Opc, Expr *LHSExpr,
14639 Expr *RHSExpr) {
14640 ExprResult LHS = LHSExpr, RHS = RHSExpr;
14641 if (!S.Context.isDependenceAllowed()) {
14642 // C cannot handle TypoExpr nodes on either side of a binop because it
14643 // doesn't handle dependent types properly, so make sure any TypoExprs have
14644 // been dealt with before checking the operands.
14645 LHS = S.CorrectDelayedTyposInExpr(LHS);
14646 RHS = S.CorrectDelayedTyposInExpr(
14647 RHS, /*InitDecl=*/nullptr, /*RecoverUncorrectedTypos=*/false,
14648 [Opc, LHS](Expr *E) {
14649 if (Opc != BO_Assign)
14650 return ExprResult(E);
14651 // Avoid correcting the RHS to the same Expr as the LHS.
14652 Decl *D = getDeclFromExpr(E);
14653 return (D && D == getDeclFromExpr(LHS.get())) ? ExprError() : E;
14654 });
14655 }
14656 return std::make_pair(LHS, RHS);
14657}
14658
14659/// Returns true if conversion between vectors of halfs and vectors of floats
14660/// is needed.
14661static bool needsConversionOfHalfVec(bool OpRequiresConversion, ASTContext &Ctx,
14662 Expr *E0, Expr *E1 = nullptr) {
14663 if (!OpRequiresConversion || Ctx.getLangOpts().NativeHalfType ||
14664 Ctx.getTargetInfo().useFP16ConversionIntrinsics())
14665 return false;
14666
14667 auto HasVectorOfHalfType = [&Ctx](Expr *E) {
14668 QualType Ty = E->IgnoreImplicit()->getType();
14669
14670 // Don't promote half precision neon vectors like float16x4_t in arm_neon.h
14671 // to vectors of floats. Although the element type of the vectors is __fp16,
14672 // the vectors shouldn't be treated as storage-only types. See the
14673 // discussion here: https://reviews.llvm.org/rG825235c140e7
14674 if (const VectorType *VT = Ty->getAs<VectorType>()) {
14675 if (VT->getVectorKind() == VectorType::NeonVector)
14676 return false;
14677 return VT->getElementType().getCanonicalType() == Ctx.HalfTy;
14678 }
14679 return false;
14680 };
14681
14682 return HasVectorOfHalfType(E0) && (!E1 || HasVectorOfHalfType(E1));
14683}
14684
14685/// CreateBuiltinBinOp - Creates a new built-in binary operation with
14686/// operator @p Opc at location @c TokLoc. This routine only supports
14687/// built-in operations; ActOnBinOp handles overloaded operators.
14688ExprResult Sema::CreateBuiltinBinOp(SourceLocation OpLoc,
14689 BinaryOperatorKind Opc,
14690 Expr *LHSExpr, Expr *RHSExpr) {
14691 if (getLangOpts().CPlusPlus11 && isa<InitListExpr>(RHSExpr)) {
14692 // The syntax only allows initializer lists on the RHS of assignment,
14693 // so we don't need to worry about accepting invalid code for
14694 // non-assignment operators.
14695 // C++11 5.17p9:
14696 // The meaning of x = {v} [...] is that of x = T(v) [...]. The meaning
14697 // of x = {} is x = T().
14698 InitializationKind Kind = InitializationKind::CreateDirectList(
14699 RHSExpr->getBeginLoc(), RHSExpr->getBeginLoc(), RHSExpr->getEndLoc());
14700 InitializedEntity Entity =
14701 InitializedEntity::InitializeTemporary(LHSExpr->getType());
14702 InitializationSequence InitSeq(*this, Entity, Kind, RHSExpr);
14703 ExprResult Init = InitSeq.Perform(*this, Entity, Kind, RHSExpr);
14704 if (Init.isInvalid())
14705 return Init;
14706 RHSExpr = Init.get();
14707 }
14708
14709 ExprResult LHS = LHSExpr, RHS = RHSExpr;
14710 QualType ResultTy; // Result type of the binary operator.
14711 // The following two variables are used for compound assignment operators
14712 QualType CompLHSTy; // Type of LHS after promotions for computation
14713 QualType CompResultTy; // Type of computation result
14714 ExprValueKind VK = VK_PRValue;
14715 ExprObjectKind OK = OK_Ordinary;
14716 bool ConvertHalfVec = false;
14717
14718 std::tie(LHS, RHS) = CorrectDelayedTyposInBinOp(*this, Opc, LHSExpr, RHSExpr);
14719 if (!LHS.isUsable() || !RHS.isUsable())
14720 return ExprError();
14721
14722 if (getLangOpts().OpenCL) {
14723 QualType LHSTy = LHSExpr->getType();
14724 QualType RHSTy = RHSExpr->getType();
14725 // OpenCLC v2.0 s6.13.11.1 allows atomic variables to be initialized by
14726 // the ATOMIC_VAR_INIT macro.
14727 if (LHSTy->isAtomicType() || RHSTy->isAtomicType()) {
14728 SourceRange SR(LHSExpr->getBeginLoc(), RHSExpr->getEndLoc());
14729 if (BO_Assign == Opc)
14730 Diag(OpLoc, diag::err_opencl_atomic_init) << 0 << SR;
14731 else
14732 ResultTy = InvalidOperands(OpLoc, LHS, RHS);
14733 return ExprError();
14734 }
14735
14736 // OpenCL special types - image, sampler, pipe, and blocks are to be used
14737 // only with a builtin functions and therefore should be disallowed here.
14738 if (LHSTy->isImageType() || RHSTy->isImageType() ||
14739 LHSTy->isSamplerT() || RHSTy->isSamplerT() ||
14740 LHSTy->isPipeType() || RHSTy->isPipeType() ||
14741 LHSTy->isBlockPointerType() || RHSTy->isBlockPointerType()) {
14742 ResultTy = InvalidOperands(OpLoc, LHS, RHS);
14743 return ExprError();
14744 }
14745 }
14746
14747 checkTypeSupport(LHSExpr->getType(), OpLoc, /*ValueDecl*/ nullptr);
14748 checkTypeSupport(RHSExpr->getType(), OpLoc, /*ValueDecl*/ nullptr);
14749
14750 switch (Opc) {
14751 case BO_Assign:
14752 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, QualType());
14753 if (getLangOpts().CPlusPlus &&
14754 LHS.get()->getObjectKind() != OK_ObjCProperty) {
14755 VK = LHS.get()->getValueKind();
14756 OK = LHS.get()->getObjectKind();
14757 }
14758 if (!ResultTy.isNull()) {
14759 DiagnoseSelfAssignment(*this, LHS.get(), RHS.get(), OpLoc, true);
14760 DiagnoseSelfMove(LHS.get(), RHS.get(), OpLoc);
14761
14762 // Avoid copying a block to the heap if the block is assigned to a local
14763 // auto variable that is declared in the same scope as the block. This
14764 // optimization is unsafe if the local variable is declared in an outer
14765 // scope. For example:
14766 //
14767 // BlockTy b;
14768 // {
14769 // b = ^{...};
14770 // }
14771 // // It is unsafe to invoke the block here if it wasn't copied to the
14772 // // heap.
14773 // b();
14774
14775 if (auto *BE = dyn_cast<BlockExpr>(RHS.get()->IgnoreParens()))
14776 if (auto *DRE = dyn_cast<DeclRefExpr>(LHS.get()->IgnoreParens()))
14777 if (auto *VD = dyn_cast<VarDecl>(DRE->getDecl()))
14778 if (VD->hasLocalStorage() && getCurScope()->isDeclScope(VD))
14779 BE->getBlockDecl()->setCanAvoidCopyToHeap();
14780
14781 if (LHS.get()->getType().hasNonTrivialToPrimitiveCopyCUnion())
14782 checkNonTrivialCUnion(LHS.get()->getType(), LHS.get()->getExprLoc(),
14783 NTCUC_Assignment, NTCUK_Copy);
14784 }
14785 RecordModifiableNonNullParam(*this, LHS.get());
14786 break;
14787 case BO_PtrMemD:
14788 case BO_PtrMemI:
14789 ResultTy = CheckPointerToMemberOperands(LHS, RHS, VK, OpLoc,
14790 Opc == BO_PtrMemI);
14791 break;
14792 case BO_Mul:
14793 case BO_Div:
14794 ConvertHalfVec = true;
14795 ResultTy = CheckMultiplyDivideOperands(LHS, RHS, OpLoc, false,
14796 Opc == BO_Div);
14797 break;
14798 case BO_Rem:
14799 ResultTy = CheckRemainderOperands(LHS, RHS, OpLoc);
14800 break;
14801 case BO_Add:
14802 ConvertHalfVec = true;
14803 ResultTy = CheckAdditionOperands(LHS, RHS, OpLoc, Opc);
14804 break;
14805 case BO_Sub:
14806 ConvertHalfVec = true;
14807 ResultTy = CheckSubtractionOperands(LHS, RHS, OpLoc);
14808 break;
14809 case BO_Shl:
14810 case BO_Shr:
14811 ResultTy = CheckShiftOperands(LHS, RHS, OpLoc, Opc);
14812 break;
14813 case BO_LE:
14814 case BO_LT:
14815 case BO_GE:
14816 case BO_GT:
14817 ConvertHalfVec = true;
14818 ResultTy = CheckCompareOperands(LHS, RHS, OpLoc, Opc);
14819 break;
14820 case BO_EQ:
14821 case BO_NE:
14822 ConvertHalfVec = true;
14823 ResultTy = CheckCompareOperands(LHS, RHS, OpLoc, Opc);
14824 break;
14825 case BO_Cmp:
14826 ConvertHalfVec = true;
14827 ResultTy = CheckCompareOperands(LHS, RHS, OpLoc, Opc);
14828 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", 14828, __extension__ __PRETTY_FUNCTION__
))
;
14829 break;
14830 case BO_And:
14831 checkObjCPointerIntrospection(*this, LHS, RHS, OpLoc);
14832 LLVM_FALLTHROUGH[[gnu::fallthrough]];
14833 case BO_Xor:
14834 case BO_Or:
14835 ResultTy = CheckBitwiseOperands(LHS, RHS, OpLoc, Opc);
14836 break;
14837 case BO_LAnd:
14838 case BO_LOr:
14839 ConvertHalfVec = true;
14840 ResultTy = CheckLogicalOperands(LHS, RHS, OpLoc, Opc);
14841 break;
14842 case BO_MulAssign:
14843 case BO_DivAssign:
14844 ConvertHalfVec = true;
14845 CompResultTy = CheckMultiplyDivideOperands(LHS, RHS, OpLoc, true,
14846 Opc == BO_DivAssign);
14847 CompLHSTy = CompResultTy;
14848 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
14849 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
14850 break;
14851 case BO_RemAssign:
14852 CompResultTy = CheckRemainderOperands(LHS, RHS, OpLoc, true);
14853 CompLHSTy = CompResultTy;
14854 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
14855 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
14856 break;
14857 case BO_AddAssign:
14858 ConvertHalfVec = true;
14859 CompResultTy = CheckAdditionOperands(LHS, RHS, OpLoc, Opc, &CompLHSTy);
14860 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
14861 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
14862 break;
14863 case BO_SubAssign:
14864 ConvertHalfVec = true;
14865 CompResultTy = CheckSubtractionOperands(LHS, RHS, OpLoc, &CompLHSTy);
14866 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
14867 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
14868 break;
14869 case BO_ShlAssign:
14870 case BO_ShrAssign:
14871 CompResultTy = CheckShiftOperands(LHS, RHS, OpLoc, Opc, true);
14872 CompLHSTy = CompResultTy;
14873 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
14874 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
14875 break;
14876 case BO_AndAssign:
14877 case BO_OrAssign: // fallthrough
14878 DiagnoseSelfAssignment(*this, LHS.get(), RHS.get(), OpLoc, true);
14879 LLVM_FALLTHROUGH[[gnu::fallthrough]];
14880 case BO_XorAssign:
14881 CompResultTy = CheckBitwiseOperands(LHS, RHS, OpLoc, Opc);
14882 CompLHSTy = CompResultTy;
14883 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
14884 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
14885 break;
14886 case BO_Comma:
14887 ResultTy = CheckCommaOperands(*this, LHS, RHS, OpLoc);
14888 if (getLangOpts().CPlusPlus && !RHS.isInvalid()) {
14889 VK = RHS.get()->getValueKind();
14890 OK = RHS.get()->getObjectKind();
14891 }
14892 break;
14893 }
14894 if (ResultTy.isNull() || LHS.isInvalid() || RHS.isInvalid())
14895 return ExprError();
14896
14897 // Some of the binary operations require promoting operands of half vector to
14898 // float vectors and truncating the result back to half vector. For now, we do
14899 // this only when HalfArgsAndReturn is set (that is, when the target is arm or
14900 // arm64).
14901 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", 14904, __extension__ __PRETTY_FUNCTION__
))
14902 (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", 14904, __extension__ __PRETTY_FUNCTION__
))
14903 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", 14904, __extension__ __PRETTY_FUNCTION__
))
14904 "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", 14904, __extension__ __PRETTY_FUNCTION__
))
;
14905 ConvertHalfVec =
14906 needsConversionOfHalfVec(ConvertHalfVec, Context, LHS.get(), RHS.get());
14907
14908 // Check for array bounds violations for both sides of the BinaryOperator
14909 CheckArrayAccess(LHS.get());
14910 CheckArrayAccess(RHS.get());
14911
14912 if (const ObjCIsaExpr *OISA = dyn_cast<ObjCIsaExpr>(LHS.get()->IgnoreParenCasts())) {
14913 NamedDecl *ObjectSetClass = LookupSingleName(TUScope,
14914 &Context.Idents.get("object_setClass"),
14915 SourceLocation(), LookupOrdinaryName);
14916 if (ObjectSetClass && isa<ObjCIsaExpr>(LHS.get())) {
14917 SourceLocation RHSLocEnd = getLocForEndOfToken(RHS.get()->getEndLoc());
14918 Diag(LHS.get()->getExprLoc(), diag::warn_objc_isa_assign)
14919 << FixItHint::CreateInsertion(LHS.get()->getBeginLoc(),
14920 "object_setClass(")
14921 << FixItHint::CreateReplacement(SourceRange(OISA->getOpLoc(), OpLoc),
14922 ",")
14923 << FixItHint::CreateInsertion(RHSLocEnd, ")");
14924 }
14925 else
14926 Diag(LHS.get()->getExprLoc(), diag::warn_objc_isa_assign);
14927 }
14928 else if (const ObjCIvarRefExpr *OIRE =
14929 dyn_cast<ObjCIvarRefExpr>(LHS.get()->IgnoreParenCasts()))
14930 DiagnoseDirectIsaAccess(*this, OIRE, OpLoc, RHS.get());
14931
14932 // Opc is not a compound assignment if CompResultTy is null.
14933 if (CompResultTy.isNull()) {
14934 if (ConvertHalfVec)
14935 return convertHalfVecBinOp(*this, LHS, RHS, Opc, ResultTy, VK, OK, false,
14936 OpLoc, CurFPFeatureOverrides());
14937 return BinaryOperator::Create(Context, LHS.get(), RHS.get(), Opc, ResultTy,
14938 VK, OK, OpLoc, CurFPFeatureOverrides());
14939 }
14940
14941 // Handle compound assignments.
14942 if (getLangOpts().CPlusPlus && LHS.get()->getObjectKind() !=
14943 OK_ObjCProperty) {
14944 VK = VK_LValue;
14945 OK = LHS.get()->getObjectKind();
14946 }
14947
14948 // The LHS is not converted to the result type for fixed-point compound
14949 // assignment as the common type is computed on demand. Reset the CompLHSTy
14950 // to the LHS type we would have gotten after unary conversions.
14951 if (CompResultTy->isFixedPointType())
14952 CompLHSTy = UsualUnaryConversions(LHS.get()).get()->getType();
14953
14954 if (ConvertHalfVec)
14955 return convertHalfVecBinOp(*this, LHS, RHS, Opc, ResultTy, VK, OK, true,
14956 OpLoc, CurFPFeatureOverrides());
14957
14958 return CompoundAssignOperator::Create(
14959 Context, LHS.get(), RHS.get(), Opc, ResultTy, VK, OK, OpLoc,
14960 CurFPFeatureOverrides(), CompLHSTy, CompResultTy);
14961}
14962
14963/// DiagnoseBitwisePrecedence - Emit a warning when bitwise and comparison
14964/// operators are mixed in a way that suggests that the programmer forgot that
14965/// comparison operators have higher precedence. The most typical example of
14966/// such code is "flags & 0x0020 != 0", which is equivalent to "flags & 1".
14967static void DiagnoseBitwisePrecedence(Sema &Self, BinaryOperatorKind Opc,
14968 SourceLocation OpLoc, Expr *LHSExpr,
14969 Expr *RHSExpr) {
14970 BinaryOperator *LHSBO = dyn_cast<BinaryOperator>(LHSExpr);
14971 BinaryOperator *RHSBO = dyn_cast<BinaryOperator>(RHSExpr);
14972
14973 // Check that one of the sides is a comparison operator and the other isn't.
14974 bool isLeftComp = LHSBO && LHSBO->isComparisonOp();
14975 bool isRightComp = RHSBO && RHSBO->isComparisonOp();
14976 if (isLeftComp == isRightComp)
14977 return;
14978
14979 // Bitwise operations are sometimes used as eager logical ops.
14980 // Don't diagnose this.
14981 bool isLeftBitwise = LHSBO && LHSBO->isBitwiseOp();
14982 bool isRightBitwise = RHSBO && RHSBO->isBitwiseOp();
14983 if (isLeftBitwise || isRightBitwise)
14984 return;
14985
14986 SourceRange DiagRange = isLeftComp
14987 ? SourceRange(LHSExpr->getBeginLoc(), OpLoc)
14988 : SourceRange(OpLoc, RHSExpr->getEndLoc());
14989 StringRef OpStr = isLeftComp ? LHSBO->getOpcodeStr() : RHSBO->getOpcodeStr();
14990 SourceRange ParensRange =
14991 isLeftComp
14992 ? SourceRange(LHSBO->getRHS()->getBeginLoc(), RHSExpr->getEndLoc())
14993 : SourceRange(LHSExpr->getBeginLoc(), RHSBO->getLHS()->getEndLoc());
14994
14995 Self.Diag(OpLoc, diag::warn_precedence_bitwise_rel)
14996 << DiagRange << BinaryOperator::getOpcodeStr(Opc) << OpStr;
14997 SuggestParentheses(Self, OpLoc,
14998 Self.PDiag(diag::note_precedence_silence) << OpStr,
14999 (isLeftComp ? LHSExpr : RHSExpr)->getSourceRange());
15000 SuggestParentheses(Self, OpLoc,
15001 Self.PDiag(diag::note_precedence_bitwise_first)
15002 << BinaryOperator::getOpcodeStr(Opc),
15003 ParensRange);
15004}
15005
15006/// It accepts a '&&' expr that is inside a '||' one.
15007/// Emit a diagnostic together with a fixit hint that wraps the '&&' expression
15008/// in parentheses.
15009static void
15010EmitDiagnosticForLogicalAndInLogicalOr(Sema &Self, SourceLocation OpLoc,
15011 BinaryOperator *Bop) {
15012 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"
, 15012, __extension__ __PRETTY_FUNCTION__))
;
15013 Self.Diag(Bop->getOperatorLoc(), diag::warn_logical_and_in_logical_or)
15014 << Bop->getSourceRange() << OpLoc;
15015 SuggestParentheses(Self, Bop->getOperatorLoc(),
15016 Self.PDiag(diag::note_precedence_silence)
15017 << Bop->getOpcodeStr(),
15018 Bop->getSourceRange());
15019}
15020
15021/// Returns true if the given expression can be evaluated as a constant
15022/// 'true'.
15023static bool EvaluatesAsTrue(Sema &S, Expr *E) {
15024 bool Res;
15025 return !E->isValueDependent() &&
15026 E->EvaluateAsBooleanCondition(Res, S.getASTContext()) && Res;
15027}
15028
15029/// Returns true if the given expression can be evaluated as a constant
15030/// 'false'.
15031static bool EvaluatesAsFalse(Sema &S, Expr *E) {
15032 bool Res;
15033 return !E->isValueDependent() &&
15034 E->EvaluateAsBooleanCondition(Res, S.getASTContext()) && !Res;
15035}
15036
15037/// Look for '&&' in the left hand of a '||' expr.
15038static void DiagnoseLogicalAndInLogicalOrLHS(Sema &S, SourceLocation OpLoc,
15039 Expr *LHSExpr, Expr *RHSExpr) {
15040 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(LHSExpr)) {
15041 if (Bop->getOpcode() == BO_LAnd) {
15042 // If it's "a && b || 0" don't warn since the precedence doesn't matter.
15043 if (EvaluatesAsFalse(S, RHSExpr))
15044 return;
15045 // If it's "1 && a || b" don't warn since the precedence doesn't matter.
15046 if (!EvaluatesAsTrue(S, Bop->getLHS()))
15047 return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, Bop);
15048 } else if (Bop->getOpcode() == BO_LOr) {
15049 if (BinaryOperator *RBop = dyn_cast<BinaryOperator>(Bop->getRHS())) {
15050 // If it's "a || b && 1 || c" we didn't warn earlier for
15051 // "a || b && 1", but warn now.
15052 if (RBop->getOpcode() == BO_LAnd && EvaluatesAsTrue(S, RBop->getRHS()))
15053 return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, RBop);
15054 }
15055 }
15056 }
15057}
15058
15059/// Look for '&&' in the right hand of a '||' expr.
15060static void DiagnoseLogicalAndInLogicalOrRHS(Sema &S, SourceLocation OpLoc,
15061 Expr *LHSExpr, Expr *RHSExpr) {
15062 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(RHSExpr)) {
15063 if (Bop->getOpcode() == BO_LAnd) {
15064 // If it's "0 || a && b" don't warn since the precedence doesn't matter.
15065 if (EvaluatesAsFalse(S, LHSExpr))
15066 return;
15067 // If it's "a || b && 1" don't warn since the precedence doesn't matter.
15068 if (!EvaluatesAsTrue(S, Bop->getRHS()))
15069 return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, Bop);
15070 }
15071 }
15072}
15073
15074/// Look for bitwise op in the left or right hand of a bitwise op with
15075/// lower precedence and emit a diagnostic together with a fixit hint that wraps
15076/// the '&' expression in parentheses.
15077static void DiagnoseBitwiseOpInBitwiseOp(Sema &S, BinaryOperatorKind Opc,
15078 SourceLocation OpLoc, Expr *SubExpr) {
15079 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(SubExpr)) {
15080 if (Bop->isBitwiseOp() && Bop->getOpcode() < Opc) {
15081 S.Diag(Bop->getOperatorLoc(), diag::warn_bitwise_op_in_bitwise_op)
15082 << Bop->getOpcodeStr() << BinaryOperator::getOpcodeStr(Opc)
15083 << Bop->getSourceRange() << OpLoc;
15084 SuggestParentheses(S, Bop->getOperatorLoc(),
15085 S.PDiag(diag::note_precedence_silence)
15086 << Bop->getOpcodeStr(),
15087 Bop->getSourceRange());
15088 }
15089 }
15090}
15091
15092static void DiagnoseAdditionInShift(Sema &S, SourceLocation OpLoc,
15093 Expr *SubExpr, StringRef Shift) {
15094 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(SubExpr)) {
15095 if (Bop->getOpcode() == BO_Add || Bop->getOpcode() == BO_Sub) {
15096 StringRef Op = Bop->getOpcodeStr();
15097 S.Diag(Bop->getOperatorLoc(), diag::warn_addition_in_bitshift)
15098 << Bop->getSourceRange() << OpLoc << Shift << Op;
15099 SuggestParentheses(S, Bop->getOperatorLoc(),
15100 S.PDiag(diag::note_precedence_silence) << Op,
15101 Bop->getSourceRange());
15102 }
15103 }
15104}
15105
15106static void DiagnoseShiftCompare(Sema &S, SourceLocation OpLoc,
15107 Expr *LHSExpr, Expr *RHSExpr) {
15108 CXXOperatorCallExpr *OCE = dyn_cast<CXXOperatorCallExpr>(LHSExpr);
15109 if (!OCE)
15110 return;
15111
15112 FunctionDecl *FD = OCE->getDirectCallee();
15113 if (!FD || !FD->isOverloadedOperator())
15114 return;
15115
15116 OverloadedOperatorKind Kind = FD->getOverloadedOperator();
15117 if (Kind != OO_LessLess && Kind != OO_GreaterGreater)
15118 return;
15119
15120 S.Diag(OpLoc, diag::warn_overloaded_shift_in_comparison)
15121 << LHSExpr->getSourceRange() << RHSExpr->getSourceRange()
15122 << (Kind == OO_LessLess);
15123 SuggestParentheses(S, OCE->getOperatorLoc(),
15124 S.PDiag(diag::note_precedence_silence)
15125 << (Kind == OO_LessLess ? "<<" : ">>"),
15126 OCE->getSourceRange());
15127 SuggestParentheses(
15128 S, OpLoc, S.PDiag(diag::note_evaluate_comparison_first),
15129 SourceRange(OCE->getArg(1)->getBeginLoc(), RHSExpr->getEndLoc()));
15130}
15131
15132/// DiagnoseBinOpPrecedence - Emit warnings for expressions with tricky
15133/// precedence.
15134static void DiagnoseBinOpPrecedence(Sema &Self, BinaryOperatorKind Opc,
15135 SourceLocation OpLoc, Expr *LHSExpr,
15136 Expr *RHSExpr){
15137 // Diagnose "arg1 'bitwise' arg2 'eq' arg3".
15138 if (BinaryOperator::isBitwiseOp(Opc))
15139 DiagnoseBitwisePrecedence(Self, Opc, OpLoc, LHSExpr, RHSExpr);
15140
15141 // Diagnose "arg1 & arg2 | arg3"
15142 if ((Opc == BO_Or || Opc == BO_Xor) &&
15143 !OpLoc.isMacroID()/* Don't warn in macros. */) {
15144 DiagnoseBitwiseOpInBitwiseOp(Self, Opc, OpLoc, LHSExpr);
15145 DiagnoseBitwiseOpInBitwiseOp(Self, Opc, OpLoc, RHSExpr);
15146 }
15147
15148 // Warn about arg1 || arg2 && arg3, as GCC 4.3+ does.
15149 // We don't warn for 'assert(a || b && "bad")' since this is safe.
15150 if (Opc == BO_LOr && !OpLoc.isMacroID()/* Don't warn in macros. */) {
15151 DiagnoseLogicalAndInLogicalOrLHS(Self, OpLoc, LHSExpr, RHSExpr);
15152 DiagnoseLogicalAndInLogicalOrRHS(Self, OpLoc, LHSExpr, RHSExpr);
15153 }
15154
15155 if ((Opc == BO_Shl && LHSExpr->getType()->isIntegralType(Self.getASTContext()))
15156 || Opc == BO_Shr) {
15157 StringRef Shift = BinaryOperator::getOpcodeStr(Opc);
15158 DiagnoseAdditionInShift(Self, OpLoc, LHSExpr, Shift);
15159 DiagnoseAdditionInShift(Self, OpLoc, RHSExpr, Shift);
15160 }
15161
15162 // Warn on overloaded shift operators and comparisons, such as:
15163 // cout << 5 == 4;
15164 if (BinaryOperator::isComparisonOp(Opc))
15165 DiagnoseShiftCompare(Self, OpLoc, LHSExpr, RHSExpr);
15166}
15167
15168// Binary Operators. 'Tok' is the token for the operator.
15169ExprResult Sema::ActOnBinOp(Scope *S, SourceLocation TokLoc,
15170 tok::TokenKind Kind,
15171 Expr *LHSExpr, Expr *RHSExpr) {
15172 BinaryOperatorKind Opc = ConvertTokenKindToBinaryOpcode(Kind);
15173 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", 15173, __extension__ __PRETTY_FUNCTION__
))
;
15174 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", 15174, __extension__ __PRETTY_FUNCTION__
))
;
15175
15176 // Emit warnings for tricky precedence issues, e.g. "bitfield & 0x4 == 0"
15177 DiagnoseBinOpPrecedence(*this, Opc, TokLoc, LHSExpr, RHSExpr);
15178
15179 return BuildBinOp(S, TokLoc, Opc, LHSExpr, RHSExpr);
15180}
15181
15182void Sema::LookupBinOp(Scope *S, SourceLocation OpLoc, BinaryOperatorKind Opc,
15183 UnresolvedSetImpl &Functions) {
15184 OverloadedOperatorKind OverOp = BinaryOperator::getOverloadedOperator(Opc);
15185 if (OverOp != OO_None && OverOp != OO_Equal)
15186 LookupOverloadedOperatorName(OverOp, S, Functions);
15187
15188 // In C++20 onwards, we may have a second operator to look up.
15189 if (getLangOpts().CPlusPlus20) {
15190 if (OverloadedOperatorKind ExtraOp = getRewrittenOverloadedOperator(OverOp))
15191 LookupOverloadedOperatorName(ExtraOp, S, Functions);
15192 }
15193}
15194
15195/// Build an overloaded binary operator expression in the given scope.
15196static ExprResult BuildOverloadedBinOp(Sema &S, Scope *Sc, SourceLocation OpLoc,
15197 BinaryOperatorKind Opc,
15198 Expr *LHS, Expr *RHS) {
15199 switch (Opc) {
15200 case BO_Assign:
15201 case BO_DivAssign:
15202 case BO_RemAssign:
15203 case BO_SubAssign:
15204 case BO_AndAssign:
15205 case BO_OrAssign:
15206 case BO_XorAssign:
15207 DiagnoseSelfAssignment(S, LHS, RHS, OpLoc, false);
15208 CheckIdentityFieldAssignment(LHS, RHS, OpLoc, S);
15209 break;
15210 default:
15211 break;
15212 }
15213
15214 // Find all of the overloaded operators visible from this point.
15215 UnresolvedSet<16> Functions;
15216 S.LookupBinOp(Sc, OpLoc, Opc, Functions);
15217
15218 // Build the (potentially-overloaded, potentially-dependent)
15219 // binary operation.
15220 return S.CreateOverloadedBinOp(OpLoc, Opc, Functions, LHS, RHS);
15221}
15222
15223ExprResult Sema::BuildBinOp(Scope *S, SourceLocation OpLoc,
15224 BinaryOperatorKind Opc,
15225 Expr *LHSExpr, Expr *RHSExpr) {
15226 ExprResult LHS, RHS;
15227 std::tie(LHS, RHS) = CorrectDelayedTyposInBinOp(*this, Opc, LHSExpr, RHSExpr);
15228 if (!LHS.isUsable() || !RHS.isUsable())
15229 return ExprError();
15230 LHSExpr = LHS.get();
15231 RHSExpr = RHS.get();
15232
15233 // We want to end up calling one of checkPseudoObjectAssignment
15234 // (if the LHS is a pseudo-object), BuildOverloadedBinOp (if
15235 // both expressions are overloadable or either is type-dependent),
15236 // or CreateBuiltinBinOp (in any other case). We also want to get
15237 // any placeholder types out of the way.
15238
15239 // Handle pseudo-objects in the LHS.
15240 if (const BuiltinType *pty = LHSExpr->getType()->getAsPlaceholderType()) {
15241 // Assignments with a pseudo-object l-value need special analysis.
15242 if (pty->getKind() == BuiltinType::PseudoObject &&
15243 BinaryOperator::isAssignmentOp(Opc))
15244 return checkPseudoObjectAssignment(S, OpLoc, Opc, LHSExpr, RHSExpr);
15245
15246 // Don't resolve overloads if the other type is overloadable.
15247 if (getLangOpts().CPlusPlus && pty->getKind() == BuiltinType::Overload) {
15248 // We can't actually test that if we still have a placeholder,
15249 // though. Fortunately, none of the exceptions we see in that
15250 // code below are valid when the LHS is an overload set. Note
15251 // that an overload set can be dependently-typed, but it never
15252 // instantiates to having an overloadable type.
15253 ExprResult resolvedRHS = CheckPlaceholderExpr(RHSExpr);
15254 if (resolvedRHS.isInvalid()) return ExprError();
15255 RHSExpr = resolvedRHS.get();
15256
15257 if (RHSExpr->isTypeDependent() ||
15258 RHSExpr->getType()->isOverloadableType())
15259 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
15260 }
15261
15262 // If we're instantiating "a.x < b" or "A::x < b" and 'x' names a function
15263 // template, diagnose the missing 'template' keyword instead of diagnosing
15264 // an invalid use of a bound member function.
15265 //
15266 // Note that "A::x < b" might be valid if 'b' has an overloadable type due
15267 // to C++1z [over.over]/1.4, but we already checked for that case above.
15268 if (Opc == BO_LT && inTemplateInstantiation() &&
15269 (pty->getKind() == BuiltinType::BoundMember ||
15270 pty->getKind() == BuiltinType::Overload)) {
15271 auto *OE = dyn_cast<OverloadExpr>(LHSExpr);
15272 if (OE && !OE->hasTemplateKeyword() && !OE->hasExplicitTemplateArgs() &&
15273 std::any_of(OE->decls_begin(), OE->decls_end(), [](NamedDecl *ND) {
15274 return isa<FunctionTemplateDecl>(ND);
15275 })) {
15276 Diag(OE->getQualifier() ? OE->getQualifierLoc().getBeginLoc()
15277 : OE->getNameLoc(),
15278 diag::err_template_kw_missing)
15279 << OE->getName().getAsString() << "";
15280 return ExprError();
15281 }
15282 }
15283
15284 ExprResult LHS = CheckPlaceholderExpr(LHSExpr);
15285 if (LHS.isInvalid()) return ExprError();
15286 LHSExpr = LHS.get();
15287 }
15288
15289 // Handle pseudo-objects in the RHS.
15290 if (const BuiltinType *pty = RHSExpr->getType()->getAsPlaceholderType()) {
15291 // An overload in the RHS can potentially be resolved by the type
15292 // being assigned to.
15293 if (Opc == BO_Assign && pty->getKind() == BuiltinType::Overload) {
15294 if (getLangOpts().CPlusPlus &&
15295 (LHSExpr->isTypeDependent() || RHSExpr->isTypeDependent() ||
15296 LHSExpr->getType()->isOverloadableType()))
15297 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
15298
15299 return CreateBuiltinBinOp(OpLoc, Opc, LHSExpr, RHSExpr);
15300 }
15301
15302 // Don't resolve overloads if the other type is overloadable.
15303 if (getLangOpts().CPlusPlus && pty->getKind() == BuiltinType::Overload &&
15304 LHSExpr->getType()->isOverloadableType())
15305 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
15306
15307 ExprResult resolvedRHS = CheckPlaceholderExpr(RHSExpr);
15308 if (!resolvedRHS.isUsable()) return ExprError();
15309 RHSExpr = resolvedRHS.get();
15310 }
15311
15312 if (getLangOpts().CPlusPlus) {
15313 // If either expression is type-dependent, always build an
15314 // overloaded op.
15315 if (LHSExpr->isTypeDependent() || RHSExpr->isTypeDependent())
15316 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
15317
15318 // Otherwise, build an overloaded op if either expression has an
15319 // overloadable type.
15320 if (LHSExpr->getType()->isOverloadableType() ||
15321 RHSExpr->getType()->isOverloadableType())
15322 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
15323 }
15324
15325 if (getLangOpts().RecoveryAST &&
15326 (LHSExpr->isTypeDependent() || RHSExpr->isTypeDependent())) {
15327 assert(!getLangOpts().CPlusPlus)(static_cast <bool> (!getLangOpts().CPlusPlus) ? void (
0) : __assert_fail ("!getLangOpts().CPlusPlus", "clang/lib/Sema/SemaExpr.cpp"
, 15327, __extension__ __PRETTY_FUNCTION__))
;
15328 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", 15329, __extension__ __PRETTY_FUNCTION__
))
15329 "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", 15329, __extension__ __PRETTY_FUNCTION__
))
;
15330 if (BinaryOperator::isCompoundAssignmentOp(Opc))
15331 // C [6.15.16] p3:
15332 // An assignment expression has the value of the left operand after the
15333 // assignment, but is not an lvalue.
15334 return CompoundAssignOperator::Create(
15335 Context, LHSExpr, RHSExpr, Opc,
15336 LHSExpr->getType().getUnqualifiedType(), VK_PRValue, OK_Ordinary,
15337 OpLoc, CurFPFeatureOverrides());
15338 QualType ResultType;
15339 switch (Opc) {
15340 case BO_Assign:
15341 ResultType = LHSExpr->getType().getUnqualifiedType();
15342 break;
15343 case BO_LT:
15344 case BO_GT:
15345 case BO_LE:
15346 case BO_GE:
15347 case BO_EQ:
15348 case BO_NE:
15349 case BO_LAnd:
15350 case BO_LOr:
15351 // These operators have a fixed result type regardless of operands.
15352 ResultType = Context.IntTy;
15353 break;
15354 case BO_Comma:
15355 ResultType = RHSExpr->getType();
15356 break;
15357 default:
15358 ResultType = Context.DependentTy;
15359 break;
15360 }
15361 return BinaryOperator::Create(Context, LHSExpr, RHSExpr, Opc, ResultType,
15362 VK_PRValue, OK_Ordinary, OpLoc,
15363 CurFPFeatureOverrides());
15364 }
15365
15366 // Build a built-in binary operation.
15367 return CreateBuiltinBinOp(OpLoc, Opc, LHSExpr, RHSExpr);
15368}
15369
15370static bool isOverflowingIntegerType(ASTContext &Ctx, QualType T) {
15371 if (T.isNull() || T->isDependentType())
15372 return false;
15373
15374 if (!T->isPromotableIntegerType())
15375 return true;
15376
15377 return Ctx.getIntWidth(T) >= Ctx.getIntWidth(Ctx.IntTy);
15378}
15379
15380ExprResult Sema::CreateBuiltinUnaryOp(SourceLocation OpLoc,
15381 UnaryOperatorKind Opc,
15382 Expr *InputExpr) {
15383 ExprResult Input = InputExpr;
15384 ExprValueKind VK = VK_PRValue;
15385 ExprObjectKind OK = OK_Ordinary;
15386 QualType resultType;
15387 bool CanOverflow = false;
15388
15389 bool ConvertHalfVec = false;
15390 if (getLangOpts().OpenCL) {
15391 QualType Ty = InputExpr->getType();
15392 // The only legal unary operation for atomics is '&'.
15393 if ((Opc != UO_AddrOf && Ty->isAtomicType()) ||
15394 // OpenCL special types - image, sampler, pipe, and blocks are to be used
15395 // only with a builtin functions and therefore should be disallowed here.
15396 (Ty->isImageType() || Ty->isSamplerT() || Ty->isPipeType()
15397 || Ty->isBlockPointerType())) {
15398 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
15399 << InputExpr->getType()
15400 << Input.get()->getSourceRange());
15401 }
15402 }
15403
15404 if (getLangOpts().HLSL) {
15405 if (Opc == UO_AddrOf)
15406 return ExprError(Diag(OpLoc, diag::err_hlsl_operator_unsupported) << 0);
15407 if (Opc == UO_Deref)
15408 return ExprError(Diag(OpLoc, diag::err_hlsl_operator_unsupported) << 1);
15409 }
15410
15411 switch (Opc) {
15412 case UO_PreInc:
15413 case UO_PreDec:
15414 case UO_PostInc:
15415 case UO_PostDec:
15416 resultType = CheckIncrementDecrementOperand(*this, Input.get(), VK, OK,
15417 OpLoc,
15418 Opc == UO_PreInc ||
15419 Opc == UO_PostInc,
15420 Opc == UO_PreInc ||
15421 Opc == UO_PreDec);
15422 CanOverflow = isOverflowingIntegerType(Context, resultType);
15423 break;
15424 case UO_AddrOf:
15425 resultType = CheckAddressOfOperand(Input, OpLoc);
15426 CheckAddressOfNoDeref(InputExpr);
15427 RecordModifiableNonNullParam(*this, InputExpr);
15428 break;
15429 case UO_Deref: {
15430 Input = DefaultFunctionArrayLvalueConversion(Input.get());
15431 if (Input.isInvalid()) return ExprError();
15432 resultType = CheckIndirectionOperand(*this, Input.get(), VK, OpLoc);
15433 break;
15434 }
15435 case UO_Plus:
15436 case UO_Minus:
15437 CanOverflow = Opc == UO_Minus &&
15438 isOverflowingIntegerType(Context, Input.get()->getType());
15439 Input = UsualUnaryConversions(Input.get());
15440 if (Input.isInvalid()) return ExprError();
15441 // Unary plus and minus require promoting an operand of half vector to a
15442 // float vector and truncating the result back to a half vector. For now, we
15443 // do this only when HalfArgsAndReturns is set (that is, when the target is
15444 // arm or arm64).
15445 ConvertHalfVec = needsConversionOfHalfVec(true, Context, Input.get());
15446
15447 // If the operand is a half vector, promote it to a float vector.
15448 if (ConvertHalfVec)
15449 Input = convertVector(Input.get(), Context.FloatTy, *this);
15450 resultType = Input.get()->getType();
15451 if (resultType->isDependentType())
15452 break;
15453 if (resultType->isArithmeticType()) // C99 6.5.3.3p1
15454 break;
15455 else if (resultType->isVectorType() &&
15456 // The z vector extensions don't allow + or - with bool vectors.
15457 (!Context.getLangOpts().ZVector ||
15458 resultType->castAs<VectorType>()->getVectorKind() !=
15459 VectorType::AltiVecBool))
15460 break;
15461 else if (getLangOpts().CPlusPlus && // C++ [expr.unary.op]p6
15462 Opc == UO_Plus &&
15463 resultType->isPointerType())
15464 break;
15465
15466 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
15467 << resultType << Input.get()->getSourceRange());
15468
15469 case UO_Not: // bitwise complement
15470 Input = UsualUnaryConversions(Input.get());
15471 if (Input.isInvalid())
15472 return ExprError();
15473 resultType = Input.get()->getType();
15474 if (resultType->isDependentType())
15475 break;
15476 // C99 6.5.3.3p1. We allow complex int and float as a GCC extension.
15477 if (resultType->isComplexType() || resultType->isComplexIntegerType())
15478 // C99 does not support '~' for complex conjugation.
15479 Diag(OpLoc, diag::ext_integer_complement_complex)
15480 << resultType << Input.get()->getSourceRange();
15481 else if (resultType->hasIntegerRepresentation())
15482 break;
15483 else if (resultType->isExtVectorType() && Context.getLangOpts().OpenCL) {
15484 // OpenCL v1.1 s6.3.f: The bitwise operator not (~) does not operate
15485 // on vector float types.
15486 QualType T = resultType->castAs<ExtVectorType>()->getElementType();
15487 if (!T->isIntegerType())
15488 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
15489 << resultType << Input.get()->getSourceRange());
15490 } else {
15491 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
15492 << resultType << Input.get()->getSourceRange());
15493 }
15494 break;
15495
15496 case UO_LNot: // logical negation
15497 // Unlike +/-/~, integer promotions aren't done here (C99 6.5.3.3p5).
15498 Input = DefaultFunctionArrayLvalueConversion(Input.get());
15499 if (Input.isInvalid()) return ExprError();
15500 resultType = Input.get()->getType();
15501
15502 // Though we still have to promote half FP to float...
15503 if (resultType->isHalfType() && !Context.getLangOpts().NativeHalfType) {
15504 Input = ImpCastExprToType(Input.get(), Context.FloatTy, CK_FloatingCast).get();
15505 resultType = Context.FloatTy;
15506 }
15507
15508 if (resultType->isDependentType())
15509 break;
15510 if (resultType->isScalarType() && !isScopedEnumerationType(resultType)) {
15511 // C99 6.5.3.3p1: ok, fallthrough;
15512 if (Context.getLangOpts().CPlusPlus) {
15513 // C++03 [expr.unary.op]p8, C++0x [expr.unary.op]p9:
15514 // operand contextually converted to bool.
15515 Input = ImpCastExprToType(Input.get(), Context.BoolTy,
15516 ScalarTypeToBooleanCastKind(resultType));
15517 } else if (Context.getLangOpts().OpenCL &&
15518 Context.getLangOpts().OpenCLVersion < 120) {
15519 // OpenCL v1.1 6.3.h: The logical operator not (!) does not
15520 // operate on scalar float types.
15521 if (!resultType->isIntegerType() && !resultType->isPointerType())
15522 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
15523 << resultType << Input.get()->getSourceRange());
15524 }
15525 } else if (resultType->isExtVectorType()) {
15526 if (Context.getLangOpts().OpenCL &&
15527 Context.getLangOpts().getOpenCLCompatibleVersion() < 120) {
15528 // OpenCL v1.1 6.3.h: The logical operator not (!) does not
15529 // operate on vector float types.
15530 QualType T = resultType->castAs<ExtVectorType>()->getElementType();
15531 if (!T->isIntegerType())
15532 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
15533 << resultType << Input.get()->getSourceRange());
15534 }
15535 // Vector logical not returns the signed variant of the operand type.
15536 resultType = GetSignedVectorType(resultType);
15537 break;
15538 } else if (Context.getLangOpts().CPlusPlus && resultType->isVectorType()) {
15539 const VectorType *VTy = resultType->castAs<VectorType>();
15540 if (VTy->getVectorKind() != VectorType::GenericVector)
15541 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
15542 << resultType << Input.get()->getSourceRange());
15543
15544 // Vector logical not returns the signed variant of the operand type.
15545 resultType = GetSignedVectorType(resultType);
15546 break;
15547 } else {
15548 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
15549 << resultType << Input.get()->getSourceRange());
15550 }
15551
15552 // LNot always has type int. C99 6.5.3.3p5.
15553 // In C++, it's bool. C++ 5.3.1p8
15554 resultType = Context.getLogicalOperationType();
15555 break;
15556 case UO_Real:
15557 case UO_Imag:
15558 resultType = CheckRealImagOperand(*this, Input, OpLoc, Opc == UO_Real);
15559 // _Real maps ordinary l-values into ordinary l-values. _Imag maps ordinary
15560 // complex l-values to ordinary l-values and all other values to r-values.
15561 if (Input.isInvalid()) return ExprError();
15562 if (Opc == UO_Real || Input.get()->getType()->isAnyComplexType()) {
15563 if (Input.get()->isGLValue() &&
15564 Input.get()->getObjectKind() == OK_Ordinary)
15565 VK = Input.get()->getValueKind();
15566 } else if (!getLangOpts().CPlusPlus) {
15567 // In C, a volatile scalar is read by __imag. In C++, it is not.
15568 Input = DefaultLvalueConversion(Input.get());
15569 }
15570 break;
15571 case UO_Extension:
15572 resultType = Input.get()->getType();
15573 VK = Input.get()->getValueKind();
15574 OK = Input.get()->getObjectKind();
15575 break;
15576 case UO_Coawait:
15577 // It's unnecessary to represent the pass-through operator co_await in the
15578 // AST; just return the input expression instead.
15579 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", 15581, __extension__ __PRETTY_FUNCTION__
))
15580 "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", 15581, __extension__ __PRETTY_FUNCTION__
))
15581 "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", 15581, __extension__ __PRETTY_FUNCTION__
))
;
15582 return Input;
15583 }
15584 if (resultType.isNull() || Input.isInvalid())
15585 return ExprError();
15586
15587 // Check for array bounds violations in the operand of the UnaryOperator,
15588 // except for the '*' and '&' operators that have to be handled specially
15589 // by CheckArrayAccess (as there are special cases like &array[arraysize]
15590 // that are explicitly defined as valid by the standard).
15591 if (Opc != UO_AddrOf && Opc != UO_Deref)
15592 CheckArrayAccess(Input.get());
15593
15594 auto *UO =
15595 UnaryOperator::Create(Context, Input.get(), Opc, resultType, VK, OK,
15596 OpLoc, CanOverflow, CurFPFeatureOverrides());
15597
15598 if (Opc == UO_Deref && UO->getType()->hasAttr(attr::NoDeref) &&
15599 !isa<ArrayType>(UO->getType().getDesugaredType(Context)) &&
15600 !isUnevaluatedContext())
15601 ExprEvalContexts.back().PossibleDerefs.insert(UO);
15602
15603 // Convert the result back to a half vector.
15604 if (ConvertHalfVec)
15605 return convertVector(UO, Context.HalfTy, *this);
15606 return UO;
15607}
15608
15609/// Determine whether the given expression is a qualified member
15610/// access expression, of a form that could be turned into a pointer to member
15611/// with the address-of operator.
15612bool Sema::isQualifiedMemberAccess(Expr *E) {
15613 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
15614 if (!DRE->getQualifier())
15615 return false;
15616
15617 ValueDecl *VD = DRE->getDecl();
15618 if (!VD->isCXXClassMember())
15619 return false;
15620
15621 if (isa<FieldDecl>(VD) || isa<IndirectFieldDecl>(VD))
15622 return true;
15623 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(VD))
15624 return Method->isInstance();
15625
15626 return false;
15627 }
15628
15629 if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(E)) {
15630 if (!ULE->getQualifier())
15631 return false;
15632
15633 for (NamedDecl *D : ULE->decls()) {
15634 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) {
15635 if (Method->isInstance())
15636 return true;
15637 } else {
15638 // Overload set does not contain methods.
15639 break;
15640 }
15641 }
15642
15643 return false;
15644 }
15645
15646 return false;
15647}
15648
15649ExprResult Sema::BuildUnaryOp(Scope *S, SourceLocation OpLoc,
15650 UnaryOperatorKind Opc, Expr *Input) {
15651 // First things first: handle placeholders so that the
15652 // overloaded-operator check considers the right type.
15653 if (const BuiltinType *pty = Input->getType()->getAsPlaceholderType()) {
15654 // Increment and decrement of pseudo-object references.
15655 if (pty->getKind() == BuiltinType::PseudoObject &&
15656 UnaryOperator::isIncrementDecrementOp(Opc))
15657 return checkPseudoObjectIncDec(S, OpLoc, Opc, Input);
15658
15659 // extension is always a builtin operator.
15660 if (Opc == UO_Extension)
15661 return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
15662
15663 // & gets special logic for several kinds of placeholder.
15664 // The builtin code knows what to do.
15665 if (Opc == UO_AddrOf &&
15666 (pty->getKind() == BuiltinType::Overload ||
15667 pty->getKind() == BuiltinType::UnknownAny ||
15668 pty->getKind() == BuiltinType::BoundMember))
15669 return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
15670
15671 // Anything else needs to be handled now.
15672 ExprResult Result = CheckPlaceholderExpr(Input);
15673 if (Result.isInvalid()) return ExprError();
15674 Input = Result.get();
15675 }
15676
15677 if (getLangOpts().CPlusPlus && Input->getType()->isOverloadableType() &&
15678 UnaryOperator::getOverloadedOperator(Opc) != OO_None &&
15679 !(Opc == UO_AddrOf && isQualifiedMemberAccess(Input))) {
15680 // Find all of the overloaded operators visible from this point.
15681 UnresolvedSet<16> Functions;
15682 OverloadedOperatorKind OverOp = UnaryOperator::getOverloadedOperator(Opc);
15683 if (S && OverOp != OO_None)
15684 LookupOverloadedOperatorName(OverOp, S, Functions);
15685
15686 return CreateOverloadedUnaryOp(OpLoc, Opc, Functions, Input);
15687 }
15688
15689 return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
15690}
15691
15692// Unary Operators. 'Tok' is the token for the operator.
15693ExprResult Sema::ActOnUnaryOp(Scope *S, SourceLocation OpLoc,
15694 tok::TokenKind Op, Expr *Input) {
15695 return BuildUnaryOp(S, OpLoc, ConvertTokenKindToUnaryOpcode(Op), Input);
15696}
15697
15698/// ActOnAddrLabel - Parse the GNU address of label extension: "&&foo".
15699ExprResult Sema::ActOnAddrLabel(SourceLocation OpLoc, SourceLocation LabLoc,
15700 LabelDecl *TheDecl) {
15701 TheDecl->markUsed(Context);
15702 // Create the AST node. The address of a label always has type 'void*'.
15703 return new (Context) AddrLabelExpr(OpLoc, LabLoc, TheDecl,
15704 Context.getPointerType(Context.VoidTy));
15705}
15706
15707void Sema::ActOnStartStmtExpr() {
15708 PushExpressionEvaluationContext(ExprEvalContexts.back().Context);
15709}
15710
15711void Sema::ActOnStmtExprError() {
15712 // Note that function is also called by TreeTransform when leaving a
15713 // StmtExpr scope without rebuilding anything.
15714
15715 DiscardCleanupsInEvaluationContext();
15716 PopExpressionEvaluationContext();
15717}
15718
15719ExprResult Sema::ActOnStmtExpr(Scope *S, SourceLocation LPLoc, Stmt *SubStmt,
15720 SourceLocation RPLoc) {
15721 return BuildStmtExpr(LPLoc, SubStmt, RPLoc, getTemplateDepth(S));
15722}
15723
15724ExprResult Sema::BuildStmtExpr(SourceLocation LPLoc, Stmt *SubStmt,
15725 SourceLocation RPLoc, unsigned TemplateDepth) {
15726 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", 15726, __extension__ __PRETTY_FUNCTION__
))
;
15727 CompoundStmt *Compound = cast<CompoundStmt>(SubStmt);
15728
15729 if (hasAnyUnrecoverableErrorsInThisFunction())
15730 DiscardCleanupsInEvaluationContext();
15731 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", 15732, __extension__ __PRETTY_FUNCTION__
))
15732 "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", 15732, __extension__ __PRETTY_FUNCTION__
))
;
15733 PopExpressionEvaluationContext();
15734
15735 // FIXME: there are a variety of strange constraints to enforce here, for
15736 // example, it is not possible to goto into a stmt expression apparently.
15737 // More semantic analysis is needed.
15738
15739 // If there are sub-stmts in the compound stmt, take the type of the last one
15740 // as the type of the stmtexpr.
15741 QualType Ty = Context.VoidTy;
15742 bool StmtExprMayBindToTemp = false;
15743 if (!Compound->body_empty()) {
15744 // For GCC compatibility we get the last Stmt excluding trailing NullStmts.
15745 if (const auto *LastStmt =
15746 dyn_cast<ValueStmt>(Compound->getStmtExprResult())) {
15747 if (const Expr *Value = LastStmt->getExprStmt()) {
15748 StmtExprMayBindToTemp = true;
15749 Ty = Value->getType();
15750 }
15751 }
15752 }
15753
15754 // FIXME: Check that expression type is complete/non-abstract; statement
15755 // expressions are not lvalues.
15756 Expr *ResStmtExpr =
15757 new (Context) StmtExpr(Compound, Ty, LPLoc, RPLoc, TemplateDepth);
15758 if (StmtExprMayBindToTemp)
15759 return MaybeBindToTemporary(ResStmtExpr);
15760 return ResStmtExpr;
15761}
15762
15763ExprResult Sema::ActOnStmtExprResult(ExprResult ER) {
15764 if (ER.isInvalid())
15765 return ExprError();
15766
15767 // Do function/array conversion on the last expression, but not
15768 // lvalue-to-rvalue. However, initialize an unqualified type.
15769 ER = DefaultFunctionArrayConversion(ER.get());
15770 if (ER.isInvalid())
15771 return ExprError();
15772 Expr *E = ER.get();
15773
15774 if (E->isTypeDependent())
15775 return E;
15776
15777 // In ARC, if the final expression ends in a consume, splice
15778 // the consume out and bind it later. In the alternate case
15779 // (when dealing with a retainable type), the result
15780 // initialization will create a produce. In both cases the
15781 // result will be +1, and we'll need to balance that out with
15782 // a bind.
15783 auto *Cast = dyn_cast<ImplicitCastExpr>(E);
15784 if (Cast && Cast->getCastKind() == CK_ARCConsumeObject)
15785 return Cast->getSubExpr();
15786
15787 // FIXME: Provide a better location for the initialization.
15788 return PerformCopyInitialization(
15789 InitializedEntity::InitializeStmtExprResult(
15790 E->getBeginLoc(), E->getType().getUnqualifiedType()),
15791 SourceLocation(), E);
15792}
15793
15794ExprResult Sema::BuildBuiltinOffsetOf(SourceLocation BuiltinLoc,
15795 TypeSourceInfo *TInfo,
15796 ArrayRef<OffsetOfComponent> Components,
15797 SourceLocation RParenLoc) {
15798 QualType ArgTy = TInfo->getType();
15799 bool Dependent = ArgTy->isDependentType();
15800 SourceRange TypeRange = TInfo->getTypeLoc().getLocalSourceRange();
15801
15802 // We must have at least one component that refers to the type, and the first
15803 // one is known to be a field designator. Verify that the ArgTy represents
15804 // a struct/union/class.
15805 if (!Dependent && !ArgTy->isRecordType())
15806 return ExprError(Diag(BuiltinLoc, diag::err_offsetof_record_type)
15807 << ArgTy << TypeRange);
15808
15809 // Type must be complete per C99 7.17p3 because a declaring a variable
15810 // with an incomplete type would be ill-formed.
15811 if (!Dependent
15812 && RequireCompleteType(BuiltinLoc, ArgTy,
15813 diag::err_offsetof_incomplete_type, TypeRange))
15814 return ExprError();
15815
15816 bool DidWarnAboutNonPOD = false;
15817 QualType CurrentType = ArgTy;
15818 SmallVector<OffsetOfNode, 4> Comps;
15819 SmallVector<Expr*, 4> Exprs;
15820 for (const OffsetOfComponent &OC : Components) {
15821 if (OC.isBrackets) {
15822 // Offset of an array sub-field. TODO: Should we allow vector elements?
15823 if (!CurrentType->isDependentType()) {
15824 const ArrayType *AT = Context.getAsArrayType(CurrentType);
15825 if(!AT)
15826 return ExprError(Diag(OC.LocEnd, diag::err_offsetof_array_type)
15827 << CurrentType);
15828 CurrentType = AT->getElementType();
15829 } else
15830 CurrentType = Context.DependentTy;
15831
15832 ExprResult IdxRval = DefaultLvalueConversion(static_cast<Expr*>(OC.U.E));
15833 if (IdxRval.isInvalid())
15834 return ExprError();
15835 Expr *Idx = IdxRval.get();
15836
15837 // The expression must be an integral expression.
15838 // FIXME: An integral constant expression?
15839 if (!Idx->isTypeDependent() && !Idx->isValueDependent() &&
15840 !Idx->getType()->isIntegerType())
15841 return ExprError(
15842 Diag(Idx->getBeginLoc(), diag::err_typecheck_subscript_not_integer)
15843 << Idx->getSourceRange());
15844
15845 // Record this array index.
15846 Comps.push_back(OffsetOfNode(OC.LocStart, Exprs.size(), OC.LocEnd));
15847 Exprs.push_back(Idx);
15848 continue;
15849 }
15850
15851 // Offset of a field.
15852 if (CurrentType->isDependentType()) {
15853 // We have the offset of a field, but we can't look into the dependent
15854 // type. Just record the identifier of the field.
15855 Comps.push_back(OffsetOfNode(OC.LocStart, OC.U.IdentInfo, OC.LocEnd));
15856 CurrentType = Context.DependentTy;
15857 continue;
15858 }
15859
15860 // We need to have a complete type to look into.
15861 if (RequireCompleteType(OC.LocStart, CurrentType,
15862 diag::err_offsetof_incomplete_type))
15863 return ExprError();
15864
15865 // Look for the designated field.
15866 const RecordType *RC = CurrentType->getAs<RecordType>();
15867 if (!RC)
15868 return ExprError(Diag(OC.LocEnd, diag::err_offsetof_record_type)
15869 << CurrentType);
15870 RecordDecl *RD = RC->getDecl();
15871
15872 // C++ [lib.support.types]p5:
15873 // The macro offsetof accepts a restricted set of type arguments in this
15874 // International Standard. type shall be a POD structure or a POD union
15875 // (clause 9).
15876 // C++11 [support.types]p4:
15877 // If type is not a standard-layout class (Clause 9), the results are
15878 // undefined.
15879 if (CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) {
15880 bool IsSafe = LangOpts.CPlusPlus11? CRD->isStandardLayout() : CRD->isPOD();
15881 unsigned DiagID =
15882 LangOpts.CPlusPlus11? diag::ext_offsetof_non_standardlayout_type
15883 : diag::ext_offsetof_non_pod_type;
15884
15885 if (!IsSafe && !DidWarnAboutNonPOD &&
15886 DiagRuntimeBehavior(BuiltinLoc, nullptr,
15887 PDiag(DiagID)
15888 << SourceRange(Components[0].LocStart, OC.LocEnd)
15889 << CurrentType))
15890 DidWarnAboutNonPOD = true;
15891 }
15892
15893 // Look for the field.
15894 LookupResult R(*this, OC.U.IdentInfo, OC.LocStart, LookupMemberName);
15895 LookupQualifiedName(R, RD);
15896 FieldDecl *MemberDecl = R.getAsSingle<FieldDecl>();
15897 IndirectFieldDecl *IndirectMemberDecl = nullptr;
15898 if (!MemberDecl) {
15899 if ((IndirectMemberDecl = R.getAsSingle<IndirectFieldDecl>()))
15900 MemberDecl = IndirectMemberDecl->getAnonField();
15901 }
15902
15903 if (!MemberDecl)
15904 return ExprError(Diag(BuiltinLoc, diag::err_no_member)
15905 << OC.U.IdentInfo << RD << SourceRange(OC.LocStart,
15906 OC.LocEnd));
15907
15908 // C99 7.17p3:
15909 // (If the specified member is a bit-field, the behavior is undefined.)
15910 //
15911 // We diagnose this as an error.
15912 if (MemberDecl->isBitField()) {
15913 Diag(OC.LocEnd, diag::err_offsetof_bitfield)
15914 << MemberDecl->getDeclName()
15915 << SourceRange(BuiltinLoc, RParenLoc);
15916 Diag(MemberDecl->getLocation(), diag::note_bitfield_decl);
15917 return ExprError();
15918 }
15919
15920 RecordDecl *Parent = MemberDecl->getParent();
15921 if (IndirectMemberDecl)
15922 Parent = cast<RecordDecl>(IndirectMemberDecl->getDeclContext());
15923
15924 // If the member was found in a base class, introduce OffsetOfNodes for
15925 // the base class indirections.
15926 CXXBasePaths Paths;
15927 if (IsDerivedFrom(OC.LocStart, CurrentType, Context.getTypeDeclType(Parent),
15928 Paths)) {
15929 if (Paths.getDetectedVirtual()) {
15930 Diag(OC.LocEnd, diag::err_offsetof_field_of_virtual_base)
15931 << MemberDecl->getDeclName()
15932 << SourceRange(BuiltinLoc, RParenLoc);
15933 return ExprError();
15934 }
15935
15936 CXXBasePath &Path = Paths.front();
15937 for (const CXXBasePathElement &B : Path)
15938 Comps.push_back(OffsetOfNode(B.Base));
15939 }
15940
15941 if (IndirectMemberDecl) {
15942 for (auto *FI : IndirectMemberDecl->chain()) {
15943 assert(isa<FieldDecl>(FI))(static_cast <bool> (isa<FieldDecl>(FI)) ? void (
0) : __assert_fail ("isa<FieldDecl>(FI)", "clang/lib/Sema/SemaExpr.cpp"
, 15943, __extension__ __PRETTY_FUNCTION__))
;
15944 Comps.push_back(OffsetOfNode(OC.LocStart,
15945 cast<FieldDecl>(FI), OC.LocEnd));
15946 }
15947 } else
15948 Comps.push_back(OffsetOfNode(OC.LocStart, MemberDecl, OC.LocEnd));
15949
15950 CurrentType = MemberDecl->getType().getNonReferenceType();
15951 }
15952
15953 return OffsetOfExpr::Create(Context, Context.getSizeType(), BuiltinLoc, TInfo,
15954 Comps, Exprs, RParenLoc);
15955}
15956
15957ExprResult Sema::ActOnBuiltinOffsetOf(Scope *S,
15958 SourceLocation BuiltinLoc,
15959 SourceLocation TypeLoc,
15960 ParsedType ParsedArgTy,
15961 ArrayRef<OffsetOfComponent> Components,
15962 SourceLocation RParenLoc) {
15963
15964 TypeSourceInfo *ArgTInfo;
15965 QualType ArgTy = GetTypeFromParser(ParsedArgTy, &ArgTInfo);
15966 if (ArgTy.isNull())
15967 return ExprError();
15968
15969 if (!ArgTInfo)
15970 ArgTInfo = Context.getTrivialTypeSourceInfo(ArgTy, TypeLoc);
15971
15972 return BuildBuiltinOffsetOf(BuiltinLoc, ArgTInfo, Components, RParenLoc);
15973}
15974
15975
15976ExprResult Sema::ActOnChooseExpr(SourceLocation BuiltinLoc,
15977 Expr *CondExpr,
15978 Expr *LHSExpr, Expr *RHSExpr,
15979 SourceLocation RPLoc) {
15980 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", 15980, __extension__ __PRETTY_FUNCTION__
))
;
15981
15982 ExprValueKind VK = VK_PRValue;
15983 ExprObjectKind OK = OK_Ordinary;
15984 QualType resType;
15985 bool CondIsTrue = false;
15986 if (CondExpr->isTypeDependent() || CondExpr->isValueDependent()) {
15987 resType = Context.DependentTy;
15988 } else {
15989 // The conditional expression is required to be a constant expression.
15990 llvm::APSInt condEval(32);
15991 ExprResult CondICE = VerifyIntegerConstantExpression(
15992 CondExpr, &condEval, diag::err_typecheck_choose_expr_requires_constant);
15993 if (CondICE.isInvalid())
15994 return ExprError();
15995 CondExpr = CondICE.get();
15996 CondIsTrue = condEval.getZExtValue();
15997
15998 // If the condition is > zero, then the AST type is the same as the LHSExpr.
15999 Expr *ActiveExpr = CondIsTrue ? LHSExpr : RHSExpr;
16000
16001 resType = ActiveExpr->getType();
16002 VK = ActiveExpr->getValueKind();
16003 OK = ActiveExpr->getObjectKind();
16004 }
16005
16006 return new (Context) ChooseExpr(BuiltinLoc, CondExpr, LHSExpr, RHSExpr,
16007 resType, VK, OK, RPLoc, CondIsTrue);
16008}
16009
16010//===----------------------------------------------------------------------===//
16011// Clang Extensions.
16012//===----------------------------------------------------------------------===//
16013
16014/// ActOnBlockStart - This callback is invoked when a block literal is started.
16015void Sema::ActOnBlockStart(SourceLocation CaretLoc, Scope *CurScope) {
16016 BlockDecl *Block = BlockDecl::Create(Context, CurContext, CaretLoc);
16017
16018 if (LangOpts.CPlusPlus) {
16019 MangleNumberingContext *MCtx;
16020 Decl *ManglingContextDecl;
16021 std::tie(MCtx, ManglingContextDecl) =
16022 getCurrentMangleNumberContext(Block->getDeclContext());
16023 if (MCtx) {
16024 unsigned ManglingNumber = MCtx->getManglingNumber(Block);
16025 Block->setBlockMangling(ManglingNumber, ManglingContextDecl);
16026 }
16027 }
16028
16029 PushBlockScope(CurScope, Block);
16030 CurContext->addDecl(Block);
16031 if (CurScope)
16032 PushDeclContext(CurScope, Block);
16033 else
16034 CurContext = Block;
16035
16036 getCurBlock()->HasImplicitReturnType = true;
16037
16038 // Enter a new evaluation context to insulate the block from any
16039 // cleanups from the enclosing full-expression.
16040 PushExpressionEvaluationContext(
16041 ExpressionEvaluationContext::PotentiallyEvaluated);
16042}
16043
16044void Sema::ActOnBlockArguments(SourceLocation CaretLoc, Declarator &ParamInfo,
16045 Scope *CurScope) {
16046 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", 16047, __extension__ __PRETTY_FUNCTION__
))
16047 "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", 16047, __extension__ __PRETTY_FUNCTION__
))
;
16048 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", 16048, __extension__ __PRETTY_FUNCTION__
))
;
16049 BlockScopeInfo *CurBlock = getCurBlock();
16050
16051 TypeSourceInfo *Sig = GetTypeForDeclarator(ParamInfo, CurScope);
16052 QualType T = Sig->getType();
16053
16054 // FIXME: We should allow unexpanded parameter packs here, but that would,
16055 // in turn, make the block expression contain unexpanded parameter packs.
16056 if (DiagnoseUnexpandedParameterPack(CaretLoc, Sig, UPPC_Block)) {
16057 // Drop the parameters.
16058 FunctionProtoType::ExtProtoInfo EPI;
16059 EPI.HasTrailingReturn = false;
16060 EPI.TypeQuals.addConst();
16061 T = Context.getFunctionType(Context.DependentTy, None, EPI);
16062 Sig = Context.getTrivialTypeSourceInfo(T);
16063 }
16064
16065 // GetTypeForDeclarator always produces a function type for a block
16066 // literal signature. Furthermore, it is always a FunctionProtoType
16067 // unless the function was written with a typedef.
16068 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", 16069, __extension__ __PRETTY_FUNCTION__
))
16069 "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", 16069, __extension__ __PRETTY_FUNCTION__
))
;
16070
16071 // Look for an explicit signature in that function type.
16072 FunctionProtoTypeLoc ExplicitSignature;
16073
16074 if ((ExplicitSignature = Sig->getTypeLoc()
16075 .getAsAdjusted<FunctionProtoTypeLoc>())) {
16076
16077 // Check whether that explicit signature was synthesized by
16078 // GetTypeForDeclarator. If so, don't save that as part of the
16079 // written signature.
16080 if (ExplicitSignature.getLocalRangeBegin() ==
16081 ExplicitSignature.getLocalRangeEnd()) {
16082 // This would be much cheaper if we stored TypeLocs instead of
16083 // TypeSourceInfos.
16084 TypeLoc Result = ExplicitSignature.getReturnLoc();
16085 unsigned Size = Result.getFullDataSize();
16086 Sig = Context.CreateTypeSourceInfo(Result.getType(), Size);
16087 Sig->getTypeLoc().initializeFullCopy(Result, Size);
16088
16089 ExplicitSignature = FunctionProtoTypeLoc();
16090 }
16091 }
16092
16093 CurBlock->TheDecl->setSignatureAsWritten(Sig);
16094 CurBlock->FunctionType = T;
16095
16096 const auto *Fn = T->castAs<FunctionType>();
16097 QualType RetTy = Fn->getReturnType();
16098 bool isVariadic =
16099 (isa<FunctionProtoType>(Fn) && cast<FunctionProtoType>(Fn)->isVariadic());
16100
16101 CurBlock->TheDecl->setIsVariadic(isVariadic);
16102
16103 // Context.DependentTy is used as a placeholder for a missing block
16104 // return type. TODO: what should we do with declarators like:
16105 // ^ * { ... }
16106 // If the answer is "apply template argument deduction"....
16107 if (RetTy != Context.DependentTy) {
16108 CurBlock->ReturnType = RetTy;
16109 CurBlock->TheDecl->setBlockMissingReturnType(false);
16110 CurBlock->HasImplicitReturnType = false;
16111 }
16112
16113 // Push block parameters from the declarator if we had them.
16114 SmallVector<ParmVarDecl*, 8> Params;
16115 if (ExplicitSignature) {
16116 for (unsigned I = 0, E = ExplicitSignature.getNumParams(); I != E; ++I) {
16117 ParmVarDecl *Param = ExplicitSignature.getParam(I);
16118 if (Param->getIdentifier() == nullptr && !Param->isImplicit() &&
16119 !Param->isInvalidDecl() && !getLangOpts().CPlusPlus) {
16120 // Diagnose this as an extension in C17 and earlier.
16121 if (!getLangOpts().C2x)
16122 Diag(Param->getLocation(), diag::ext_parameter_name_omitted_c2x);
16123 }
16124 Params.push_back(Param);
16125 }
16126
16127 // Fake up parameter variables if we have a typedef, like
16128 // ^ fntype { ... }
16129 } else if (const FunctionProtoType *Fn = T->getAs<FunctionProtoType>()) {
16130 for (const auto &I : Fn->param_types()) {
16131 ParmVarDecl *Param = BuildParmVarDeclForTypedef(
16132 CurBlock->TheDecl, ParamInfo.getBeginLoc(), I);
16133 Params.push_back(Param);
16134 }
16135 }
16136
16137 // Set the parameters on the block decl.
16138 if (!Params.empty()) {
16139 CurBlock->TheDecl->setParams(Params);
16140 CheckParmsForFunctionDef(CurBlock->TheDecl->parameters(),
16141 /*CheckParameterNames=*/false);
16142 }
16143
16144 // Finally we can process decl attributes.
16145 ProcessDeclAttributes(CurScope, CurBlock->TheDecl, ParamInfo);
16146
16147 // Put the parameter variables in scope.
16148 for (auto AI : CurBlock->TheDecl->parameters()) {
16149 AI->setOwningFunction(CurBlock->TheDecl);
16150
16151 // If this has an identifier, add it to the scope stack.
16152 if (AI->getIdentifier()) {
16153 CheckShadow(CurBlock->TheScope, AI);
16154
16155 PushOnScopeChains(AI, CurBlock->TheScope);
16156 }
16157 }
16158}
16159
16160/// ActOnBlockError - If there is an error parsing a block, this callback
16161/// is invoked to pop the information about the block from the action impl.
16162void Sema::ActOnBlockError(SourceLocation CaretLoc, Scope *CurScope) {
16163 // Leave the expression-evaluation context.
16164 DiscardCleanupsInEvaluationContext();
16165 PopExpressionEvaluationContext();
16166
16167 // Pop off CurBlock, handle nested blocks.
16168 PopDeclContext();
16169 PopFunctionScopeInfo();
16170}
16171
16172/// ActOnBlockStmtExpr - This is called when the body of a block statement
16173/// literal was successfully completed. ^(int x){...}
16174ExprResult Sema::ActOnBlockStmtExpr(SourceLocation CaretLoc,
16175 Stmt *Body, Scope *CurScope) {
16176 // If blocks are disabled, emit an error.
16177 if (!LangOpts.Blocks)
16178 Diag(CaretLoc, diag::err_blocks_disable) << LangOpts.OpenCL;
16179
16180 // Leave the expression-evaluation context.
16181 if (hasAnyUnrecoverableErrorsInThisFunction())
16182 DiscardCleanupsInEvaluationContext();
16183 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", 16184, __extension__ __PRETTY_FUNCTION__
))
16184 "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", 16184, __extension__ __PRETTY_FUNCTION__
))
;
16185 PopExpressionEvaluationContext();
16186
16187 BlockScopeInfo *BSI = cast<BlockScopeInfo>(FunctionScopes.back());
16188 BlockDecl *BD = BSI->TheDecl;
16189
16190 if (BSI->HasImplicitReturnType)
16191 deduceClosureReturnType(*BSI);
16192
16193 QualType RetTy = Context.VoidTy;
16194 if (!BSI->ReturnType.isNull())
16195 RetTy = BSI->ReturnType;
16196
16197 bool NoReturn = BD->hasAttr<NoReturnAttr>();
16198 QualType BlockTy;
16199
16200 // If the user wrote a function type in some form, try to use that.
16201 if (!BSI->FunctionType.isNull()) {
16202 const FunctionType *FTy = BSI->FunctionType->castAs<FunctionType>();
16203
16204 FunctionType::ExtInfo Ext = FTy->getExtInfo();
16205 if (NoReturn && !Ext.getNoReturn()) Ext = Ext.withNoReturn(true);
16206
16207 // Turn protoless block types into nullary block types.
16208 if (isa<FunctionNoProtoType>(FTy)) {
16209 FunctionProtoType::ExtProtoInfo EPI;
16210 EPI.ExtInfo = Ext;
16211 BlockTy = Context.getFunctionType(RetTy, None, EPI);
16212
16213 // Otherwise, if we don't need to change anything about the function type,
16214 // preserve its sugar structure.
16215 } else if (FTy->getReturnType() == RetTy &&
16216 (!NoReturn || FTy->getNoReturnAttr())) {
16217 BlockTy = BSI->FunctionType;
16218
16219 // Otherwise, make the minimal modifications to the function type.
16220 } else {
16221 const FunctionProtoType *FPT = cast<FunctionProtoType>(FTy);
16222 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
16223 EPI.TypeQuals = Qualifiers();
16224 EPI.ExtInfo = Ext;
16225 BlockTy = Context.getFunctionType(RetTy, FPT->getParamTypes(), EPI);
16226 }
16227
16228 // If we don't have a function type, just build one from nothing.
16229 } else {
16230 FunctionProtoType::ExtProtoInfo EPI;
16231 EPI.ExtInfo = FunctionType::ExtInfo().withNoReturn(NoReturn);
16232 BlockTy = Context.getFunctionType(RetTy, None, EPI);
16233 }
16234
16235 DiagnoseUnusedParameters(BD->parameters());
16236 BlockTy = Context.getBlockPointerType(BlockTy);
16237
16238 // If needed, diagnose invalid gotos and switches in the block.
16239 if (getCurFunction()->NeedsScopeChecking() &&
16240 !PP.isCodeCompletionEnabled())
16241 DiagnoseInvalidJumps(cast<CompoundStmt>(Body));
16242
16243 BD->setBody(cast<CompoundStmt>(Body));
16244
16245 if (Body && getCurFunction()->HasPotentialAvailabilityViolations)
16246 DiagnoseUnguardedAvailabilityViolations(BD);
16247
16248 // Try to apply the named return value optimization. We have to check again
16249 // if we can do this, though, because blocks keep return statements around
16250 // to deduce an implicit return type.
16251 if (getLangOpts().CPlusPlus && RetTy->isRecordType() &&
16252 !BD->isDependentContext())
16253 computeNRVO(Body, BSI);
16254
16255 if (RetTy.hasNonTrivialToPrimitiveDestructCUnion() ||
16256 RetTy.hasNonTrivialToPrimitiveCopyCUnion())
16257 checkNonTrivialCUnion(RetTy, BD->getCaretLocation(), NTCUC_FunctionReturn,
16258 NTCUK_Destruct|NTCUK_Copy);
16259
16260 PopDeclContext();
16261
16262 // Set the captured variables on the block.
16263 SmallVector<BlockDecl::Capture, 4> Captures;
16264 for (Capture &Cap : BSI->Captures) {
16265 if (Cap.isInvalid() || Cap.isThisCapture())
16266 continue;
16267
16268 VarDecl *Var = Cap.getVariable();
16269 Expr *CopyExpr = nullptr;
16270 if (getLangOpts().CPlusPlus && Cap.isCopyCapture()) {
16271 if (const RecordType *Record =
16272 Cap.getCaptureType()->getAs<RecordType>()) {
16273 // The capture logic needs the destructor, so make sure we mark it.
16274 // Usually this is unnecessary because most local variables have
16275 // their destructors marked at declaration time, but parameters are
16276 // an exception because it's technically only the call site that
16277 // actually requires the destructor.
16278 if (isa<ParmVarDecl>(Var))
16279 FinalizeVarWithDestructor(Var, Record);
16280
16281 // Enter a separate potentially-evaluated context while building block
16282 // initializers to isolate their cleanups from those of the block
16283 // itself.
16284 // FIXME: Is this appropriate even when the block itself occurs in an
16285 // unevaluated operand?
16286 EnterExpressionEvaluationContext EvalContext(
16287 *this, ExpressionEvaluationContext::PotentiallyEvaluated);
16288
16289 SourceLocation Loc = Cap.getLocation();
16290
16291 ExprResult Result = BuildDeclarationNameExpr(
16292 CXXScopeSpec(), DeclarationNameInfo(Var->getDeclName(), Loc), Var);
16293
16294 // According to the blocks spec, the capture of a variable from
16295 // the stack requires a const copy constructor. This is not true
16296 // of the copy/move done to move a __block variable to the heap.
16297 if (!Result.isInvalid() &&
16298 !Result.get()->getType().isConstQualified()) {
16299 Result = ImpCastExprToType(Result.get(),
16300 Result.get()->getType().withConst(),
16301 CK_NoOp, VK_LValue);
16302 }
16303
16304 if (!Result.isInvalid()) {
16305 Result = PerformCopyInitialization(
16306 InitializedEntity::InitializeBlock(Var->getLocation(),
16307 Cap.getCaptureType()),
16308 Loc, Result.get());
16309 }
16310
16311 // Build a full-expression copy expression if initialization
16312 // succeeded and used a non-trivial constructor. Recover from
16313 // errors by pretending that the copy isn't necessary.
16314 if (!Result.isInvalid() &&
16315 !cast<CXXConstructExpr>(Result.get())->getConstructor()
16316 ->isTrivial()) {
16317 Result = MaybeCreateExprWithCleanups(Result);
16318 CopyExpr = Result.get();
16319 }
16320 }
16321 }
16322
16323 BlockDecl::Capture NewCap(Var, Cap.isBlockCapture(), Cap.isNested(),
16324 CopyExpr);
16325 Captures.push_back(NewCap);
16326 }
16327 BD->setCaptures(Context, Captures, BSI->CXXThisCaptureIndex != 0);
16328
16329 // Pop the block scope now but keep it alive to the end of this function.
16330 AnalysisBasedWarnings::Policy WP = AnalysisWarnings.getDefaultPolicy();
16331 PoppedFunctionScopePtr ScopeRAII = PopFunctionScopeInfo(&WP, BD, BlockTy);
16332
16333 BlockExpr *Result = new (Context) BlockExpr(BD, BlockTy);
16334
16335 // If the block isn't obviously global, i.e. it captures anything at
16336 // all, then we need to do a few things in the surrounding context:
16337 if (Result->getBlockDecl()->hasCaptures()) {
16338 // First, this expression has a new cleanup object.
16339 ExprCleanupObjects.push_back(Result->getBlockDecl());
16340 Cleanup.setExprNeedsCleanups(true);
16341
16342 // It also gets a branch-protected scope if any of the captured
16343 // variables needs destruction.
16344 for (const auto &CI : Result->getBlockDecl()->captures()) {
16345 const VarDecl *var = CI.getVariable();
16346 if (var->getType().isDestructedType() != QualType::DK_none) {
16347 setFunctionHasBranchProtectedScope();
16348 break;
16349 }
16350 }
16351 }
16352
16353 if (getCurFunction())
16354 getCurFunction()->addBlock(BD);
16355
16356 return Result;
16357}
16358
16359ExprResult Sema::ActOnVAArg(SourceLocation BuiltinLoc, Expr *E, ParsedType Ty,
16360 SourceLocation RPLoc) {
16361 TypeSourceInfo *TInfo;
16362 GetTypeFromParser(Ty, &TInfo);
16363 return BuildVAArgExpr(BuiltinLoc, E, TInfo, RPLoc);
16364}
16365
16366ExprResult Sema::BuildVAArgExpr(SourceLocation BuiltinLoc,
16367 Expr *E, TypeSourceInfo *TInfo,
16368 SourceLocation RPLoc) {
16369 Expr *OrigExpr = E;
16370 bool IsMS = false;
16371
16372 // CUDA device code does not support varargs.
16373 if (getLangOpts().CUDA && getLangOpts().CUDAIsDevice) {
16374 if (const FunctionDecl *F = dyn_cast<FunctionDecl>(CurContext)) {
16375 CUDAFunctionTarget T = IdentifyCUDATarget(F);
16376 if (T == CFT_Global || T == CFT_Device || T == CFT_HostDevice)
16377 return ExprError(Diag(E->getBeginLoc(), diag::err_va_arg_in_device));
16378 }
16379 }
16380
16381 // NVPTX does not support va_arg expression.
16382 if (getLangOpts().OpenMP && getLangOpts().OpenMPIsDevice &&
16383 Context.getTargetInfo().getTriple().isNVPTX())
16384 targetDiag(E->getBeginLoc(), diag::err_va_arg_in_device);
16385
16386 // It might be a __builtin_ms_va_list. (But don't ever mark a va_arg()
16387 // as Microsoft ABI on an actual Microsoft platform, where
16388 // __builtin_ms_va_list and __builtin_va_list are the same.)
16389 if (!E->isTypeDependent() && Context.getTargetInfo().hasBuiltinMSVaList() &&
16390 Context.getTargetInfo().getBuiltinVaListKind() != TargetInfo::CharPtrBuiltinVaList) {
16391 QualType MSVaListType = Context.getBuiltinMSVaListType();
16392 if (Context.hasSameType(MSVaListType, E->getType())) {
16393 if (CheckForModifiableLvalue(E, BuiltinLoc, *this))
16394 return ExprError();
16395 IsMS = true;
16396 }
16397 }
16398
16399 // Get the va_list type
16400 QualType VaListType = Context.getBuiltinVaListType();
16401 if (!IsMS) {
16402 if (VaListType->isArrayType()) {
16403 // Deal with implicit array decay; for example, on x86-64,
16404 // va_list is an array, but it's supposed to decay to
16405 // a pointer for va_arg.
16406 VaListType = Context.getArrayDecayedType(VaListType);
16407 // Make sure the input expression also decays appropriately.
16408 ExprResult Result = UsualUnaryConversions(E);
16409 if (Result.isInvalid())
16410 return ExprError();
16411 E = Result.get();
16412 } else if (VaListType->isRecordType() && getLangOpts().CPlusPlus) {
16413 // If va_list is a record type and we are compiling in C++ mode,
16414 // check the argument using reference binding.
16415 InitializedEntity Entity = InitializedEntity::InitializeParameter(
16416 Context, Context.getLValueReferenceType(VaListType), false);
16417 ExprResult Init = PerformCopyInitialization(Entity, SourceLocation(), E);
16418 if (Init.isInvalid())
16419 return ExprError();
16420 E = Init.getAs<Expr>();
16421 } else {
16422 // Otherwise, the va_list argument must be an l-value because
16423 // it is modified by va_arg.
16424 if (!E->isTypeDependent() &&
16425 CheckForModifiableLvalue(E, BuiltinLoc, *this))
16426 return ExprError();
16427 }
16428 }
16429
16430 if (!IsMS && !E->isTypeDependent() &&
16431 !Context.hasSameType(VaListType, E->getType()))
16432 return ExprError(
16433 Diag(E->getBeginLoc(),
16434 diag::err_first_argument_to_va_arg_not_of_type_va_list)
16435 << OrigExpr->getType() << E->getSourceRange());
16436
16437 if (!TInfo->getType()->isDependentType()) {
16438 if (RequireCompleteType(TInfo->getTypeLoc().getBeginLoc(), TInfo->getType(),
16439 diag::err_second_parameter_to_va_arg_incomplete,
16440 TInfo->getTypeLoc()))
16441 return ExprError();
16442
16443 if (RequireNonAbstractType(TInfo->getTypeLoc().getBeginLoc(),
16444 TInfo->getType(),
16445 diag::err_second_parameter_to_va_arg_abstract,
16446 TInfo->getTypeLoc()))
16447 return ExprError();
16448
16449 if (!TInfo->getType().isPODType(Context)) {
16450 Diag(TInfo->getTypeLoc().getBeginLoc(),
16451 TInfo->getType()->isObjCLifetimeType()
16452 ? diag::warn_second_parameter_to_va_arg_ownership_qualified
16453 : diag::warn_second_parameter_to_va_arg_not_pod)
16454 << TInfo->getType()
16455 << TInfo->getTypeLoc().getSourceRange();
16456 }
16457
16458 // Check for va_arg where arguments of the given type will be promoted
16459 // (i.e. this va_arg is guaranteed to have undefined behavior).
16460 QualType PromoteType;
16461 if (TInfo->getType()->isPromotableIntegerType()) {
16462 PromoteType = Context.getPromotedIntegerType(TInfo->getType());
16463 // [cstdarg.syn]p1 defers the C++ behavior to what the C standard says,
16464 // and C2x 7.16.1.1p2 says, in part:
16465 // If type is not compatible with the type of the actual next argument
16466 // (as promoted according to the default argument promotions), the
16467 // behavior is undefined, except for the following cases:
16468 // - both types are pointers to qualified or unqualified versions of
16469 // compatible types;
16470 // - one type is a signed integer type, the other type is the
16471 // corresponding unsigned integer type, and the value is
16472 // representable in both types;
16473 // - one type is pointer to qualified or unqualified void and the
16474 // other is a pointer to a qualified or unqualified character type.
16475 // Given that type compatibility is the primary requirement (ignoring
16476 // qualifications), you would think we could call typesAreCompatible()
16477 // directly to test this. However, in C++, that checks for *same type*,
16478 // which causes false positives when passing an enumeration type to
16479 // va_arg. Instead, get the underlying type of the enumeration and pass
16480 // that.
16481 QualType UnderlyingType = TInfo->getType();
16482 if (const auto *ET = UnderlyingType->getAs<EnumType>())
16483 UnderlyingType = ET->getDecl()->getIntegerType();
16484 if (Context.typesAreCompatible(PromoteType, UnderlyingType,
16485 /*CompareUnqualified*/ true))
16486 PromoteType = QualType();
16487
16488 // If the types are still not compatible, we need to test whether the
16489 // promoted type and the underlying type are the same except for
16490 // signedness. Ask the AST for the correctly corresponding type and see
16491 // if that's compatible.
16492 if (!PromoteType.isNull() && !UnderlyingType->isBooleanType() &&
16493 PromoteType->isUnsignedIntegerType() !=
16494 UnderlyingType->isUnsignedIntegerType()) {
16495 UnderlyingType =
16496 UnderlyingType->isUnsignedIntegerType()
16497 ? Context.getCorrespondingSignedType(UnderlyingType)
16498 : Context.getCorrespondingUnsignedType(UnderlyingType);
16499 if (Context.typesAreCompatible(PromoteType, UnderlyingType,
16500 /*CompareUnqualified*/ true))
16501 PromoteType = QualType();
16502 }
16503 }
16504 if (TInfo->getType()->isSpecificBuiltinType(BuiltinType::Float))
16505 PromoteType = Context.DoubleTy;
16506 if (!PromoteType.isNull())
16507 DiagRuntimeBehavior(TInfo->getTypeLoc().getBeginLoc(), E,
16508 PDiag(diag::warn_second_parameter_to_va_arg_never_compatible)
16509 << TInfo->getType()
16510 << PromoteType
16511 << TInfo->getTypeLoc().getSourceRange());
16512 }
16513
16514 QualType T = TInfo->getType().getNonLValueExprType(Context);
16515 return new (Context) VAArgExpr(BuiltinLoc, E, TInfo, RPLoc, T, IsMS);
16516}
16517
16518ExprResult Sema::ActOnGNUNullExpr(SourceLocation TokenLoc) {
16519 // The type of __null will be int or long, depending on the size of
16520 // pointers on the target.
16521 QualType Ty;
16522 unsigned pw = Context.getTargetInfo().getPointerWidth(0);
16523 if (pw == Context.getTargetInfo().getIntWidth())
16524 Ty = Context.IntTy;
16525 else if (pw == Context.getTargetInfo().getLongWidth())
16526 Ty = Context.LongTy;
16527 else if (pw == Context.getTargetInfo().getLongLongWidth())
16528 Ty = Context.LongLongTy;
16529 else {
16530 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", 16530)
;
16531 }
16532
16533 return new (Context) GNUNullExpr(Ty, TokenLoc);
16534}
16535
16536static CXXRecordDecl *LookupStdSourceLocationImpl(Sema &S, SourceLocation Loc) {
16537 CXXRecordDecl *ImplDecl = nullptr;
16538
16539 // Fetch the std::source_location::__impl decl.
16540 if (NamespaceDecl *Std = S.getStdNamespace()) {
16541 LookupResult ResultSL(S, &S.PP.getIdentifierTable().get("source_location"),
16542 Loc, Sema::LookupOrdinaryName);
16543 if (S.LookupQualifiedName(ResultSL, Std)) {
16544 if (auto *SLDecl = ResultSL.getAsSingle<RecordDecl>()) {
16545 LookupResult ResultImpl(S, &S.PP.getIdentifierTable().get("__impl"),
16546 Loc, Sema::LookupOrdinaryName);
16547 if ((SLDecl->isCompleteDefinition() || SLDecl->isBeingDefined()) &&
16548 S.LookupQualifiedName(ResultImpl, SLDecl)) {
16549 ImplDecl = ResultImpl.getAsSingle<CXXRecordDecl>();
16550 }
16551 }
16552 }
16553 }
16554
16555 if (!ImplDecl || !ImplDecl->isCompleteDefinition()) {
16556 S.Diag(Loc, diag::err_std_source_location_impl_not_found);
16557 return nullptr;
16558 }
16559
16560 // Verify that __impl is a trivial struct type, with no base classes, and with
16561 // only the four expected fields.
16562 if (ImplDecl->isUnion() || !ImplDecl->isStandardLayout() ||
16563 ImplDecl->getNumBases() != 0) {
16564 S.Diag(Loc, diag::err_std_source_location_impl_malformed);
16565 return nullptr;
16566 }
16567
16568 unsigned Count = 0;
16569 for (FieldDecl *F : ImplDecl->fields()) {
16570 StringRef Name = F->getName();
16571
16572 if (Name == "_M_file_name") {
16573 if (F->getType() !=
16574 S.Context.getPointerType(S.Context.CharTy.withConst()))
16575 break;
16576 Count++;
16577 } else if (Name == "_M_function_name") {
16578 if (F->getType() !=
16579 S.Context.getPointerType(S.Context.CharTy.withConst()))
16580 break;
16581 Count++;
16582 } else if (Name == "_M_line") {
16583 if (!F->getType()->isIntegerType())
16584 break;
16585 Count++;
16586 } else if (Name == "_M_column") {
16587 if (!F->getType()->isIntegerType())
16588 break;
16589 Count++;
16590 } else {
16591 Count = 100; // invalid
16592 break;
16593 }
16594 }
16595 if (Count != 4) {
16596 S.Diag(Loc, diag::err_std_source_location_impl_malformed);
16597 return nullptr;
16598 }
16599
16600 return ImplDecl;
16601}
16602
16603ExprResult Sema::ActOnSourceLocExpr(SourceLocExpr::IdentKind Kind,
16604 SourceLocation BuiltinLoc,
16605 SourceLocation RPLoc) {
16606 QualType ResultTy;
16607 switch (Kind) {
16608 case SourceLocExpr::File:
16609 case SourceLocExpr::Function: {
16610 QualType ArrTy = Context.getStringLiteralArrayType(Context.CharTy, 0);
16611 ResultTy =
16612 Context.getPointerType(ArrTy->getAsArrayTypeUnsafe()->getElementType());
16613 break;
16614 }
16615 case SourceLocExpr::Line:
16616 case SourceLocExpr::Column:
16617 ResultTy = Context.UnsignedIntTy;
16618 break;
16619 case SourceLocExpr::SourceLocStruct:
16620 if (!StdSourceLocationImplDecl) {
16621 StdSourceLocationImplDecl =
16622 LookupStdSourceLocationImpl(*this, BuiltinLoc);
16623 if (!StdSourceLocationImplDecl)
16624 return ExprError();
16625 }
16626 ResultTy = Context.getPointerType(
16627 Context.getRecordType(StdSourceLocationImplDecl).withConst());
16628 break;
16629 }
16630
16631 return BuildSourceLocExpr(Kind, ResultTy, BuiltinLoc, RPLoc, CurContext);
16632}
16633
16634ExprResult Sema::BuildSourceLocExpr(SourceLocExpr::IdentKind Kind,
16635 QualType ResultTy,
16636 SourceLocation BuiltinLoc,
16637 SourceLocation RPLoc,
16638 DeclContext *ParentContext) {
16639 return new (Context)
16640 SourceLocExpr(Context, Kind, ResultTy, BuiltinLoc, RPLoc, ParentContext);
16641}
16642
16643bool Sema::CheckConversionToObjCLiteral(QualType DstType, Expr *&Exp,
16644 bool Diagnose) {
16645 if (!getLangOpts().ObjC)
16646 return false;
16647
16648 const ObjCObjectPointerType *PT = DstType->getAs<ObjCObjectPointerType>();
16649 if (!PT)
16650 return false;
16651 const ObjCInterfaceDecl *ID = PT->getInterfaceDecl();
16652
16653 // Ignore any parens, implicit casts (should only be
16654 // array-to-pointer decays), and not-so-opaque values. The last is
16655 // important for making this trigger for property assignments.
16656 Expr *SrcExpr = Exp->IgnoreParenImpCasts();
16657 if (OpaqueValueExpr *OV = dyn_cast<OpaqueValueExpr>(SrcExpr))
16658 if (OV->getSourceExpr())
16659 SrcExpr = OV->getSourceExpr()->IgnoreParenImpCasts();
16660
16661 if (auto *SL = dyn_cast<StringLiteral>(SrcExpr)) {
16662 if (!PT->isObjCIdType() &&
16663 !(ID && ID->getIdentifier()->isStr("NSString")))
16664 return false;
16665 if (!SL->isAscii())
16666 return false;
16667
16668 if (Diagnose) {
16669 Diag(SL->getBeginLoc(), diag::err_missing_atsign_prefix)
16670 << /*string*/0 << FixItHint::CreateInsertion(SL->getBeginLoc(), "@");
16671 Exp = BuildObjCStringLiteral(SL->getBeginLoc(), SL).get();
16672 }
16673 return true;
16674 }
16675
16676 if ((isa<IntegerLiteral>(SrcExpr) || isa<CharacterLiteral>(SrcExpr) ||
16677 isa<FloatingLiteral>(SrcExpr) || isa<ObjCBoolLiteralExpr>(SrcExpr) ||
16678 isa<CXXBoolLiteralExpr>(SrcExpr)) &&
16679 !SrcExpr->isNullPointerConstant(
16680 getASTContext(), Expr::NPC_NeverValueDependent)) {
16681 if (!ID || !ID->getIdentifier()->isStr("NSNumber"))
16682 return false;
16683 if (Diagnose) {
16684 Diag(SrcExpr->getBeginLoc(), diag::err_missing_atsign_prefix)
16685 << /*number*/1
16686 << FixItHint::CreateInsertion(SrcExpr->getBeginLoc(), "@");
16687 Expr *NumLit =
16688 BuildObjCNumericLiteral(SrcExpr->getBeginLoc(), SrcExpr).get();
16689 if (NumLit)
16690 Exp = NumLit;
16691 }
16692 return true;
16693 }
16694
16695 return false;
16696}
16697
16698static bool maybeDiagnoseAssignmentToFunction(Sema &S, QualType DstType,
16699 const Expr *SrcExpr) {
16700 if (!DstType->isFunctionPointerType() ||
16701 !SrcExpr->getType()->isFunctionType())
16702 return false;
16703
16704 auto *DRE = dyn_cast<DeclRefExpr>(SrcExpr->IgnoreParenImpCasts());
16705 if (!DRE)
16706 return false;
16707
16708 auto *FD = dyn_cast<FunctionDecl>(DRE->getDecl());
16709 if (!FD)
16710 return false;
16711
16712 return !S.checkAddressOfFunctionIsAvailable(FD,
16713 /*Complain=*/true,
16714 SrcExpr->getBeginLoc());
16715}
16716
16717bool Sema::DiagnoseAssignmentResult(AssignConvertType ConvTy,
16718 SourceLocation Loc,
16719 QualType DstType, QualType SrcType,
16720 Expr *SrcExpr, AssignmentAction Action,
16721 bool *Complained) {
16722 if (Complained)
16723 *Complained = false;
16724
16725 // Decode the result (notice that AST's are still created for extensions).
16726 bool CheckInferredResultType = false;
16727 bool isInvalid = false;
16728 unsigned DiagKind = 0;
16729 ConversionFixItGenerator ConvHints;
16730 bool MayHaveConvFixit = false;
16731 bool MayHaveFunctionDiff = false;
16732 const ObjCInterfaceDecl *IFace = nullptr;
16733 const ObjCProtocolDecl *PDecl = nullptr;
16734
16735 switch (ConvTy) {
16736 case Compatible:
16737 DiagnoseAssignmentEnum(DstType, SrcType, SrcExpr);
16738 return false;
16739
16740 case PointerToInt:
16741 if (getLangOpts().CPlusPlus) {
16742 DiagKind = diag::err_typecheck_convert_pointer_int;
16743 isInvalid = true;
16744 } else {
16745 DiagKind = diag::ext_typecheck_convert_pointer_int;
16746 }
16747 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
16748 MayHaveConvFixit = true;
16749 break;
16750 case IntToPointer:
16751 if (getLangOpts().CPlusPlus) {
16752 DiagKind = diag::err_typecheck_convert_int_pointer;
16753 isInvalid = true;
16754 } else {
16755 DiagKind = diag::ext_typecheck_convert_int_pointer;
16756 }
16757 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
16758 MayHaveConvFixit = true;
16759 break;
16760 case IncompatibleFunctionPointer:
16761 if (getLangOpts().CPlusPlus) {
16762 DiagKind = diag::err_typecheck_convert_incompatible_function_pointer;
16763 isInvalid = true;
16764 } else {
16765 DiagKind = diag::ext_typecheck_convert_incompatible_function_pointer;
16766 }
16767 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
16768 MayHaveConvFixit = true;
16769 break;
16770 case IncompatiblePointer:
16771 if (Action == AA_Passing_CFAudited) {
16772 DiagKind = diag::err_arc_typecheck_convert_incompatible_pointer;
16773 } else if (getLangOpts().CPlusPlus) {
16774 DiagKind = diag::err_typecheck_convert_incompatible_pointer;
16775 isInvalid = true;
16776 } else {
16777 DiagKind = diag::ext_typecheck_convert_incompatible_pointer;
16778 }
16779 CheckInferredResultType = DstType->isObjCObjectPointerType() &&
16780 SrcType->isObjCObjectPointerType();
16781 if (!CheckInferredResultType) {
16782 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
16783 } else if (CheckInferredResultType) {
16784 SrcType = SrcType.getUnqualifiedType();
16785 DstType = DstType.getUnqualifiedType();
16786 }
16787 MayHaveConvFixit = true;
16788 break;
16789 case IncompatiblePointerSign:
16790 if (getLangOpts().CPlusPlus) {
16791 DiagKind = diag::err_typecheck_convert_incompatible_pointer_sign;
16792 isInvalid = true;
16793 } else {
16794 DiagKind = diag::ext_typecheck_convert_incompatible_pointer_sign;
16795 }
16796 break;
16797 case FunctionVoidPointer:
16798 if (getLangOpts().CPlusPlus) {
16799 DiagKind = diag::err_typecheck_convert_pointer_void_func;
16800 isInvalid = true;
16801 } else {
16802 DiagKind = diag::ext_typecheck_convert_pointer_void_func;
16803 }
16804 break;
16805 case IncompatiblePointerDiscardsQualifiers: {
16806 // Perform array-to-pointer decay if necessary.
16807 if (SrcType->isArrayType()) SrcType = Context.getArrayDecayedType(SrcType);
16808
16809 isInvalid = true;
16810
16811 Qualifiers lhq = SrcType->getPointeeType().getQualifiers();
16812 Qualifiers rhq = DstType->getPointeeType().getQualifiers();
16813 if (lhq.getAddressSpace() != rhq.getAddressSpace()) {
16814 DiagKind = diag::err_typecheck_incompatible_address_space;
16815 break;
16816
16817 } else if (lhq.getObjCLifetime() != rhq.getObjCLifetime()) {
16818 DiagKind = diag::err_typecheck_incompatible_ownership;
16819 break;
16820 }
16821
16822 llvm_unreachable("unknown error case for discarding qualifiers!")::llvm::llvm_unreachable_internal("unknown error case for discarding qualifiers!"
, "clang/lib/Sema/SemaExpr.cpp", 16822)
;
16823 // fallthrough
16824 }
16825 case CompatiblePointerDiscardsQualifiers:
16826 // If the qualifiers lost were because we were applying the
16827 // (deprecated) C++ conversion from a string literal to a char*
16828 // (or wchar_t*), then there was no error (C++ 4.2p2). FIXME:
16829 // Ideally, this check would be performed in
16830 // checkPointerTypesForAssignment. However, that would require a
16831 // bit of refactoring (so that the second argument is an
16832 // expression, rather than a type), which should be done as part
16833 // of a larger effort to fix checkPointerTypesForAssignment for
16834 // C++ semantics.
16835 if (getLangOpts().CPlusPlus &&
16836 IsStringLiteralToNonConstPointerConversion(SrcExpr, DstType))
16837 return false;
16838 if (getLangOpts().CPlusPlus) {
16839 DiagKind = diag::err_typecheck_convert_discards_qualifiers;
16840 isInvalid = true;
16841 } else {
16842 DiagKind = diag::ext_typecheck_convert_discards_qualifiers;
16843 }
16844
16845 break;
16846 case IncompatibleNestedPointerQualifiers:
16847 if (getLangOpts().CPlusPlus) {
16848 isInvalid = true;
16849 DiagKind = diag::err_nested_pointer_qualifier_mismatch;
16850 } else {
16851 DiagKind = diag::ext_nested_pointer_qualifier_mismatch;
16852 }
16853 break;
16854 case IncompatibleNestedPointerAddressSpaceMismatch:
16855 DiagKind = diag::err_typecheck_incompatible_nested_address_space;
16856 isInvalid = true;
16857 break;
16858 case IntToBlockPointer:
16859 DiagKind = diag::err_int_to_block_pointer;
16860 isInvalid = true;
16861 break;
16862 case IncompatibleBlockPointer:
16863 DiagKind = diag::err_typecheck_convert_incompatible_block_pointer;
16864 isInvalid = true;
16865 break;
16866 case IncompatibleObjCQualifiedId: {
16867 if (SrcType->isObjCQualifiedIdType()) {
16868 const ObjCObjectPointerType *srcOPT =
16869 SrcType->castAs<ObjCObjectPointerType>();
16870 for (auto *srcProto : srcOPT->quals()) {
16871 PDecl = srcProto;
16872 break;
16873 }
16874 if (const ObjCInterfaceType *IFaceT =
16875 DstType->castAs<ObjCObjectPointerType>()->getInterfaceType())
16876 IFace = IFaceT->getDecl();
16877 }
16878 else if (DstType->isObjCQualifiedIdType()) {
16879 const ObjCObjectPointerType *dstOPT =
16880 DstType->castAs<ObjCObjectPointerType>();
16881 for (auto *dstProto : dstOPT->quals()) {
16882 PDecl = dstProto;
16883 break;
16884 }
16885 if (const ObjCInterfaceType *IFaceT =
16886 SrcType->castAs<ObjCObjectPointerType>()->getInterfaceType())
16887 IFace = IFaceT->getDecl();
16888 }
16889 if (getLangOpts().CPlusPlus) {
16890 DiagKind = diag::err_incompatible_qualified_id;
16891 isInvalid = true;
16892 } else {
16893 DiagKind = diag::warn_incompatible_qualified_id;
16894 }
16895 break;
16896 }
16897 case IncompatibleVectors:
16898 if (getLangOpts().CPlusPlus) {
16899 DiagKind = diag::err_incompatible_vectors;
16900 isInvalid = true;
16901 } else {
16902 DiagKind = diag::warn_incompatible_vectors;
16903 }
16904 break;
16905 case IncompatibleObjCWeakRef:
16906 DiagKind = diag::err_arc_weak_unavailable_assign;
16907 isInvalid = true;
16908 break;
16909 case Incompatible:
16910 if (maybeDiagnoseAssignmentToFunction(*this, DstType, SrcExpr)) {
16911 if (Complained)
16912 *Complained = true;
16913 return true;
16914 }
16915
16916 DiagKind = diag::err_typecheck_convert_incompatible;
16917 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
16918 MayHaveConvFixit = true;
16919 isInvalid = true;
16920 MayHaveFunctionDiff = true;
16921 break;
16922 }
16923
16924 QualType FirstType, SecondType;
16925 switch (Action) {
16926 case AA_Assigning:
16927 case AA_Initializing:
16928 // The destination type comes first.
16929 FirstType = DstType;
16930 SecondType = SrcType;
16931 break;
16932
16933 case AA_Returning:
16934 case AA_Passing:
16935 case AA_Passing_CFAudited:
16936 case AA_Converting:
16937 case AA_Sending:
16938 case AA_Casting:
16939 // The source type comes first.
16940 FirstType = SrcType;
16941 SecondType = DstType;
16942 break;
16943 }
16944
16945 PartialDiagnostic FDiag = PDiag(DiagKind);
16946 if (Action == AA_Passing_CFAudited)
16947 FDiag << FirstType << SecondType << AA_Passing << SrcExpr->getSourceRange();
16948 else
16949 FDiag << FirstType << SecondType << Action << SrcExpr->getSourceRange();
16950
16951 if (DiagKind == diag::ext_typecheck_convert_incompatible_pointer_sign ||
16952 DiagKind == diag::err_typecheck_convert_incompatible_pointer_sign) {
16953 auto isPlainChar = [](const clang::Type *Type) {
16954 return Type->isSpecificBuiltinType(BuiltinType::Char_S) ||
16955 Type->isSpecificBuiltinType(BuiltinType::Char_U);
16956 };
16957 FDiag << (isPlainChar(FirstType->getPointeeOrArrayElementType()) ||
16958 isPlainChar(SecondType->getPointeeOrArrayElementType()));
16959 }
16960
16961 // If we can fix the conversion, suggest the FixIts.
16962 if (!ConvHints.isNull()) {
16963 for (FixItHint &H : ConvHints.Hints)
16964 FDiag << H;
16965 }
16966
16967 if (MayHaveConvFixit) { FDiag << (unsigned) (ConvHints.Kind); }
16968
16969 if (MayHaveFunctionDiff)
16970 HandleFunctionTypeMismatch(FDiag, SecondType, FirstType);
16971
16972 Diag(Loc, FDiag);
16973 if ((DiagKind == diag::warn_incompatible_qualified_id ||
16974 DiagKind == diag::err_incompatible_qualified_id) &&
16975 PDecl && IFace && !IFace->hasDefinition())
16976 Diag(IFace->getLocation(), diag::note_incomplete_class_and_qualified_id)
16977 << IFace << PDecl;
16978
16979 if (SecondType == Context.OverloadTy)
16980 NoteAllOverloadCandidates(OverloadExpr::find(SrcExpr).Expression,
16981 FirstType, /*TakingAddress=*/true);
16982
16983 if (CheckInferredResultType)
16984 EmitRelatedResultTypeNote(SrcExpr);
16985
16986 if (Action == AA_Returning && ConvTy == IncompatiblePointer)
16987 EmitRelatedResultTypeNoteForReturn(DstType);
16988
16989 if (Complained)
16990 *Complained = true;
16991 return isInvalid;
16992}
16993
16994ExprResult Sema::VerifyIntegerConstantExpression(Expr *E,
16995 llvm::APSInt *Result,
16996 AllowFoldKind CanFold) {
16997 class SimpleICEDiagnoser : public VerifyICEDiagnoser {
16998 public:
16999 SemaDiagnosticBuilder diagnoseNotICEType(Sema &S, SourceLocation Loc,
17000 QualType T) override {
17001 return S.Diag(Loc, diag::err_ice_not_integral)
17002 << T << S.LangOpts.CPlusPlus;
17003 }
17004 SemaDiagnosticBuilder diagnoseNotICE(Sema &S, SourceLocation Loc) override {
17005 return S.Diag(Loc, diag::err_expr_not_ice) << S.LangOpts.CPlusPlus;
17006 }
17007 } Diagnoser;
17008
17009 return VerifyIntegerConstantExpression(E, Result, Diagnoser, CanFold);
17010}
17011
17012ExprResult Sema::VerifyIntegerConstantExpression(Expr *E,
17013 llvm::APSInt *Result,
17014 unsigned DiagID,
17015 AllowFoldKind CanFold) {
17016 class IDDiagnoser : public VerifyICEDiagnoser {
17017 unsigned DiagID;
17018
17019 public:
17020 IDDiagnoser(unsigned DiagID)
17021 : VerifyICEDiagnoser(DiagID == 0), DiagID(DiagID) { }
17022
17023 SemaDiagnosticBuilder diagnoseNotICE(Sema &S, SourceLocation Loc) override {
17024 return S.Diag(Loc, DiagID);
17025 }
17026 } Diagnoser(DiagID);
17027
17028 return VerifyIntegerConstantExpression(E, Result, Diagnoser, CanFold);
17029}
17030
17031Sema::SemaDiagnosticBuilder
17032Sema::VerifyICEDiagnoser::diagnoseNotICEType(Sema &S, SourceLocation Loc,
17033 QualType T) {
17034 return diagnoseNotICE(S, Loc);
17035}
17036
17037Sema::SemaDiagnosticBuilder
17038Sema::VerifyICEDiagnoser::diagnoseFold(Sema &S, SourceLocation Loc) {
17039 return S.Diag(Loc, diag::ext_expr_not_ice) << S.LangOpts.CPlusPlus;
17040}
17041
17042ExprResult
17043Sema::VerifyIntegerConstantExpression(Expr *E, llvm::APSInt *Result,
17044 VerifyICEDiagnoser &Diagnoser,
17045 AllowFoldKind CanFold) {
17046 SourceLocation DiagLoc = E->getBeginLoc();
17047
17048 if (getLangOpts().CPlusPlus11) {
17049 // C++11 [expr.const]p5:
17050 // If an expression of literal class type is used in a context where an
17051 // integral constant expression is required, then that class type shall
17052 // have a single non-explicit conversion function to an integral or
17053 // unscoped enumeration type
17054 ExprResult Converted;
17055 class CXX11ConvertDiagnoser : public ICEConvertDiagnoser {
17056 VerifyICEDiagnoser &BaseDiagnoser;
17057 public:
17058 CXX11ConvertDiagnoser(VerifyICEDiagnoser &BaseDiagnoser)
17059 : ICEConvertDiagnoser(/*AllowScopedEnumerations*/ false,
17060 BaseDiagnoser.Suppress, true),
17061 BaseDiagnoser(BaseDiagnoser) {}
17062
17063 SemaDiagnosticBuilder diagnoseNotInt(Sema &S, SourceLocation Loc,
17064 QualType T) override {
17065 return BaseDiagnoser.diagnoseNotICEType(S, Loc, T);
17066 }
17067
17068 SemaDiagnosticBuilder diagnoseIncomplete(
17069 Sema &S, SourceLocation Loc, QualType T) override {
17070 return S.Diag(Loc, diag::err_ice_incomplete_type) << T;
17071 }
17072
17073 SemaDiagnosticBuilder diagnoseExplicitConv(
17074 Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) override {
17075 return S.Diag(Loc, diag::err_ice_explicit_conversion) << T << ConvTy;
17076 }
17077
17078 SemaDiagnosticBuilder noteExplicitConv(
17079 Sema &S, CXXConversionDecl *Conv, QualType ConvTy) override {
17080 return S.Diag(Conv->getLocation(), diag::note_ice_conversion_here)
17081 << ConvTy->isEnumeralType() << ConvTy;
17082 }
17083
17084 SemaDiagnosticBuilder diagnoseAmbiguous(
17085 Sema &S, SourceLocation Loc, QualType T) override {
17086 return S.Diag(Loc, diag::err_ice_ambiguous_conversion) << T;
17087 }
17088
17089 SemaDiagnosticBuilder noteAmbiguous(
17090 Sema &S, CXXConversionDecl *Conv, QualType ConvTy) override {
17091 return S.Diag(Conv->getLocation(), diag::note_ice_conversion_here)
17092 << ConvTy->isEnumeralType() << ConvTy;
17093 }
17094
17095 SemaDiagnosticBuilder diagnoseConversion(
17096 Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) override {
17097 llvm_unreachable("conversion functions are permitted")::llvm::llvm_unreachable_internal("conversion functions are permitted"
, "clang/lib/Sema/SemaExpr.cpp", 17097)
;
17098 }
17099 } ConvertDiagnoser(Diagnoser);
17100
17101 Converted = PerformContextualImplicitConversion(DiagLoc, E,
17102 ConvertDiagnoser);
17103 if (Converted.isInvalid())
17104 return Converted;
17105 E = Converted.get();
17106 if (!E->getType()->isIntegralOrUnscopedEnumerationType())
17107 return ExprError();
17108 } else if (!E->getType()->isIntegralOrUnscopedEnumerationType()) {
17109 // An ICE must be of integral or unscoped enumeration type.
17110 if (!Diagnoser.Suppress)
17111 Diagnoser.diagnoseNotICEType(*this, DiagLoc, E->getType())
17112 << E->getSourceRange();
17113 return ExprError();
17114 }
17115
17116 ExprResult RValueExpr = DefaultLvalueConversion(E);
17117 if (RValueExpr.isInvalid())
17118 return ExprError();
17119
17120 E = RValueExpr.get();
17121
17122 // Circumvent ICE checking in C++11 to avoid evaluating the expression twice
17123 // in the non-ICE case.
17124 if (!getLangOpts().CPlusPlus11 && E->isIntegerConstantExpr(Context)) {
17125 if (Result)
17126 *Result = E->EvaluateKnownConstIntCheckOverflow(Context);
17127 if (!isa<ConstantExpr>(E))
17128 E = Result ? ConstantExpr::Create(Context, E, APValue(*Result))
17129 : ConstantExpr::Create(Context, E);
17130 return E;
17131 }
17132
17133 Expr::EvalResult EvalResult;
17134 SmallVector<PartialDiagnosticAt, 8> Notes;
17135 EvalResult.Diag = &Notes;
17136
17137 // Try to evaluate the expression, and produce diagnostics explaining why it's
17138 // not a constant expression as a side-effect.
17139 bool Folded =
17140 E->EvaluateAsRValue(EvalResult, Context, /*isConstantContext*/ true) &&
17141 EvalResult.Val.isInt() && !EvalResult.HasSideEffects;
17142
17143 if (!isa<ConstantExpr>(E))
17144 E = ConstantExpr::Create(Context, E, EvalResult.Val);
17145
17146 // In C++11, we can rely on diagnostics being produced for any expression
17147 // which is not a constant expression. If no diagnostics were produced, then
17148 // this is a constant expression.
17149 if (Folded && getLangOpts().CPlusPlus11 && Notes.empty()) {
17150 if (Result)
17151 *Result = EvalResult.Val.getInt();
17152 return E;
17153 }
17154
17155 // If our only note is the usual "invalid subexpression" note, just point
17156 // the caret at its location rather than producing an essentially
17157 // redundant note.
17158 if (Notes.size() == 1 && Notes[0].second.getDiagID() ==
17159 diag::note_invalid_subexpr_in_const_expr) {
17160 DiagLoc = Notes[0].first;
17161 Notes.clear();
17162 }
17163
17164 if (!Folded || !CanFold) {
17165 if (!Diagnoser.Suppress) {
17166 Diagnoser.diagnoseNotICE(*this, DiagLoc) << E->getSourceRange();
17167 for (const PartialDiagnosticAt &Note : Notes)
17168 Diag(Note.first, Note.second);
17169 }
17170
17171 return ExprError();
17172 }
17173
17174 Diagnoser.diagnoseFold(*this, DiagLoc) << E->getSourceRange();
17175 for (const PartialDiagnosticAt &Note : Notes)
17176 Diag(Note.first, Note.second);
17177
17178 if (Result)
17179 *Result = EvalResult.Val.getInt();
17180 return E;
17181}
17182
17183namespace {
17184 // Handle the case where we conclude a expression which we speculatively
17185 // considered to be unevaluated is actually evaluated.
17186 class TransformToPE : public TreeTransform<TransformToPE> {
17187 typedef TreeTransform<TransformToPE> BaseTransform;
17188
17189 public:
17190 TransformToPE(Sema &SemaRef) : BaseTransform(SemaRef) { }
17191
17192 // Make sure we redo semantic analysis
17193 bool AlwaysRebuild() { return true; }
17194 bool ReplacingOriginal() { return true; }
17195
17196 // We need to special-case DeclRefExprs referring to FieldDecls which
17197 // are not part of a member pointer formation; normal TreeTransforming
17198 // doesn't catch this case because of the way we represent them in the AST.
17199 // FIXME: This is a bit ugly; is it really the best way to handle this
17200 // case?
17201 //
17202 // Error on DeclRefExprs referring to FieldDecls.
17203 ExprResult TransformDeclRefExpr(DeclRefExpr *E) {
17204 if (isa<FieldDecl>(E->getDecl()) &&
17205 !SemaRef.isUnevaluatedContext())
17206 return SemaRef.Diag(E->getLocation(),
17207 diag::err_invalid_non_static_member_use)
17208 << E->getDecl() << E->getSourceRange();
17209
17210 return BaseTransform::TransformDeclRefExpr(E);
17211 }
17212
17213 // Exception: filter out member pointer formation
17214 ExprResult TransformUnaryOperator(UnaryOperator *E) {
17215 if (E->getOpcode() == UO_AddrOf && E->getType()->isMemberPointerType())
17216 return E;
17217
17218 return BaseTransform::TransformUnaryOperator(E);
17219 }
17220
17221 // The body of a lambda-expression is in a separate expression evaluation
17222 // context so never needs to be transformed.
17223 // FIXME: Ideally we wouldn't transform the closure type either, and would
17224 // just recreate the capture expressions and lambda expression.
17225 StmtResult TransformLambdaBody(LambdaExpr *E, Stmt *Body) {
17226 return SkipLambdaBody(E, Body);
17227 }
17228 };
17229}
17230
17231ExprResult Sema::TransformToPotentiallyEvaluated(Expr *E) {
17232 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", 17233, __extension__ __PRETTY_FUNCTION__
))
17233 "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", 17233, __extension__ __PRETTY_FUNCTION__
))
;
17234 ExprEvalContexts.back().Context =
17235 ExprEvalContexts[ExprEvalContexts.size()-2].Context;
17236 if (isUnevaluatedContext())
17237 return E;
17238 return TransformToPE(*this).TransformExpr(E);
17239}
17240
17241TypeSourceInfo *Sema::TransformToPotentiallyEvaluated(TypeSourceInfo *TInfo) {
17242 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", 17243, __extension__ __PRETTY_FUNCTION__
))
17243 "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", 17243, __extension__ __PRETTY_FUNCTION__
))
;
17244 ExprEvalContexts.back().Context =
17245 ExprEvalContexts[ExprEvalContexts.size() - 2].Context;
17246 if (isUnevaluatedContext())
17247 return TInfo;
17248 return TransformToPE(*this).TransformType(TInfo);
17249}
17250
17251void
17252Sema::PushExpressionEvaluationContext(
17253 ExpressionEvaluationContext NewContext, Decl *LambdaContextDecl,
17254 ExpressionEvaluationContextRecord::ExpressionKind ExprContext) {
17255 ExprEvalContexts.emplace_back(NewContext, ExprCleanupObjects.size(), Cleanup,
17256 LambdaContextDecl, ExprContext);
17257
17258 // Discarded statements and immediate contexts nested in other
17259 // discarded statements or immediate context are themselves
17260 // a discarded statement or an immediate context, respectively.
17261 ExprEvalContexts.back().InDiscardedStatement =
17262 ExprEvalContexts[ExprEvalContexts.size() - 2]
17263 .isDiscardedStatementContext();
17264 ExprEvalContexts.back().InImmediateFunctionContext =
17265 ExprEvalContexts[ExprEvalContexts.size() - 2]
17266 .isImmediateFunctionContext();
17267
17268 Cleanup.reset();
17269 if (!MaybeODRUseExprs.empty())
17270 std::swap(MaybeODRUseExprs, ExprEvalContexts.back().SavedMaybeODRUseExprs);
17271}
17272
17273void
17274Sema::PushExpressionEvaluationContext(
17275 ExpressionEvaluationContext NewContext, ReuseLambdaContextDecl_t,
17276 ExpressionEvaluationContextRecord::ExpressionKind ExprContext) {
17277 Decl *ClosureContextDecl = ExprEvalContexts.back().ManglingContextDecl;
17278 PushExpressionEvaluationContext(NewContext, ClosureContextDecl, ExprContext);
17279}
17280
17281namespace {
17282
17283const DeclRefExpr *CheckPossibleDeref(Sema &S, const Expr *PossibleDeref) {
17284 PossibleDeref = PossibleDeref->IgnoreParenImpCasts();
17285 if (const auto *E = dyn_cast<UnaryOperator>(PossibleDeref)) {
17286 if (E->getOpcode() == UO_Deref)
17287 return CheckPossibleDeref(S, E->getSubExpr());
17288 } else if (const auto *E = dyn_cast<ArraySubscriptExpr>(PossibleDeref)) {
17289 return CheckPossibleDeref(S, E->getBase());
17290 } else if (const auto *E = dyn_cast<MemberExpr>(PossibleDeref)) {
17291 return CheckPossibleDeref(S, E->getBase());
17292 } else if (const auto E = dyn_cast<DeclRefExpr>(PossibleDeref)) {
17293 QualType Inner;
17294 QualType Ty = E->getType();
17295 if (const auto *Ptr = Ty->getAs<PointerType>())
17296 Inner = Ptr->getPointeeType();
17297 else if (const auto *Arr = S.Context.getAsArrayType(Ty))
17298 Inner = Arr->getElementType();
17299 else
17300 return nullptr;
17301
17302 if (Inner->hasAttr(attr::NoDeref))
17303 return E;
17304 }
17305 return nullptr;
17306}
17307
17308} // namespace
17309
17310void Sema::WarnOnPendingNoDerefs(ExpressionEvaluationContextRecord &Rec) {
17311 for (const Expr *E : Rec.PossibleDerefs) {
17312 const DeclRefExpr *DeclRef = CheckPossibleDeref(*this, E);
17313 if (DeclRef) {
17314 const ValueDecl *Decl = DeclRef->getDecl();
17315 Diag(E->getExprLoc(), diag::warn_dereference_of_noderef_type)
17316 << Decl->getName() << E->getSourceRange();
17317 Diag(Decl->getLocation(), diag::note_previous_decl) << Decl->getName();
17318 } else {
17319 Diag(E->getExprLoc(), diag::warn_dereference_of_noderef_type_no_decl)
17320 << E->getSourceRange();
17321 }
17322 }
17323 Rec.PossibleDerefs.clear();
17324}
17325
17326/// Check whether E, which is either a discarded-value expression or an
17327/// unevaluated operand, is a simple-assignment to a volatlie-qualified lvalue,
17328/// and if so, remove it from the list of volatile-qualified assignments that
17329/// we are going to warn are deprecated.
17330void Sema::CheckUnusedVolatileAssignment(Expr *E) {
17331 if (!E->getType().isVolatileQualified() || !getLangOpts().CPlusPlus20)
17332 return;
17333
17334 // Note: ignoring parens here is not justified by the standard rules, but
17335 // ignoring parentheses seems like a more reasonable approach, and this only
17336 // drives a deprecation warning so doesn't affect conformance.
17337 if (auto *BO = dyn_cast<BinaryOperator>(E->IgnoreParenImpCasts())) {
17338 if (BO->getOpcode() == BO_Assign) {
17339 auto &LHSs = ExprEvalContexts.back().VolatileAssignmentLHSs;
17340 llvm::erase_value(LHSs, BO->getLHS());
17341 }
17342 }
17343}
17344
17345ExprResult Sema::CheckForImmediateInvocation(ExprResult E, FunctionDecl *Decl) {
17346 if (isUnevaluatedContext() || !E.isUsable() || !Decl ||
17347 !Decl->isConsteval() || isConstantEvaluated() ||
17348 RebuildingImmediateInvocation || isImmediateFunctionContext())
17349 return E;
17350
17351 /// Opportunistically remove the callee from ReferencesToConsteval if we can.
17352 /// It's OK if this fails; we'll also remove this in
17353 /// HandleImmediateInvocations, but catching it here allows us to avoid
17354 /// walking the AST looking for it in simple cases.
17355 if (auto *Call = dyn_cast<CallExpr>(E.get()->IgnoreImplicit()))
17356 if (auto *DeclRef =
17357 dyn_cast<DeclRefExpr>(Call->getCallee()->IgnoreImplicit()))
17358 ExprEvalContexts.back().ReferenceToConsteval.erase(DeclRef);
17359
17360 E = MaybeCreateExprWithCleanups(E);
17361
17362 ConstantExpr *Res = ConstantExpr::Create(
17363 getASTContext(), E.get(),
17364 ConstantExpr::getStorageKind(Decl->getReturnType().getTypePtr(),
17365 getASTContext()),
17366 /*IsImmediateInvocation*/ true);
17367 /// Value-dependent constant expressions should not be immediately
17368 /// evaluated until they are instantiated.
17369 if (!Res->isValueDependent())
17370 ExprEvalContexts.back().ImmediateInvocationCandidates.emplace_back(Res, 0);
17371 return Res;
17372}
17373
17374static void EvaluateAndDiagnoseImmediateInvocation(
17375 Sema &SemaRef, Sema::ImmediateInvocationCandidate Candidate) {
17376 llvm::SmallVector<PartialDiagnosticAt, 8> Notes;
17377 Expr::EvalResult Eval;
17378 Eval.Diag = &Notes;
17379 ConstantExpr *CE = Candidate.getPointer();
17380 bool Result = CE->EvaluateAsConstantExpr(
17381 Eval, SemaRef.getASTContext(), ConstantExprKind::ImmediateInvocation);
17382 if (!Result || !Notes.empty()) {
17383 Expr *InnerExpr = CE->getSubExpr()->IgnoreImplicit();
17384 if (auto *FunctionalCast = dyn_cast<CXXFunctionalCastExpr>(InnerExpr))
17385 InnerExpr = FunctionalCast->getSubExpr();
17386 FunctionDecl *FD = nullptr;
17387 if (auto *Call = dyn_cast<CallExpr>(InnerExpr))
17388 FD = cast<FunctionDecl>(Call->getCalleeDecl());
17389 else if (auto *Call = dyn_cast<CXXConstructExpr>(InnerExpr))
17390 FD = Call->getConstructor();
17391 else
17392 llvm_unreachable("unhandled decl kind")::llvm::llvm_unreachable_internal("unhandled decl kind", "clang/lib/Sema/SemaExpr.cpp"
, 17392)
;
17393 assert(FD->isConsteval())(static_cast <bool> (FD->isConsteval()) ? void (0) :
__assert_fail ("FD->isConsteval()", "clang/lib/Sema/SemaExpr.cpp"
, 17393, __extension__ __PRETTY_FUNCTION__))
;
17394 SemaRef.Diag(CE->getBeginLoc(), diag::err_invalid_consteval_call) << FD;
17395 for (auto &Note : Notes)
17396 SemaRef.Diag(Note.first, Note.second);
17397 return;
17398 }
17399 CE->MoveIntoResult(Eval.Val, SemaRef.getASTContext());
17400}
17401
17402static void RemoveNestedImmediateInvocation(
17403 Sema &SemaRef, Sema::ExpressionEvaluationContextRecord &Rec,
17404 SmallVector<Sema::ImmediateInvocationCandidate, 4>::reverse_iterator It) {
17405 struct ComplexRemove : TreeTransform<ComplexRemove> {
17406 using Base = TreeTransform<ComplexRemove>;
17407 llvm::SmallPtrSetImpl<DeclRefExpr *> &DRSet;
17408 SmallVector<Sema::ImmediateInvocationCandidate, 4> &IISet;
17409 SmallVector<Sema::ImmediateInvocationCandidate, 4>::reverse_iterator
17410 CurrentII;
17411 ComplexRemove(Sema &SemaRef, llvm::SmallPtrSetImpl<DeclRefExpr *> &DR,
17412 SmallVector<Sema::ImmediateInvocationCandidate, 4> &II,
17413 SmallVector<Sema::ImmediateInvocationCandidate,
17414 4>::reverse_iterator Current)
17415 : Base(SemaRef), DRSet(DR), IISet(II), CurrentII(Current) {}
17416 void RemoveImmediateInvocation(ConstantExpr* E) {
17417 auto It = std::find_if(CurrentII, IISet.rend(),
17418 [E](Sema::ImmediateInvocationCandidate Elem) {
17419 return Elem.getPointer() == E;
17420 });
17421 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", 17423, __extension__ __PRETTY_FUNCTION__
))
17422 "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", 17423, __extension__ __PRETTY_FUNCTION__
))
17423 "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", 17423, __extension__ __PRETTY_FUNCTION__
))
;
17424 It->setInt(1); // Mark as deleted
17425 }
17426 ExprResult TransformConstantExpr(ConstantExpr *E) {
17427 if (!E->isImmediateInvocation())
17428 return Base::TransformConstantExpr(E);
17429 RemoveImmediateInvocation(E);
17430 return Base::TransformExpr(E->getSubExpr());
17431 }
17432 /// Base::TransfromCXXOperatorCallExpr doesn't traverse the callee so
17433 /// we need to remove its DeclRefExpr from the DRSet.
17434 ExprResult TransformCXXOperatorCallExpr(CXXOperatorCallExpr *E) {
17435 DRSet.erase(cast<DeclRefExpr>(E->getCallee()->IgnoreImplicit()));
17436 return Base::TransformCXXOperatorCallExpr(E);
17437 }
17438 /// Base::TransformInitializer skip ConstantExpr so we need to visit them
17439 /// here.
17440 ExprResult TransformInitializer(Expr *Init, bool NotCopyInit) {
17441 if (!Init)
17442 return Init;
17443 /// ConstantExpr are the first layer of implicit node to be removed so if
17444 /// Init isn't a ConstantExpr, no ConstantExpr will be skipped.
17445 if (auto *CE = dyn_cast<ConstantExpr>(Init))
17446 if (CE->isImmediateInvocation())
17447 RemoveImmediateInvocation(CE);
17448 return Base::TransformInitializer(Init, NotCopyInit);
17449 }
17450 ExprResult TransformDeclRefExpr(DeclRefExpr *E) {
17451 DRSet.erase(E);
17452 return E;
17453 }
17454 bool AlwaysRebuild() { return false; }
17455 bool ReplacingOriginal() { return true; }
17456 bool AllowSkippingCXXConstructExpr() {
17457 bool Res = AllowSkippingFirstCXXConstructExpr;
17458 AllowSkippingFirstCXXConstructExpr = true;
17459 return Res;
17460 }
17461 bool AllowSkippingFirstCXXConstructExpr = true;
17462 } Transformer(SemaRef, Rec.ReferenceToConsteval,
17463 Rec.ImmediateInvocationCandidates, It);
17464
17465 /// CXXConstructExpr with a single argument are getting skipped by
17466 /// TreeTransform in some situtation because they could be implicit. This
17467 /// can only occur for the top-level CXXConstructExpr because it is used
17468 /// nowhere in the expression being transformed therefore will not be rebuilt.
17469 /// Setting AllowSkippingFirstCXXConstructExpr to false will prevent from
17470 /// skipping the first CXXConstructExpr.
17471 if (isa<CXXConstructExpr>(It->getPointer()->IgnoreImplicit()))
17472 Transformer.AllowSkippingFirstCXXConstructExpr = false;
17473
17474 ExprResult Res = Transformer.TransformExpr(It->getPointer()->getSubExpr());
17475 assert(Res.isUsable())(static_cast <bool> (Res.isUsable()) ? void (0) : __assert_fail
("Res.isUsable()", "clang/lib/Sema/SemaExpr.cpp", 17475, __extension__
__PRETTY_FUNCTION__))
;
17476 Res = SemaRef.MaybeCreateExprWithCleanups(Res);
17477 It->getPointer()->setSubExpr(Res.get());
17478}
17479
17480static void
17481HandleImmediateInvocations(Sema &SemaRef,
17482 Sema::ExpressionEvaluationContextRecord &Rec) {
17483 if ((Rec.ImmediateInvocationCandidates.size() == 0 &&
17484 Rec.ReferenceToConsteval.size() == 0) ||
17485 SemaRef.RebuildingImmediateInvocation)
17486 return;
17487
17488 /// When we have more then 1 ImmediateInvocationCandidates we need to check
17489 /// for nested ImmediateInvocationCandidates. when we have only 1 we only
17490 /// need to remove ReferenceToConsteval in the immediate invocation.
17491 if (Rec.ImmediateInvocationCandidates.size() > 1) {
17492
17493 /// Prevent sema calls during the tree transform from adding pointers that
17494 /// are already in the sets.
17495 llvm::SaveAndRestore<bool> DisableIITracking(
17496 SemaRef.RebuildingImmediateInvocation, true);
17497
17498 /// Prevent diagnostic during tree transfrom as they are duplicates
17499 Sema::TentativeAnalysisScope DisableDiag(SemaRef);
17500
17501 for (auto It = Rec.ImmediateInvocationCandidates.rbegin();
17502 It != Rec.ImmediateInvocationCandidates.rend(); It++)
17503 if (!It->getInt())
17504 RemoveNestedImmediateInvocation(SemaRef, Rec, It);
17505 } else if (Rec.ImmediateInvocationCandidates.size() == 1 &&
17506 Rec.ReferenceToConsteval.size()) {
17507 struct SimpleRemove : RecursiveASTVisitor<SimpleRemove> {
17508 llvm::SmallPtrSetImpl<DeclRefExpr *> &DRSet;
17509 SimpleRemove(llvm::SmallPtrSetImpl<DeclRefExpr *> &S) : DRSet(S) {}
17510 bool VisitDeclRefExpr(DeclRefExpr *E) {
17511 DRSet.erase(E);
17512 return DRSet.size();
17513 }
17514 } Visitor(Rec.ReferenceToConsteval);
17515 Visitor.TraverseStmt(
17516 Rec.ImmediateInvocationCandidates.front().getPointer()->getSubExpr());
17517 }
17518 for (auto CE : Rec.ImmediateInvocationCandidates)
17519 if (!CE.getInt())
17520 EvaluateAndDiagnoseImmediateInvocation(SemaRef, CE);
17521 for (auto DR : Rec.ReferenceToConsteval) {
17522 auto *FD = cast<FunctionDecl>(DR->getDecl());
17523 SemaRef.Diag(DR->getBeginLoc(), diag::err_invalid_consteval_take_address)
17524 << FD;
17525 SemaRef.Diag(FD->getLocation(), diag::note_declared_at);
17526 }
17527}
17528
17529void Sema::PopExpressionEvaluationContext() {
17530 ExpressionEvaluationContextRecord& Rec = ExprEvalContexts.back();
17531 unsigned NumTypos = Rec.NumTypos;
17532
17533 if (!Rec.Lambdas.empty()) {
17534 using ExpressionKind = ExpressionEvaluationContextRecord::ExpressionKind;
17535 if (!getLangOpts().CPlusPlus20 &&
17536 (Rec.ExprContext == ExpressionKind::EK_TemplateArgument ||
17537 Rec.isUnevaluated() ||
17538 (Rec.isConstantEvaluated() && !getLangOpts().CPlusPlus17))) {
17539 unsigned D;
17540 if (Rec.isUnevaluated()) {
17541 // C++11 [expr.prim.lambda]p2:
17542 // A lambda-expression shall not appear in an unevaluated operand
17543 // (Clause 5).
17544 D = diag::err_lambda_unevaluated_operand;
17545 } else if (Rec.isConstantEvaluated() && !getLangOpts().CPlusPlus17) {
17546 // C++1y [expr.const]p2:
17547 // A conditional-expression e is a core constant expression unless the
17548 // evaluation of e, following the rules of the abstract machine, would
17549 // evaluate [...] a lambda-expression.
17550 D = diag::err_lambda_in_constant_expression;
17551 } else if (Rec.ExprContext == ExpressionKind::EK_TemplateArgument) {
17552 // C++17 [expr.prim.lamda]p2:
17553 // A lambda-expression shall not appear [...] in a template-argument.
17554 D = diag::err_lambda_in_invalid_context;
17555 } else
17556 llvm_unreachable("Couldn't infer lambda error message.")::llvm::llvm_unreachable_internal("Couldn't infer lambda error message."
, "clang/lib/Sema/SemaExpr.cpp", 17556)
;
17557
17558 for (const auto *L : Rec.Lambdas)
17559 Diag(L->getBeginLoc(), D);
17560 }
17561 }
17562
17563 WarnOnPendingNoDerefs(Rec);
17564 HandleImmediateInvocations(*this, Rec);
17565
17566 // Warn on any volatile-qualified simple-assignments that are not discarded-
17567 // value expressions nor unevaluated operands (those cases get removed from
17568 // this list by CheckUnusedVolatileAssignment).
17569 for (auto *BO : Rec.VolatileAssignmentLHSs)
17570 Diag(BO->getBeginLoc(), diag::warn_deprecated_simple_assign_volatile)
17571 << BO->getType();
17572
17573 // When are coming out of an unevaluated context, clear out any
17574 // temporaries that we may have created as part of the evaluation of
17575 // the expression in that context: they aren't relevant because they
17576 // will never be constructed.
17577 if (Rec.isUnevaluated() || Rec.isConstantEvaluated()) {
17578 ExprCleanupObjects.erase(ExprCleanupObjects.begin() + Rec.NumCleanupObjects,
17579 ExprCleanupObjects.end());
17580 Cleanup = Rec.ParentCleanup;
17581 CleanupVarDeclMarking();
17582 std::swap(MaybeODRUseExprs, Rec.SavedMaybeODRUseExprs);
17583 // Otherwise, merge the contexts together.
17584 } else {
17585 Cleanup.mergeFrom(Rec.ParentCleanup);
17586 MaybeODRUseExprs.insert(Rec.SavedMaybeODRUseExprs.begin(),
17587 Rec.SavedMaybeODRUseExprs.end());
17588 }
17589
17590 // Pop the current expression evaluation context off the stack.
17591 ExprEvalContexts.pop_back();
17592
17593 // The global expression evaluation context record is never popped.
17594 ExprEvalContexts.back().NumTypos += NumTypos;
17595}
17596
17597void Sema::DiscardCleanupsInEvaluationContext() {
17598 ExprCleanupObjects.erase(
17599 ExprCleanupObjects.begin() + ExprEvalContexts.back().NumCleanupObjects,
17600 ExprCleanupObjects.end());
17601 Cleanup.reset();
17602 MaybeODRUseExprs.clear();
17603}
17604
17605ExprResult Sema::HandleExprEvaluationContextForTypeof(Expr *E) {
17606 ExprResult Result = CheckPlaceholderExpr(E);
17607 if (Result.isInvalid())
17608 return ExprError();
17609 E = Result.get();
17610 if (!E->getType()->isVariablyModifiedType())
17611 return E;
17612 return TransformToPotentiallyEvaluated(E);
17613}
17614
17615/// Are we in a context that is potentially constant evaluated per C++20
17616/// [expr.const]p12?
17617static bool isPotentiallyConstantEvaluatedContext(Sema &SemaRef) {
17618 /// C++2a [expr.const]p12:
17619 // An expression or conversion is potentially constant evaluated if it is
17620 switch (SemaRef.ExprEvalContexts.back().Context) {
17621 case Sema::ExpressionEvaluationContext::ConstantEvaluated:
17622 case Sema::ExpressionEvaluationContext::ImmediateFunctionContext:
17623
17624 // -- a manifestly constant-evaluated expression,
17625 case Sema::ExpressionEvaluationContext::PotentiallyEvaluated:
17626 case Sema::ExpressionEvaluationContext::PotentiallyEvaluatedIfUsed:
17627 case Sema::ExpressionEvaluationContext::DiscardedStatement:
17628 // -- a potentially-evaluated expression,
17629 case Sema::ExpressionEvaluationContext::UnevaluatedList:
17630 // -- an immediate subexpression of a braced-init-list,
17631
17632 // -- [FIXME] an expression of the form & cast-expression that occurs
17633 // within a templated entity
17634 // -- a subexpression of one of the above that is not a subexpression of
17635 // a nested unevaluated operand.
17636 return true;
17637
17638 case Sema::ExpressionEvaluationContext::Unevaluated:
17639 case Sema::ExpressionEvaluationContext::UnevaluatedAbstract:
17640 // Expressions in this context are never evaluated.
17641 return false;
17642 }
17643 llvm_unreachable("Invalid context")::llvm::llvm_unreachable_internal("Invalid context", "clang/lib/Sema/SemaExpr.cpp"
, 17643)
;
17644}
17645
17646/// Return true if this function has a calling convention that requires mangling
17647/// in the size of the parameter pack.
17648static bool funcHasParameterSizeMangling(Sema &S, FunctionDecl *FD) {
17649 // These manglings don't do anything on non-Windows or non-x86 platforms, so
17650 // we don't need parameter type sizes.
17651 const llvm::Triple &TT = S.Context.getTargetInfo().getTriple();
17652 if (!TT.isOSWindows() || !TT.isX86())
17653 return false;
17654
17655 // If this is C++ and this isn't an extern "C" function, parameters do not
17656 // need to be complete. In this case, C++ mangling will apply, which doesn't
17657 // use the size of the parameters.
17658 if (S.getLangOpts().CPlusPlus && !FD->isExternC())
17659 return false;
17660
17661 // Stdcall, fastcall, and vectorcall need this special treatment.
17662 CallingConv CC = FD->getType()->castAs<FunctionType>()->getCallConv();
17663 switch (CC) {
17664 case CC_X86StdCall:
17665 case CC_X86FastCall:
17666 case CC_X86VectorCall:
17667 return true;
17668 default:
17669 break;
17670 }
17671 return false;
17672}
17673
17674/// Require that all of the parameter types of function be complete. Normally,
17675/// parameter types are only required to be complete when a function is called
17676/// or defined, but to mangle functions with certain calling conventions, the
17677/// mangler needs to know the size of the parameter list. In this situation,
17678/// MSVC doesn't emit an error or instantiate templates. Instead, MSVC mangles
17679/// the function as _foo@0, i.e. zero bytes of parameters, which will usually
17680/// result in a linker error. Clang doesn't implement this behavior, and instead
17681/// attempts to error at compile time.
17682static void CheckCompleteParameterTypesForMangler(Sema &S, FunctionDecl *FD,
17683 SourceLocation Loc) {
17684 class ParamIncompleteTypeDiagnoser : public Sema::TypeDiagnoser {
17685 FunctionDecl *FD;
17686 ParmVarDecl *Param;
17687
17688 public:
17689 ParamIncompleteTypeDiagnoser(FunctionDecl *FD, ParmVarDecl *Param)
17690 : FD(FD), Param(Param) {}
17691
17692 void diagnose(Sema &S, SourceLocation Loc, QualType T) override {
17693 CallingConv CC = FD->getType()->castAs<FunctionType>()->getCallConv();
17694 StringRef CCName;
17695 switch (CC) {
17696 case CC_X86StdCall:
17697 CCName = "stdcall";
17698 break;
17699 case CC_X86FastCall:
17700 CCName = "fastcall";
17701 break;
17702 case CC_X86VectorCall:
17703 CCName = "vectorcall";
17704 break;
17705 default:
17706 llvm_unreachable("CC does not need mangling")::llvm::llvm_unreachable_internal("CC does not need mangling"
, "clang/lib/Sema/SemaExpr.cpp", 17706)
;
17707 }
17708
17709 S.Diag(Loc, diag::err_cconv_incomplete_param_type)
17710 << Param->getDeclName() << FD->getDeclName() << CCName;
17711 }
17712 };
17713
17714 for (ParmVarDecl *Param : FD->parameters()) {
17715 ParamIncompleteTypeDiagnoser Diagnoser(FD, Param);
17716 S.RequireCompleteType(Loc, Param->getType(), Diagnoser);
17717 }
17718}
17719
17720namespace {
17721enum class OdrUseContext {
17722 /// Declarations in this context are not odr-used.
17723 None,
17724 /// Declarations in this context are formally odr-used, but this is a
17725 /// dependent context.
17726 Dependent,
17727 /// Declarations in this context are odr-used but not actually used (yet).
17728 FormallyOdrUsed,
17729 /// Declarations in this context are used.
17730 Used
17731};
17732}
17733
17734/// Are we within a context in which references to resolved functions or to
17735/// variables result in odr-use?
17736static OdrUseContext isOdrUseContext(Sema &SemaRef) {
17737 OdrUseContext Result;
17738
17739 switch (SemaRef.ExprEvalContexts.back().Context) {
17740 case Sema::ExpressionEvaluationContext::Unevaluated:
17741 case Sema::ExpressionEvaluationContext::UnevaluatedList:
17742 case Sema::ExpressionEvaluationContext::UnevaluatedAbstract:
17743 return OdrUseContext::None;
17744
17745 case Sema::ExpressionEvaluationContext::ConstantEvaluated:
17746 case Sema::ExpressionEvaluationContext::ImmediateFunctionContext:
17747 case Sema::ExpressionEvaluationContext::PotentiallyEvaluated:
17748 Result = OdrUseContext::Used;
17749 break;
17750
17751 case Sema::ExpressionEvaluationContext::DiscardedStatement:
17752 Result = OdrUseContext::FormallyOdrUsed;
17753 break;
17754
17755 case Sema::ExpressionEvaluationContext::PotentiallyEvaluatedIfUsed:
17756 // A default argument formally results in odr-use, but doesn't actually
17757 // result in a use in any real sense until it itself is used.
17758 Result = OdrUseContext::FormallyOdrUsed;
17759 break;
17760 }
17761
17762 if (SemaRef.CurContext->isDependentContext())
17763 return OdrUseContext::Dependent;
17764
17765 return Result;
17766}
17767
17768static bool isImplicitlyDefinableConstexprFunction(FunctionDecl *Func) {
17769 if (!Func->isConstexpr())
17770 return false;
17771
17772 if (Func->isImplicitlyInstantiable() || !Func->isUserProvided())
17773 return true;
17774 auto *CCD = dyn_cast<CXXConstructorDecl>(Func);
17775 return CCD && CCD->getInheritedConstructor();
17776}
17777
17778/// Mark a function referenced, and check whether it is odr-used
17779/// (C++ [basic.def.odr]p2, C99 6.9p3)
17780void Sema::MarkFunctionReferenced(SourceLocation Loc, FunctionDecl *Func,
17781 bool MightBeOdrUse) {
17782 assert(Func && "No function?")(static_cast <bool> (Func && "No function?") ? void
(0) : __assert_fail ("Func && \"No function?\"", "clang/lib/Sema/SemaExpr.cpp"
, 17782, __extension__ __PRETTY_FUNCTION__))
;
17783
17784 Func->setReferenced();
17785
17786 // Recursive functions aren't really used until they're used from some other
17787 // context.
17788 bool IsRecursiveCall = CurContext == Func;
17789
17790 // C++11 [basic.def.odr]p3:
17791 // A function whose name appears as a potentially-evaluated expression is
17792 // odr-used if it is the unique lookup result or the selected member of a
17793 // set of overloaded functions [...].
17794 //
17795 // We (incorrectly) mark overload resolution as an unevaluated context, so we
17796 // can just check that here.
17797 OdrUseContext OdrUse =
17798 MightBeOdrUse ? isOdrUseContext(*this) : OdrUseContext::None;
17799 if (IsRecursiveCall && OdrUse == OdrUseContext::Used)
17800 OdrUse = OdrUseContext::FormallyOdrUsed;
17801
17802 // Trivial default constructors and destructors are never actually used.
17803 // FIXME: What about other special members?
17804 if (Func->isTrivial() && !Func->hasAttr<DLLExportAttr>() &&
17805 OdrUse == OdrUseContext::Used) {
17806 if (auto *Constructor = dyn_cast<CXXConstructorDecl>(Func))
17807 if (Constructor->isDefaultConstructor())
17808 OdrUse = OdrUseContext::FormallyOdrUsed;
17809 if (isa<CXXDestructorDecl>(Func))
17810 OdrUse = OdrUseContext::FormallyOdrUsed;
17811 }
17812
17813 // C++20 [expr.const]p12:
17814 // A function [...] is needed for constant evaluation if it is [...] a
17815 // constexpr function that is named by an expression that is potentially
17816 // constant evaluated
17817 bool NeededForConstantEvaluation =
17818 isPotentiallyConstantEvaluatedContext(*this) &&
17819 isImplicitlyDefinableConstexprFunction(Func);
17820
17821 // Determine whether we require a function definition to exist, per
17822 // C++11 [temp.inst]p3:
17823 // Unless a function template specialization has been explicitly
17824 // instantiated or explicitly specialized, the function template
17825 // specialization is implicitly instantiated when the specialization is
17826 // referenced in a context that requires a function definition to exist.
17827 // C++20 [temp.inst]p7:
17828 // The existence of a definition of a [...] function is considered to
17829 // affect the semantics of the program if the [...] function is needed for
17830 // constant evaluation by an expression
17831 // C++20 [basic.def.odr]p10:
17832 // Every program shall contain exactly one definition of every non-inline
17833 // function or variable that is odr-used in that program outside of a
17834 // discarded statement
17835 // C++20 [special]p1:
17836 // The implementation will implicitly define [defaulted special members]
17837 // if they are odr-used or needed for constant evaluation.
17838 //
17839 // Note that we skip the implicit instantiation of templates that are only
17840 // used in unused default arguments or by recursive calls to themselves.
17841 // This is formally non-conforming, but seems reasonable in practice.
17842 bool NeedDefinition = !IsRecursiveCall && (OdrUse == OdrUseContext::Used ||
17843 NeededForConstantEvaluation);
17844
17845 // C++14 [temp.expl.spec]p6:
17846 // If a template [...] is explicitly specialized then that specialization
17847 // shall be declared before the first use of that specialization that would
17848 // cause an implicit instantiation to take place, in every translation unit
17849 // in which such a use occurs
17850 if (NeedDefinition &&
17851 (Func->getTemplateSpecializationKind() != TSK_Undeclared ||
17852 Func->getMemberSpecializationInfo()))
17853 checkSpecializationVisibility(Loc, Func);
17854
17855 if (getLangOpts().CUDA)
17856 CheckCUDACall(Loc, Func);
17857
17858 if (getLangOpts().SYCLIsDevice)
17859 checkSYCLDeviceFunction(Loc, Func);
17860
17861 // If we need a definition, try to create one.
17862 if (NeedDefinition && !Func->getBody()) {
17863 runWithSufficientStackSpace(Loc, [&] {
17864 if (CXXConstructorDecl *Constructor =
17865 dyn_cast<CXXConstructorDecl>(Func)) {
17866 Constructor = cast<CXXConstructorDecl>(Constructor->getFirstDecl());
17867 if (Constructor->isDefaulted() && !Constructor->isDeleted()) {
17868 if (Constructor->isDefaultConstructor()) {
17869 if (Constructor->isTrivial() &&
17870 !Constructor->hasAttr<DLLExportAttr>())
17871 return;
17872 DefineImplicitDefaultConstructor(Loc, Constructor);
17873 } else if (Constructor->isCopyConstructor()) {
17874 DefineImplicitCopyConstructor(Loc, Constructor);
17875 } else if (Constructor->isMoveConstructor()) {
17876 DefineImplicitMoveConstructor(Loc, Constructor);
17877 }
17878 } else if (Constructor->getInheritedConstructor()) {
17879 DefineInheritingConstructor(Loc, Constructor);
17880 }
17881 } else if (CXXDestructorDecl *Destructor =
17882 dyn_cast<CXXDestructorDecl>(Func)) {
17883 Destructor = cast<CXXDestructorDecl>(Destructor->getFirstDecl());
17884 if (Destructor->isDefaulted() && !Destructor->isDeleted()) {
17885 if (Destructor->isTrivial() && !Destructor->hasAttr<DLLExportAttr>())
17886 return;
17887 DefineImplicitDestructor(Loc, Destructor);
17888 }
17889 if (Destructor->isVirtual() && getLangOpts().AppleKext)
17890 MarkVTableUsed(Loc, Destructor->getParent());
17891 } else if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(Func)) {
17892 if (MethodDecl->isOverloadedOperator() &&
17893 MethodDecl->getOverloadedOperator() == OO_Equal) {
17894 MethodDecl = cast<CXXMethodDecl>(MethodDecl->getFirstDecl());
17895 if (MethodDecl->isDefaulted() && !MethodDecl->isDeleted()) {
17896 if (MethodDecl->isCopyAssignmentOperator())
17897 DefineImplicitCopyAssignment(Loc, MethodDecl);
17898 else if (MethodDecl->isMoveAssignmentOperator())
17899 DefineImplicitMoveAssignment(Loc, MethodDecl);
17900 }
17901 } else if (isa<CXXConversionDecl>(MethodDecl) &&
17902 MethodDecl->getParent()->isLambda()) {
17903 CXXConversionDecl *Conversion =
17904 cast<CXXConversionDecl>(MethodDecl->getFirstDecl());
17905 if (Conversion->isLambdaToBlockPointerConversion())
17906 DefineImplicitLambdaToBlockPointerConversion(Loc, Conversion);
17907 else
17908 DefineImplicitLambdaToFunctionPointerConversion(Loc, Conversion);
17909 } else if (MethodDecl->isVirtual() && getLangOpts().AppleKext)
17910 MarkVTableUsed(Loc, MethodDecl->getParent());
17911 }
17912
17913 if (Func->isDefaulted() && !Func->isDeleted()) {
17914 DefaultedComparisonKind DCK = getDefaultedComparisonKind(Func);
17915 if (DCK != DefaultedComparisonKind::None)
17916 DefineDefaultedComparison(Loc, Func, DCK);
17917 }
17918
17919 // Implicit instantiation of function templates and member functions of
17920 // class templates.
17921 if (Func->isImplicitlyInstantiable()) {
17922 TemplateSpecializationKind TSK =
17923 Func->getTemplateSpecializationKindForInstantiation();
17924 SourceLocation PointOfInstantiation = Func->getPointOfInstantiation();
17925 bool FirstInstantiation = PointOfInstantiation.isInvalid();
17926 if (FirstInstantiation) {
17927 PointOfInstantiation = Loc;
17928 if (auto *MSI = Func->getMemberSpecializationInfo())
17929 MSI->setPointOfInstantiation(Loc);
17930 // FIXME: Notify listener.
17931 else
17932 Func->setTemplateSpecializationKind(TSK, PointOfInstantiation);
17933 } else if (TSK != TSK_ImplicitInstantiation) {
17934 // Use the point of use as the point of instantiation, instead of the
17935 // point of explicit instantiation (which we track as the actual point
17936 // of instantiation). This gives better backtraces in diagnostics.
17937 PointOfInstantiation = Loc;
17938 }
17939
17940 if (FirstInstantiation || TSK != TSK_ImplicitInstantiation ||
17941 Func->isConstexpr()) {
17942 if (isa<CXXRecordDecl>(Func->getDeclContext()) &&
17943 cast<CXXRecordDecl>(Func->getDeclContext())->isLocalClass() &&
17944 CodeSynthesisContexts.size())
17945 PendingLocalImplicitInstantiations.push_back(
17946 std::make_pair(Func, PointOfInstantiation));
17947 else if (Func->isConstexpr())
17948 // Do not defer instantiations of constexpr functions, to avoid the
17949 // expression evaluator needing to call back into Sema if it sees a
17950 // call to such a function.
17951 InstantiateFunctionDefinition(PointOfInstantiation, Func);
17952 else {
17953 Func->setInstantiationIsPending(true);
17954 PendingInstantiations.push_back(
17955 std::make_pair(Func, PointOfInstantiation));
17956 // Notify the consumer that a function was implicitly instantiated.
17957 Consumer.HandleCXXImplicitFunctionInstantiation(Func);
17958 }
17959 }
17960 } else {
17961 // Walk redefinitions, as some of them may be instantiable.
17962 for (auto i : Func->redecls()) {
17963 if (!i->isUsed(false) && i->isImplicitlyInstantiable())
17964 MarkFunctionReferenced(Loc, i, MightBeOdrUse);
17965 }
17966 }
17967 });
17968 }
17969
17970 // C++14 [except.spec]p17:
17971 // An exception-specification is considered to be needed when:
17972 // - the function is odr-used or, if it appears in an unevaluated operand,
17973 // would be odr-used if the expression were potentially-evaluated;
17974 //
17975 // Note, we do this even if MightBeOdrUse is false. That indicates that the
17976 // function is a pure virtual function we're calling, and in that case the
17977 // function was selected by overload resolution and we need to resolve its
17978 // exception specification for a different reason.
17979 const FunctionProtoType *FPT = Func->getType()->getAs<FunctionProtoType>();
17980 if (FPT && isUnresolvedExceptionSpec(FPT->getExceptionSpecType()))
17981 ResolveExceptionSpec(Loc, FPT);
17982
17983 // If this is the first "real" use, act on that.
17984 if (OdrUse == OdrUseContext::Used && !Func->isUsed(/*CheckUsedAttr=*/false)) {
17985 // Keep track of used but undefined functions.
17986 if (!Func->isDefined()) {
17987 if (mightHaveNonExternalLinkage(Func))
17988 UndefinedButUsed.insert(std::make_pair(Func->getCanonicalDecl(), Loc));
17989 else if (Func->getMostRecentDecl()->isInlined() &&
17990 !LangOpts.GNUInline &&
17991 !Func->getMostRecentDecl()->hasAttr<GNUInlineAttr>())
17992 UndefinedButUsed.insert(std::make_pair(Func->getCanonicalDecl(), Loc));
17993 else if (isExternalWithNoLinkageType(Func))
17994 UndefinedButUsed.insert(std::make_pair(Func->getCanonicalDecl(), Loc));
17995 }
17996
17997 // Some x86 Windows calling conventions mangle the size of the parameter
17998 // pack into the name. Computing the size of the parameters requires the
17999 // parameter types to be complete. Check that now.
18000 if (funcHasParameterSizeMangling(*this, Func))
18001 CheckCompleteParameterTypesForMangler(*this, Func, Loc);
18002
18003 // In the MS C++ ABI, the compiler emits destructor variants where they are
18004 // used. If the destructor is used here but defined elsewhere, mark the
18005 // virtual base destructors referenced. If those virtual base destructors
18006 // are inline, this will ensure they are defined when emitting the complete
18007 // destructor variant. This checking may be redundant if the destructor is
18008 // provided later in this TU.
18009 if (Context.getTargetInfo().getCXXABI().isMicrosoft()) {
18010 if (auto *Dtor = dyn_cast<CXXDestructorDecl>(Func)) {
18011 CXXRecordDecl *Parent = Dtor->getParent();
18012 if (Parent->getNumVBases() > 0 && !Dtor->getBody())
18013 CheckCompleteDestructorVariant(Loc, Dtor);
18014 }
18015 }
18016
18017 Func->markUsed(Context);
18018 }
18019}
18020
18021/// Directly mark a variable odr-used. Given a choice, prefer to use
18022/// MarkVariableReferenced since it does additional checks and then
18023/// calls MarkVarDeclODRUsed.
18024/// If the variable must be captured:
18025/// - if FunctionScopeIndexToStopAt is null, capture it in the CurContext
18026/// - else capture it in the DeclContext that maps to the
18027/// *FunctionScopeIndexToStopAt on the FunctionScopeInfo stack.
18028static void
18029MarkVarDeclODRUsed(VarDecl *Var, SourceLocation Loc, Sema &SemaRef,
18030 const unsigned *const FunctionScopeIndexToStopAt = nullptr) {
18031 // Keep track of used but undefined variables.
18032 // FIXME: We shouldn't suppress this warning for static data members.
18033 if (Var->hasDefinition(SemaRef.Context) == VarDecl::DeclarationOnly &&
18034 (!Var->isExternallyVisible() || Var->isInline() ||
18035 SemaRef.isExternalWithNoLinkageType(Var)) &&
18036 !(Var->isStaticDataMember() && Var->hasInit())) {
18037 SourceLocation &old = SemaRef.UndefinedButUsed[Var->getCanonicalDecl()];
18038 if (old.isInvalid())
18039 old = Loc;
18040 }
18041 QualType CaptureType, DeclRefType;
18042 if (SemaRef.LangOpts.OpenMP)
18043 SemaRef.tryCaptureOpenMPLambdas(Var);
18044 SemaRef.tryCaptureVariable(Var, Loc, Sema::TryCapture_Implicit,
18045 /*EllipsisLoc*/ SourceLocation(),
18046 /*BuildAndDiagnose*/ true,
18047 CaptureType, DeclRefType,
18048 FunctionScopeIndexToStopAt);
18049
18050 if (SemaRef.LangOpts.CUDA && Var->hasGlobalStorage()) {
18051 auto *FD = dyn_cast_or_null<FunctionDecl>(SemaRef.CurContext);
18052 auto VarTarget = SemaRef.IdentifyCUDATarget(Var);
18053 auto UserTarget = SemaRef.IdentifyCUDATarget(FD);
18054 if (VarTarget == Sema::CVT_Host &&
18055 (UserTarget == Sema::CFT_Device || UserTarget == Sema::CFT_HostDevice ||
18056 UserTarget == Sema::CFT_Global)) {
18057 // Diagnose ODR-use of host global variables in device functions.
18058 // Reference of device global variables in host functions is allowed
18059 // through shadow variables therefore it is not diagnosed.
18060 if (SemaRef.LangOpts.CUDAIsDevice) {
18061 SemaRef.targetDiag(Loc, diag::err_ref_bad_target)
18062 << /*host*/ 2 << /*variable*/ 1 << Var << UserTarget;
18063 SemaRef.targetDiag(Var->getLocation(),
18064 Var->getType().isConstQualified()
18065 ? diag::note_cuda_const_var_unpromoted
18066 : diag::note_cuda_host_var);
18067 }
18068 } else if (VarTarget == Sema::CVT_Device &&
18069 (UserTarget == Sema::CFT_Host ||
18070 UserTarget == Sema::CFT_HostDevice)) {
18071 // Record a CUDA/HIP device side variable if it is ODR-used
18072 // by host code. This is done conservatively, when the variable is
18073 // referenced in any of the following contexts:
18074 // - a non-function context
18075 // - a host function
18076 // - a host device function
18077 // This makes the ODR-use of the device side variable by host code to
18078 // be visible in the device compilation for the compiler to be able to
18079 // emit template variables instantiated by host code only and to
18080 // externalize the static device side variable ODR-used by host code.
18081 if (!Var->hasExternalStorage())
18082 SemaRef.getASTContext().CUDADeviceVarODRUsedByHost.insert(Var);
18083 else if (SemaRef.LangOpts.GPURelocatableDeviceCode)
18084 SemaRef.getASTContext().CUDAExternalDeviceDeclODRUsedByHost.insert(Var);
18085 }
18086 }
18087
18088 Var->markUsed(SemaRef.Context);
18089}
18090
18091void Sema::MarkCaptureUsedInEnclosingContext(VarDecl *Capture,
18092 SourceLocation Loc,
18093 unsigned CapturingScopeIndex) {
18094 MarkVarDeclODRUsed(Capture, Loc, *this, &CapturingScopeIndex);
18095}
18096
18097static void diagnoseUncapturableValueReference(Sema &S, SourceLocation loc,
18098 ValueDecl *var) {
18099 DeclContext *VarDC = var->getDeclContext();
18100
18101 // If the parameter still belongs to the translation unit, then
18102 // we're actually just using one parameter in the declaration of
18103 // the next.
18104 if (isa<ParmVarDecl>(var) &&
18105 isa<TranslationUnitDecl>(VarDC))
18106 return;
18107
18108 // For C code, don't diagnose about capture if we're not actually in code
18109 // right now; it's impossible to write a non-constant expression outside of
18110 // function context, so we'll get other (more useful) diagnostics later.
18111 //
18112 // For C++, things get a bit more nasty... it would be nice to suppress this
18113 // diagnostic for certain cases like using a local variable in an array bound
18114 // for a member of a local class, but the correct predicate is not obvious.
18115 if (!S.getLangOpts().CPlusPlus && !S.CurContext->isFunctionOrMethod())
18116 return;
18117
18118 unsigned ValueKind = isa<BindingDecl>(var) ? 1 : 0;
18119 unsigned ContextKind = 3; // unknown
18120 if (isa<CXXMethodDecl>(VarDC) &&
18121 cast<CXXRecordDecl>(VarDC->getParent())->isLambda()) {
18122 ContextKind = 2;
18123 } else if (isa<FunctionDecl>(VarDC)) {
18124 ContextKind = 0;
18125 } else if (isa<BlockDecl>(VarDC)) {
18126 ContextKind = 1;
18127 }
18128
18129 S.Diag(loc, diag::err_reference_to_local_in_enclosing_context)
18130 << var << ValueKind << ContextKind << VarDC;
18131 S.Diag(var->getLocation(), diag::note_entity_declared_at)
18132 << var;
18133
18134 // FIXME: Add additional diagnostic info about class etc. which prevents
18135 // capture.
18136}
18137
18138
18139static bool isVariableAlreadyCapturedInScopeInfo(CapturingScopeInfo *CSI, VarDecl *Var,
18140 bool &SubCapturesAreNested,
18141 QualType &CaptureType,
18142 QualType &DeclRefType) {
18143 // Check whether we've already captured it.
18144 if (CSI->CaptureMap.count(Var)) {
18145 // If we found a capture, any subcaptures are nested.
18146 SubCapturesAreNested = true;
18147
18148 // Retrieve the capture type for this variable.
18149 CaptureType = CSI->getCapture(Var).getCaptureType();
18150
18151 // Compute the type of an expression that refers to this variable.
18152 DeclRefType = CaptureType.getNonReferenceType();
18153
18154 // Similarly to mutable captures in lambda, all the OpenMP captures by copy
18155 // are mutable in the sense that user can change their value - they are
18156 // private instances of the captured declarations.
18157 const Capture &Cap = CSI->getCapture(Var);
18158 if (Cap.isCopyCapture() &&
18159 !(isa<LambdaScopeInfo>(CSI) && cast<LambdaScopeInfo>(CSI)->Mutable) &&
18160 !(isa<CapturedRegionScopeInfo>(CSI) &&
18161 cast<CapturedRegionScopeInfo>(CSI)->CapRegionKind == CR_OpenMP))
18162 DeclRefType.addConst();
18163 return true;
18164 }
18165 return false;
18166}
18167
18168// Only block literals, captured statements, and lambda expressions can
18169// capture; other scopes don't work.
18170static DeclContext *getParentOfCapturingContextOrNull(DeclContext *DC, VarDecl *Var,
18171 SourceLocation Loc,
18172 const bool Diagnose, Sema &S) {
18173 if (isa<BlockDecl>(DC) || isa<CapturedDecl>(DC) || isLambdaCallOperator(DC))
18174 return getLambdaAwareParentOfDeclContext(DC);
18175 else if (Var->hasLocalStorage()) {
18176 if (Diagnose)
18177 diagnoseUncapturableValueReference(S, Loc, Var);
18178 }
18179 return nullptr;
18180}
18181
18182// Certain capturing entities (lambdas, blocks etc.) are not allowed to capture
18183// certain types of variables (unnamed, variably modified types etc.)
18184// so check for eligibility.
18185static bool isVariableCapturable(CapturingScopeInfo *CSI, VarDecl *Var,
18186 SourceLocation Loc,
18187 const bool Diagnose, Sema &S) {
18188
18189 bool IsBlock = isa<BlockScopeInfo>(CSI);
18190 bool IsLambda = isa<LambdaScopeInfo>(CSI);
18191
18192 // Lambdas are not allowed to capture unnamed variables
18193 // (e.g. anonymous unions).
18194 // FIXME: The C++11 rule don't actually state this explicitly, but I'm
18195 // assuming that's the intent.
18196 if (IsLambda && !Var->getDeclName()) {
18197 if (Diagnose) {
18198 S.Diag(Loc, diag::err_lambda_capture_anonymous_var);
18199 S.Diag(Var->getLocation(), diag::note_declared_at);
18200 }
18201 return false;
18202 }
18203
18204 // Prohibit variably-modified types in blocks; they're difficult to deal with.
18205 if (Var->getType()->isVariablyModifiedType() && IsBlock) {
18206 if (Diagnose) {
18207 S.Diag(Loc, diag::err_ref_vm_type);
18208 S.Diag(Var->getLocation(), diag::note_previous_decl) << Var;
18209 }
18210 return false;
18211 }
18212 // Prohibit structs with flexible array members too.
18213 // We cannot capture what is in the tail end of the struct.
18214 if (const RecordType *VTTy = Var->getType()->getAs<RecordType>()) {
18215 if (VTTy->getDecl()->hasFlexibleArrayMember()) {
18216 if (Diagnose) {
18217 if (IsBlock)
18218 S.Diag(Loc, diag::err_ref_flexarray_type);
18219 else
18220 S.Diag(Loc, diag::err_lambda_capture_flexarray_type) << Var;
18221 S.Diag(Var->getLocation(), diag::note_previous_decl) << Var;
18222 }
18223 return false;
18224 }
18225 }
18226 const bool HasBlocksAttr = Var->hasAttr<BlocksAttr>();
18227 // Lambdas and captured statements are not allowed to capture __block
18228 // variables; they don't support the expected semantics.
18229 if (HasBlocksAttr && (IsLambda || isa<CapturedRegionScopeInfo>(CSI))) {
18230 if (Diagnose) {
18231 S.Diag(Loc, diag::err_capture_block_variable) << Var << !IsLambda;
18232 S.Diag(Var->getLocation(), diag::note_previous_decl) << Var;
18233 }
18234 return false;
18235 }
18236 // OpenCL v2.0 s6.12.5: Blocks cannot reference/capture other blocks
18237 if (S.getLangOpts().OpenCL && IsBlock &&
18238 Var->getType()->isBlockPointerType()) {
18239 if (Diagnose)
18240 S.Diag(Loc, diag::err_opencl_block_ref_block);
18241 return false;
18242 }
18243
18244 return true;
18245}
18246
18247// Returns true if the capture by block was successful.
18248static bool captureInBlock(BlockScopeInfo *BSI, VarDecl *Var,
18249 SourceLocation Loc,
18250 const bool BuildAndDiagnose,
18251 QualType &CaptureType,
18252 QualType &DeclRefType,
18253 const bool Nested,
18254 Sema &S, bool Invalid) {
18255 bool ByRef = false;
18256
18257 // Blocks are not allowed to capture arrays, excepting OpenCL.
18258 // OpenCL v2.0 s1.12.5 (revision 40): arrays are captured by reference
18259 // (decayed to pointers).
18260 if (!Invalid && !S.getLangOpts().OpenCL && CaptureType->isArrayType()) {
18261 if (BuildAndDiagnose) {
18262 S.Diag(Loc, diag::err_ref_array_type);
18263 S.Diag(Var->getLocation(), diag::note_previous_decl) << Var;
18264 Invalid = true;
18265 } else {
18266 return false;
18267 }
18268 }
18269
18270 // Forbid the block-capture of autoreleasing variables.
18271 if (!Invalid &&
18272 CaptureType.getObjCLifetime() == Qualifiers::OCL_Autoreleasing) {
18273 if (BuildAndDiagnose) {
18274 S.Diag(Loc, diag::err_arc_autoreleasing_capture)
18275 << /*block*/ 0;
18276 S.Diag(Var->getLocation(), diag::note_previous_decl) << Var;
18277 Invalid = true;
18278 } else {
18279 return false;
18280 }
18281 }
18282
18283 // Warn about implicitly autoreleasing indirect parameters captured by blocks.
18284 if (const auto *PT = CaptureType->getAs<PointerType>()) {
18285 QualType PointeeTy = PT->getPointeeType();
18286
18287 if (!Invalid && PointeeTy->getAs<ObjCObjectPointerType>() &&
18288 PointeeTy.getObjCLifetime() == Qualifiers::OCL_Autoreleasing &&
18289 !S.Context.hasDirectOwnershipQualifier(PointeeTy)) {
18290 if (BuildAndDiagnose) {
18291 SourceLocation VarLoc = Var->getLocation();
18292 S.Diag(Loc, diag::warn_block_capture_autoreleasing);
18293 S.Diag(VarLoc, diag::note_declare_parameter_strong);
18294 }
18295 }
18296 }
18297
18298 const bool HasBlocksAttr = Var->hasAttr<BlocksAttr>();
18299 if (HasBlocksAttr || CaptureType->isReferenceType() ||
18300 (S.getLangOpts().OpenMP && S.isOpenMPCapturedDecl(Var))) {
18301 // Block capture by reference does not change the capture or
18302 // declaration reference types.
18303 ByRef = true;
18304 } else {
18305 // Block capture by copy introduces 'const'.
18306 CaptureType = CaptureType.getNonReferenceType().withConst();
18307 DeclRefType = CaptureType;
18308 }
18309
18310 // Actually capture the variable.
18311 if (BuildAndDiagnose)
18312 BSI->addCapture(Var, HasBlocksAttr, ByRef, Nested, Loc, SourceLocation(),
18313 CaptureType, Invalid);
18314
18315 return !Invalid;
18316}
18317
18318
18319/// Capture the given variable in the captured region.
18320static bool captureInCapturedRegion(
18321 CapturedRegionScopeInfo *RSI, VarDecl *Var, SourceLocation Loc,
18322 const bool BuildAndDiagnose, QualType &CaptureType, QualType &DeclRefType,
18323 const bool RefersToCapturedVariable, Sema::TryCaptureKind Kind,
18324 bool IsTopScope, Sema &S, bool Invalid) {
18325 // By default, capture variables by reference.
18326 bool ByRef = true;
18327 if (IsTopScope && Kind != Sema::TryCapture_Implicit) {
18328 ByRef = (Kind == Sema::TryCapture_ExplicitByRef);
18329 } else if (S.getLangOpts().OpenMP && RSI->CapRegionKind == CR_OpenMP) {
18330 // Using an LValue reference type is consistent with Lambdas (see below).
18331 if (S.isOpenMPCapturedDecl(Var)) {
18332 bool HasConst = DeclRefType.isConstQualified();
18333 DeclRefType = DeclRefType.getUnqualifiedType();
18334 // Don't lose diagnostics about assignments to const.
18335 if (HasConst)
18336 DeclRefType.addConst();
18337 }
18338 // Do not capture firstprivates in tasks.
18339 if (S.isOpenMPPrivateDecl(Var, RSI->OpenMPLevel, RSI->OpenMPCaptureLevel) !=
18340 OMPC_unknown)
18341 return true;
18342 ByRef = S.isOpenMPCapturedByRef(Var, RSI->OpenMPLevel,
18343 RSI->OpenMPCaptureLevel);
18344 }
18345
18346 if (ByRef)
18347 CaptureType = S.Context.getLValueReferenceType(DeclRefType);
18348 else
18349 CaptureType = DeclRefType;
18350
18351 // Actually capture the variable.
18352 if (BuildAndDiagnose)
18353 RSI->addCapture(Var, /*isBlock*/ false, ByRef, RefersToCapturedVariable,
18354 Loc, SourceLocation(), CaptureType, Invalid);
18355
18356 return !Invalid;
18357}
18358
18359/// Capture the given variable in the lambda.
18360static bool captureInLambda(LambdaScopeInfo *LSI,
18361 VarDecl *Var,
18362 SourceLocation Loc,
18363 const bool BuildAndDiagnose,
18364 QualType &CaptureType,
18365 QualType &DeclRefType,
18366 const bool RefersToCapturedVariable,
18367 const Sema::TryCaptureKind Kind,
18368 SourceLocation EllipsisLoc,
18369 const bool IsTopScope,
18370 Sema &S, bool Invalid) {
18371 // Determine whether we are capturing by reference or by value.
18372 bool ByRef = false;
18373 if (IsTopScope && Kind != Sema::TryCapture_Implicit) {
18374 ByRef = (Kind == Sema::TryCapture_ExplicitByRef);
18375 } else {
18376 ByRef = (LSI->ImpCaptureStyle == LambdaScopeInfo::ImpCap_LambdaByref);
18377 }
18378
18379 // Compute the type of the field that will capture this variable.
18380 if (ByRef) {
18381 // C++11 [expr.prim.lambda]p15:
18382 // An entity is captured by reference if it is implicitly or
18383 // explicitly captured but not captured by copy. It is
18384 // unspecified whether additional unnamed non-static data
18385 // members are declared in the closure type for entities
18386 // captured by reference.
18387 //
18388 // FIXME: It is not clear whether we want to build an lvalue reference
18389 // to the DeclRefType or to CaptureType.getNonReferenceType(). GCC appears
18390 // to do the former, while EDG does the latter. Core issue 1249 will
18391 // clarify, but for now we follow GCC because it's a more permissive and
18392 // easily defensible position.
18393 CaptureType = S.Context.getLValueReferenceType(DeclRefType);
18394 } else {
18395 // C++11 [expr.prim.lambda]p14:
18396 // For each entity captured by copy, an unnamed non-static
18397 // data member is declared in the closure type. The
18398 // declaration order of these members is unspecified. The type
18399 // of such a data member is the type of the corresponding
18400 // captured entity if the entity is not a reference to an
18401 // object, or the referenced type otherwise. [Note: If the
18402 // captured entity is a reference to a function, the
18403 // corresponding data member is also a reference to a
18404 // function. - end note ]
18405 if (const ReferenceType *RefType = CaptureType->getAs<ReferenceType>()){
18406 if (!RefType->getPointeeType()->isFunctionType())
18407 CaptureType = RefType->getPointeeType();
18408 }
18409
18410 // Forbid the lambda copy-capture of autoreleasing variables.
18411 if (!Invalid &&
18412 CaptureType.getObjCLifetime() == Qualifiers::OCL_Autoreleasing) {
18413 if (BuildAndDiagnose) {
18414 S.Diag(Loc, diag::err_arc_autoreleasing_capture) << /*lambda*/ 1;
18415 S.Diag(Var->getLocation(), diag::note_previous_decl)
18416 << Var->getDeclName();
18417 Invalid = true;
18418 } else {
18419 return false;
18420 }
18421 }
18422
18423 // Make sure that by-copy captures are of a complete and non-abstract type.
18424 if (!Invalid && BuildAndDiagnose) {
18425 if (!CaptureType->isDependentType() &&
18426 S.RequireCompleteSizedType(
18427 Loc, CaptureType,
18428 diag::err_capture_of_incomplete_or_sizeless_type,
18429 Var->getDeclName()))
18430 Invalid = true;
18431 else if (S.RequireNonAbstractType(Loc, CaptureType,
18432 diag::err_capture_of_abstract_type))
18433 Invalid = true;
18434 }
18435 }
18436
18437 // Compute the type of a reference to this captured variable.
18438 if (ByRef)
18439 DeclRefType = CaptureType.getNonReferenceType();
18440 else {
18441 // C++ [expr.prim.lambda]p5:
18442 // The closure type for a lambda-expression has a public inline
18443 // function call operator [...]. This function call operator is
18444 // declared const (9.3.1) if and only if the lambda-expression's
18445 // parameter-declaration-clause is not followed by mutable.
18446 DeclRefType = CaptureType.getNonReferenceType();
18447 if (!LSI->Mutable && !CaptureType->isReferenceType())
18448 DeclRefType.addConst();
18449 }
18450
18451 // Add the capture.
18452 if (BuildAndDiagnose)
18453 LSI->addCapture(Var, /*isBlock=*/false, ByRef, RefersToCapturedVariable,
18454 Loc, EllipsisLoc, CaptureType, Invalid);
18455
18456 return !Invalid;
18457}
18458
18459static bool canCaptureVariableByCopy(VarDecl *Var, const ASTContext &Context) {
18460 // Offer a Copy fix even if the type is dependent.
18461 if (Var->getType()->isDependentType())
18462 return true;
18463 QualType T = Var->getType().getNonReferenceType();
18464 if (T.isTriviallyCopyableType(Context))
18465 return true;
18466 if (CXXRecordDecl *RD = T->getAsCXXRecordDecl()) {
18467
18468 if (!(RD = RD->getDefinition()))
18469 return false;
18470 if (RD->hasSimpleCopyConstructor())
18471 return true;
18472 if (RD->hasUserDeclaredCopyConstructor())
18473 for (CXXConstructorDecl *Ctor : RD->ctors())
18474 if (Ctor->isCopyConstructor())
18475 return !Ctor->isDeleted();
18476 }
18477 return false;
18478}
18479
18480/// Create up to 4 fix-its for explicit reference and value capture of \p Var or
18481/// default capture. Fixes may be omitted if they aren't allowed by the
18482/// standard, for example we can't emit a default copy capture fix-it if we
18483/// already explicitly copy capture capture another variable.
18484static void buildLambdaCaptureFixit(Sema &Sema, LambdaScopeInfo *LSI,
18485 VarDecl *Var) {
18486 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", 18486, __extension__ __PRETTY_FUNCTION__
))
;
18487 // Don't offer Capture by copy of default capture by copy fixes if Var is
18488 // known not to be copy constructible.
18489 bool ShouldOfferCopyFix = canCaptureVariableByCopy(Var, Sema.getASTContext());
18490
18491 SmallString<32> FixBuffer;
18492 StringRef Separator = LSI->NumExplicitCaptures > 0 ? ", " : "";
18493 if (Var->getDeclName().isIdentifier() && !Var->getName().empty()) {
18494 SourceLocation VarInsertLoc = LSI->IntroducerRange.getEnd();
18495 if (ShouldOfferCopyFix) {
18496 // Offer fixes to insert an explicit capture for the variable.
18497 // [] -> [VarName]
18498 // [OtherCapture] -> [OtherCapture, VarName]
18499 FixBuffer.assign({Separator, Var->getName()});
18500 Sema.Diag(VarInsertLoc, diag::note_lambda_variable_capture_fixit)
18501 << Var << /*value*/ 0
18502 << FixItHint::CreateInsertion(VarInsertLoc, FixBuffer);
18503 }
18504 // As above but capture by reference.
18505 FixBuffer.assign({Separator, "&", Var->getName()});
18506 Sema.Diag(VarInsertLoc, diag::note_lambda_variable_capture_fixit)
18507 << Var << /*reference*/ 1
18508 << FixItHint::CreateInsertion(VarInsertLoc, FixBuffer);
18509 }
18510
18511 // Only try to offer default capture if there are no captures excluding this
18512 // and init captures.
18513 // [this]: OK.
18514 // [X = Y]: OK.
18515 // [&A, &B]: Don't offer.
18516 // [A, B]: Don't offer.
18517 if (llvm::any_of(LSI->Captures, [](Capture &C) {
18518 return !C.isThisCapture() && !C.isInitCapture();
18519 }))
18520 return;
18521
18522 // The default capture specifiers, '=' or '&', must appear first in the
18523 // capture body.
18524 SourceLocation DefaultInsertLoc =
18525 LSI->IntroducerRange.getBegin().getLocWithOffset(1);
18526
18527 if (ShouldOfferCopyFix) {
18528 bool CanDefaultCopyCapture = true;
18529 // [=, *this] OK since c++17
18530 // [=, this] OK since c++20
18531 if (LSI->isCXXThisCaptured() && !Sema.getLangOpts().CPlusPlus20)
18532 CanDefaultCopyCapture = Sema.getLangOpts().CPlusPlus17
18533 ? LSI->getCXXThisCapture().isCopyCapture()
18534 : false;
18535 // We can't use default capture by copy if any captures already specified
18536 // capture by copy.
18537 if (CanDefaultCopyCapture && llvm::none_of(LSI->Captures, [](Capture &C) {
18538 return !C.isThisCapture() && !C.isInitCapture() && C.isCopyCapture();
18539 })) {
18540 FixBuffer.assign({"=", Separator});
18541 Sema.Diag(DefaultInsertLoc, diag::note_lambda_default_capture_fixit)
18542 << /*value*/ 0
18543 << FixItHint::CreateInsertion(DefaultInsertLoc, FixBuffer);
18544 }
18545 }
18546
18547 // We can't use default capture by reference if any captures already specified
18548 // capture by reference.
18549 if (llvm::none_of(LSI->Captures, [](Capture &C) {
18550 return !C.isInitCapture() && C.isReferenceCapture() &&
18551 !C.isThisCapture();
18552 })) {
18553 FixBuffer.assign({"&", Separator});
18554 Sema.Diag(DefaultInsertLoc, diag::note_lambda_default_capture_fixit)
18555 << /*reference*/ 1
18556 << FixItHint::CreateInsertion(DefaultInsertLoc, FixBuffer);
18557 }
18558}
18559
18560static bool CheckCaptureUseBeforeLambdaQualifiers(Sema &S, VarDecl *Var,
18561 SourceLocation ExprLoc,
18562 LambdaScopeInfo *LSI) {
18563
18564 // Allow `[a = 1](decltype(a)) {}` as per CWG2569.
18565 if (S.InMutableAgnosticContext)
18566 return true;
18567
18568 if (Var->isInvalidDecl())
18569 return false;
18570
18571 bool ByCopy = LSI->ImpCaptureStyle == LambdaScopeInfo::ImpCap_LambdaByval;
18572 SourceLocation Loc = LSI->IntroducerRange.getBegin();
18573 bool Explicitly = false;
18574 for (auto &&C : LSI->DelayedCaptures) {
18575 VarDecl *CV = C.second.Var;
18576 if (Var != CV)
18577 continue;
18578 ByCopy = C.second.Kind == LambdaCaptureKind::LCK_ByCopy;
18579 Loc = C.second.Loc;
18580 Explicitly = true;
18581 break;
18582 }
18583 if (ByCopy && LSI->BeforeLambdaQualifiersScope) {
18584 // This can only occur in a non-ODR context, so we need to diagnose eagerly,
18585 // even when BuildAndDiagnose is false
18586 S.Diag(ExprLoc, diag::err_lambda_used_before_capture) << Var;
18587 S.Diag(Loc, diag::note_var_explicitly_captured_here) << Var << Explicitly;
18588 if (!Var->isInitCapture())
18589 S.Diag(Var->getBeginLoc(), diag::note_entity_declared_at) << Var;
18590 Var->setInvalidDecl();
18591 return false;
18592 }
18593 return true;
18594}
18595
18596bool Sema::tryCaptureVariable(
18597 VarDecl *Var, SourceLocation ExprLoc, TryCaptureKind Kind,
18598 SourceLocation EllipsisLoc, bool BuildAndDiagnose, QualType &CaptureType,
18599 QualType &DeclRefType, const unsigned *const FunctionScopeIndexToStopAt) {
18600 // An init-capture is notionally from the context surrounding its
18601 // declaration, but its parent DC is the lambda class.
18602 DeclContext *VarDC = Var->getDeclContext();
18603 if (Var->isInitCapture())
18604 VarDC = VarDC->getParent();
18605
18606 DeclContext *DC = CurContext;
18607 const unsigned MaxFunctionScopesIndex = FunctionScopeIndexToStopAt
18608 ? *FunctionScopeIndexToStopAt : FunctionScopes.size() - 1;
18609 // We need to sync up the Declaration Context with the
18610 // FunctionScopeIndexToStopAt
18611 if (FunctionScopeIndexToStopAt) {
18612 unsigned FSIndex = FunctionScopes.size() - 1;
18613 while (FSIndex != MaxFunctionScopesIndex) {
18614 DC = getLambdaAwareParentOfDeclContext(DC);
18615 --FSIndex;
18616 }
18617 }
18618
18619 // Capture global variables if it is required to use private copy of this
18620 // variable.
18621 bool IsGlobal = !Var->hasLocalStorage();
18622 if (IsGlobal &&
18623 !(LangOpts.OpenMP && isOpenMPCapturedDecl(Var, /*CheckScopeInfo=*/true,
18624 MaxFunctionScopesIndex)))
18625 return true;
18626 Var = Var->getCanonicalDecl();
18627
18628 // Walk up the stack to determine whether we can capture the variable,
18629 // performing the "simple" checks that don't depend on type. We stop when
18630 // we've either hit the declared scope of the variable or find an existing
18631 // capture of that variable. We start from the innermost capturing-entity
18632 // (the DC) and ensure that all intervening capturing-entities
18633 // (blocks/lambdas etc.) between the innermost capturer and the variable`s
18634 // declcontext can either capture the variable or have already captured
18635 // the variable.
18636 CaptureType = Var->getType();
18637 DeclRefType = CaptureType.getNonReferenceType();
18638 bool Nested = false;
18639 bool Explicit = (Kind != TryCapture_Implicit);
18640 unsigned FunctionScopesIndex = MaxFunctionScopesIndex;
18641 bool IsInLambdaBeforeQualifiers;
18642 do {
18643 IsInLambdaBeforeQualifiers = false;
18644
18645 LambdaScopeInfo *LSI = nullptr;
18646 if (!FunctionScopes.empty())
18647 LSI = dyn_cast_or_null<LambdaScopeInfo>(
18648 FunctionScopes[FunctionScopesIndex]);
18649 if (LSI && LSI->BeforeLambdaQualifiersScope) {
18650 if (isa<ParmVarDecl>(Var) && !Var->getDeclContext()->isFunctionOrMethod())
18651 return true;
18652 IsInLambdaBeforeQualifiers = true;
18653 if (!CheckCaptureUseBeforeLambdaQualifiers(*this, Var, ExprLoc, LSI)) {
18654 break;
18655 }
18656 }
18657
18658 // If the variable is declared in the current context, there is no need to
18659 // capture it.
18660 if (!IsInLambdaBeforeQualifiers &&
18661 FunctionScopesIndex == MaxFunctionScopesIndex && VarDC == DC)
18662 return true;
18663
18664 // Only block literals, captured statements, and lambda expressions can
18665 // capture; other scopes don't work.
18666 DeclContext *ParentDC =
18667 IsInLambdaBeforeQualifiers
18668 ? DC->getParent()
18669 : getParentOfCapturingContextOrNull(DC, Var, ExprLoc,
18670 BuildAndDiagnose, *this);
18671 // We need to check for the parent *first* because, if we *have*
18672 // private-captured a global variable, we need to recursively capture it in
18673 // intermediate blocks, lambdas, etc.
18674 if (!ParentDC) {
18675 if (IsGlobal) {
18676 FunctionScopesIndex = MaxFunctionScopesIndex - 1;
18677 break;
18678 }
18679 return true;
18680 }
18681
18682 FunctionScopeInfo *FSI = FunctionScopes[FunctionScopesIndex];
18683 CapturingScopeInfo *CSI = cast<CapturingScopeInfo>(FSI);
18684
18685 // Check whether we've already captured it.
18686 if (!IsInLambdaBeforeQualifiers &&
18687 isVariableAlreadyCapturedInScopeInfo(CSI, Var, Nested, CaptureType,
18688 DeclRefType)) {
18689 CSI->getCapture(Var).markUsed(BuildAndDiagnose);
18690 break;
18691 }
18692 // If we are instantiating a generic lambda call operator body,
18693 // we do not want to capture new variables. What was captured
18694 // during either a lambdas transformation or initial parsing
18695 // should be used.
18696 if (!IsInLambdaBeforeQualifiers &&
18697 isGenericLambdaCallOperatorSpecialization(DC)) {
18698 if (BuildAndDiagnose) {
18699 LambdaScopeInfo *LSI = cast<LambdaScopeInfo>(CSI);
18700 if (LSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_None) {
18701 Diag(ExprLoc, diag::err_lambda_impcap) << Var;
18702 Diag(Var->getLocation(), diag::note_previous_decl) << Var;
18703 Diag(LSI->Lambda->getBeginLoc(), diag::note_lambda_decl);
18704 buildLambdaCaptureFixit(*this, LSI, Var);
18705 } else
18706 diagnoseUncapturableValueReference(*this, ExprLoc, Var);
18707 }
18708 return true;
18709 }
18710
18711 // Try to capture variable-length arrays types.
18712 if (!IsInLambdaBeforeQualifiers &&
18713 Var->getType()->isVariablyModifiedType()) {
18714 // We're going to walk down into the type and look for VLA
18715 // expressions.
18716 QualType QTy = Var->getType();
18717 if (ParmVarDecl *PVD = dyn_cast_or_null<ParmVarDecl>(Var))
18718 QTy = PVD->getOriginalType();
18719 captureVariablyModifiedType(Context, QTy, CSI);
18720 }
18721
18722 if (!IsInLambdaBeforeQualifiers && getLangOpts().OpenMP) {
18723 if (auto *RSI = dyn_cast<CapturedRegionScopeInfo>(CSI)) {
18724 // OpenMP private variables should not be captured in outer scope, so
18725 // just break here. Similarly, global variables that are captured in a
18726 // target region should not be captured outside the scope of the region.
18727 if (RSI->CapRegionKind == CR_OpenMP) {
18728 OpenMPClauseKind IsOpenMPPrivateDecl = isOpenMPPrivateDecl(
18729 Var, RSI->OpenMPLevel, RSI->OpenMPCaptureLevel);
18730 // If the variable is private (i.e. not captured) and has variably
18731 // modified type, we still need to capture the type for correct
18732 // codegen in all regions, associated with the construct. Currently,
18733 // it is captured in the innermost captured region only.
18734 if (IsOpenMPPrivateDecl != OMPC_unknown &&
18735 Var->getType()->isVariablyModifiedType()) {
18736 QualType QTy = Var->getType();
18737 if (ParmVarDecl *PVD = dyn_cast_or_null<ParmVarDecl>(Var))
18738 QTy = PVD->getOriginalType();
18739 for (int I = 1, E = getNumberOfConstructScopes(RSI->OpenMPLevel);
18740 I < E; ++I) {
18741 auto *OuterRSI = cast<CapturedRegionScopeInfo>(
18742 FunctionScopes[FunctionScopesIndex - I]);
18743 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", 18745, __extension__ __PRETTY_FUNCTION__
))
18744 "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", 18745, __extension__ __PRETTY_FUNCTION__
))
18745 "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", 18745, __extension__ __PRETTY_FUNCTION__
))
;
18746 captureVariablyModifiedType(Context, QTy, OuterRSI);
18747 }
18748 }
18749 bool IsTargetCap =
18750 IsOpenMPPrivateDecl != OMPC_private &&
18751 isOpenMPTargetCapturedDecl(Var, RSI->OpenMPLevel,
18752 RSI->OpenMPCaptureLevel);
18753 // Do not capture global if it is not privatized in outer regions.
18754 bool IsGlobalCap =
18755 IsGlobal && isOpenMPGlobalCapturedDecl(Var, RSI->OpenMPLevel,
18756 RSI->OpenMPCaptureLevel);
18757
18758 // When we detect target captures we are looking from inside the
18759 // target region, therefore we need to propagate the capture from the
18760 // enclosing region. Therefore, the capture is not initially nested.
18761 if (IsTargetCap)
18762 adjustOpenMPTargetScopeIndex(FunctionScopesIndex, RSI->OpenMPLevel);
18763
18764 if (IsTargetCap || IsOpenMPPrivateDecl == OMPC_private ||
18765 (IsGlobal && !IsGlobalCap)) {
18766 Nested = !IsTargetCap;
18767 bool HasConst = DeclRefType.isConstQualified();
18768 DeclRefType = DeclRefType.getUnqualifiedType();
18769 // Don't lose diagnostics about assignments to const.
18770 if (HasConst)
18771 DeclRefType.addConst();
18772 CaptureType = Context.getLValueReferenceType(DeclRefType);
18773 break;
18774 }
18775 }
18776 }
18777 }
18778 if (CSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_None && !Explicit) {
18779 // No capture-default, and this is not an explicit capture
18780 // so cannot capture this variable.
18781 if (BuildAndDiagnose) {
18782 Diag(ExprLoc, diag::err_lambda_impcap) << Var;
18783 Diag(Var->getLocation(), diag::note_previous_decl) << Var;
18784 auto *LSI = cast<LambdaScopeInfo>(CSI);
18785 if (LSI->Lambda) {
18786 Diag(LSI->Lambda->getBeginLoc(), diag::note_lambda_decl);
18787 buildLambdaCaptureFixit(*this, LSI, Var);
18788 }
18789 // FIXME: If we error out because an outer lambda can not implicitly
18790 // capture a variable that an inner lambda explicitly captures, we
18791 // should have the inner lambda do the explicit capture - because
18792 // it makes for cleaner diagnostics later. This would purely be done
18793 // so that the diagnostic does not misleadingly claim that a variable
18794 // can not be captured by a lambda implicitly even though it is captured
18795 // explicitly. Suggestion:
18796 // - create const bool VariableCaptureWasInitiallyExplicit = Explicit
18797 // at the function head
18798 // - cache the StartingDeclContext - this must be a lambda
18799 // - captureInLambda in the innermost lambda the variable.
18800 }
18801 return true;
18802 }
18803 Explicit = false;
18804 FunctionScopesIndex--;
18805 if (!IsInLambdaBeforeQualifiers)
18806 DC = ParentDC;
18807 } while (IsInLambdaBeforeQualifiers || !VarDC->Equals(DC));
18808
18809 // Walk back down the scope stack, (e.g. from outer lambda to inner lambda)
18810 // computing the type of the capture at each step, checking type-specific
18811 // requirements, and adding captures if requested.
18812 // If the variable had already been captured previously, we start capturing
18813 // at the lambda nested within that one.
18814 bool Invalid = false;
18815 for (unsigned I = ++FunctionScopesIndex, N = MaxFunctionScopesIndex + 1; I != N;
18816 ++I) {
18817 CapturingScopeInfo *CSI = cast<CapturingScopeInfo>(FunctionScopes[I]);
18818
18819 // Certain capturing entities (lambdas, blocks etc.) are not allowed to capture
18820 // certain types of variables (unnamed, variably modified types etc.)
18821 // so check for eligibility.
18822 if (!Invalid)
18823 Invalid =
18824 !isVariableCapturable(CSI, Var, ExprLoc, BuildAndDiagnose, *this);
18825
18826 // After encountering an error, if we're actually supposed to capture, keep
18827 // capturing in nested contexts to suppress any follow-on diagnostics.
18828 if (Invalid && !BuildAndDiagnose)
18829 return true;
18830
18831 if (BlockScopeInfo *BSI = dyn_cast<BlockScopeInfo>(CSI)) {
18832 Invalid = !captureInBlock(BSI, Var, ExprLoc, BuildAndDiagnose, CaptureType,
18833 DeclRefType, Nested, *this, Invalid);
18834 Nested = true;
18835 } else if (CapturedRegionScopeInfo *RSI = dyn_cast<CapturedRegionScopeInfo>(CSI)) {
18836 Invalid = !captureInCapturedRegion(
18837 RSI, Var, ExprLoc, BuildAndDiagnose, CaptureType, DeclRefType, Nested,
18838 Kind, /*IsTopScope*/ I == N - 1, *this, Invalid);
18839 Nested = true;
18840 } else {
18841 LambdaScopeInfo *LSI = cast<LambdaScopeInfo>(CSI);
18842 if (!CheckCaptureUseBeforeLambdaQualifiers(*this, Var, ExprLoc, LSI)) {
18843 return true;
18844 }
18845 Invalid =
18846 !captureInLambda(LSI, Var, ExprLoc, BuildAndDiagnose, CaptureType,
18847 DeclRefType, Nested, Kind, EllipsisLoc,
18848 /*IsTopScope*/ I == N - 1, *this, Invalid);
18849 Nested = true;
18850 }
18851
18852 if (Invalid && !BuildAndDiagnose)
18853 return true;
18854 }
18855 return Invalid;
18856}
18857
18858bool Sema::tryCaptureVariable(VarDecl *Var, SourceLocation Loc,
18859 TryCaptureKind Kind, SourceLocation EllipsisLoc) {
18860 QualType CaptureType;
18861 QualType DeclRefType;
18862 return tryCaptureVariable(Var, Loc, Kind, EllipsisLoc,
18863 /*BuildAndDiagnose=*/true, CaptureType,
18864 DeclRefType, nullptr);
18865}
18866
18867bool Sema::NeedToCaptureVariable(VarDecl *Var, SourceLocation Loc) {
18868 QualType CaptureType;
18869 QualType DeclRefType;
18870 return !tryCaptureVariable(Var, Loc, TryCapture_Implicit, SourceLocation(),
18871 /*BuildAndDiagnose=*/false, CaptureType,
18872 DeclRefType, nullptr);
18873}
18874
18875QualType Sema::getCapturedDeclRefType(VarDecl *Var, SourceLocation Loc) {
18876 QualType CaptureType;
18877 QualType DeclRefType;
18878
18879 // Determine whether we can capture this variable.
18880 if (tryCaptureVariable(Var, Loc, TryCapture_Implicit, SourceLocation(),
18881 /*BuildAndDiagnose=*/false, CaptureType,
18882 DeclRefType, nullptr))
18883 return QualType();
18884
18885 return DeclRefType;
18886}
18887
18888namespace {
18889// Helper to copy the template arguments from a DeclRefExpr or MemberExpr.
18890// The produced TemplateArgumentListInfo* points to data stored within this
18891// object, so should only be used in contexts where the pointer will not be
18892// used after the CopiedTemplateArgs object is destroyed.
18893class CopiedTemplateArgs {
18894 bool HasArgs;
18895 TemplateArgumentListInfo TemplateArgStorage;
18896public:
18897 template<typename RefExpr>
18898 CopiedTemplateArgs(RefExpr *E) : HasArgs(E->hasExplicitTemplateArgs()) {
18899 if (HasArgs)
18900 E->copyTemplateArgumentsInto(TemplateArgStorage);
18901 }
18902 operator TemplateArgumentListInfo*()
18903#ifdef __has_cpp_attribute
18904#if0 __has_cpp_attribute(clang::lifetimebound)1
18905 [[clang::lifetimebound]]
18906#endif
18907#endif
18908 {
18909 return HasArgs ? &TemplateArgStorage : nullptr;
18910 }
18911};
18912}
18913
18914/// Walk the set of potential results of an expression and mark them all as
18915/// non-odr-uses if they satisfy the side-conditions of the NonOdrUseReason.
18916///
18917/// \return A new expression if we found any potential results, ExprEmpty() if
18918/// not, and ExprError() if we diagnosed an error.
18919static ExprResult rebuildPotentialResultsAsNonOdrUsed(Sema &S, Expr *E,
18920 NonOdrUseReason NOUR) {
18921 // Per C++11 [basic.def.odr], a variable is odr-used "unless it is
18922 // an object that satisfies the requirements for appearing in a
18923 // constant expression (5.19) and the lvalue-to-rvalue conversion (4.1)
18924 // is immediately applied." This function handles the lvalue-to-rvalue
18925 // conversion part.
18926 //
18927 // If we encounter a node that claims to be an odr-use but shouldn't be, we
18928 // transform it into the relevant kind of non-odr-use node and rebuild the
18929 // tree of nodes leading to it.
18930 //
18931 // This is a mini-TreeTransform that only transforms a restricted subset of
18932 // nodes (and only certain operands of them).
18933
18934 // Rebuild a subexpression.
18935 auto Rebuild = [&](Expr *Sub) {
18936 return rebuildPotentialResultsAsNonOdrUsed(S, Sub, NOUR);
18937 };
18938
18939 // Check whether a potential result satisfies the requirements of NOUR.
18940 auto IsPotentialResultOdrUsed = [&](NamedDecl *D) {
18941 // Any entity other than a VarDecl is always odr-used whenever it's named
18942 // in a potentially-evaluated expression.
18943 auto *VD = dyn_cast<VarDecl>(D);
18944 if (!VD)
18945 return true;
18946
18947 // C++2a [basic.def.odr]p4:
18948 // A variable x whose name appears as a potentially-evalauted expression
18949 // e is odr-used by e unless
18950 // -- x is a reference that is usable in constant expressions, or
18951 // -- x is a variable of non-reference type that is usable in constant
18952 // expressions and has no mutable subobjects, and e is an element of
18953 // the set of potential results of an expression of
18954 // non-volatile-qualified non-class type to which the lvalue-to-rvalue
18955 // conversion is applied, or
18956 // -- x is a variable of non-reference type, and e is an element of the
18957 // set of potential results of a discarded-value expression to which
18958 // the lvalue-to-rvalue conversion is not applied
18959 //
18960 // We check the first bullet and the "potentially-evaluated" condition in
18961 // BuildDeclRefExpr. We check the type requirements in the second bullet
18962 // in CheckLValueToRValueConversionOperand below.
18963 switch (NOUR) {
18964 case NOUR_None:
18965 case NOUR_Unevaluated:
18966 llvm_unreachable("unexpected non-odr-use-reason")::llvm::llvm_unreachable_internal("unexpected non-odr-use-reason"
, "clang/lib/Sema/SemaExpr.cpp", 18966)
;
18967
18968 case NOUR_Constant:
18969 // Constant references were handled when they were built.
18970 if (VD->getType()->isReferenceType())
18971 return true;
18972 if (auto *RD = VD->getType()->getAsCXXRecordDecl())
18973 if (RD->hasMutableFields())
18974 return true;
18975 if (!VD->isUsableInConstantExpressions(S.Context))
18976 return true;
18977 break;
18978
18979 case NOUR_Discarded:
18980 if (VD->getType()->isReferenceType())
18981 return true;
18982 break;
18983 }
18984 return false;
18985 };
18986
18987 // Mark that this expression does not constitute an odr-use.
18988 auto MarkNotOdrUsed = [&] {
18989 S.MaybeODRUseExprs.remove(E);
18990 if (LambdaScopeInfo *LSI = S.getCurLambda())
18991 LSI->markVariableExprAsNonODRUsed(E);
18992 };
18993
18994 // C++2a [basic.def.odr]p2:
18995 // The set of potential results of an expression e is defined as follows:
18996 switch (E->getStmtClass()) {
18997 // -- If e is an id-expression, ...
18998 case Expr::DeclRefExprClass: {
18999 auto *DRE = cast<DeclRefExpr>(E);
19000 if (DRE->isNonOdrUse() || IsPotentialResultOdrUsed(DRE->getDecl()))
19001 break;
19002
19003 // Rebuild as a non-odr-use DeclRefExpr.
19004 MarkNotOdrUsed();
19005 return DeclRefExpr::Create(
19006 S.Context, DRE->getQualifierLoc(), DRE->getTemplateKeywordLoc(),
19007 DRE->getDecl(), DRE->refersToEnclosingVariableOrCapture(),
19008 DRE->getNameInfo(), DRE->getType(), DRE->getValueKind(),
19009 DRE->getFoundDecl(), CopiedTemplateArgs(DRE), NOUR);
19010 }
19011
19012 case Expr::FunctionParmPackExprClass: {
19013 auto *FPPE = cast<FunctionParmPackExpr>(E);
19014 // If any of the declarations in the pack is odr-used, then the expression
19015 // as a whole constitutes an odr-use.
19016 for (VarDecl *D : *FPPE)
19017 if (IsPotentialResultOdrUsed(D))
19018 return ExprEmpty();
19019
19020 // FIXME: Rebuild as a non-odr-use FunctionParmPackExpr? In practice,
19021 // nothing cares about whether we marked this as an odr-use, but it might
19022 // be useful for non-compiler tools.
19023 MarkNotOdrUsed();
19024 break;
19025 }
19026
19027 // -- If e is a subscripting operation with an array operand...
19028 case Expr::ArraySubscriptExprClass: {
19029 auto *ASE = cast<ArraySubscriptExpr>(E);
19030 Expr *OldBase = ASE->getBase()->IgnoreImplicit();
19031 if (!OldBase->getType()->isArrayType())
19032 break;
19033 ExprResult Base = Rebuild(OldBase);
19034 if (!Base.isUsable())
19035 return Base;
19036 Expr *LHS = ASE->getBase() == ASE->getLHS() ? Base.get() : ASE->getLHS();
19037 Expr *RHS = ASE->getBase() == ASE->getRHS() ? Base.get() : ASE->getRHS();
19038 SourceLocation LBracketLoc = ASE->getBeginLoc(); // FIXME: Not stored.
19039 return S.ActOnArraySubscriptExpr(nullptr, LHS, LBracketLoc, RHS,
19040 ASE->getRBracketLoc());
19041 }
19042
19043 case Expr::MemberExprClass: {
19044 auto *ME = cast<MemberExpr>(E);
19045 // -- If e is a class member access expression [...] naming a non-static
19046 // data member...
19047 if (isa<FieldDecl>(ME->getMemberDecl())) {
19048 ExprResult Base = Rebuild(ME->getBase());
19049 if (!Base.isUsable())
19050 return Base;
19051 return MemberExpr::Create(
19052 S.Context, Base.get(), ME->isArrow(), ME->getOperatorLoc(),
19053 ME->getQualifierLoc(), ME->getTemplateKeywordLoc(),
19054 ME->getMemberDecl(), ME->getFoundDecl(), ME->getMemberNameInfo(),
19055 CopiedTemplateArgs(ME), ME->getType(), ME->getValueKind(),
19056 ME->getObjectKind(), ME->isNonOdrUse());
19057 }
19058
19059 if (ME->getMemberDecl()->isCXXInstanceMember())
19060 break;
19061
19062 // -- If e is a class member access expression naming a static data member,
19063 // ...
19064 if (ME->isNonOdrUse() || IsPotentialResultOdrUsed(ME->getMemberDecl()))
19065 break;
19066
19067 // Rebuild as a non-odr-use MemberExpr.
19068 MarkNotOdrUsed();
19069 return MemberExpr::Create(
19070 S.Context, ME->getBase(), ME->isArrow(), ME->getOperatorLoc(),
19071 ME->getQualifierLoc(), ME->getTemplateKeywordLoc(), ME->getMemberDecl(),
19072 ME->getFoundDecl(), ME->getMemberNameInfo(), CopiedTemplateArgs(ME),
19073 ME->getType(), ME->getValueKind(), ME->getObjectKind(), NOUR);
19074 }
19075
19076 case Expr::BinaryOperatorClass: {
19077 auto *BO = cast<BinaryOperator>(E);
19078 Expr *LHS = BO->getLHS();
19079 Expr *RHS = BO->getRHS();
19080 // -- If e is a pointer-to-member expression of the form e1 .* e2 ...
19081 if (BO->getOpcode() == BO_PtrMemD) {
19082 ExprResult Sub = Rebuild(LHS);
19083 if (!Sub.isUsable())
19084 return Sub;
19085 LHS = Sub.get();
19086 // -- If e is a comma expression, ...
19087 } else if (BO->getOpcode() == BO_Comma) {
19088 ExprResult Sub = Rebuild(RHS);
19089 if (!Sub.isUsable())
19090 return Sub;
19091 RHS = Sub.get();
19092 } else {
19093 break;
19094 }
19095 return S.BuildBinOp(nullptr, BO->getOperatorLoc(), BO->getOpcode(),
19096 LHS, RHS);
19097 }
19098
19099 // -- If e has the form (e1)...
19100 case Expr::ParenExprClass: {
19101 auto *PE = cast<ParenExpr>(E);
19102 ExprResult Sub = Rebuild(PE->getSubExpr());
19103 if (!Sub.isUsable())
19104 return Sub;
19105 return S.ActOnParenExpr(PE->getLParen(), PE->getRParen(), Sub.get());
19106 }
19107
19108 // -- If e is a glvalue conditional expression, ...
19109 // We don't apply this to a binary conditional operator. FIXME: Should we?
19110 case Expr::ConditionalOperatorClass: {
19111 auto *CO = cast<ConditionalOperator>(E);
19112 ExprResult LHS = Rebuild(CO->getLHS());
19113 if (LHS.isInvalid())
19114 return ExprError();
19115 ExprResult RHS = Rebuild(CO->getRHS());
19116 if (RHS.isInvalid())
19117 return ExprError();
19118 if (!LHS.isUsable() && !RHS.isUsable())
19119 return ExprEmpty();
19120 if (!LHS.isUsable())
19121 LHS = CO->getLHS();
19122 if (!RHS.isUsable())
19123 RHS = CO->getRHS();
19124 return S.ActOnConditionalOp(CO->getQuestionLoc(), CO->getColonLoc(),
19125 CO->getCond(), LHS.get(), RHS.get());
19126 }
19127
19128 // [Clang extension]
19129 // -- If e has the form __extension__ e1...
19130 case Expr::UnaryOperatorClass: {
19131 auto *UO = cast<UnaryOperator>(E);
19132 if (UO->getOpcode() != UO_Extension)
19133 break;
19134 ExprResult Sub = Rebuild(UO->getSubExpr());
19135 if (!Sub.isUsable())
19136 return Sub;
19137 return S.BuildUnaryOp(nullptr, UO->getOperatorLoc(), UO_Extension,
19138 Sub.get());
19139 }
19140
19141 // [Clang extension]
19142 // -- If e has the form _Generic(...), the set of potential results is the
19143 // union of the sets of potential results of the associated expressions.
19144 case Expr::GenericSelectionExprClass: {
19145 auto *GSE = cast<GenericSelectionExpr>(E);
19146
19147 SmallVector<Expr *, 4> AssocExprs;
19148 bool AnyChanged = false;
19149 for (Expr *OrigAssocExpr : GSE->getAssocExprs()) {
19150 ExprResult AssocExpr = Rebuild(OrigAssocExpr);
19151 if (AssocExpr.isInvalid())
19152 return ExprError();
19153 if (AssocExpr.isUsable()) {
19154 AssocExprs.push_back(AssocExpr.get());
19155 AnyChanged = true;
19156 } else {
19157 AssocExprs.push_back(OrigAssocExpr);
19158 }
19159 }
19160
19161 return AnyChanged ? S.CreateGenericSelectionExpr(
19162 GSE->getGenericLoc(), GSE->getDefaultLoc(),
19163 GSE->getRParenLoc(), GSE->getControllingExpr(),
19164 GSE->getAssocTypeSourceInfos(), AssocExprs)
19165 : ExprEmpty();
19166 }
19167
19168 // [Clang extension]
19169 // -- If e has the form __builtin_choose_expr(...), the set of potential
19170 // results is the union of the sets of potential results of the
19171 // second and third subexpressions.
19172 case Expr::ChooseExprClass: {
19173 auto *CE = cast<ChooseExpr>(E);
19174
19175 ExprResult LHS = Rebuild(CE->getLHS());
19176 if (LHS.isInvalid())
19177 return ExprError();
19178
19179 ExprResult RHS = Rebuild(CE->getLHS());
19180 if (RHS.isInvalid())
19181 return ExprError();
19182
19183 if (!LHS.get() && !RHS.get())
19184 return ExprEmpty();
19185 if (!LHS.isUsable())
19186 LHS = CE->getLHS();
19187 if (!RHS.isUsable())
19188 RHS = CE->getRHS();
19189
19190 return S.ActOnChooseExpr(CE->getBuiltinLoc(), CE->getCond(), LHS.get(),
19191 RHS.get(), CE->getRParenLoc());
19192 }
19193
19194 // Step through non-syntactic nodes.
19195 case Expr::ConstantExprClass: {
19196 auto *CE = cast<ConstantExpr>(E);
19197 ExprResult Sub = Rebuild(CE->getSubExpr());
19198 if (!Sub.isUsable())
19199 return Sub;
19200 return ConstantExpr::Create(S.Context, Sub.get());
19201 }
19202
19203 // We could mostly rely on the recursive rebuilding to rebuild implicit
19204 // casts, but not at the top level, so rebuild them here.
19205 case Expr::ImplicitCastExprClass: {
19206 auto *ICE = cast<ImplicitCastExpr>(E);
19207 // Only step through the narrow set of cast kinds we expect to encounter.
19208 // Anything else suggests we've left the region in which potential results
19209 // can be found.
19210 switch (ICE->getCastKind()) {
19211 case CK_NoOp:
19212 case CK_DerivedToBase:
19213 case CK_UncheckedDerivedToBase: {
19214 ExprResult Sub = Rebuild(ICE->getSubExpr());
19215 if (!Sub.isUsable())
19216 return Sub;
19217 CXXCastPath Path(ICE->path());
19218 return S.ImpCastExprToType(Sub.get(), ICE->getType(), ICE->getCastKind(),
19219 ICE->getValueKind(), &Path);
19220 }
19221
19222 default:
19223 break;
19224 }
19225 break;
19226 }
19227
19228 default:
19229 break;
19230 }
19231
19232 // Can't traverse through this node. Nothing to do.
19233 return ExprEmpty();
19234}
19235
19236ExprResult Sema::CheckLValueToRValueConversionOperand(Expr *E) {
19237 // Check whether the operand is or contains an object of non-trivial C union
19238 // type.
19239 if (E->getType().isVolatileQualified() &&
19240 (E->getType().hasNonTrivialToPrimitiveDestructCUnion() ||
19241 E->getType().hasNonTrivialToPrimitiveCopyCUnion()))
19242 checkNonTrivialCUnion(E->getType(), E->getExprLoc(),
19243 Sema::NTCUC_LValueToRValueVolatile,
19244 NTCUK_Destruct|NTCUK_Copy);
19245
19246 // C++2a [basic.def.odr]p4:
19247 // [...] an expression of non-volatile-qualified non-class type to which
19248 // the lvalue-to-rvalue conversion is applied [...]
19249 if (E->getType().isVolatileQualified() || E->getType()->getAs<RecordType>())
19250 return E;
19251
19252 ExprResult Result =
19253 rebuildPotentialResultsAsNonOdrUsed(*this, E, NOUR_Constant);
19254 if (Result.isInvalid())
19255 return ExprError();
19256 return Result.get() ? Result : E;
19257}
19258
19259ExprResult Sema::ActOnConstantExpression(ExprResult Res) {
19260 Res = CorrectDelayedTyposInExpr(Res);
19261
19262 if (!Res.isUsable())
19263 return Res;
19264
19265 // If a constant-expression is a reference to a variable where we delay
19266 // deciding whether it is an odr-use, just assume we will apply the
19267 // lvalue-to-rvalue conversion. In the one case where this doesn't happen
19268 // (a non-type template argument), we have special handling anyway.
19269 return CheckLValueToRValueConversionOperand(Res.get());
19270}
19271
19272void Sema::CleanupVarDeclMarking() {
19273 // Iterate through a local copy in case MarkVarDeclODRUsed makes a recursive
19274 // call.
19275 MaybeODRUseExprSet LocalMaybeODRUseExprs;
19276 std::swap(LocalMaybeODRUseExprs, MaybeODRUseExprs);
19277
19278 for (Expr *E : LocalMaybeODRUseExprs) {
19279 if (auto *DRE = dyn_cast<DeclRefExpr>(E)) {
19280 MarkVarDeclODRUsed(cast<VarDecl>(DRE->getDecl()),
19281 DRE->getLocation(), *this);
19282 } else if (auto *ME = dyn_cast<MemberExpr>(E)) {
19283 MarkVarDeclODRUsed(cast<VarDecl>(ME->getMemberDecl()), ME->getMemberLoc(),
19284 *this);
19285 } else if (auto *FP = dyn_cast<FunctionParmPackExpr>(E)) {
19286 for (VarDecl *VD : *FP)
19287 MarkVarDeclODRUsed(VD, FP->getParameterPackLocation(), *this);
19288 } else {
19289 llvm_unreachable("Unexpected expression")::llvm::llvm_unreachable_internal("Unexpected expression", "clang/lib/Sema/SemaExpr.cpp"
, 19289)
;
19290 }
19291 }
19292
19293 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", 19294, __extension__ __PRETTY_FUNCTION__
))
19294 "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", 19294, __extension__ __PRETTY_FUNCTION__
))
;
19295}
19296
19297static void DoMarkVarDeclReferenced(
19298 Sema &SemaRef, SourceLocation Loc, VarDecl *Var, Expr *E,
19299 llvm::DenseMap<const VarDecl *, int> &RefsMinusAssignments) {
19300 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", 19302, __extension__ __PRETTY_FUNCTION__
))
19301 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", 19302, __extension__ __PRETTY_FUNCTION__
))
19302 "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", 19302, __extension__ __PRETTY_FUNCTION__
))
;
19303 Var->setReferenced();
19304
19305 if (Var->isInvalidDecl())
19306 return;
19307
19308 auto *MSI = Var->getMemberSpecializationInfo();
19309 TemplateSpecializationKind TSK = MSI ? MSI->getTemplateSpecializationKind()
19310 : Var->getTemplateSpecializationKind();
19311
19312 OdrUseContext OdrUse = isOdrUseContext(SemaRef);
19313 bool UsableInConstantExpr =
19314 Var->mightBeUsableInConstantExpressions(SemaRef.Context);
19315
19316 if (Var->isLocalVarDeclOrParm() && !Var->hasExternalStorage()) {
19317 RefsMinusAssignments.insert({Var, 0}).first->getSecond()++;
19318 }
19319
19320 // C++20 [expr.const]p12:
19321 // A variable [...] is needed for constant evaluation if it is [...] a
19322 // variable whose name appears as a potentially constant evaluated
19323 // expression that is either a contexpr variable or is of non-volatile
19324 // const-qualified integral type or of reference type
19325 bool NeededForConstantEvaluation =
19326 isPotentiallyConstantEvaluatedContext(SemaRef) && UsableInConstantExpr;
19327
19328 bool NeedDefinition =
19329 OdrUse == OdrUseContext::Used || NeededForConstantEvaluation;
19330
19331 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", 19332, __extension__ __PRETTY_FUNCTION__
))
19332 "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", 19332, __extension__ __PRETTY_FUNCTION__
))
;
19333
19334 // If this might be a member specialization of a static data member, check
19335 // the specialization is visible. We already did the checks for variable
19336 // template specializations when we created them.
19337 if (NeedDefinition && TSK != TSK_Undeclared &&
19338 !isa<VarTemplateSpecializationDecl>(Var))
19339 SemaRef.checkSpecializationVisibility(Loc, Var);
19340
19341 // Perform implicit instantiation of static data members, static data member
19342 // templates of class templates, and variable template specializations. Delay
19343 // instantiations of variable templates, except for those that could be used
19344 // in a constant expression.
19345 if (NeedDefinition && isTemplateInstantiation(TSK)) {
19346 // Per C++17 [temp.explicit]p10, we may instantiate despite an explicit
19347 // instantiation declaration if a variable is usable in a constant
19348 // expression (among other cases).
19349 bool TryInstantiating =
19350 TSK == TSK_ImplicitInstantiation ||
19351 (TSK == TSK_ExplicitInstantiationDeclaration && UsableInConstantExpr);
19352
19353 if (TryInstantiating) {
19354 SourceLocation PointOfInstantiation =
19355 MSI ? MSI->getPointOfInstantiation() : Var->getPointOfInstantiation();
19356 bool FirstInstantiation = PointOfInstantiation.isInvalid();
19357 if (FirstInstantiation) {
19358 PointOfInstantiation = Loc;
19359 if (MSI)
19360 MSI->setPointOfInstantiation(PointOfInstantiation);
19361 // FIXME: Notify listener.
19362 else
19363 Var->setTemplateSpecializationKind(TSK, PointOfInstantiation);
19364 }
19365
19366 if (UsableInConstantExpr) {
19367 // Do not defer instantiations of variables that could be used in a
19368 // constant expression.
19369 SemaRef.runWithSufficientStackSpace(PointOfInstantiation, [&] {
19370 SemaRef.InstantiateVariableDefinition(PointOfInstantiation, Var);
19371 });
19372
19373 // Re-set the member to trigger a recomputation of the dependence bits
19374 // for the expression.
19375 if (auto *DRE = dyn_cast_or_null<DeclRefExpr>(E))
19376 DRE->setDecl(DRE->getDecl());
19377 else if (auto *ME = dyn_cast_or_null<MemberExpr>(E))
19378 ME->setMemberDecl(ME->getMemberDecl());
19379 } else if (FirstInstantiation ||
19380 isa<VarTemplateSpecializationDecl>(Var)) {
19381 // FIXME: For a specialization of a variable template, we don't
19382 // distinguish between "declaration and type implicitly instantiated"
19383 // and "implicit instantiation of definition requested", so we have
19384 // no direct way to avoid enqueueing the pending instantiation
19385 // multiple times.
19386 SemaRef.PendingInstantiations
19387 .push_back(std::make_pair(Var, PointOfInstantiation));
19388 }
19389 }
19390 }
19391
19392 // C++2a [basic.def.odr]p4:
19393 // A variable x whose name appears as a potentially-evaluated expression e
19394 // is odr-used by e unless
19395 // -- x is a reference that is usable in constant expressions
19396 // -- x is a variable of non-reference type that is usable in constant
19397 // expressions and has no mutable subobjects [FIXME], and e is an
19398 // element of the set of potential results of an expression of
19399 // non-volatile-qualified non-class type to which the lvalue-to-rvalue
19400 // conversion is applied
19401 // -- x is a variable of non-reference type, and e is an element of the set
19402 // of potential results of a discarded-value expression to which the
19403 // lvalue-to-rvalue conversion is not applied [FIXME]
19404 //
19405 // We check the first part of the second bullet here, and
19406 // Sema::CheckLValueToRValueConversionOperand deals with the second part.
19407 // FIXME: To get the third bullet right, we need to delay this even for
19408 // variables that are not usable in constant expressions.
19409
19410 // If we already know this isn't an odr-use, there's nothing more to do.
19411 if (DeclRefExpr *DRE = dyn_cast_or_null<DeclRefExpr>(E))
19412 if (DRE->isNonOdrUse())
19413 return;
19414 if (MemberExpr *ME = dyn_cast_or_null<MemberExpr>(E))
19415 if (ME->isNonOdrUse())
19416 return;
19417
19418 switch (OdrUse) {
19419 case OdrUseContext::None:
19420 assert((!E || isa<FunctionParmPackExpr>(E)) &&(static_cast <bool> ((!E || isa<FunctionParmPackExpr
>(E)) && "missing non-odr-use marking for unevaluated decl ref"
) ? void (0) : __assert_fail ("(!E || isa<FunctionParmPackExpr>(E)) && \"missing non-odr-use marking for unevaluated decl ref\""
, "clang/lib/Sema/SemaExpr.cpp", 19421, __extension__ __PRETTY_FUNCTION__
))
19421 "missing non-odr-use marking for unevaluated decl ref")(static_cast <bool> ((!E || isa<FunctionParmPackExpr
>(E)) && "missing non-odr-use marking for unevaluated decl ref"
) ? void (0) : __assert_fail ("(!E || isa<FunctionParmPackExpr>(E)) && \"missing non-odr-use marking for unevaluated decl ref\""
, "clang/lib/Sema/SemaExpr.cpp", 19421, __extension__ __PRETTY_FUNCTION__
))
;
19422 break;
19423
19424 case OdrUseContext::FormallyOdrUsed:
19425 // FIXME: Ignoring formal odr-uses results in incorrect lambda capture
19426 // behavior.
19427 break;
19428
19429 case OdrUseContext::Used:
19430 // If we might later find that this expression isn't actually an odr-use,
19431 // delay the marking.
19432 if (E && Var->isUsableInConstantExpressions(SemaRef.Context))
19433 SemaRef.MaybeODRUseExprs.insert(E);
19434 else
19435 MarkVarDeclODRUsed(Var, Loc, SemaRef);
19436 break;
19437
19438 case OdrUseContext::Dependent:
19439 // If this is a dependent context, we don't need to mark variables as
19440 // odr-used, but we may still need to track them for lambda capture.
19441 // FIXME: Do we also need to do this inside dependent typeid expressions
19442 // (which are modeled as unevaluated at this point)?
19443 const bool RefersToEnclosingScope =
19444 (SemaRef.CurContext != Var->getDeclContext() &&
19445 Var->getDeclContext()->isFunctionOrMethod() && Var->hasLocalStorage());
19446 if (RefersToEnclosingScope) {
19447 LambdaScopeInfo *const LSI =
19448 SemaRef.getCurLambda(/*IgnoreNonLambdaCapturingScope=*/true);
19449 if (LSI && (!LSI->CallOperator ||
19450 !LSI->CallOperator->Encloses(Var->getDeclContext()))) {
19451 // If a variable could potentially be odr-used, defer marking it so
19452 // until we finish analyzing the full expression for any
19453 // lvalue-to-rvalue
19454 // or discarded value conversions that would obviate odr-use.
19455 // Add it to the list of potential captures that will be analyzed
19456 // later (ActOnFinishFullExpr) for eventual capture and odr-use marking
19457 // unless the variable is a reference that was initialized by a constant
19458 // expression (this will never need to be captured or odr-used).
19459 //
19460 // FIXME: We can simplify this a lot after implementing P0588R1.
19461 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", 19461, __extension__ __PRETTY_FUNCTION__
))
;
19462 if (!Var->getType()->isReferenceType() ||
19463 !Var->isUsableInConstantExpressions(SemaRef.Context))
19464 LSI->addPotentialCapture(E->IgnoreParens());
19465 }
19466 }
19467 break;
19468 }
19469}
19470
19471/// Mark a variable referenced, and check whether it is odr-used
19472/// (C++ [basic.def.odr]p2, C99 6.9p3). Note that this should not be
19473/// used directly for normal expressions referring to VarDecl.
19474void Sema::MarkVariableReferenced(SourceLocation Loc, VarDecl *Var) {
19475 DoMarkVarDeclReferenced(*this, Loc, Var, nullptr, RefsMinusAssignments);
19476}
19477
19478static void
19479MarkExprReferenced(Sema &SemaRef, SourceLocation Loc, Decl *D, Expr *E,
19480 bool MightBeOdrUse,
19481 llvm::DenseMap<const VarDecl *, int> &RefsMinusAssignments) {
19482 if (SemaRef.isInOpenMPDeclareTargetContext())
19483 SemaRef.checkDeclIsAllowedInOpenMPTarget(E, D);
19484
19485 if (VarDecl *Var = dyn_cast<VarDecl>(D)) {
19486 DoMarkVarDeclReferenced(SemaRef, Loc, Var, E, RefsMinusAssignments);
19487 return;
19488 }
19489
19490 SemaRef.MarkAnyDeclReferenced(Loc, D, MightBeOdrUse);
19491
19492 // If this is a call to a method via a cast, also mark the method in the
19493 // derived class used in case codegen can devirtualize the call.
19494 const MemberExpr *ME = dyn_cast<MemberExpr>(E);
19495 if (!ME)
19496 return;
19497 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ME->getMemberDecl());
19498 if (!MD)
19499 return;
19500 // Only attempt to devirtualize if this is truly a virtual call.
19501 bool IsVirtualCall = MD->isVirtual() &&
19502 ME->performsVirtualDispatch(SemaRef.getLangOpts());
19503 if (!IsVirtualCall)
19504 return;
19505
19506 // If it's possible to devirtualize the call, mark the called function
19507 // referenced.
19508 CXXMethodDecl *DM = MD->getDevirtualizedMethod(
19509 ME->getBase(), SemaRef.getLangOpts().AppleKext);
19510 if (DM)
19511 SemaRef.MarkAnyDeclReferenced(Loc, DM, MightBeOdrUse);
19512}
19513
19514/// Perform reference-marking and odr-use handling for a DeclRefExpr.
19515///
19516/// Note, this may change the dependence of the DeclRefExpr, and so needs to be
19517/// handled with care if the DeclRefExpr is not newly-created.
19518void Sema::MarkDeclRefReferenced(DeclRefExpr *E, const Expr *Base) {
19519 // TODO: update this with DR# once a defect report is filed.
19520 // C++11 defect. The address of a pure member should not be an ODR use, even
19521 // if it's a qualified reference.
19522 bool OdrUse = true;
19523 if (const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(E->getDecl()))
19524 if (Method->isVirtual() &&
19525 !Method->getDevirtualizedMethod(Base, getLangOpts().AppleKext))
19526 OdrUse = false;
19527
19528 if (auto *FD = dyn_cast<FunctionDecl>(E->getDecl()))
19529 if (!isUnevaluatedContext() && !isConstantEvaluated() &&
19530 FD->isConsteval() && !RebuildingImmediateInvocation)
19531 ExprEvalContexts.back().ReferenceToConsteval.insert(E);
19532 MarkExprReferenced(*this, E->getLocation(), E->getDecl(), E, OdrUse,
19533 RefsMinusAssignments);
19534}
19535
19536/// Perform reference-marking and odr-use handling for a MemberExpr.
19537void Sema::MarkMemberReferenced(MemberExpr *E) {
19538 // C++11 [basic.def.odr]p2:
19539 // A non-overloaded function whose name appears as a potentially-evaluated
19540 // expression or a member of a set of candidate functions, if selected by
19541 // overload resolution when referred to from a potentially-evaluated
19542 // expression, is odr-used, unless it is a pure virtual function and its
19543 // name is not explicitly qualified.
19544 bool MightBeOdrUse = true;
19545 if (E->performsVirtualDispatch(getLangOpts())) {
19546 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(E->getMemberDecl()))
19547 if (Method->isPure())
19548 MightBeOdrUse = false;
19549 }
19550 SourceLocation Loc =
19551 E->getMemberLoc().isValid() ? E->getMemberLoc() : E->getBeginLoc();
19552 MarkExprReferenced(*this, Loc, E->getMemberDecl(), E, MightBeOdrUse,
19553 RefsMinusAssignments);
19554}
19555
19556/// Perform reference-marking and odr-use handling for a FunctionParmPackExpr.
19557void Sema::MarkFunctionParmPackReferenced(FunctionParmPackExpr *E) {
19558 for (VarDecl *VD : *E)
19559 MarkExprReferenced(*this, E->getParameterPackLocation(), VD, E, true,
19560 RefsMinusAssignments);
19561}
19562
19563/// Perform marking for a reference to an arbitrary declaration. It
19564/// marks the declaration referenced, and performs odr-use checking for
19565/// functions and variables. This method should not be used when building a
19566/// normal expression which refers to a variable.
19567void Sema::MarkAnyDeclReferenced(SourceLocation Loc, Decl *D,
19568 bool MightBeOdrUse) {
19569 if (MightBeOdrUse) {
19570 if (auto *VD = dyn_cast<VarDecl>(D)) {
19571 MarkVariableReferenced(Loc, VD);
19572 return;
19573 }
19574 }
19575 if (auto *FD = dyn_cast<FunctionDecl>(D)) {
19576 MarkFunctionReferenced(Loc, FD, MightBeOdrUse);
19577 return;
19578 }
19579 D->setReferenced();
19580}
19581
19582namespace {
19583 // Mark all of the declarations used by a type as referenced.
19584 // FIXME: Not fully implemented yet! We need to have a better understanding
19585 // of when we're entering a context we should not recurse into.
19586 // FIXME: This is and EvaluatedExprMarker are more-or-less equivalent to
19587 // TreeTransforms rebuilding the type in a new context. Rather than
19588 // duplicating the TreeTransform logic, we should consider reusing it here.
19589 // Currently that causes problems when rebuilding LambdaExprs.
19590 class MarkReferencedDecls : public RecursiveASTVisitor<MarkReferencedDecls> {
19591 Sema &S;
19592 SourceLocation Loc;
19593
19594 public:
19595 typedef RecursiveASTVisitor<MarkReferencedDecls> Inherited;
19596
19597 MarkReferencedDecls(Sema &S, SourceLocation Loc) : S(S), Loc(Loc) { }
19598
19599 bool TraverseTemplateArgument(const TemplateArgument &Arg);
19600 };
19601}
19602
19603bool MarkReferencedDecls::TraverseTemplateArgument(
19604 const TemplateArgument &Arg) {
19605 {
19606 // A non-type template argument is a constant-evaluated context.
19607 EnterExpressionEvaluationContext Evaluated(
19608 S, Sema::ExpressionEvaluationContext::ConstantEvaluated);
19609 if (Arg.getKind() == TemplateArgument::Declaration) {
19610 if (Decl *D = Arg.getAsDecl())
19611 S.MarkAnyDeclReferenced(Loc, D, true);
19612 } else if (Arg.getKind() == TemplateArgument::Expression) {
19613 S.MarkDeclarationsReferencedInExpr(Arg.getAsExpr(), false);
19614 }
19615 }
19616
19617 return Inherited::TraverseTemplateArgument(Arg);
19618}
19619
19620void Sema::MarkDeclarationsReferencedInType(SourceLocation Loc, QualType T) {
19621 MarkReferencedDecls Marker(*this, Loc);
19622 Marker.TraverseType(T);
19623}
19624
19625namespace {
19626/// Helper class that marks all of the declarations referenced by
19627/// potentially-evaluated subexpressions as "referenced".
19628class EvaluatedExprMarker : public UsedDeclVisitor<EvaluatedExprMarker> {
19629public:
19630 typedef UsedDeclVisitor<EvaluatedExprMarker> Inherited;
19631 bool SkipLocalVariables;
19632 ArrayRef<const Expr *> StopAt;
19633
19634 EvaluatedExprMarker(Sema &S, bool SkipLocalVariables,
19635 ArrayRef<const Expr *> StopAt)
19636 : Inherited(S), SkipLocalVariables(SkipLocalVariables), StopAt(StopAt) {}
19637
19638 void visitUsedDecl(SourceLocation Loc, Decl *D) {
19639 S.MarkFunctionReferenced(Loc, cast<FunctionDecl>(D));
19640 }
19641
19642 void Visit(Expr *E) {
19643 if (std::find(StopAt.begin(), StopAt.end(), E) != StopAt.end())
19644 return;
19645 Inherited::Visit(E);
19646 }
19647
19648 void VisitDeclRefExpr(DeclRefExpr *E) {
19649 // If we were asked not to visit local variables, don't.
19650 if (SkipLocalVariables) {
19651 if (VarDecl *VD = dyn_cast<VarDecl>(E->getDecl()))
19652 if (VD->hasLocalStorage())
19653 return;
19654 }
19655
19656 // FIXME: This can trigger the instantiation of the initializer of a
19657 // variable, which can cause the expression to become value-dependent
19658 // or error-dependent. Do we need to propagate the new dependence bits?
19659 S.MarkDeclRefReferenced(E);
19660 }
19661
19662 void VisitMemberExpr(MemberExpr *E) {
19663 S.MarkMemberReferenced(E);
19664 Visit(E->getBase());
19665 }
19666};
19667} // namespace
19668
19669/// Mark any declarations that appear within this expression or any
19670/// potentially-evaluated subexpressions as "referenced".
19671///
19672/// \param SkipLocalVariables If true, don't mark local variables as
19673/// 'referenced'.
19674/// \param StopAt Subexpressions that we shouldn't recurse into.
19675void Sema::MarkDeclarationsReferencedInExpr(Expr *E,
19676 bool SkipLocalVariables,
19677 ArrayRef<const Expr*> StopAt) {
19678 EvaluatedExprMarker(*this, SkipLocalVariables, StopAt).Visit(E);
19679}
19680
19681/// Emit a diagnostic when statements are reachable.
19682/// FIXME: check for reachability even in expressions for which we don't build a
19683/// CFG (eg, in the initializer of a global or in a constant expression).
19684/// For example,
19685/// namespace { auto *p = new double[3][false ? (1, 2) : 3]; }
19686bool Sema::DiagIfReachable(SourceLocation Loc, ArrayRef<const Stmt *> Stmts,
19687 const PartialDiagnostic &PD) {
19688 if (!Stmts.empty() && getCurFunctionOrMethodDecl()) {
19689 if (!FunctionScopes.empty())
19690 FunctionScopes.back()->PossiblyUnreachableDiags.push_back(
19691 sema::PossiblyUnreachableDiag(PD, Loc, Stmts));
19692 return true;
19693 }
19694
19695 // The initializer of a constexpr variable or of the first declaration of a
19696 // static data member is not syntactically a constant evaluated constant,
19697 // but nonetheless is always required to be a constant expression, so we
19698 // can skip diagnosing.
19699 // FIXME: Using the mangling context here is a hack.
19700 if (auto *VD = dyn_cast_or_null<VarDecl>(
19701 ExprEvalContexts.back().ManglingContextDecl)) {
19702 if (VD->isConstexpr() ||
19703 (VD->isStaticDataMember() && VD->isFirstDecl() && !VD->isInline()))
19704 return false;
19705 // FIXME: For any other kind of variable, we should build a CFG for its
19706 // initializer and check whether the context in question is reachable.
19707 }
19708
19709 Diag(Loc, PD);
19710 return true;
19711}
19712
19713/// Emit a diagnostic that describes an effect on the run-time behavior
19714/// of the program being compiled.
19715///
19716/// This routine emits the given diagnostic when the code currently being
19717/// type-checked is "potentially evaluated", meaning that there is a
19718/// possibility that the code will actually be executable. Code in sizeof()
19719/// expressions, code used only during overload resolution, etc., are not
19720/// potentially evaluated. This routine will suppress such diagnostics or,
19721/// in the absolutely nutty case of potentially potentially evaluated
19722/// expressions (C++ typeid), queue the diagnostic to potentially emit it
19723/// later.
19724///
19725/// This routine should be used for all diagnostics that describe the run-time
19726/// behavior of a program, such as passing a non-POD value through an ellipsis.
19727/// Failure to do so will likely result in spurious diagnostics or failures
19728/// during overload resolution or within sizeof/alignof/typeof/typeid.
19729bool Sema::DiagRuntimeBehavior(SourceLocation Loc, ArrayRef<const Stmt*> Stmts,
19730 const PartialDiagnostic &PD) {
19731
19732 if (ExprEvalContexts.back().isDiscardedStatementContext())
19733 return false;
19734
19735 switch (ExprEvalContexts.back().Context) {
19736 case ExpressionEvaluationContext::Unevaluated:
19737 case ExpressionEvaluationContext::UnevaluatedList:
19738 case ExpressionEvaluationContext::UnevaluatedAbstract:
19739 case ExpressionEvaluationContext::DiscardedStatement:
19740 // The argument will never be evaluated, so don't complain.
19741 break;
19742
19743 case ExpressionEvaluationContext::ConstantEvaluated:
19744 case ExpressionEvaluationContext::ImmediateFunctionContext:
19745 // Relevant diagnostics should be produced by constant evaluation.
19746 break;
19747
19748 case ExpressionEvaluationContext::PotentiallyEvaluated:
19749 case ExpressionEvaluationContext::PotentiallyEvaluatedIfUsed:
19750 return DiagIfReachable(Loc, Stmts, PD);
19751 }
19752
19753 return false;
19754}
19755
19756bool Sema::DiagRuntimeBehavior(SourceLocation Loc, const Stmt *Statement,
19757 const PartialDiagnostic &PD) {
19758 return DiagRuntimeBehavior(
19759 Loc, Statement ? llvm::makeArrayRef(Statement) : llvm::None, PD);
19760}
19761
19762bool Sema::CheckCallReturnType(QualType ReturnType, SourceLocation Loc,
19763 CallExpr *CE, FunctionDecl *FD) {
19764 if (ReturnType->isVoidType() || !ReturnType->isIncompleteType())
19765 return false;
19766
19767 // If we're inside a decltype's expression, don't check for a valid return
19768 // type or construct temporaries until we know whether this is the last call.
19769 if (ExprEvalContexts.back().ExprContext ==
19770 ExpressionEvaluationContextRecord::EK_Decltype) {
19771 ExprEvalContexts.back().DelayedDecltypeCalls.push_back(CE);
19772 return false;
19773 }
19774
19775 class CallReturnIncompleteDiagnoser : public TypeDiagnoser {
19776 FunctionDecl *FD;
19777 CallExpr *CE;
19778
19779 public:
19780 CallReturnIncompleteDiagnoser(FunctionDecl *FD, CallExpr *CE)
19781 : FD(FD), CE(CE) { }
19782
19783 void diagnose(Sema &S, SourceLocation Loc, QualType T) override {
19784 if (!FD) {
19785 S.Diag(Loc, diag::err_call_incomplete_return)
19786 << T << CE->getSourceRange();
19787 return;
19788 }
19789
19790 S.Diag(Loc, diag::err_call_function_incomplete_return)
19791 << CE->getSourceRange() << FD << T;
19792 S.Diag(FD->getLocation(), diag::note_entity_declared_at)
19793 << FD->getDeclName();
19794 }
19795 } Diagnoser(FD, CE);
19796
19797 if (RequireCompleteType(Loc, ReturnType, Diagnoser))
19798 return true;
19799
19800 return false;
19801}
19802
19803// Diagnose the s/=/==/ and s/\|=/!=/ typos. Note that adding parentheses
19804// will prevent this condition from triggering, which is what we want.
19805void Sema::DiagnoseAssignmentAsCondition(Expr *E) {
19806 SourceLocation Loc;
19807
19808 unsigned diagnostic = diag::warn_condition_is_assignment;
19809 bool IsOrAssign = false;
19810
19811 if (BinaryOperator *Op = dyn_cast<BinaryOperator>(E)) {
19812 if (Op->getOpcode() != BO_Assign && Op->getOpcode() != BO_OrAssign)
19813 return;
19814
19815 IsOrAssign = Op->getOpcode() == BO_OrAssign;
19816
19817 // Greylist some idioms by putting them into a warning subcategory.
19818 if (ObjCMessageExpr *ME
19819 = dyn_cast<ObjCMessageExpr>(Op->getRHS()->IgnoreParenCasts())) {
19820 Selector Sel = ME->getSelector();
19821
19822 // self = [<foo> init...]
19823 if (isSelfExpr(Op->getLHS()) && ME->getMethodFamily() == OMF_init)
19824 diagnostic = diag::warn_condition_is_idiomatic_assignment;
19825
19826 // <foo> = [<bar> nextObject]
19827 else if (Sel.isUnarySelector() && Sel.getNameForSlot(0) == "nextObject")
19828 diagnostic = diag::warn_condition_is_idiomatic_assignment;
19829 }
19830
19831 Loc = Op->getOperatorLoc();
19832 } else if (CXXOperatorCallExpr *Op = dyn_cast<CXXOperatorCallExpr>(E)) {
19833 if (Op->getOperator() != OO_Equal && Op->getOperator() != OO_PipeEqual)
19834 return;
19835
19836 IsOrAssign = Op->getOperator() == OO_PipeEqual;
19837 Loc = Op->getOperatorLoc();
19838 } else if (PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(E))
19839 return DiagnoseAssignmentAsCondition(POE->getSyntacticForm());
19840 else {
19841 // Not an assignment.
19842 return;
19843 }
19844
19845 Diag(Loc, diagnostic) << E->getSourceRange();
19846
19847 SourceLocation Open = E->getBeginLoc();
19848 SourceLocation Close = getLocForEndOfToken(E->getSourceRange().getEnd());
19849 Diag(Loc, diag::note_condition_assign_silence)
19850 << FixItHint::CreateInsertion(Open, "(")
19851 << FixItHint::CreateInsertion(Close, ")");
19852
19853 if (IsOrAssign)
19854 Diag(Loc, diag::note_condition_or_assign_to_comparison)
19855 << FixItHint::CreateReplacement(Loc, "!=");
19856 else
19857 Diag(Loc, diag::note_condition_assign_to_comparison)
19858 << FixItHint::CreateReplacement(Loc, "==");
19859}
19860
19861/// Redundant parentheses over an equality comparison can indicate
19862/// that the user intended an assignment used as condition.
19863void Sema::DiagnoseEqualityWithExtraParens(ParenExpr *ParenE) {
19864 // Don't warn if the parens came from a macro.
19865 SourceLocation parenLoc = ParenE->getBeginLoc();
19866 if (parenLoc.isInvalid() || parenLoc.isMacroID())
19867 return;
19868 // Don't warn for dependent expressions.
19869 if (ParenE->isTypeDependent())
19870 return;
19871
19872 Expr *E = ParenE->IgnoreParens();
19873
19874 if (BinaryOperator *opE = dyn_cast<BinaryOperator>(E))
19875 if (opE->getOpcode() == BO_EQ &&
19876 opE->getLHS()->IgnoreParenImpCasts()->isModifiableLvalue(Context)
19877 == Expr::MLV_Valid) {
19878 SourceLocation Loc = opE->getOperatorLoc();
19879
19880 Diag(Loc, diag::warn_equality_with_extra_parens) << E->getSourceRange();
19881 SourceRange ParenERange = ParenE->getSourceRange();
19882 Diag(Loc, diag::note_equality_comparison_silence)
19883 << FixItHint::CreateRemoval(ParenERange.getBegin())
19884 << FixItHint::CreateRemoval(ParenERange.getEnd());
19885 Diag(Loc, diag::note_equality_comparison_to_assign)
19886 << FixItHint::CreateReplacement(Loc, "=");
19887 }
19888}
19889
19890ExprResult Sema::CheckBooleanCondition(SourceLocation Loc, Expr *E,
19891 bool IsConstexpr) {
19892 DiagnoseAssignmentAsCondition(E);
19893 if (ParenExpr *parenE = dyn_cast<ParenExpr>(E))
19894 DiagnoseEqualityWithExtraParens(parenE);
19895
19896 ExprResult result = CheckPlaceholderExpr(E);
19897 if (result.isInvalid()) return ExprError();
19898 E = result.get();
19899
19900 if (!E->isTypeDependent()) {
19901 if (getLangOpts().CPlusPlus)
19902 return CheckCXXBooleanCondition(E, IsConstexpr); // C++ 6.4p4
19903
19904 ExprResult ERes = DefaultFunctionArrayLvalueConversion(E);
19905 if (ERes.isInvalid())
19906 return ExprError();
19907 E = ERes.get();
19908
19909 QualType T = E->getType();
19910 if (!T->isScalarType()) { // C99 6.8.4.1p1
19911 Diag(Loc, diag::err_typecheck_statement_requires_scalar)
19912 << T << E->getSourceRange();
19913 return ExprError();
19914 }
19915 CheckBoolLikeConversion(E, Loc);
19916 }
19917
19918 return E;
19919}
19920
19921Sema::ConditionResult Sema::ActOnCondition(Scope *S, SourceLocation Loc,
19922 Expr *SubExpr, ConditionKind CK,
19923 bool MissingOK) {
19924 // MissingOK indicates whether having no condition expression is valid
19925 // (for loop) or invalid (e.g. while loop).
19926 if (!SubExpr)
19927 return MissingOK ? ConditionResult() : ConditionError();
19928
19929 ExprResult Cond;
19930 switch (CK) {
19931 case ConditionKind::Boolean:
19932 Cond = CheckBooleanCondition(Loc, SubExpr);
19933 break;
19934
19935 case ConditionKind::ConstexprIf:
19936 Cond = CheckBooleanCondition(Loc, SubExpr, true);
19937 break;
19938
19939 case ConditionKind::Switch:
19940 Cond = CheckSwitchCondition(Loc, SubExpr);
19941 break;
19942 }
19943 if (Cond.isInvalid()) {
19944 Cond = CreateRecoveryExpr(SubExpr->getBeginLoc(), SubExpr->getEndLoc(),
19945 {SubExpr}, PreferredConditionType(CK));
19946 if (!Cond.get())
19947 return ConditionError();
19948 }
19949 // FIXME: FullExprArg doesn't have an invalid bit, so check nullness instead.
19950 FullExprArg FullExpr = MakeFullExpr(Cond.get(), Loc);
19951 if (!FullExpr.get())
19952 return ConditionError();
19953
19954 return ConditionResult(*this, nullptr, FullExpr,
19955 CK == ConditionKind::ConstexprIf);
19956}
19957
19958namespace {
19959 /// A visitor for rebuilding a call to an __unknown_any expression
19960 /// to have an appropriate type.
19961 struct RebuildUnknownAnyFunction
19962 : StmtVisitor<RebuildUnknownAnyFunction, ExprResult> {
19963
19964 Sema &S;
19965
19966 RebuildUnknownAnyFunction(Sema &S) : S(S) {}
19967
19968 ExprResult VisitStmt(Stmt *S) {
19969 llvm_unreachable("unexpected statement!")::llvm::llvm_unreachable_internal("unexpected statement!", "clang/lib/Sema/SemaExpr.cpp"
, 19969)
;
19970 }
19971
19972 ExprResult VisitExpr(Expr *E) {
19973 S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_call)
19974 << E->getSourceRange();
19975 return ExprError();
19976 }
19977
19978 /// Rebuild an expression which simply semantically wraps another
19979 /// expression which it shares the type and value kind of.
19980 template <class T> ExprResult rebuildSugarExpr(T *E) {
19981 ExprResult SubResult = Visit(E->getSubExpr());
19982 if (SubResult.isInvalid()) return ExprError();
19983
19984 Expr *SubExpr = SubResult.get();
19985 E->setSubExpr(SubExpr);
19986 E->setType(SubExpr->getType());
19987 E->setValueKind(SubExpr->getValueKind());
19988 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", 19988, __extension__ __PRETTY_FUNCTION__
))
;
19989 return E;
19990 }
19991
19992 ExprResult VisitParenExpr(ParenExpr *E) {
19993 return rebuildSugarExpr(E);
19994 }
19995
19996 ExprResult VisitUnaryExtension(UnaryOperator *E) {
19997 return rebuildSugarExpr(E);
19998 }
19999
20000 ExprResult VisitUnaryAddrOf(UnaryOperator *E) {
20001 ExprResult SubResult = Visit(E->getSubExpr());
20002 if (SubResult.isInvalid()) return ExprError();
20003
20004 Expr *SubExpr = SubResult.get();
20005 E->setSubExpr(SubExpr);
20006 E->setType(S.Context.getPointerType(SubExpr->getType()));
20007 assert(E->isPRValue())(static_cast <bool> (E->isPRValue()) ? void (0) : __assert_fail
("E->isPRValue()", "clang/lib/Sema/SemaExpr.cpp", 20007, __extension__
__PRETTY_FUNCTION__))
;
20008 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", 20008, __extension__ __PRETTY_FUNCTION__
))
;
20009 return E;
20010 }
20011
20012 ExprResult resolveDecl(Expr *E, ValueDecl *VD) {
20013 if (!isa<FunctionDecl>(VD)) return VisitExpr(E);
20014
20015 E->setType(VD->getType());
20016
20017 assert(E->isPRValue())(static_cast <bool> (E->isPRValue()) ? void (0) : __assert_fail
("E->isPRValue()", "clang/lib/Sema/SemaExpr.cpp", 20017, __extension__
__PRETTY_FUNCTION__))
;
20018 if (S.getLangOpts().CPlusPlus &&
20019 !(isa<CXXMethodDecl>(VD) &&
20020 cast<CXXMethodDecl>(VD)->isInstance()))
20021 E->setValueKind(VK_LValue);
20022
20023 return E;
20024 }
20025
20026 ExprResult VisitMemberExpr(MemberExpr *E) {
20027 return resolveDecl(E, E->getMemberDecl());
20028 }
20029
20030 ExprResult VisitDeclRefExpr(DeclRefExpr *E) {
20031 return resolveDecl(E, E->getDecl());
20032 }
20033 };
20034}
20035
20036/// Given a function expression of unknown-any type, try to rebuild it
20037/// to have a function type.
20038static ExprResult rebuildUnknownAnyFunction(Sema &S, Expr *FunctionExpr) {
20039 ExprResult Result = RebuildUnknownAnyFunction(S).Visit(FunctionExpr);
20040 if (Result.isInvalid()) return ExprError();
20041 return S.DefaultFunctionArrayConversion(Result.get());
20042}
20043
20044namespace {
20045 /// A visitor for rebuilding an expression of type __unknown_anytype
20046 /// into one which resolves the type directly on the referring
20047 /// expression. Strict preservation of the original source
20048 /// structure is not a goal.
20049 struct RebuildUnknownAnyExpr
20050 : StmtVisitor<RebuildUnknownAnyExpr, ExprResult> {
20051
20052 Sema &S;
20053
20054 /// The current destination type.
20055 QualType DestType;
20056
20057 RebuildUnknownAnyExpr(Sema &S, QualType CastType)
20058 : S(S), DestType(CastType) {}
20059
20060 ExprResult VisitStmt(Stmt *S) {
20061 llvm_unreachable("unexpected statement!")::llvm::llvm_unreachable_internal("unexpected statement!", "clang/lib/Sema/SemaExpr.cpp"
, 20061)
;
20062 }
20063
20064 ExprResult VisitExpr(Expr *E) {
20065 S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_expr)
20066 << E->getSourceRange();
20067 return ExprError();
20068 }
20069
20070 ExprResult VisitCallExpr(CallExpr *E);
20071 ExprResult VisitObjCMessageExpr(ObjCMessageExpr *E);
20072
20073 /// Rebuild an expression which simply semantically wraps another
20074 /// expression which it shares the type and value kind of.
20075 template <class T> ExprResult rebuildSugarExpr(T *E) {
20076 ExprResult SubResult = Visit(E->getSubExpr());
20077 if (SubResult.isInvalid()) return ExprError();
20078 Expr *SubExpr = SubResult.get();
20079 E->setSubExpr(SubExpr);
20080 E->setType(SubExpr->getType());
20081 E->setValueKind(SubExpr->getValueKind());
20082 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", 20082, __extension__ __PRETTY_FUNCTION__
))
;
20083 return E;
20084 }
20085
20086 ExprResult VisitParenExpr(ParenExpr *E) {
20087 return rebuildSugarExpr(E);
20088 }
20089
20090 ExprResult VisitUnaryExtension(UnaryOperator *E) {
20091 return rebuildSugarExpr(E);
20092 }
20093
20094 ExprResult VisitUnaryAddrOf(UnaryOperator *E) {
20095 const PointerType *Ptr = DestType->getAs<PointerType>();
20096 if (!Ptr) {
20097 S.Diag(E->getOperatorLoc(), diag::err_unknown_any_addrof)
20098 << E->getSourceRange();
20099 return ExprError();
20100 }
20101
20102 if (isa<CallExpr>(E->getSubExpr())) {
20103 S.Diag(E->getOperatorLoc(), diag::err_unknown_any_addrof_call)
20104 << E->getSourceRange();
20105 return ExprError();
20106 }
20107
20108 assert(E->isPRValue())(static_cast <bool> (E->isPRValue()) ? void (0) : __assert_fail
("E->isPRValue()", "clang/lib/Sema/SemaExpr.cpp", 20108, __extension__
__PRETTY_FUNCTION__))
;
20109 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", 20109, __extension__ __PRETTY_FUNCTION__
))
;
20110 E->setType(DestType);
20111
20112 // Build the sub-expression as if it were an object of the pointee type.
20113 DestType = Ptr->getPointeeType();
20114 ExprResult SubResult = Visit(E->getSubExpr());
20115 if (SubResult.isInvalid()) return ExprError();
20116 E->setSubExpr(SubResult.get());
20117 return E;
20118 }
20119
20120 ExprResult VisitImplicitCastExpr(ImplicitCastExpr *E);
20121
20122 ExprResult resolveDecl(Expr *E, ValueDecl *VD);
20123
20124 ExprResult VisitMemberExpr(MemberExpr *E) {
20125 return resolveDecl(E, E->getMemberDecl());
20126 }
20127
20128 ExprResult VisitDeclRefExpr(DeclRefExpr *E) {
20129 return resolveDecl(E, E->getDecl());
20130 }
20131 };
20132}
20133
20134/// Rebuilds a call expression which yielded __unknown_anytype.
20135ExprResult RebuildUnknownAnyExpr::VisitCallExpr(CallExpr *E) {
20136 Expr *CalleeExpr = E->getCallee();
20137
20138 enum FnKind {
20139 FK_MemberFunction,
20140 FK_FunctionPointer,
20141 FK_BlockPointer
20142 };
20143
20144 FnKind Kind;
20145 QualType CalleeType = CalleeExpr->getType();
20146 if (CalleeType == S.Context.BoundMemberTy) {
20147 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", 20147, __extension__ __PRETTY_FUNCTION__
))
;
20148 Kind = FK_MemberFunction;
20149 CalleeType = Expr::findBoundMemberType(CalleeExpr);
20150 } else if (const PointerType *Ptr = CalleeType->getAs<PointerType>()) {
20151 CalleeType = Ptr->getPointeeType();
20152 Kind = FK_FunctionPointer;
20153 } else {
20154 CalleeType = CalleeType->castAs<BlockPointerType>()->getPointeeType();
20155 Kind = FK_BlockPointer;
20156 }
20157 const FunctionType *FnType = CalleeType->castAs<FunctionType>();
20158
20159 // Verify that this is a legal result type of a function.
20160 if (DestType->isArrayType() || DestType->isFunctionType()) {
20161 unsigned diagID = diag::err_func_returning_array_function;
20162 if (Kind == FK_BlockPointer)
20163 diagID = diag::err_block_returning_array_function;
20164
20165 S.Diag(E->getExprLoc(), diagID)
20166 << DestType->isFunctionType() << DestType;
20167 return ExprError();
20168 }
20169
20170 // Otherwise, go ahead and set DestType as the call's result.
20171 E->setType(DestType.getNonLValueExprType(S.Context));
20172 E->setValueKind(Expr::getValueKindForType(DestType));
20173 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", 20173, __extension__ __PRETTY_FUNCTION__
))
;
20174
20175 // Rebuild the function type, replacing the result type with DestType.
20176 const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FnType);
20177 if (Proto) {
20178 // __unknown_anytype(...) is a special case used by the debugger when
20179 // it has no idea what a function's signature is.
20180 //
20181 // We want to build this call essentially under the K&R
20182 // unprototyped rules, but making a FunctionNoProtoType in C++
20183 // would foul up all sorts of assumptions. However, we cannot
20184 // simply pass all arguments as variadic arguments, nor can we
20185 // portably just call the function under a non-variadic type; see
20186 // the comment on IR-gen's TargetInfo::isNoProtoCallVariadic.
20187 // However, it turns out that in practice it is generally safe to
20188 // call a function declared as "A foo(B,C,D);" under the prototype
20189 // "A foo(B,C,D,...);". The only known exception is with the
20190 // Windows ABI, where any variadic function is implicitly cdecl
20191 // regardless of its normal CC. Therefore we change the parameter
20192 // types to match the types of the arguments.
20193 //
20194 // This is a hack, but it is far superior to moving the
20195 // corresponding target-specific code from IR-gen to Sema/AST.
20196
20197 ArrayRef<QualType> ParamTypes = Proto->getParamTypes();
20198 SmallVector<QualType, 8> ArgTypes;
20199 if (ParamTypes.empty() && Proto->isVariadic()) { // the special case
20200 ArgTypes.reserve(E->getNumArgs());
20201 for (unsigned i = 0, e = E->getNumArgs(); i != e; ++i) {
20202 ArgTypes.push_back(S.Context.getReferenceQualifiedType(E->getArg(i)));
20203 }
20204 ParamTypes = ArgTypes;
20205 }
20206 DestType = S.Context.getFunctionType(DestType, ParamTypes,
20207 Proto->getExtProtoInfo());
20208 } else {
20209 DestType = S.Context.getFunctionNoProtoType(DestType,
20210 FnType->getExtInfo());
20211 }
20212
20213 // Rebuild the appropriate pointer-to-function type.
20214 switch (Kind) {
20215 case FK_MemberFunction:
20216 // Nothing to do.
20217 break;
20218
20219 case FK_FunctionPointer:
20220 DestType = S.Context.getPointerType(DestType);
20221 break;
20222
20223 case FK_BlockPointer:
20224 DestType = S.Context.getBlockPointerType(DestType);
20225 break;
20226 }
20227
20228 // Finally, we can recurse.
20229 ExprResult CalleeResult = Visit(CalleeExpr);
20230 if (!CalleeResult.isUsable()) return ExprError();
20231 E->setCallee(CalleeResult.get());
20232
20233 // Bind a temporary if necessary.
20234 return S.MaybeBindToTemporary(E);
20235}
20236
20237ExprResult RebuildUnknownAnyExpr::VisitObjCMessageExpr(ObjCMessageExpr *E) {
20238 // Verify that this is a legal result type of a call.
20239 if (DestType->isArrayType() || DestType->isFunctionType()) {
20240 S.Diag(E->getExprLoc(), diag::err_func_returning_array_function)
20241 << DestType->isFunctionType() << DestType;
20242 return ExprError();
20243 }
20244
20245 // Rewrite the method result type if available.
20246 if (ObjCMethodDecl *Method = E->getMethodDecl()) {
20247 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", 20247, __extension__ __PRETTY_FUNCTION__
))
;
20248 Method->setReturnType(DestType);
20249 }
20250
20251 // Change the type of the message.
20252 E->setType(DestType.getNonReferenceType());
20253 E->setValueKind(Expr::getValueKindForType(DestType));
20254
20255 return S.MaybeBindToTemporary(E);
20256}
20257
20258ExprResult RebuildUnknownAnyExpr::VisitImplicitCastExpr(ImplicitCastExpr *E) {
20259 // The only case we should ever see here is a function-to-pointer decay.
20260 if (E->getCastKind() == CK_FunctionToPointerDecay) {
20261 assert(E->isPRValue())(static_cast <bool> (E->isPRValue()) ? void (0) : __assert_fail
("E->isPRValue()", "clang/lib/Sema/SemaExpr.cpp", 20261, __extension__
__PRETTY_FUNCTION__))
;
20262 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", 20262, __extension__ __PRETTY_FUNCTION__
))
;
20263
20264 E->setType(DestType);
20265
20266 // Rebuild the sub-expression as the pointee (function) type.
20267 DestType = DestType->castAs<PointerType>()->getPointeeType();
20268
20269 ExprResult Result = Visit(E->getSubExpr());
20270 if (!Result.isUsable()) return ExprError();
20271
20272 E->setSubExpr(Result.get());
20273 return E;
20274 } else if (E->getCastKind() == CK_LValueToRValue) {
20275 assert(E->isPRValue())(static_cast <bool> (E->isPRValue()) ? void (0) : __assert_fail
("E->isPRValue()", "clang/lib/Sema/SemaExpr.cpp", 20275, __extension__
__PRETTY_FUNCTION__))
;
20276 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", 20276, __extension__ __PRETTY_FUNCTION__
))
;
20277
20278 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", 20278, __extension__ __PRETTY_FUNCTION__
))
;
20279
20280 E->setType(DestType);
20281
20282 // The sub-expression has to be a lvalue reference, so rebuild it as such.
20283 DestType = S.Context.getLValueReferenceType(DestType);
20284
20285 ExprResult Result = Visit(E->getSubExpr());
20286 if (!Result.isUsable()) return ExprError();
20287
20288 E->setSubExpr(Result.get());
20289 return E;
20290 } else {
20291 llvm_unreachable("Unhandled cast type!")::llvm::llvm_unreachable_internal("Unhandled cast type!", "clang/lib/Sema/SemaExpr.cpp"
, 20291)
;
20292 }
20293}
20294
20295ExprResult RebuildUnknownAnyExpr::resolveDecl(Expr *E, ValueDecl *VD) {
20296 ExprValueKind ValueKind = VK_LValue;
20297 QualType Type = DestType;
20298
20299 // We know how to make this work for certain kinds of decls:
20300
20301 // - functions
20302 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(VD)) {
20303 if (const PointerType *Ptr = Type->getAs<PointerType>()) {
20304 DestType = Ptr->getPointeeType();
20305 ExprResult Result = resolveDecl(E, VD);
20306 if (Result.isInvalid()) return ExprError();
20307 return S.ImpCastExprToType(Result.get(), Type, CK_FunctionToPointerDecay,
20308 VK_PRValue);
20309 }
20310
20311 if (!Type->isFunctionType()) {
20312 S.Diag(E->getExprLoc(), diag::err_unknown_any_function)
20313 << VD << E->getSourceRange();
20314 return ExprError();
20315 }
20316 if (const FunctionProtoType *FT = Type->getAs<FunctionProtoType>()) {
20317 // We must match the FunctionDecl's type to the hack introduced in
20318 // RebuildUnknownAnyExpr::VisitCallExpr to vararg functions of unknown
20319 // type. See the lengthy commentary in that routine.
20320 QualType FDT = FD->getType();
20321 const FunctionType *FnType = FDT->castAs<FunctionType>();
20322 const FunctionProtoType *Proto = dyn_cast_or_null<FunctionProtoType>(FnType);
20323 DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E);
20324 if (DRE && Proto && Proto->getParamTypes().empty() && Proto->isVariadic()) {
20325 SourceLocation Loc = FD->getLocation();
20326 FunctionDecl *NewFD = FunctionDecl::Create(
20327 S.Context, FD->getDeclContext(), Loc, Loc,
20328 FD->getNameInfo().getName(), DestType, FD->getTypeSourceInfo(),
20329 SC_None, S.getCurFPFeatures().isFPConstrained(),
20330 false /*isInlineSpecified*/, FD->hasPrototype(),
20331 /*ConstexprKind*/ ConstexprSpecKind::Unspecified);
20332
20333 if (FD->getQualifier())
20334 NewFD->setQualifierInfo(FD->getQualifierLoc());
20335
20336 SmallVector<ParmVarDecl*, 16> Params;
20337 for (const auto &AI : FT->param_types()) {
20338 ParmVarDecl *Param =
20339 S.BuildParmVarDeclForTypedef(FD, Loc, AI);
20340 Param->setScopeInfo(0, Params.size());
20341 Params.push_back(Param);
20342 }
20343 NewFD->setParams(Params);
20344 DRE->setDecl(NewFD);
20345 VD = DRE->getDecl();
20346 }
20347 }
20348
20349 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD))
20350 if (MD->isInstance()) {
20351 ValueKind = VK_PRValue;
20352 Type = S.Context.BoundMemberTy;
20353 }
20354
20355 // Function references aren't l-values in C.
20356 if (!S.getLangOpts().CPlusPlus)
20357 ValueKind = VK_PRValue;
20358
20359 // - variables
20360 } else if (isa<VarDecl>(VD)) {
20361 if (const ReferenceType *RefTy = Type->getAs<ReferenceType>()) {
20362 Type = RefTy->getPointeeType();
20363 } else if (Type->isFunctionType()) {
20364 S.Diag(E->getExprLoc(), diag::err_unknown_any_var_function_type)
20365 << VD << E->getSourceRange();
20366 return ExprError();
20367 }
20368
20369 // - nothing else
20370 } else {
20371 S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_decl)
20372 << VD << E->getSourceRange();
20373 return ExprError();
20374 }
20375
20376 // Modifying the declaration like this is friendly to IR-gen but
20377 // also really dangerous.
20378 VD->setType(DestType);
20379 E->setType(Type);
20380 E->setValueKind(ValueKind);
20381 return E;
20382}
20383
20384/// Check a cast of an unknown-any type. We intentionally only
20385/// trigger this for C-style casts.
20386ExprResult Sema::checkUnknownAnyCast(SourceRange TypeRange, QualType CastType,
20387 Expr *CastExpr, CastKind &CastKind,
20388 ExprValueKind &VK, CXXCastPath &Path) {
20389 // The type we're casting to must be either void or complete.
20390 if (!CastType->isVoidType() &&
20391 RequireCompleteType(TypeRange.getBegin(), CastType,
20392 diag::err_typecheck_cast_to_incomplete))
20393 return ExprError();
20394
20395 // Rewrite the casted expression from scratch.
20396 ExprResult result = RebuildUnknownAnyExpr(*this, CastType).Visit(CastExpr);
20397 if (!result.isUsable()) return ExprError();
20398
20399 CastExpr = result.get();
20400 VK = CastExpr->getValueKind();
20401 CastKind = CK_NoOp;
20402
20403 return CastExpr;
20404}
20405
20406ExprResult Sema::forceUnknownAnyToType(Expr *E, QualType ToType) {
20407 return RebuildUnknownAnyExpr(*this, ToType).Visit(E);
20408}
20409
20410ExprResult Sema::checkUnknownAnyArg(SourceLocation callLoc,
20411 Expr *arg, QualType &paramType) {
20412 // If the syntactic form of the argument is not an explicit cast of
20413 // any sort, just do default argument promotion.
20414 ExplicitCastExpr *castArg = dyn_cast<ExplicitCastExpr>(arg->IgnoreParens());
20415 if (!castArg) {
20416 ExprResult result = DefaultArgumentPromotion(arg);
20417 if (result.isInvalid()) return ExprError();
20418 paramType = result.get()->getType();
20419 return result;
20420 }
20421
20422 // Otherwise, use the type that was written in the explicit cast.
20423 assert(!arg->hasPlaceholderType())(static_cast <bool> (!arg->hasPlaceholderType()) ? void
(0) : __assert_fail ("!arg->hasPlaceholderType()", "clang/lib/Sema/SemaExpr.cpp"
, 20423, __extension__ __PRETTY_FUNCTION__))
;
20424 paramType = castArg->getTypeAsWritten();
20425
20426 // Copy-initialize a parameter of that type.
20427 InitializedEntity entity =
20428 InitializedEntity::InitializeParameter(Context, paramType,
20429 /*consumed*/ false);
20430 return PerformCopyInitialization(entity, callLoc, arg);
20431}
20432
20433static ExprResult diagnoseUnknownAnyExpr(Sema &S, Expr *E) {
20434 Expr *orig = E;
20435 unsigned diagID = diag::err_uncasted_use_of_unknown_any;
20436 while (true) {
20437 E = E->IgnoreParenImpCasts();
20438 if (CallExpr *call = dyn_cast<CallExpr>(E)) {
20439 E = call->getCallee();
20440 diagID = diag::err_uncasted_call_of_unknown_any;
20441 } else {
20442 break;
20443 }
20444 }
20445
20446 SourceLocation loc;
20447 NamedDecl *d;
20448 if (DeclRefExpr *ref = dyn_cast<DeclRefExpr>(E)) {
20449 loc = ref->getLocation();
20450 d = ref->getDecl();
20451 } else if (MemberExpr *mem = dyn_cast<MemberExpr>(E)) {
20452 loc = mem->getMemberLoc();
20453 d = mem->getMemberDecl();
20454 } else if (ObjCMessageExpr *msg = dyn_cast<ObjCMessageExpr>(E)) {
20455 diagID = diag::err_uncasted_call_of_unknown_any;
20456 loc = msg->getSelectorStartLoc();
20457 d = msg->getMethodDecl();
20458 if (!d) {
20459 S.Diag(loc, diag::err_uncasted_send_to_unknown_any_method)
20460 << static_cast<unsigned>(msg->isClassMessage()) << msg->getSelector()
20461 << orig->getSourceRange();
20462 return ExprError();
20463 }
20464 } else {
20465 S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_expr)
20466 << E->getSourceRange();
20467 return ExprError();
20468 }
20469
20470 S.Diag(loc, diagID) << d << orig->getSourceRange();
20471
20472 // Never recoverable.
20473 return ExprError();
20474}
20475
20476/// Check for operands with placeholder types and complain if found.
20477/// Returns ExprError() if there was an error and no recovery was possible.
20478ExprResult Sema::CheckPlaceholderExpr(Expr *E) {
20479 if (!Context.isDependenceAllowed()) {
20480 // C cannot handle TypoExpr nodes on either side of a binop because it
20481 // doesn't handle dependent types properly, so make sure any TypoExprs have
20482 // been dealt with before checking the operands.
20483 ExprResult Result = CorrectDelayedTyposInExpr(E);
20484 if (!Result.isUsable()) return ExprError();
20485 E = Result.get();
20486 }
20487
20488 const BuiltinType *placeholderType = E->getType()->getAsPlaceholderType();
20489 if (!placeholderType) return E;
20490
20491 switch (placeholderType->getKind()) {
20492
20493 // Overloaded expressions.
20494 case BuiltinType::Overload: {
20495 // Try to resolve a single function template specialization.
20496 // This is obligatory.
20497 ExprResult Result = E;
20498 if (ResolveAndFixSingleFunctionTemplateSpecialization(Result, false))
20499 return Result;
20500
20501 // No guarantees that ResolveAndFixSingleFunctionTemplateSpecialization
20502 // leaves Result unchanged on failure.
20503 Result = E;
20504 if (resolveAndFixAddressOfSingleOverloadCandidate(Result))
20505 return Result;
20506
20507 // If that failed, try to recover with a call.
20508 tryToRecoverWithCall(Result, PDiag(diag::err_ovl_unresolvable),
20509 /*complain*/ true);
20510 return Result;
20511 }
20512
20513 // Bound member functions.
20514 case BuiltinType::BoundMember: {
20515 ExprResult result = E;
20516 const Expr *BME = E->IgnoreParens();
20517 PartialDiagnostic PD = PDiag(diag::err_bound_member_function);
20518 // Try to give a nicer diagnostic if it is a bound member that we recognize.
20519 if (isa<CXXPseudoDestructorExpr>(BME)) {
20520 PD = PDiag(diag::err_dtor_expr_without_call) << /*pseudo-destructor*/ 1;
20521 } else if (const auto *ME = dyn_cast<MemberExpr>(BME)) {
20522 if (ME->getMemberNameInfo().getName().getNameKind() ==
20523 DeclarationName::CXXDestructorName)
20524 PD = PDiag(diag::err_dtor_expr_without_call) << /*destructor*/ 0;
20525 }
20526 tryToRecoverWithCall(result, PD,
20527 /*complain*/ true);
20528 return result;
20529 }
20530
20531 // ARC unbridged casts.
20532 case BuiltinType::ARCUnbridgedCast: {
20533 Expr *realCast = stripARCUnbridgedCast(E);
20534 diagnoseARCUnbridgedCast(realCast);
20535 return realCast;
20536 }
20537
20538 // Expressions of unknown type.
20539 case BuiltinType::UnknownAny:
20540 return diagnoseUnknownAnyExpr(*this, E);
20541
20542 // Pseudo-objects.
20543 case BuiltinType::PseudoObject:
20544 return checkPseudoObjectRValue(E);
20545
20546 case BuiltinType::BuiltinFn: {
20547 // Accept __noop without parens by implicitly converting it to a call expr.
20548 auto *DRE = dyn_cast<DeclRefExpr>(E->IgnoreParenImpCasts());
20549 if (DRE) {
20550 auto *FD = cast<FunctionDecl>(DRE->getDecl());
20551 unsigned BuiltinID = FD->getBuiltinID();
20552 if (BuiltinID == Builtin::BI__noop) {
20553 E = ImpCastExprToType(E, Context.getPointerType(FD->getType()),
20554 CK_BuiltinFnToFnPtr)
20555 .get();
20556 return CallExpr::Create(Context, E, /*Args=*/{}, Context.IntTy,
20557 VK_PRValue, SourceLocation(),
20558 FPOptionsOverride());
20559 }
20560
20561 if (Context.BuiltinInfo.isInStdNamespace(BuiltinID)) {
20562 // Any use of these other than a direct call is ill-formed as of C++20,
20563 // because they are not addressable functions. In earlier language
20564 // modes, warn and force an instantiation of the real body.
20565 Diag(E->getBeginLoc(),
20566 getLangOpts().CPlusPlus20
20567 ? diag::err_use_of_unaddressable_function
20568 : diag::warn_cxx20_compat_use_of_unaddressable_function);
20569 if (FD->isImplicitlyInstantiable()) {
20570 // Require a definition here because a normal attempt at
20571 // instantiation for a builtin will be ignored, and we won't try
20572 // again later. We assume that the definition of the template
20573 // precedes this use.
20574 InstantiateFunctionDefinition(E->getBeginLoc(), FD,
20575 /*Recursive=*/false,
20576 /*DefinitionRequired=*/true,
20577 /*AtEndOfTU=*/false);
20578 }
20579 // Produce a properly-typed reference to the function.
20580 CXXScopeSpec SS;
20581 SS.Adopt(DRE->getQualifierLoc());
20582 TemplateArgumentListInfo TemplateArgs;
20583 DRE->copyTemplateArgumentsInto(TemplateArgs);
20584 return BuildDeclRefExpr(
20585 FD, FD->getType(), VK_LValue, DRE->getNameInfo(),
20586 DRE->hasQualifier() ? &SS : nullptr, DRE->getFoundDecl(),
20587 DRE->getTemplateKeywordLoc(),
20588 DRE->hasExplicitTemplateArgs() ? &TemplateArgs : nullptr);
20589 }
20590 }
20591
20592 Diag(E->getBeginLoc(), diag::err_builtin_fn_use);
20593 return ExprError();
20594 }
20595
20596 case BuiltinType::IncompleteMatrixIdx:
20597 Diag(cast<MatrixSubscriptExpr>(E->IgnoreParens())
20598 ->getRowIdx()
20599 ->getBeginLoc(),
20600 diag::err_matrix_incomplete_index);
20601 return ExprError();
20602
20603 // Expressions of unknown type.
20604 case BuiltinType::OMPArraySection:
20605 Diag(E->getBeginLoc(), diag::err_omp_array_section_use);
20606 return ExprError();
20607
20608 // Expressions of unknown type.
20609 case BuiltinType::OMPArrayShaping:
20610 return ExprError(Diag(E->getBeginLoc(), diag::err_omp_array_shaping_use));
20611
20612 case BuiltinType::OMPIterator:
20613 return ExprError(Diag(E->getBeginLoc(), diag::err_omp_iterator_use));
20614
20615 // Everything else should be impossible.
20616#define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
20617 case BuiltinType::Id:
20618#include "clang/Basic/OpenCLImageTypes.def"
20619#define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \
20620 case BuiltinType::Id:
20621#include "clang/Basic/OpenCLExtensionTypes.def"
20622#define SVE_TYPE(Name, Id, SingletonId) \
20623 case BuiltinType::Id:
20624#include "clang/Basic/AArch64SVEACLETypes.def"
20625#define PPC_VECTOR_TYPE(Name, Id, Size) \
20626 case BuiltinType::Id:
20627#include "clang/Basic/PPCTypes.def"
20628#define RVV_TYPE(Name, Id, SingletonId) case BuiltinType::Id:
20629#include "clang/Basic/RISCVVTypes.def"
20630#define BUILTIN_TYPE(Id, SingletonId) case BuiltinType::Id:
20631#define PLACEHOLDER_TYPE(Id, SingletonId)
20632#include "clang/AST/BuiltinTypes.def"
20633 break;
20634 }
20635
20636 llvm_unreachable("invalid placeholder type!")::llvm::llvm_unreachable_internal("invalid placeholder type!"
, "clang/lib/Sema/SemaExpr.cpp", 20636)
;
20637}
20638
20639bool Sema::CheckCaseExpression(Expr *E) {
20640 if (E->isTypeDependent())
20641 return true;
20642 if (E->isValueDependent() || E->isIntegerConstantExpr(Context))
20643 return E->getType()->isIntegralOrEnumerationType();
20644 return false;
20645}
20646
20647/// ActOnObjCBoolLiteral - Parse {__objc_yes,__objc_no} literals.
20648ExprResult
20649Sema::ActOnObjCBoolLiteral(SourceLocation OpLoc, tok::TokenKind Kind) {
20650 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", 20651, __extension__ __PRETTY_FUNCTION__
))
20651 "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", 20651, __extension__ __PRETTY_FUNCTION__
))
;
20652 QualType BoolT = Context.ObjCBuiltinBoolTy;
20653 if (!Context.getBOOLDecl()) {
20654 LookupResult Result(*this, &Context.Idents.get("BOOL"), OpLoc,
20655 Sema::LookupOrdinaryName);
20656 if (LookupName(Result, getCurScope()) && Result.isSingleResult()) {
20657 NamedDecl *ND = Result.getFoundDecl();
20658 if (TypedefDecl *TD = dyn_cast<TypedefDecl>(ND))
20659 Context.setBOOLDecl(TD);
20660 }
20661 }
20662 if (Context.getBOOLDecl())
20663 BoolT = Context.getBOOLType();
20664 return new (Context)
20665 ObjCBoolLiteralExpr(Kind == tok::kw___objc_yes, BoolT, OpLoc);
20666}
20667
20668ExprResult Sema::ActOnObjCAvailabilityCheckExpr(
20669 llvm::ArrayRef<AvailabilitySpec> AvailSpecs, SourceLocation AtLoc,
20670 SourceLocation RParen) {
20671 auto FindSpecVersion = [&](StringRef Platform) -> Optional<VersionTuple> {
20672 auto Spec = llvm::find_if(AvailSpecs, [&](const AvailabilitySpec &Spec) {
20673 return Spec.getPlatform() == Platform;
20674 });
20675 // Transcribe the "ios" availability check to "maccatalyst" when compiling
20676 // for "maccatalyst" if "maccatalyst" is not specified.
20677 if (Spec == AvailSpecs.end() && Platform == "maccatalyst") {
20678 Spec = llvm::find_if(AvailSpecs, [&](const AvailabilitySpec &Spec) {
20679 return Spec.getPlatform() == "ios";
20680 });
20681 }
20682 if (Spec == AvailSpecs.end())
20683 return None;
20684 return Spec->getVersion();
20685 };
20686
20687 VersionTuple Version;
20688 if (auto MaybeVersion =
20689 FindSpecVersion(Context.getTargetInfo().getPlatformName()))
20690 Version = *MaybeVersion;
20691
20692 // The use of `@available` in the enclosing context should be analyzed to
20693 // warn when it's used inappropriately (i.e. not if(@available)).
20694 if (FunctionScopeInfo *Context = getCurFunctionAvailabilityContext())
20695 Context->HasPotentialAvailabilityViolations = true;
20696
20697 return new (Context)
20698 ObjCAvailabilityCheckExpr(Version, AtLoc, RParen, Context.BoolTy);
20699}
20700
20701ExprResult Sema::CreateRecoveryExpr(SourceLocation Begin, SourceLocation End,
20702 ArrayRef<Expr *> SubExprs, QualType T) {
20703 if (!Context.getLangOpts().RecoveryAST)
20704 return ExprError();
20705
20706 if (isSFINAEContext())
20707 return ExprError();
20708
20709 if (T.isNull() || T->isUndeducedType() ||
20710 !Context.getLangOpts().RecoveryASTType)
20711 // We don't know the concrete type, fallback to dependent type.
20712 T = Context.DependentTy;
20713
20714 return RecoveryExpr::Create(Context, T, Begin, End, SubExprs);
20715}